Saturday, February 25, 2012

Conditional compile the connection string in datasets

I need to find a way to useconditional compilation option to change the connection string in ado.net datasets 2.0.

Debug > connection 1 : test server
Release > connection 2 : real server

How is it possible ?This is often accomplished by storing the connection string in the web.config file, and using different web.config files on your test and real servers.|||

This is what I do in global.asax.vb:

Sub Application_Start(ByVal senderAsObject,ByVal eAs EventArgs)' Fires when the application is startedIf System.Environment.MachineName ="{Your production machine name here}"Then

Application(

"IsProduction") =TrueElse

Application(

"IsProduction") =FalseEndIfDim configAs Configuration

config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(

"~")Dim cssAs ConnectionStringsSection

css = config.ConnectionStrings

Dim settingAs ConnectionStringSettingsDim fUpdateAsBoolean =FalseDim cAsNew ConnectionStringSettingsCollectionForEach settingIn css.ConnectionStrings

c.Add(setting)

NextForEach settingIn cIf (Left(setting.Name, 5).ToUpper ="TEST-"AndNot Application("IsProduction"))Or _

(Left(setting.Name, 5).ToUpper =

"PROD-"And Application("IsProduction"))ThenIf css.ConnectionStrings(setting.Name.Substring(5))IsNothingThen

css.ConnectionStrings.Add(

New ConnectionStringSettings(setting.Name.Substring(5), setting.ConnectionString, setting.ProviderName))

fUpdate =

TrueElseIf css.ConnectionStrings(setting.Name.Substring(5)).ConnectionString <> setting.ConnectionStringThen

css.ConnectionStrings(setting.Name.Substring(5)).ConnectionString = setting.ConnectionString

fUpdate =

TrueEndIfEndIfEndIfNext' Make sure debug is turned off when running on the production serverDim xAs System.Web.Configuration.CompilationSection = config.GetSection("system.web/compilation")If x.DebugAnd Application("IsProduction")Then

x.Debug =

False

fUpdate =

TrueEndIfIf fUpdateThen

config.Save()

EndIfEndSub

Then I'll create connection strings like "TEST-MyConnection" and "PROD-MyConnection", etc. In code (or from data controls), I'll reference them as "MyConnection". When the application starts up, it'll update the web.config with the correct connection string to use on the machine it's running (and possibly restarting the application).

|||thanks a lot

No comments:

Post a Comment