When you are developing or maintaining a website, it is normal to keep separate databases, app settings, etc. to prevent corruption of live data.
The problem is, you really don't want to maintain separate versions of any files, and that includes "
web.config".
The trouble is,
web.config contains so much important stuff, that it is a real pain to maintain separate versions for development and production - it just leaves too much scope for mistakes, which can get expensive.
Fear not! You can easily maintain a single "
web.config", but keep development settings and configuration strings out of this file, but available when you need them.
How? By maintaining four files instead. No, no, keep on reading, it's not as mad as it sounds.
Web.config has two sections we are interested in:
1)
AppSettings
2)
ConnectionSettings
Let's put these in two separate files:
WebAppSettings.config and
WebConnectionSettings.config.
More files to maintain! No, not really. With
AppSettings
, we can provide default values in
Web.Config which are overridden if and only if
WebAppSettings.config is present. So, the defaults are for production, the development ones go in
WebAppSettings.config which is kept back from source control and never exported to the production environment. Result? Oh yes! How do we do it?
Change your
web.config so that the
appSettings
section contains a reference to the new file:
<appSettings file="WebAppSettings.config">
...
</appSettings>
You can keep all your normal app settings for production:
<appSettings file="WebAppSettings.config">
<add key="Development" value="False"/>
<add key="SMTPServer" value="smtp.mycompany.com"/>
</appSettings>
Your
WebAppSettings.config file contains only the settings for development:
<appSettings>
<add key="Development" value="True"/>
<add key="SMTPServer" value="smtp.mydevelopmentserver.net"/>
</appSettings>
Done! If the file is there, it works with development settings. If not, it works with production.
We can do a similar thing with connection strings, but unfortunately without the defaults - the
connectionStrings
section must be empty if you use an external file. Still, it is simpler to maintain a production and a development
WebConnectionSettings.config file that only ever change when the server changes than to maintain two separate but parallel
web.config files which may change quite frequently.
Use the "
configSource
" attribute of the "
connectionStrings
" tag in your
web.config (remember the section must now be empty):
<connectionStrings configSource="WebConnectionSettings.config">
</connectionStrings>
The "
WebConnectionSettings.config" file contains only the connections strings section:
<connectionStrings>
<clear/>
<add name="MySqlServer"
connectionString="Data Source=(local);Initial Catalog=MyProductionDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Keep a second version for development only, and you are good to go.