19 12 2010
Our solution is simple. We will add new configuration setting to our web.config file (including cloud transform file of it) and new property to our web application. In master page where scripts are included we will include scripts from CDN conditionally. There is nothing complex, all changes we make are simple ones.
1. Adding new property to web application
Although I am using ASP.NET MVC web application these modifications work also very well with ASP.NET Forms. Open Global.asax and add new static property to your application class.
public static bool UseCdn
var valueString = ConfigurationManager.AppSettings["useCdn"];
bool.TryParse(valueString, out useCdn);
If you want less round-trips to configuration data you can keep some nullable boolean in your application class scope and load CDN setting first time it is asked.
2. Adding new configuration setting to web.config
By default my application uses local scripts. Although my application runs on cloud I can do a lot of stuff without staging environment in cloud. So by default I don’t have costs on traffic when including scripts from application folders.
<add key="UseCdn" value="false" />
You can also set UseCdn value to true and change it to false when you are not connected to network.
3. Modifying web.config cloud transform
I have special configuration for my solution that I use when deploying my web application to cloud. This configuration is called Cloud and transform for this configuration is located in web.cloud.config. To make application using CDN when deployed to cloud we need the following transform.
Now when you publish your application to cloud it uses CDN by default.
4. Including scripts in master pages
The last thing we need to change is our master page. My solution is simple. I check if I have to include scripts from CDN and if it is true then I include scripts from there. Otherwise my scripts will be included from application folder.
Although here is only one script shown you can add all your scripts that are also available in some CDN in this if-else block. You are free to include scripts from different CDN services if you need.