Tuesday, June 12, 2012

Web Config Transformation - TransformXml

In certain circumstances, we would need all the configs to be transformed when we publish or build it in release/build mode while default behavior of  visual studio is to transform  the build specific web.config. I needed the same for one of my projects and here is how it was accomplished.

The actual transform logic is all in the TransformXml MSBuild task from Microsoft.Web.Publishing.Tasks.dll. So we can utilise the same functionality for generating any config file with a simple MSBuild script. Microsoft.Web.Publishing.Tasks.dll is part of VS 2010 and the default install location is C:\Program Files\MSBuild\Microsoft\VisualStudio \v10.0\Web

Here are the steps to get all the config transformed at one-shot irrespective of the build configuration that is selected in visual studio.
  1. Unload the project or open up the *.csproj (C#) in any text editor. 

  2. Edit the project in visual studio/ any text editor

  3. Add the below Target inside the "Project" node. This would transform the web.Debug.config to WebDebugTransformed.config irrespective of the build configuration.
    <Target Name="BeforeBuild">
    <TransformXml Source="$(SolutionDir)Widget\Web.config"
         Transform="$(SolutionDir)Widget\Web.Debug.config"
         Destination="$(SolutionDir)Widget\WebDebugTransformed.config"
         StackTrace="true" />  
    </Target>
    
    The "BeforeBuild" and "AfterBuild" targets will be already defined in comments at the end of most project files. Multiple TransformXml tags can be added to get all the required config files. 

    Here are the targets in Microsoft.Common.targets that you can safely override.
    BeforeCompile, AfterCompile, BeforeBuild, AfterBuild, BeforeRebuild, AfterRebuild, BeforeClean, AfterClean, BeforePublish, AfterPublish, BeforeResolveReference,AfterResolveReferences, BeforeResGen, AfterResGen

  4. Now, Reload and build the project. The transformed config file would be in the specified destination directory.

Happy Coding!!!

No comments:

Post a Comment