Managing configuration differences between environments in Visual Studio 2010/2012

 


Working in a team where every developer has to keep their own custom config file can be achieved using the Visual Studio built-in configuration transformation feature ( here is more about configuration transformation ).
By default the configuration transformation is applied during project package / publish process. To enable the transformation on the project build we can follow the steps described by Tim in his answer.
Additionally there is an extension tool SlowCheetah - XMLTransforms which can be added to the project as a Nuget package. Once it is installed the Preview Transform context menu becomes available on the transform files. It allows to preview the web.config after transformation. Really cool!

Below is the summary of how to enable web configuration transformation on the build for the Web Application Project in VS2012:

  • Create a new XML file with the following content in your project and rename it to "[YourProjectName].wpp.targets".  This file will be automatically imported into project file.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>
    <Target Name="CustomTarget" BeforeTargets="BeforeBuild">
        <Message Text="Transforming: Web.$(Configuration).config" Importance="high" />
        <TransformXml Source="Web.base.config"
                      Transform="Web.$(Configuration).config"
                      Destination="Web.config" />
    </Target>
  <!-- Exclude the config template files from the created package -->
  <Target Name="ExcludeCustomConfigTransformFiles" BeforeTargets="ExcludeFilesFromPackage">
    <ItemGroup>
      <ExcludeFromPackageFiles Include="web.base.config"/>
    </ItemGroup>
    <Message Text="ExcludeFromPackageFiles: @(ExcludeFromPackageFiles)" Importance="high"/>
  </Target>
</Project>


  • Create the web.base.config file based on the original web.config while the original web.config should be removed from the source repository (see the provided link above). This will prevent local web.config to be included into commits by source control system.
  • Create required solution Configuration for different environments using Visual Studio’s Configuration Manager. In my case Production, Staging, Developer1, Developer2.
  • Add transformation actions into each transform file created based on the solution configuration.

Now all in one place whereas different configurations can be managed without hassle both for development and publishing needs.

Comments