Thursday, February 18, 2010

ASP.NET 4 Web.config Transformations

NOTE:  I am running Visual Studio 2010 Beta 2 Ultimate Edition, so any references to or images of Visual Studio 2010 are from that version.

The web.config file in ASP.NET is a good thing.  Among other things, it gives us a consolidated place to store configuration settings and connections strings, providing a single place to maintain these settings.  That way, when it's time to migrate our awesome code from development to a test/staging/production environment, we can go into the web.config and change the appropriate settings and away we go.  If you're anything like me, your web.config files have groups of settings that are commented out, allowing me to do some simple copy/paste when I'm ready to change settings for a different environment. But, what if we could just create multiple configurations, and have the appropriate ones get used, based on Visual Studio build configurations?  What if switching from Debug to Release was all it took to swap in all of the relevant appSettings, connectionStrings, or whatever else needs to be changed?  Well, ASP.NET 4 provides this in the form of web.config transformations.

By default, when you create a new Web Application project in Visual Studio 2010 (from what I can tell so far, Web Site projects do not provide this functionality, only Web Application projects), you automatically get a Web.config, and also two new items, Web.Debug.config and Web.Release.config, which correspond to the two default build configurations (Debug and Release).  By using transformations, we can provide config-specific changes that get applied to the web.config at build time.  There is an MSDN article that goes over the transforms at a high level, which can be found here.  There is a great deal of flexibility, allowing you a great deal of control over how the actual web.config file gets built.  Here, I'll provide a specific example, one that we all deal with regularly.  Let's say we have different database connection strings for Debug (development) vs. Release (production).  Below are contents from a sample web.config, web.debug.config, and web.release.config that would make this automatic.

Web.config:


Web.Debug.config:


Web.Release.config:


In my next post, I'll expand on this and show how to very easily tweak this to create configurations for development, staging, and production environments.

No comments: