Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to generate web.config in every compilation for every build configuration

Posted on: 2014-02-04

This article explains how to generate web.config or app.config to every build configurations when compiling. This can be useful if you want to apply transformation for every built without having to compile multiple time. Normally, you have to specify what is the target build to apply the configuration to the web.config. The problem is it requires to compile multiple times for the same code. If you are working in a DEV then TEST then PROD, you have to compile 3 times which could insert bug if code change or is not compiled in the same environment.

This is why, it is better to have all configuration files generated when everything is compiled before any testing. The challenge is that the transformation file is a good system. It allows to not have to copy paste the whole configuration files to change only few settings. To be able to use the transformation within a single compilation, we have to modify the web project file in notepad.

This is the xml code that needs to be pasted into the .csproj at the end of the file within the project xml element.

 <Target Name="BeforeBuild"> <!-- Variable that contains the path of where the configuration file will be located --> <ItemGroup> <TransformedWebConfigsDir Include="$(OutDir)..\\_TransformedWebConfigs" /> </ItemGroup> <!-- MSBuild transform the web.config into the destination folder--> <!-- Remove the temporary folder where transformation are located. This is used only after this process as run once --> <RemoveDir Directories="@(TransformedWebConfigsDir)" /> <!-- Create the transformation directory only if not existing. --> <MakeDir Directories="@(TransformedWebConfigsDir)" Condition="!Exists('@(TransformedWebConfigsDir)')" /> <!-- Transform for debug --> <TransformXml Source="Web.config" Transform="Web.Debug.config" Destination="@(TransformedWebConfigsDir)\\Web.Debug.config" StackTrace="true" /> <!-- Transform for release --> <TransformXml Source="Web.config" Transform="Web.Release.Dev.config" Destination="@(TransformedWebConfigsDir)\\Web.Release.Dev.config" StackTrace="true" /> </Target> <Target Name="BeforeClean"> <RemoveDir Directories="@(TransformedWebConfigsDir)" /> </Target> 

The XML creates a target before build that specify an output directory which in my case is named TransformedWebConfigs in the project directory. It cleans everything then it create the directory and apply the transformation for Debug and Release Dev. If you have a Test and Production than you have to have additional lines that specify the Transformation name (build name in Visual Studio) and the destination of the file. As you can see, the XML has a ItemGroup that let you reuse the path everywhere in your MsBuild command.