91

I know that web.config in Visual Studio 2010 provides the ability to switch from databases from Debug mode to Release mode.

Here is my Web.Release.config:

<?xml version="1.0"?>

<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->

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

  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

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

</configuration>

Here is my Web.Debug.config code:

<?xml version="1.0"?>

<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->

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

  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Live1" connectionString="Data Source=Live;Initial Catalog=LiveDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

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

</configuration>

And this is my Web.config code:

<?xml version="1.0"?>

<!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 -->
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <authentication mode="Forms">
       <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>

    <membership>
       <providers>
          <clear/>
          <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
         enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
         applicationName="/" />
       </providers>
    </membership>

    <profile>
       <providers>
          <clear/>
          <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
       </providers>
    </profile>

    <roleManager enabled="false">
       <providers>
          <clear/>
          <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
    <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
       </providers>
    </roleManager>

  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

When I publish my project there is nothing showing in my Web.config file.it Is not showing my Live Database connection string?

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
RG-3
  • 6,088
  • 19
  • 69
  • 125

4 Answers4

144

The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

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

This will cause each connection string line to find the matching name and update the attributes accordingly.

Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

Here's an example from one of my apps. Here's the web.config file section:

<connectionStrings>
      <add name="EAF" connectionString="[Test Connection String]" />
</connectionString>

And here's the web.config.release section doing the proper transform:

<connectionStrings>
      <add name="EAF" connectionString="[Prod Connection String]"
           xdt:Transform="SetAttributes"
           xdt:Locator="Match(name)" />
</connectionStrings>

One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

For more details you can see the MSDN documentation

https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

Dillie-O
  • 29,277
  • 14
  • 101
  • 140
  • 22
    Can you add a note that this happens in publish time NOT F5 time to the answer? Apparently I've had this correct for 2 hours but didn't realize that. – Paul Aug 01 '14 at 18:59
  • How can I make this work with Visual Studio Online Continuous Build? I want it to transform my Web.Config during build and deploy to Azure. – Rosdi Kasim Apr 01 '15 at 05:31
  • 1
    @RosdiKasim - I'm not sure if this will match up 100% for Visual Studio online, but when I need to deploy a specific project (if I have multiple) or use a different build (and thus transform) I specify things directly in the Azure website instance. Here's some details I wrote up on that a while back: http://www.freshconsulting.com/2-alternate-configurations-for-windows-azure-deployment/ – Dillie-O Apr 01 '15 at 17:03
  • here is a link to MSDN that descirbe this in details https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx – Hakan Fıstık Sep 21 '15 at 11:13
  • Only for remember: the line `` must be only in web.debug.config and web.release.config. But not in web.config. – Davide Castronovo Jan 22 '18 at 10:16
  • 1
    Your added note regarding running the site in VS via F5 vs. publishing was very helpful to me. – Denis M. Kitchen Oct 17 '18 at 19:25
  • @Paul - For a "F5 time" (=build) solution look at Dennis's great answer. – BornToCode Jun 07 '19 at 09:14
  • @Dillie-O What about the **web.config.release section**? You do not post it here :( –  May 06 '20 at 13:03
  • @Jason - The web.config.release section actually has the transform, you just have to scroll all the way to the right to see where the XDT attributes are. I probably could have made things a little shorter to emphasize the important parts. – Dillie-O May 28 '20 at 21:55
  • @Dillie-O The shorter the more less clarifiier.So, it is better tı edit I think. –  May 28 '20 at 23:45
9

It is possible using ConfigTransform build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/

All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.

The same applies to "app.*.config" transform files in non-web projects.

and then adding the following target to your *.csproj.

<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
    <TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>

Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.

BurnsBA
  • 4,347
  • 27
  • 39
Dennis
  • 20,275
  • 4
  • 64
  • 80
  • 1
    This great method worked perfectly for me. However I did not have to install the ConfigTransform NuGet you mentioned (which has the effect of always transforming all configurations). I just copied the target snippet in your answer to the csproj. Then when I set the active build configuration on Visual Studio (e.g. change it to debug) the transform is done accordingly when I build the solution. – BornToCode May 09 '21 at 19:05
5

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

  • 1
    In order to preserve white spaces (prevents the transformed config to be on one line) add preservewhitespace indent IndentChars:" " to the command line. `$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config" preservewhitespace indent IndentChars:" "` – Emanuel Nilsson Jan 28 '16 at 03:36
4

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

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

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

Community
  • 1
  • 1
VSB
  • 9,825
  • 16
  • 72
  • 145