How do I use Web.Config transform on my connection strings?

Mike Bailey picture Mike Bailey · Dec 3, 2011 · Viewed 39.3k times · Source

In my current project, I have some connection strings that are valid for local development machines:

<configuration>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="Data Source=localhost;Initial Catalog=MyDB;Integrated Security=SSPI"
  </connectionStrings>
....
</configuration>

How would I use the Web.Config transforms to convert from this expression to one valid for our production server? The production server one would look something like:

<configuration>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="Data Source=IPAddress,Port;Initial Catalog=SomeOtherDB;User ID=TopSecretUsername;Password=SecurePassword"
  </connectionStrings>
....
</configuration>

The syntax isn't obvious to me, and I'm completely failing at grokking the page on it.

Answer

sbeskur picture sbeskur · Dec 3, 2011

This works for me but I too have found it to be a bit flakey at times. You will need to create another file called Web.Config.Release and fill it with the following:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

  <connectionStrings>
    <add name="local" connectionString="Data Source=IPAddress,Port;Initial Catalog=SomeOtherDB;User ID=TopSecretUsername;Password=SecurePassword" 
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
  </connectionStrings>

  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />

  </system.web>
    <appSettings>
        <add key="default_db_connection" value="local" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
    </appSettings>
</configuration>