Web.config transformations have been around for a while now, and a lot of developers use them in their staple day-to-day environment deployment strategies – hell, Scott Hanselman was spouting about them way back in the beginning on 2010 with his “Web Deployment Made Awesome: If you’re using XCOPY, you’re doing it wrong” post. As usual though, one size does not fit all – and in the case of Continuous Integration fans out there that may have specific build-configuration-based build and deployment scenarios (such as myself), there is the need to have finer grained control over the Web.config transformation process. If this sounds like you, then this post is aimed to deliver.
What a second… what the hell are “Web.config Transforms”?
ASP.net has had a few features that that been around for what seems like forever when it comes to abstracting away or alternating between different configuration data for your website (i’m talking about configSource functionality mostly). The features were very minimal and usually created a less-than-ideal solution for developers working on big websites in multiple environments. With the advent of Visual Studio 2010 Microsoft kindly helped us all out by taking note that “hey maybe not all websites are being built for a single server with a single configuration”… Smart guys. They created web.config transformations to help deal with this problem and Jokes aside, the feature is actually pretty cool and allows you to write a base web.config file as you normally would and then transform it for each of your environments.
Your base web.config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="ExampleApplicationSetting" value="Value being replaced by Transform"/>
</appSettings>
<connectionStrings>
<add name="MyConnectionString" connectionString="..." providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true">
</compilation>
</system.web>
</configuration>
Your web.config transform (note the change to my connection string, my custom errors and my compilation mode):
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="ExampleApplicationSetting"
xdt:Transform="SetAttributes(value)"
xdt:Locator="Condition(@key='ExampleApplicationSetting')"
value="The new value to replace after transform"/>
</appSettings>
<connectionStrings>
<add name="MySolutionDatabase" xdt:Transform="Replace" xdt:Locator="Condition(@name='MySolutionDatabase')"
connectionString="... My New Connection String ..." providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<customErrors xdt:Transform="Replace" mode="RemoteOnly" />
<compilation xdt:Transform="SetAttributes(debug)" debug="false" />
</system.web>
</configuration>
Read more: DZone
QR: