Web.Config Transforms Per Build
Since the introduction of .Net 4.0, Visual Studio 2012 has supported Web.Config transforms. That is you can publish a Web.Config file per solution configuration in Visual Studio. This is great if you are attempting to deploy to different environments that would require different settings such as Connection Strings or AppSettings. However, it is limited to only the Publish Feature. With this trick you can configure Visual Studio 2012 to perform the Transform with every build. This would allow you to run your local development environment against other configurations. One reason for wanting to do this might be to debug a data issue in a QA Environment.
The following will step you through setting up the build based config transform.
- Make a backup of your current Web.Config.
- Remove your current Web.Config and generated Web.Debug.Config and Web.Release.Config. These will not be needed.
- Create a Web.Transform.Config file.
- Copy the contents of your existing Web.Config to this file.
- In the project root folder create a file <ProjectName>.wpp.targets
- Open the newly created .targets folder with NotePad, or your favorite text editor.
- Enter the following into the file:
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- Make sure web.config will be there even for package/publish --> <!-- <Target Name="CopyWebTemplateConfig" BeforeTargets="Build"> <Copy SourceFiles="web.transform.config" DestinationFiles="web.config"/> </Target> --> <PropertyGroup> <PrepareForRunDependsOn> $(PrepareForRunDependsOn); UpdateWebConfigBeforeRun; </PrepareForRunDependsOn> </PropertyGroup> <!-- This target will run right before you run your app in Visual Studio --> <Target Name="UpdateWebConfigBeforeRun"> <Message Text="Configuration: $(Configuration): web.transform.$(Configuration).config"/> <TransformXml Source="web.transform.config" Transform="web.transform.$(Configuration).config" Destination="web.config" /> </Target> <!-- Exclude the config template files from the created package --> <Target Name="ExcludeCustomConfigTransformFiles" BeforeTargets="ExcludeFilesFromPackage"> <ItemGroup> <ExcludeFromPackageFiles Include="web.transform.config;web.transform.*.config"/> </ItemGroup> <Message Text="ExcludeFromPackageFiles: @(ExcludeFromPackageFiles)" Importance="high"/> </Target> </Project>
- Save the file.
- Create a Web.Transform.<ConfigurationName>.config for each of your deployment environments.
- Use the normal Web.Config Transform syntax found here.
Once you have created your config files for each configuration you are ready to test it out. Pick a Solution Configuration, and start the web application.
An optional step would be to install the VSCommands for Visual Studio 2012 and use that to group your Web.Transform.<ConfigurationName>.config files under your Web.Transform.config file.