Web.Config/App.Config Maintainability

Web Configuration Snippet When working on large projects whether it be websites or software applications, I like to try and make sure that settings from within my app/web configuration files are not only easily accessible within code, but also maintainable for future updates.

Over the years, I have tried different approaches in an attempt to streamline how I use ASP.NET's configuration files within my day-to-day development and this is what I currently do.

Group and Alphabetise

I have started to sort all my settings alphabetically and group common functions/settings together. This alone makes navigating through a large configuration file much more easier.

In addition, having a standard in-house development style and agreeing with your fellow developers how sections within the configuration file is expected to be structured can be useful. For example, on web projects I've worked on, all key sections are  sorted in the following order:

  1. configSections
  2. appSettings
  3. connectionStrings
  4. system.web
  5. customErrors
  6. system.webServer
  7. locations

Common Naming Conventions

I like to name my appsettings in the following format: "<Setting-Group>.<Name>". So if I were to add appsettings that related to Twitter, it would look something as the following:

<add key="Twitter.ApiUrl" value="https://api.twitter.com/1.1/statuses/show.json" />
<add key="Twitter.ApiKey" value="" />
<add key="Twitter.ApiSecret" value="" />
<add key="Twitter.AccessToken" value="" />
<add key="Twitter.AccessTokenSecret" value="" />
<add key="Twitter.Username" value="shomra" />

This provides a simple and descriptive approach to breaking down all settings into manageable chunks.

Strongly-Type AppSettings

One thing that truly annoyed me when I first started .NET development is calling configuration values from within C# code. Not only did you have to write out (the very long-winded!) "ConfigurationManager.AppSettings["Twitter.Username"]", but also cast the value to a specific type.

Using the "ConfigurationManager.AppSettings[]" call is awful. It creates the potential for typo's that aren't caught by the compiler and there's no nice intellisense to make our coding easier.

I create a static configuration wrapper class to strongly-type all my config settings. The way I name my settings (as you can see from the "Common Naming Conventions" section) compliments the structure of my wrapper class.

public class Config
    public static class Social
        #region Twitter

        public static class Twitter
            public static string TwitterApiUrl
                    return ConfigurationManager.AppSettings["Twitter.ApiUrl"];

            public static string TwitterUsername
                    return ConfigurationManager.AppSettings["Twitter.Username"];

            public static string TwitterApiKey
                    return ConfigurationManager.AppSettings["Twitter.ApiKey"];

            public static string TwitterApiSecret
                    return ConfigurationManager.AppSettings["Twitter.ApiSecret"];

            public static string TwitterAccessToken
                    return ConfigurationManager.AppSettings["Twitter.AccessToken"];

            public static string TwitterAccessTokenSecret
                    return ConfigurationManager.AppSettings["Twitter.AccessTokenSecret"];


Admittingly, this can be quite time-consuming but when compared to the long-term benefits this has saved me a lot of headache.

What Else Could Be Done?

I've seen some developers use Applications Settings Architecture within the .NET framework when building Windows applications by creating a "Settings" file within the project.

The only downside I can see with this approach is that all config values declared within the "Settings" file will be compiled at runtime and you lose the flexibility to change configuration values externally. Here's a nice StackOverflow post that describes this method in greater detail.

If any of you readers have further suggestions or advice, I am all ears! :-)

The Future...

As Nick Dyer quite rightly pointed out to me yesterday on Google+, that our beloved web.config file will no longer form part of the applications we create in ASP.NET 5. We will have the freedom to create an applications configuration the way we want, simplifying the whole process.

As I understand, there will be support for creating configuration inputs that can be placed inside JSON, XML and INI files using the new IConfiguration and ConfigurationModel sources.

Sounds very promising.

Error - Platform type SqlAzureDatabaseSchemaProvider does not support schema file version '2.5'

Whilst trying to import a .bacpac database exported from an SQL Azure platform onto Microsoft SQL Server 2012, I received the following error:

Internal Error. The internal target platform type SqlAzureDatabaseSchemaProvider does not support schema file version '2.5'. (File: C:\Users\Surinder\Downloads\SurinderAzureDB.bacpac) (Microsoft.Data.Tools.Schema.Sql)

Now it seems many people online have been encountering this horrible error and majority of my fellow bloggers have suggested that installing the SQL Server Data Tools – December 2012 Update for VS 2010 or 2012 will resolve this issue. Unfortunately installing this alone did not help me. I found out that I missed one key part of my SQL Server installation: Service Pack 2!

Can't believe this one small oversight caused me such a headache.

You can download Microsoft SQL Server 2012 SP2 from the following link: https://www.microsoft.com/en-gb/download/details.aspx?id=43340.

Extension Method To Render Action As String

A while ago, I wrote a post that showed how you would Render a Partial View As A String. But what if you had a Partial View and wanted to output its action to a string?

Just like the majority of all other coding problems I encounter, StackOverflow always has the answer. In this case, a clever guy posted this piece of code:

var sw = new StringWriter();
PartialViewResult result = Email("Subject", "Body");

result.View = ViewEngines.Engines.FindPartialView(ControllerContext, "Email").View;

ViewContext vc = new ViewContext(ControllerContext, result.View, result.ViewData, result.TempData, sw);

result.View.Render(vc, sw);

var html = sw.GetStringBuilder().ToString();

Works well enough. However, I didn't like the thought of having to add all this code inside my controller, especially when I have to output many Partial View actions to a string. So I created an extension method:

/// <summary>
/// Renders a Partial View Action to string.
/// </summary>
/// <param name="controller">Controller to extend</param>
/// <param name="partialView">PartialView to render</param>
/// <param name="partialViewName">Name of Partial View</param>
/// <returns>Renders Partial View as a string</returns>
public static string RenderActionToString(this Controller controller, PartialViewResult partialView, string partialViewName)
    using (var sw = new StringWriter())
        partialView.View = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;

        ViewContext vc = new ViewContext(controller.ControllerContext, partialView.View, partialView.ViewData,
            partialView.TempData, sw);

        partialView.View.Render(vc, sw);

        return sw.GetStringBuilder().ToString();

This extension method can be used in the following way:

//Access PollController class.
PollController pc = new PollController();

//Get the LatestPoll PartialView action and output to string.
string myPartialView = this.RenderActionToString(pc.LatestPoll(), "../Poll/_LatestPoll");

Much cleaner!

TextMode Causes Max Length To Not Work In ASP.NET Web Forms

After quite a successful stint in creating some really amazing websites using MVC Razor 5, I had to revert back to working in the world of Web Forms for a new client project. Now I have to deal with .NET web controls, Postbacks and Viewstates.

When creating a few simple forms consisting of some drop down lists, textboxes and textareas, I noticed wherever I set a "MaxLength" property it would not work. A character limit on my input field would just be ignored in all browsers. I could only replicate this bug when the Max Length property is used alongside the "TextMode" property.

There were various places where I had the "TextMode" property set to either "Number" or "MultiLine". Soon as this was removed, the value set in "MaxLength" would work.

How very odd...

Thankfully, I am not the only person to experience the same issue. Currently, the only way to get around this problem is to add the following JavaScript code (slightly refactored for my own implementation) to check the character length "onKeyDown".

var ASPNETForm = {
    "CheckTextAreaLength": function(textBox, e, length) {
        var mLen = textBox["MaxLength"];

        if (null == mLen)
            mLen = length;

        var maxLength = parseInt(mLen);
        if (!ASPNETForm.CheckSpecialKeys(e)) {
            if (textBox.value.length > maxLength - 1) {
                if (window.event) { //IE
                    e.returnValue = false;
                    return false;
                else //Firefox
    "CheckSpecialKeys": function(e) {
        if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)
            return false;
            return true;

Add to your ASP.NET TextBox control as so:

<asp:textbox id="Instructions" MaxLength="50" onkeydown="return ASPNETForm.CheckTextAreaLength(this,event,'50');" runat="server" textmode="MultiLine">

I am hoping there will be a more elegant solution in ASP.NET 5, or even better, a fix. This problem has been lurking around since 2009!

Change Colour of Address Bar In Chrome For Android

My Nexus 5 upgraded to Android version 5.0 a few months back and it's by far the best update yet (apart from the minor bugs). An OS that is as beautiful to look at as well as use.

One of the most intriguing things I noticed was that the colour of my Chrome browser address bar would occasionally change if I went certain websites. Being a developer who works in the web industry, this peaked my interest. So I had to find out how to do this.

After doing some online research, I found adding the this feature couldn't be simpler. Just add the following META tag to your page:

<meta name="theme-color" content="#4c7a9f">

I carried out this change on my site and it looks kinda cool!

Android Chrome Browser Colour (Before)
Android Chrome Browser Colour (After)

Redirect Non-WWW to WWW Domain In Azure Websites

If you require your website URL to always be prefixed with a "www" at the start of the domain, then you will need to modify the web.config (preferably in the Web.Release.Config) with the following addition:

    <rewrite xdt:Transform="Insert">
        <rule name="Redirect to WWW site">
          <match url=".*" />
          <conditions logicalGrouping="MatchAny">
            <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" negate="true" />
          <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" redirectType="Permanent" />

In addition to the web.config file changes, ensure the Azure Website instance contains the correct domain bindings within the "Manage Domains" area. For example:

Azure Manage Custom Domains

Detecting Facebook In-App Browser

It seems there is going to be a growing trend where apps on our mobile devices will open webpages whilst you are inside the app itself instead of using the devices' native browser. A prime example of this is Facebook. In recent updates during the tail end of last year, both their iOS and Android offerings open webpages from within the application.

This isn't a bad thing. In fact I quite like having webpages opening within the application, since this creates a nice seamless experience. However, the Facebook in-app browser doesn't seem to render a webpage in the same manner as the devices' own native browser (Safari/Chrome). I started noticing this whilst working on a complex website that was very much custom JavaScript driven.

The only thing I could do is modify specific mark-up or features that affected my website negatively when opened from within Facebook by detecting the user-agent. In my code (using ASP.NET C#), I was required to carry out additional browser checks:

//User is within Facebook browser.
if (Request.UserAgent.IndexOf("FBAN") > -1)
    if (Request.UserAgent.Contains("iPhone OS 8_0_2"))
        //You are using iPhone version 8.0.2.
    if (Request.UserAgent.Contains("Chrome"))
        //You are in the Facebook App in Android.
    //You are not in Facebook App.

You can modify the code above to create a nice self-contained method to return an enumeration as I ended up doing to be used when required.

Dynamic Robots.txt file for ASP.NET MVC Sites

Changing the contents of a robots.txt file when a site is moved from staging to a live environment is quite a manual and somewhat cumbersome process. I sometimes have the fear of forgetting to replace the "Disallow: /" line with correct indexable entries required for the website.

To give me one less thing to remember during my pre-live deployments, all my current and upcoming ASP.NET MVC sites will use a dynamic robots.txt file containing different entries depending on whether a site is in stage or live. In order to do this, we need to let the ASP.NET MVC application serve up the robots.txt file. This can be done by the following:

  • Create a new controller called "SEOController"
  • Add a new FileContentResult action called "Robots".
  • Add a new route.
  • Modify web.config.


I have created a new controller that renders our "Robots" action as a plain text file. As you can see, my controller is not a type of "ActionResult" but a "FileContentResult". The great thing about "FileContentResult" is that it allows us to return bytes from the controller.

In this example, I am converting bytes from a string using Encoding.UTF8.GetBytes() method. Ideal for what we need to generate a robots.txt file.

public FileContentResult Robots()
    StringBuilder robotsEntries = new StringBuilder();
    robotsEntries.AppendLine("User-agent: *");

    //If the website is in debug mode, then set the robots.txt file to not index the site.
    if (System.Web.HttpContext.Current.IsDebuggingEnabled)
        robotsEntries.AppendLine("Disallow: /");
        robotsEntries.AppendLine("Disallow: /Error");
        robotsEntries.AppendLine("Disallow: /resources");
        robotsEntries.AppendLine("Sitemap: http://www.surinderbhomra.com/sitemap.xml");

    return File(Encoding.UTF8.GetBytes(robotsEntries.ToString()), "text/plain");


Since I add my routing at controller level, I add the "MapMvcAttributeRoutes" method to the RouteConfig.cs file. But if you prefer to add your routes directly here, then this method can be removed.

public class RouteConfig
    public static void RegisterRoutes(RouteCollection routes)

        routes.MapMvcAttributeRoutes(); //Add this line!

            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }


Add a "runAllManagedModulesForAllRequests" attribute to the modules tag in the web.config file to allow our robot.txt text file to be rendered by ASP.NET.

  <modules runallmanagedmodulesforallrequests="true"></modules>

What's Currently Wrong With Star Trek Franchise?

NOTE: I write this post as a person who just appreciates the Star Trek movie franchise. Not as a massive fan.

Star Trek has always had a special place in my heart for as long as I can remember. The moment I sat down with my Dad and watched Star Trek III: Search for Spock with fresh new eyes, I was instantly grabbed by the action, ships, characters and vastness of space. It didn't take me long to understand the basic premise of the show even if I didn't completely understand the plot points.

I've dabbled in and out of the franchise over the years. But ever since the reboot in 2009, I have gained a renewed interest and started to look back at the classic movies with much fondness and appreciation. I truly admire how clever and gripping they were. Of course, there are some bad eggs when it came to the sequels (I'm talking about you Star Trek V!), nevertheless, they always managed to have memorable scenes.

Thoughts On The New Trek

I thought the reboot was off to a great start (no matter what the naysayers say), JJ Abrams managed to give Star Trek the kick in the butt it (quite frankly!) needed and looked forward to many more adventures with the characters I have grown to love. Star Trek became exciting again!

Four years later, we were given Star Trek Into Darkness and I remember leaving the cinema quite satisfied. But after I let the film digest within my subconscious, I started to pick holes in the storyline and came to the conclusion the highly anticipated sequel didn't actually offer anything new. It felt like a remake of Star Trek II: The Wrath of Kahn pure and simple, a film that I will always hold dear to my heart. A film that contains themes of revenge, coming of age, friendship and sacrifice.

So what's wrong with the current incarnation of Star Trek?

1) Lack of Continuity Between Films

One of the finest moment of the original films for me was the continuity between films that had an underlying theme that linked them together. Of course, I am talking about movies II - IV. It was quite satisfying seeing the characters develop and grow based on the decisions made from the previous films.

You might be thinking: What am I complaining about? The current reboot hasn't had a chance to grow yet?

Valid point. However, I believe this is something the writers could have done already. Planted the seed to grow in future adventures.

2) The Length of Time Between Sequels

The main problem with the Star Trek franchise is the length of time between installments. The films need to be out more frequently. Currently, the length of time between films is 4 years. This is too long, especially if a film hasn't been as strong in the story department, nor met the expectations of fans. I think it's safe to say Into Darkness was not embraced as positively when compared to the 2009 film.

What impact does this have? A big one. The momentum just disappears and the franchise has the added pressure of having to re-establish itself again to the public.

As it stands, the cast, designs and production are all delivered to a very high standard. But if the likes of Paramount spend too long about the story they wish to tell, they really need to get better script writers and directors with a coherent vision.

Come on Paramount! Pull your finger out!

3) Bring Writers In Who Aren't Fans of The Trek-lore

Some of the best Trek have come from people who aren't avid fans of the world of Star Trek. They have the ability to take a step back in order to create a unique and interesting vision. They take important facets of the characters and then weave Star Trek into the story.

I personally would love to see Nicholas Meyer have the opportunity to write the next installment. Now that would be something to look forward to!

4) Retreading The Same Ground

For those who have watched Star Trek in film or TV form and made a comparison with the current Trek movies, you would get a sense of deja-vu. As I've briefly stated above, there doesn't seem to be anything new being brought to the screens that we haven't already seen before, which is a little disappointing for the Trek veterans.

Into Darkness could have been the film to show something new and original. Retreading old ground in a universe purely built to tell new stories was never going to go down well.

5) No More Spock Prime

I loved seeing Leonard Nimoy reprise his role as Spock Prime in the 2009 reboot. It was pure genius and managed to make a connection with all previous films so that they still remained relevant. This was probably a ploy to get buy in from the proper Star Trek fans. I for one appreciated the sentiment.

However, it was unnecessary bringing him back for a brief appearance in Into Darkness and dare I say...a little cringe worthy.

Final Thoughts

There is so much to explore in the Star Trek universe and the formula to get Star Trek right is not as complex as it may seem. The script writers need to take a good hard look at what made the original films so successful (without plagiarising!) and make us a Trek film where no one has gone before...

Tools Every Azure Developer Should Be Using

Having developed quite a few websites in Azure, there are some key tools I found that made my life easier when accessing all areas of my Azure cloud instance. The great thing about the selection of tools I have listed below is that it gives me access to all the features I need wrapped in a nice interface.

So lets get to it!

Azure Storage Explorer

Azure Storage Explorer is a useful tool for inspecting and altering the data in your Azure storage projects, including the logs of your cloud-hosted applications. This includes:

  • Blobs
  • Queues
  • Tables

Unlike some of the previous storage explorer software I've used in the past, Azure Storage Explorer allows you to preview a blob directly through its interface, such as: Images, Video or Text files. So you don't have to waste time downloading a blob just to check if its been generated correctly. Amazing time saver!

Once you have your storage set up within your Azure account, you can use this application to manage everything: create, view, copy, rename and delete all three types of storage types (listed above).

Azure Storage Explorer

An application as full featured as this shouldn't be free. But luckily for us, it is.

Download: https://azurestorageexplorer.codeplex.com/

Azure User Management Console

Azure User Management Console manages the users and logins of an Azure SQL database. The tool is simply converting your action into T-SQL commands and execute them against an Azure database of your choice.

Azure User Management Console

What some beginner Azure developers do is they use the same master credentials that is assigned to the database on creation within their web application too. Of course, this master user has full "db_owner" privileges against the database. Not a good idea! This application allows you to create a new new user with restricted access access levels really easily.

Download: https://aumc.codeplex.com/

Redgate SQL Azure Backup

One thing I found lacking in Azure SQL databases is the ease of creating a regular backup. There doesn't seem to be an automated way to do this directly through the Azure account.

I've been toying around with Redgate's Azure backup service and that seems to do the job quite nicely. But it does come at a price. For a daily backup on one database will cost around £7 per month.

Full range of backup plans: http://cloudservices.red-gate.com/


Whenever I needed to take a quick look at any of my blob containers, Azure Storage Explorer would suffice for majority of cases. However, the only thing I've started noticing with Azure Storage Explorer is that it lacks the efficiency of being able to export a batch of files from a blob to local storage with ease.

CloudXplorer by ClumsyLeaf Software made browsing files within my blob container a breeze. All files were organised and displayed in a folder structure allowing me to download specific directories. The slick UI alone makes CloudXplorer a pleasure to use, especially if you have blob that is large in volume.

I have downloaded around 200MB worth of files from one of my blobs to a local drive without any issue.