Web Config Transformation in .NET

In this article I am going to explain a new feature of .NET 4.0. It is Web.Config Transformtion. Just imagine that you have multiple environments that you deploy your application to. So you must keep separate config files for each environment.

Let's see how we can do that using web config transformation.

Step 1: We will take a new web application project and we will see that we have two default web.config files in the Root itself.

First.png

Now just assume that we have a total of four environments:

  • Debug
  • DEV
  • STAGING
  • PRODUCTION

Now we will add a separate web.config file for each environment.

Step 2: Now we will open the Configuration Manager in the Build Menu:

four.png

Step 3: In the Configuration Manager:

Second.png

We will add a new configuration file:

three.png

We will do it for each environment and for each file we will right-click on web.config file and Add Config Transforms.

five.png

Now we have added four web.config files.

Step 4Now we open the web.Release.config file and we will make the same changes. We will only change the Connectionstring:

    <connectionStrings>
      <add name="MyDB"
        connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>

Step 5: Now we will pubish our application.

Six.png

And we will open the publish folder web.config file:

<configuration>
  <connectionStrings>
    <add name="MyDB"
      connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <configuration>
  </configuration>
    <system.web>
        <compilation targetFramework="4.0" />
    </system.web>
</configuration>

See, in the above web.config file now our Connection String is pointing to the Release Database.

There are many things we can do using:

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

Referencehttp://msdn.microsoft.com/en-us/library/dd465326.aspx

Happy Coding.. 


Similar Articles