ASP.NET and Web.config in DA House

It is this time again when I have to switch platform I work at. This time I jumped into .NET world. It is not an unfamiliar ground, I was doing some work with .NET before and I like it (not all of it though).

dotnetOne of the interesting things we came across this week was a config file for web   application, so called Web.config. So we desired to switch some settings based on environment where application was deployed. Simplest thing we could think of was referring in a config section to external file with settings. Something like this:

<web.model configSource=”file.with.config” />

Deployment with NAnt was just deploying proper file to server and all was automated.

Everything was beautiful until appSettings. It is impossible in Web.config to specify multiple sources for appSettings. It is the section of config file where you can create your own configuration properties and set its values. Later in application you can use it. It looks like this:

<appSettings>

<add key=”my_cool_property” value=”extra_awesome_value” />

</appSettings>

So, it is possible to point appSettings section into a file but it can be only one file. So if you would like different parts of your application be configured in different config files, forget it.

So, we have ended up with custom section in Web.config. It is absolutely possible to do it, only thing is that when configuration manager is reading config file it needs to know how to read this settings. To achieve the same result as appSettings we need simple Key – Value collection read from configuration.

First we need to define a custom section in our web config.

<configSections>

<section name=”myAwasomeSection” type=”System.Configuration.NameValueSectionHandler” />

</configSections>

And then in our section something we can configure whatever we want.

<myAwesomeSection>

<add key=”some_key” value=”some_value_blabla” />

</myAwesomeSection>

 

We can ask in application for configuration properties by asking ConfigurationManager, something like this:

ConfigurationManager.GetSection(“myAwesomeSection”)

This guy will return an object of System.Collections.Specialized.NameValueCollection

From this point we are home. We can get all configuration properties we need 🙂 I hope this will help someone. At least I have some reference to go back to.

Good source of information on custom sections is this article http://www.codeproject.com/KB/aspnet/ConfigSections.aspx

Cheers, Gregster

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s