views:

61

answers:

2

Hi,

how can i configure my Visual Studio 2010 C# solution/project so that when i select a Debug configuration - ConnectionString#1 would be used Release - Connection string #2 and "Myconfiguarion1" (which was copied from debug) -> Connection string #3

I got to it work with debug in such a way:

if (ConfigurationManager.ConnectionStrings["ConnectionString1"] != null)
{
    winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
}

#if DEBUG
if(ConfigurationManager.ConnectionStrings["ConnectionString2"] != null) 
{
    winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
}
#endif

but this doesn't work with "MybuildConfiguration"

+4  A: 

If you're trying to do this for the web.config file of an ASP.NET project in Visual Studio 2010, it's built-in via XML Transformations for web.config.

Web Deployment: Web.Config Transformations

If you're trying to do this for an app.config file, you can use the same transformations but working with them is a bit of a hack:

Visual Studio App.config XML Transformations

Both boil down to actually using separate config files for the different environments you are going to be running your app in. That allows you to supply different values for any of the keys based on what environment you're running in.

Justin Niessner
There's an active issue at connect site to support app.config just like web.config is. Vote here: https://connect.microsoft.com/VisualStudio/feedback/details/564414/support-for-transforming-app-config-files-in-the-same-way-web-config-files-can-be-transformed-per-configuration?wa=wsignin1.0
veljkoz
Thank You. Will try.
Martynas
Will this work for .net 3.5 sp1 ?
Martynas
@Martynas - Yes. As long as you're using Visual Studio 2010.
Justin Niessner
Am, tried it. Works nice. One problem though. Cannot use Enterprise library to encrypt the connection strings with RSA cause this approach requires adding text like this "xdt:Transform="Replace" xdt:Locator="Match(name)"Any idea how to fix this ?
Martynas
+1  A: 

I think you can use conditional compilation constants. To define them, you have to open project property window, select compilation tab, and define a name in the conditional constants field, e.g. CONN1.

This constants get defined only for your active build configuration, so you can define CONN1 for Debug configuration,CONN2 for Release configuration,CONN3 for your custom configuration etc.

then, in your code, you can use:

#ifdef CONN1
//use connection 1
#else
 #ifdef CONN2
  //use connection 2

 #else
  //use connection 3

 #endif
#endif
Andrea Parodi
Thanx :) That's a useful tip.
Martynas