Pages

Monday, February 23, 2009

Connection Strings, Web.Config, and the Development Environment

Ok, admittedly it's not as enticing as Sex, Lies, and Video Tape, but this is an awesome way of helping you with ASP.NET website development.

The Problem

You create a site on your local machine(s) and get it working perfectly. Now it comes time to publish your changes to the live website, and you run into a giant problem whenever there are any changes to your web.config file. All your connectionstrings (Data Source=localhost\SQLEXPRESS;Initial Catalog=myDB;Integrated Security=True) and configurations get promoted to the live site, where they fail until they are hand-edited to reflect the web site's configuration. Alternately, you can forbid the publishing of web.config, forcing all changes to this one file to be done by hand.

Following is a procedure showing how to remove the appSettings and connectionStrings sections into a separate file, enabling the publishing of web.config whenever without hand-editing.

  1. with your project open, add a new item (control-shift-A).
  2. choose Web Configuration File and name it appsettings.config Ignore the text that Visual Web Developer automatically puts in there.
  3. create another one named connectionstrings.config.
  4. wipe the text from these 2 new files.
  5. copy the appSettings section from your web.config appSettings section into the appsettings.config file. It should look like this:
    <appSettings>
    <add key="connectionstring" value="Data Source=localhost\SQLEXPRESS;Initial Catalog=myDB;Integrated Security=True"/>
    </appSettings>
  6. now do the same for connectionstrings:
    <connectionStrings >
    <add name="ConnectionString" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=myDB;Integrated Security=True"   providerName="System.Data.SqlClient"/>
    </connectionStrings>
  7. Now replace these sections only in your web.config file as follows:
    
    <appSettings configSource="appsettings.config"> </appSettings>
    <connectionStrings configSource="connectionstrings.config"> </connectionStrings>
  8. Note: if anyone knows how to tell the Copy Web Site dialog to NEVER publish these files, I am all ears.

Now you can hand-edit the web server's copy of appSettings.config and connectionstrings.config to give them the correct environment for the webserver. If you can't edit these remotely, then you can edit them on the development server, publish them and then change them back for your development environment.

No comments:

Share This!

Contact Us

Name

Email *

Message *