TIP: Modifying Connection String dynamically for a strongly typed dataset in a different assembly

Imagine, I am working on a Visual Studio 2005/2008 solution with class library project (DAL) and Web Application Project (ASP.NET).  Say, the DAL is being developed using Dataset Designer with different Strongly Typed DataSets/DataTables together with TableAdapters.  Then I would certainly run into a problem.
 
The DAL (by default) maintains its own connection string in application configuration settings (app.config) and the ASP.NET application maintains its own connection string in Web.config file.  Any project, by principle, should not contain connection strings at more than one location.
 
To make DAL pickup Connection String automatically from web.config by itself (without writing any code) during run-time,  simply make sure that the names of connection strings (not the values) are identical in both app.config and web.config.
 
To make DAL pickup Connection String dynamically from web.config during run-time (at least).  It can be easily accomplished by adding the following code to the "MySettings" class in "Setting.Designer.vb" file.
 
Private Sub MySettings_SettingsLoaded(ByVal sender As Object, ByVal e As System.Configuration.SettingsLoadedEventArgs) Handles Me.SettingsLoaded
            Dim s As MySettings = TryCast(sender, MySettings)
            s.Item("SampleConnectionString") = System.Configuration.ConfigurationManager.ConnectionStrings("cnDev").ConnectionString
        End Sub
 
To make the above work, you may also need to refer to "System.Configuration" in your class library project.
 
 
Hope the above solves the problem…
 
thanks
Jag
 

About Jag

.NET Architect
This entry was posted in ASP.NET and tagged , . Bookmark the permalink.