Enabling and configuring Http-Redirection on IIS 7

There is always a use case or a scenario where one might want to redirect all request from your website to some other website. The element configures settings for Internet Information Services (IIS) 7 that redirect client requests to a new location.

To begin with, make sure you have HttpRedirect feature enabled, if not it can be easily be enabled by going to the “Programs & Features” >> “Turn Windows features on or off” and enabling “HTTP Redirection” module.

enter image description here

Once you have made sure you have the necessary module installed. Let’s quickly see how to setup the redirection.

enter image description here

enter image description here

Simply put in the url where you want the redirection to happen. You can also redirect to the exact destination instead of relative using the options provided.

Hope this helps. Cheers!

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:

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;
}

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.

How to get a list of all users when using ASP.NET Membership ?

ASP.NET Membership helps you manage user authentication for your websites. Its supports facilities to create user, assign roles, reset password and almost everything under the user management domain.

Its a common requirement to list down all the users using the ASP.NET Membership provider. Though ASP.NET Membership has a inbuilt MembershipProvider‘s MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords); method where you can pass pageIndex, pageSize using which paging also can be handled.

However I found an another way to get this list, without having to play with the pageIndex and pageSize options on this StackOverflow thread.

var users = Membership.GetAllUsers();

var userList = new List<MembershipUser>();
foreach (MembershipUser user in users) 
{
    userList.Add(user);
}

Injecting dependencies into WebViewPages / Razor View in ASP.NET MVC

Even before you start reading this post, I am sure many of you ll would have already had discussions on this like

“Why would you need to access services on your view?”

or

“Why would you want to inject dependencies into your view?”

and even

“Shouldn’t your View be plain and dumb and be used only to render HTML from a model?”

But anyways here is something that should help you, should you want to inject dependencies in your views.

For example’s sake let’s consider you have a ‘PermissionService’ which has a method IsModuleAllowedForUser(Guid userId, string moduleName) which decides if the module is allowed for the user and only then renders it. Now I want to access this service method from my view.

Demo.Services.Core.PermissionService.cs

namespace Demo.Service.Core
{
    public class PermissionService : IPermissionService
    {
        public bool IsModuleAllowedForUser(Guid userId, string moduleName)
        {
            // blah
        }
    }
}

Here’s a way to do it.

To start with we’ll need to create a class which will inherit from the WebViewPage class. I have injected the IPermissionService using property inject with Ninject.

Demo.Web.Core.MyInjectedWebViewPage.cs

using System.Web.Mvc;
using Ninject;

namespace Demo.Web.Core
{
    public abstract class MyInjectedWebViewPage : WebViewPage
    {
        [Inject]
        public IPermissionService PermissionManager { get; set; }
    }
}

in my NinjectWebCommon.cs class I have added bindings for the same

Bind<WebViewPage>().To<MaxInjectedWebViewPage<dynamic>>();
Bind<IPermissionService>().To<PermissionService>();    

and now in the view I can use the services like as shown below

@inherits MyInjectedWebViewPage

@if(PermissionManager.IsModuleAllowedForUser(Helper.GetUserId(), "precious"))
{
    <div>My precious div!</div>
}

Hope this helps :)

References:

  1. ASP.NET MVC 3 Service Location, Part 3: View Engines/View Pages
  2. Can you inject dependencies into a constructor of a custom WebViewPage, using an IOC container?

Using GIT with Visual Studio 2013

Git, has been around for quite some time now. All major repository hosting services like GitHub, Bitbucket and now even Codeplex recommended users to opt for GIT as a recommended/default type of source control system for your project.

I have been avoiding GIT for a very longg time, the only reason being is familiarity and love for SVN :) So when I wanted to created a new project – qask on Codeplex and found that the SVN option was no longer present on codeplex. I decided to (finally) give GIT a try…

enter image description here

You might also want to read this beautiful question & answer on GIT vs SVN : Why is Git better than Subversion?

1. Changing the Source Control plugin

Once you have your project opened, go to ‘Tools > Options’, go to ‘Source Control’ sub menu and select ‘Microsoft Git Provider’ from the source control plugin dropdown and press ‘ok’.

enter image description here

and that’s it.

2. Commit and Sync

Once you have configured as above, your team explorer will look something like this :

enter image description here

you can see your pending changes, and commit with a message using the screen below :

enter image description here

enter image description here

Post every commit you will be given an option to sync, you can sync every time you commit or whenever you want to.

enter image description here

enter image description here

enter image description here

Hope this helps. A more detailed post on Git version control with Visual Studio 2013 is present here, a must read for any newbies to GIT.

How to pass values from ASP.NET MVC Razor Views to Angular Controller ?

I have been using a lot of AngularJs code on my razor views lately. On one of my page, I wanted to pass to my angular controller the model which is being passed to my razor view.

Can be done with the following code

ng-init="init(@JsonConvert.SerializeObject(Model))"

JsonConvert.SerializeObject helps you convert an object to a JSON string and you can use ng-init to pass and use this value in your controller.

How to configure the default ASP.NET Membership’s Role Manager in ASP.NET MVC 4

If you do not want to create your own custom Role Provider and use the ASP.NET Membership’s in built RoleManager. Then you should use the following setting in your web.config file.

<roleManager enabled="true" defaultProvider="SqlRoleProvider" >
  <providers>
    <add name="SqlRoleProvider"
         type="System.Web.Security.SqlRoleProvider"
         connectionStringName="AbcAspNetConnection"
         applicationName="Abc Web Application"/>
  </providers>
</roleManager>