Link to home
Start Free TrialLog in
Avatar of codequest
codequest

asked on

ASP.NET Modify connection string at application start page

I'm going to have several sub-domains point to an asp.net website application.  After detecting the originating sub-domain (a separate question), I need to use that sub-domain name to modify a site connectionstring to point to a different database (one database per sub-domain.)

This has to happen in the Page_Load method of a login page that uses the aspnet_Membership login control.  That is, I need to reset the connection string to point to the correct DB before the login control can operate.

I've seen a couple suggested methods for modifying connection strings however, I'm not clear on which one to use.

I tried the code below, however, the second response.write, which should show the result, shows no change.  However, maybe I'm re-reading the original unchanged value.

 Dim wrkNewConnStr As String
            wrkNewConnStr = "Data Source=localhost; Initial Catalog=test01;"
            wrkNewConnStr = wrkNewConnStr & " User ID=testuser1; Password=testuserpw1"

            Dim config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")

            'Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
            Dim connectionStringsSection = DirectCast(config.GetSection("connectionStrings"), ConnectionStringsSection)

            Response.Write("1 - " & connectionStringsSection.ConnectionStrings("TestDB1ConnectionString").ConnectionString)
            Response.Write("<br/>")

            Dim wrkOrigConnStr As String
            wrkOrigConnStr = connectionStringsSection.ConnectionStrings("TestDB1ConnectionString").ConnectionString
            wrkOrigConnStr = wrkNewConnStr
            config.Save()
            ConfigurationManager.RefreshSection("connectionStrings")

            Response.Write("2 - " & connectionStringsSection.ConnectionStrings("TestDB1ConnectionString").ConnectionString)

Open in new window


It seems like any such modification to a connection string would need to take place in memory, not on disk, since many users could be accessing the main site from several sub-domains.  However, I would appreciate pointers to something that spells that out explicitly, so I can understand it better.

So, questions:
>  How to dynamically change a connection string at the initial load of a membership login page
>  How does that only affect memory and not disk

Thanks!
Avatar of Mlanda T
Mlanda T
Flag of South Africa image

Suppose sub-domains: dom1.myapp.com and dom2.myapp.com

Create multiple named connection strings in your web.config
<connectionStrings>
<add name="dom1" connectionString="server=localhost;database=myDb1;uid=myUser1;password=myPass1;" />
<add name="dom2" connectionString="server=localhost;database=myDb2;uid=myUser2;password=myPass2;" />
</connectionStrings>

Open in new window

Store the result in a session variable
Internally, map the domain to a mapped connection string (domain name could even be name of connection string in web.config for example). You can do this in the AcquireRequestState in Global.asax. Session is available in this event and this event also fires for each request:
void Application_AcquireRequestState(object sender, EventArgs e)
{
     //Session is Available here
     HttpContext context = HttpContext.Current;
     if(context.Session["ConnectionStringName"]==null)
          context.Session["ConnectionStringName"] = HttpContext.Current.Request.Url.AbsoluteUri.Host.Split('.')[0];
}

Open in new window

Then, whenever you need to access the database, you can use:
ConfigurationManager.ConnectionStrings[Session["ConnectionStringName"]].ConnectionString

Open in new window

which reads the connection string from web.config.

A nice way to work with session is presented here: http://blog.theobjectguy.com/2009/12/session-with-style.html (then you can avoid accessing Session["var"] directly.
Avatar of codequest
codequest

ASKER

Thanks for the input.  I can see that that is a way to access the various connection strings.  

This application is exclusively and extensively using typed datasets for the database i/o layer.

The remaining part of the puzzle is how to apply the selected configuration string to the dataset(s)  at runtime.

Any suggestions on that?
ASKER CERTIFIED SOLUTION
Avatar of Mlanda T
Mlanda T
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@MlandaT:  Thanks for the input.  I modified the code in the link and got it to work.  So, that's good.
Unfortunately, there are additional complications, which I'm documenting here for my sake as well as in hope that there might be an answer.

I have a web /site/ project instead of a web /application/ project, so there is no project file and no project settings to modify.
(link says web site projects have no project files)
https://msdn.microsoft.com/en-us/library/e5x4xz73.aspx

So, I would need to modify the table adapters each time they are instantiated.  That looks to be on the order of 200 times.  Then i would have to modify all the object data sources, which is many times.  Heading for an alpha/demo release as soon as possible, that's just not in the budget.

I'm going to mark your answers as solutions, though I'd like to leave this out there for a few days and see if it draws any further comments.

It's good to get this resolved in any case.