How to redirect Urls without www to with www – Permanent (301) Redirection in

First, why should we redirect Urls without “www” to with “www” or vice versa?

Answer – If you site cares for search engine ranking then this is a must. Famous search engines like Google or Bing prefer that you have ONLY one domain associated with your website. In search engine world, “” and are considered two different domains. If you don’t redirect calls for to “”  Or vice-a-versa, crawler will treat these two as two different yet totally duplicate sites. Hence, your search engine ranking will have a negative impact.

Other than this important reason, you also might want to stick to one of these Urls to maintain your Social Media Like Counters e.g. Facebook will also consider two of these as two different sites.

This post is not about understanding the benefits of permanent redirection to one preferred domain url. For more information you can read this article by google.

Now lets get to fixing this issue in URL rewrite can be done in IIS or by using <rewrite> rule in web.config file.

Adding above code to web.config will permanent redirect (status code 301) all requests for to “” .

1) Inbound Rule – “.*” regex will match all request coming to web server for

2) Condition – Regex pattern “^$” will match domain name without “www” prefix.

3) Action – Re-write action replaces the current query string with a substitution string. In other words, pattern specified in condition input will be replaced with url specified in action tag and we will force this as Permanent redirection Type (it goes with status 301).

If you are not familiar with Regex expressions, read this tutorial by Microsoft to know more.

To further better understand <rewrite> module and various attributes in-depth, I suggest reading this excellent article from Microsoft.

I hope this helps you reach the solution you were looking for.


Happy Coding!


IF Azure Role Instances Stop Unexpectedly – Do not Panic!

Recently, our Azure Deployed Production Web Sites stopped and were giving message – “503 Service Unavailable Error“. I think we jumped on error too quickly since production was down.  Checked Errors logs, nothing there. Logged on to Azure Portal  and found that our Azure Worker and Web role Instances have stopped unexpectedly . If you experience this error, do not panic and wait for few minutes. Most likely cause of this unexpected stoppage is Microsoft Guest OS Updates. After the scheduled updates, instances will auto-start and websites will be up and running again.

Approximate every month Microsoft releases Guest OS Updates for Azure PaaS VMs. As long as you have 2 or more instance per role, you will not experience this downtime. In-fact, 2 instances of a role are required to meet the 99.95% up-time SLA. A great article about having max up and running time for azure website, I found here –

Learn more about Guest OS updates history and schedules here – Windows Guest OS Releases


How to Update Stored Procedures in EF 6 Database First

In EF 3.5 DB First, there  was no direct way to update SP result sets and I was surprised to learn yesterday that EF 6 also has same issue. Please note, updates do not mean SP code is not updated, that works fine. Its just the Result Set you are returning from a SP with a simple SELECT clause or Using SELECT from TEMP table .

Lets look at this in more detail.

In Db first approach, for all SPs included in .edmx file will generate a Complex Type Set. Naming Conventionis => {SPName}_Result and you can view all result sets in “Model Browser”, under Complex Types. Lets take a simple example for illustration.

e.g. we wish to call a SP named – GetRecipeByRecipeId . We know it will return us Result Set GetRecipeByRecipeId_Result , say which gives me columns {RecipeName, Description, CookTime, PrepTime }. Everything works fine.

Now, we update our SP to include two new columns {TotalTime, Serves}. Update the .edmx file in VS and run the Stored Procedure again. You will notice that underlying Result Set GetRecipeByRecipeId_Result, still has four old columns and 2 new columns have not been added. Do a s\quick search on SP name  “GetRecipeByRecipeId”, you will notice that instead of updating the existing SP, EF has created a new SP named – “GetRecipeByRecipeId1” with prefix 1. This behavior repeats every time you try to update an already added SP.

Solution to this issue is a hack but works perfectly. Open Model Browser Window and do following steps:

  1. Delete  GetRecipeByRecipeIdResult and GetRecipeByRecipeId1_Result from  Complex Types.
  2. Delete GetRecipeByRecipeId and GetRecipeByRecipeId1 from Function Imports
  3. Delete GetRecipeByRecipeId and GetRecipeByRecipeId1 from DBModel.Store > Stored Procedures /Functions
  4. Save changes and Update the Model From Daatabase and include the SP GetRecipeByRecipeId

This time you will notice, Result Set will have all 6 columns and everything works like a charm.

NEXT Post –  SPs with SELECT on Temp Tables are not included in result set in EF 6.

The good, the bad and the ugly of ASP.NET Identity


Ok, here we go again… and if you don’t know what I’m talking about, then see this post.

With Visual Studio 2013 and .NET 4.5.1 we have a new framework called ASP.NET Identity. ASP.NET Identity is yet another identity management framework from Microsoft (recall that we also had two prior frameworks from Microsoft: Membership and SimpleMembership).  Let’s take a look at the good and the bad aspects of this new framework.

TLDR; Click here to get to the ugly conclusion.

Good: Storage customization

One of the major complaints with the previous identity management frameworks was that it was either too cumbersome (with Membership) or too subtle (with SimpleMembership) to customize the storage. With this release, they’ve actually achieved a separation of the storage of the identity information (e.g. username, password, etc.) from the code that implements the security (e.g., password hashing, password validation, etc.). The way they’ve done…

View original post 3,115 more words

Solution to ALTER TABLE statement conflicted with the FOREIGN KEY constraint

Have you experienced “ALTER TABLE statement conflicted with the FOREIGN KEY constraint” error while trying to add a Foreign Key Constraint to a pre-existing table?


ALTER TABLE [dbo].[Table_X]
REFERENCES [dbo].[Table_Y] ([YId])


“Msg 547, Level 16, State 0, Line 1

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint “FK_Table_X_Table_Y”. The conflict occurred in database “XYDB”, table “dbo.Table_Y”, column ‘YId’.”

Actually message is pretty clear but sometimes can be bit illusive. We are here trying to add a FK constraint to an already existing table dbo.Table_X. If this table has no records, this error will never occur. But, if you have data in Table_X prior to applying this constraint , that data is (may be) conflicting with the constraint, so you have to first correct the data before forcing a constraint.

In above case, dbo].[Table_X] had orphan value – 100 in YId column of all records prior to forcing constraint, whereas Table_Y does not have a record with YId 100.


In this scenario, either

1) you can delete all “100” orphan records  from Table_Y (Only if data loss isn’t an issue)

2) Update all orphan records with a valid YId which exist in Table_Y (consider your business model before  updating data)

3) Add a new record to Table_Y with YId = 100 (again consider your business model before updating data )

No matter, which option above you apt for, at the end we want to fix the records in Table_Y which are conflicting with the constraint in question. Once you fix that, statement will work like a charm.

Happy Coding!!

Redirect Old Image Url to New Image Url in MVC

Recently, we upgraded the project I working on to MVC 5 and we also decided to move and deploy all images used in application to a separate location. This will reduce the load on Application since image processing will happen separately. e.g. we resize and watremark our images on fly using handlers, so it will be cool to keep this work separate from app work load.

Current Image Location (A) :  http://{DomainName}/Images/{Itemfolders}/{ImageName}

New Image Location (B) : http://{Assets.DomainName}/Images/{Itemfolders}/{ImageName}

First, how to achieve this re-routing? – Using .net Routing engine. You can either create a Custom Route Handler and redirect all requests for A to B. Or you can simply create Action in controller and decorate it with Route tag. We opted for later and here is the snippet of code (extra code removed for brevity):

[Route(“/Images/{itemfolders}/{imageName}“, Name = “RedirectImageUrl“)]
public void RedirectImageUrl(string itemfolders, string imageName)

Response.Redirect(string.Format(“http://assets.DomainName/Images/{0}/{1}”, itemfolders, imageName), true);


If you try accessing old route now, it might throw error “The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.” If you type same old route without extension of image file (in debug mode) , it does hit the action method but is  no use to us. We obviously want it to work with extension. There are two ways to send this request to .net engine:

a) Enabling RAMMFAR – Enabling “runAllManagedModulesForAllRequests” will enable all managed modules for all requests. That means static files such as images, PDFs and everything else will be processed by .NET when they don’t need to be. This option does result in overhead but works like a charm. Enable it and you will see, above error will disappear and routing will start working.

b) Using Transfer Request Handler – This HTTP handler looks for specific path criteria. If request matches, it correctly sent to .NET for processing. Add following line of code to site’s main web.config under system.webserver / handler section and try requesting the old url (A), .net will beautifully redirect it to new url (B).

<add name="ApiURIs-ISAPI-Integrated-4.0"
     preCondition="integratedMode,runtimeVersionv4.0" />

Have fun and Happy coding!!

New Features in VS 2013

I am excited about launch of Visual Stuido 2013, packed with lots of new features that developers can (must) learn to make their dev jobs a bit easier and rewarding ( may be!!)

Lets look at the features:

1. Social Authentication Helpers : There are some neat templates in 2013 dedicated to social sign-in with Facebook, Google OAuth2 and OpenId Sign-on. So badly awaited feature. Say goodbye to all add-on packages and custom wrappers for social sign-in and have everything pre-packaged in VS 2013. Read more about it here.

2. .NET 4.5.1 : Yes!! VS 2013 comes with new version of .NET SDK 4.5.1. It has bug fixes on release on .NET 4.5 and there are new  performance improvements, and opt-in features etc. Like Idle connection resiliency, Async callstack aware debugging windows etc. Read more here.

3. Attributing routing in MVC 5 and Web API 2: Oh Boy!! this will be a life saver or what? Goodbye all constraints you apply on custom routes to control the routing mach. And good news is, you can combine it with conventional custom routing to get the best of both worlds. Mike Wasson has added a good article to understand Attribute Routing in Web Api 2. This article will be your one stop learning about Attribute Routing.

4. Browser Link: Refresh multiple browser from IDE to see impact of your changes all at once. Learn more here.

5. Entity Framework 6: VS 2013 is shipped with new and improved EF 6.

6. ASP.NET Identity: ASP.NET Identity (new membership system for ASP.NET) promises to start unifying things a little better. Learn more about ASP.NET Identity feature here.

7.Peek Definition Window: A cool way to view and change the code that is been called from your current in-focus code. It shows same result as Go To Definition does, but results are added in a pop-up window which you can edit there itself without loosing context of your current page. More about this here.