Prevent Elmah to send mail on specific type of errors but log them to db.

Approach 1 :

The below filter when added, will stop both – sending out error email and logging to the db.

<errorFilter>
    <test>
        <!--<equal binding="HttpStatusCode" value="404" type="Int32" />-->
        <regex binding="BaseException.Message" pattern="404 request received" />
    </test>
</errorFilter>

Approach 2 :

The below filter will only stop sending out mail, but will continue to log to the db.

<errorFilter>
    <test>
        <or>
            <and>
                <regex binding="BaseException.Message" pattern="404 request received" />
                <regex binding="FilterSourceType.Name" pattern="mail" />
            </and>
            <and>
                <regex binding="BaseException.Message" pattern="Any xyz pattern can go in here..." />
                <regex binding="FilterSourceType.Name" pattern="mail" />
            </and>
        </or>
    </test>
</errorFilter>

Prevent elmah to be cached when using CDN.

It has been a common practice to use ELMAH for pretty much all of my web projects built using the ASP.NET stack.

One problem I kept running into was when using CDN with a website, there was no simple/direct way to tell the CDN to not cache the elmah urls. Here’s a solution which worked for me.

Step 1: Select website and add a url rewrite rule

Step 2: Make sure to select the “Outbound” rule when selecting the rule template

Step 3: Add a precondition, in this case add the elmah url

Step 4: Add a rule to update your response header’s Cache-Control with no-cache

Step 5: Done, now check the http response on your browser

References:

Using key press event in Angular JS

It is a very common use case to catch event of certain key press, like the enter key for example. In this post, I am gonna write about how to handle key press event in Angular JS – using the so called “angular way” approach.

Problem statement:
Let’s define a problem statement to begin with. I have a form with one text field and a button next to it.

enter image description here

And then there was a directive…
This directive checks for keydown & keypress and checks the keycode, 13 in case of the enter key.

app.directive('EnterPressed', function() {
    return function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {
            if (event.which === 13) { // 13 is the code for enter
                scope.$apply(function() {
                    scope.$eval(attrs.myEnter);
                });
                event.preventDefault();
            }
        });
    };
});

and that’s about it. We are done.

Usage:

<div ng-app="" ng-controller="WierdController">
    <input type="text" enter-pressed="doSomething()">
    <button ng-click="doSomething()">Let's go!</button>
</div>

When to use ng-if vs ng-show/ng-hide in Angular JS

Both ng-if and ng-show/ng-hide directives, shows/hides/removes/add HTML to the DOM based on expression provided to the attribute. The approach they use to do this is different though.

ng-show – The element is shown or hidden by removing or adding the .ng-hide CSS class onto the element.

ng-if, on other hand differs from ng-show and ng-hide in that ng-if completely removes and recreates the element in the DOM rather than changing its visibility via the display CSS property.

You might notice a significant improvement in the responsiveness of your app if you repalce all your ng-show/ng-hide with ng-if. Because ng-show leaves the element on the DOM and all of its watch expressions and performance costs would still exists even though these elements are not viewable to the user.

References :

Installing Node JS on windows & Creating my first application using Node JS.

Step 1: Installing Node on Windows:

Node JS has a dedicated page for how to install node on all type of OS – https://github.com/joyent/node/wiki/Installation. Installing node on windows is pretty simple and straight forward, just head over to the node download page and download the appropriate .exe/.msi to install node.

Once installed, the node folder and related files gets added as shown below and that is all there is as far as installing “node on my machine” goes. enter image description here

Step 2: Creating my first node application:

Open up a notepad(or your favorite text editor) and create a js file with the name helloworld.js and put the below code into that file.

var http = require('http');
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World. And then there was light.\n');
}).listen(8124, "127.0.0.1");

console.log('Server running at http://127.0.0.1:8124/');

Save the file, now its time to execute the file using node. To do that open up your command prompt and execute your file using the below mentioned command.

node helloworld.js

enter image description here

With this, your node HTTP server is up and running. (note :make sure you are running node from the same folder where the file is present.)

Browse to http://127.0.0.1:8124/ to check it.

enter image description here

How to add an exclusion list to an HTTP Module in ASP.NET MVC

When writing your own HTTP Module you will need to have an exclusion list, so that not all HTTP request are intercepted by this module. Like for example: HTTP requests for CSS, JS, Images and even Html templates.

Here is what I used in one of our recent projects

private bool ShouldProcessRequestForSignUp(HttpRequest request)
{
    bool isAnAjaxRequest = request.RequestContext.HttpContext.Request.IsAjaxRequest();
    bool isRequestIsForLogoff = request.Url.AbsolutePath.ToLower().Contains("/account/logoff");
    bool isRequestIsForLogin = request.Url.AbsolutePath.ToLower().Contains("/account/login");
    bool isRequestForResources = (request.Url.AbsolutePath.ToLower().Contains("content") || request.Url.AbsolutePath.ToLower().Contains("scripts"));
    if (isAnAjaxRequest)
        return false;
    if (isRequestFortheSignupPage || isRequestIsForLogoff || isRequestIsForLogin)
        return false;
    if (isRequestForResources)
        return false;
    return true;
}

Updating one to many relationship tables using Entity Framework 6

Problem Statement

Consider the following diagram, where there is one to many relationship between the Employee and Assest table. Here 1 Employee can have M Assests.

enter image description here

Lets say an Employee has 2 assests namely -

OldList NewList
Home Home
Bike Car

So there are 3 things to be done when updating this data using the Entity Framework

  1. Look for items present in the newlist and missing in the oldlist, these items are to be added. The item “Car” in this example.
  2. Look for items present in the oldlist and missing in the newlist, these items are to be removed. The item “Bike” in this example.
  3. And finally the items that are present in both the list. The item “Home” in this example, is to be untouched.

Code

The following code uses ExceptBy extension method to compare two lists and return based on the key passed to it.

public void UpdateEmployeeAssests(int employeeId, List<EmpAssets> updatedAssests)
{
    using (var context = new SampleDbEntities())
    {
        List<EmpAssets> oldAssests = context.EmpAssets.Where(x => x.EmployeeId == employeeId).ToList();

        List<EmpAssets> addedAssests = updatedAssests.ExceptBy(oldAssests, x => x.CityId).ToList();
        List<EmpAssets> deletedAssests = oldAssests.ExceptBy(updatedAssests, x => x.CityId).ToList();

        deletedAssests.ForEach( x => context.Entry(x).State = EntityState.Deleted);
        addedAssests.ForEach(x => context.Entry(x).State = EntityState.Added);

        context.SaveChanges();
    }
}

References:

Validation summary with custom message for each field in Angular JS

It is a common requirement to list down all the validation errors of a form in one place, however when using Angular, this gets a little tricky to do it the “Angular Way”.

1. Showing validation summary of the form

<ul>
    <li ng-repeat="(key, errors) in form1.$error track by $index"> <strong>{{ key }}</strong> errors
        <ul>
            <li ng-repeat="e in errors">{{ e.$name }} has an error: <strong>{{ key }}</strong>.</li>
        </ul>
    </li>
</ul>

Screenshot : This can be demoed here – http://plnkr.co/edit/05oDTf?p=preview

enter image description here

2. Showing Errors next to input fields

<form name="userForm" ng-submit="submitForm()" novalidate>
 <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
   <label>Name</label>
   <input type="text" name="name" class="form-control" ng-model="user.name" required>
   <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p>
 </div>

3. Disabling the form submit button, if any of the form input fields are invalid.

<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button>

References:

Injecting into Custom Validation or Authorization Attributes in ASP.NET MVC

Dependency Injection can be done when using Custom Validation or Authorization attributes in ASP.NET MVC. This can be achieved Ninject’s Property injection.

Here is an example of property injection. For a property to be injected it must be annotated with [Inject].

public class ZipCodeAttribute : ValidationAttribute
{
    [Inject]
    public IZipCodeService ZipCodeService { get; set; }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return true;
        }

        if ((value is string) && string.IsNullOrEmpty((string)value))
        {
            return true;
        }

        var zipCode = Convert.ToInt32(value);
        return this.ZipCodeService.IsValidZipCode(zipCode);
    }
}

More on “Injection of validators” can be read here.