Friday, February 11, 2011

Applying Web.config Settings For Each Solution Configuration

Configuration management with .NET has always been a pain. Visual Studio 2010 introduced the concept of configuration transforms which, on the surface, looks like it solves many of these woes. Unfortunately, out of the box, it only applies transforms when publishing a web site. With a few quick hacks, we can getting it applying transforms after every build, before running your application. First of all, we need to rename the existing Web.config to something different, as the output of the transform needs to be to that file (at least for web applications - desktop apps can write the output to the bin/$(Configuration) folder). I use Web.Master.config. If they are not already there, create the configuration transform files by right clicking on the Web.Master.config file and selecting "Add config transforms". Next, we need to add a post build step to the project. This can be done by using post-build events, but I find it cleaner to add the step into the .csproj file directly. Right click the project in solution explorer and select "Unload project". Right click again and select "Edit .......csproj". Paste the following section into the file, immediately before the </Project> closing tag at the end of the file (sorry for the formatting... I still haven't sorted a decent method for pasting code or markup): <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" /> <Target Name="AfterBuild"> <TransformXml Source="Web.Master.config" Transform="Web.Master.$(Configuration).config" Destination="Web.config" StackTrace="false" /> </Target> Reload the project and your Web.config should now be transformed and applied after each build. I usually add the transformed Web.config file to the project by clicking "Show All Files" in solution explorer, right clicking Web.config and selecting "Include in project". Though I haven't tried it, there should be no reason this process couldn't be applied to any sort of Visual Studio project, WPF, WinForms, whatever.

Labels: ,

1 Comments:

Blogger Unknown said...

ccc

6:24 PM  

Post a Comment

Note: Only a member of this blog may post a comment.

<< Home