Tuesday 29 January 2008

Generating Custom Configuration Sections in web.config (Part 2)

My earlier post about creating custom configuration sections in web.config, referred to a custom tool that can be used to do the leg work.

If you wish to implement custom sections yourself, here’s a simple example of how. This simple example uses standard key/value attributes and data that is not strongly typed. I shall later post a more advanced example, using strongly-typed data.

First, within the element of web.config, add the following element exactly as is, replacing MySectionName with the name you want to give your section:

<configSections>
<sectionGroup name="MySectionName">
<section name="Portal"
type="System.Configuration.NameValueSectionHandler,system,
Version=1.0.3300.0,Culture=neutral,
PublicKeyToken=b77a5c561934e089,Custom=null" />
</sectionGroup>
</configSections>

This uses the built-in handler. No further development is necessary.

You can then add keys to your custom section:

<MySectionName>
<MyStuff>
<add key="fruit1" value="apples" />
<add key="fruit2" value="oranges" />
</ MyStuff >
</MySectionName>

Finally, you extract the keys as follows:


NameValueCollection settings =
ConfigurationManager.GetSection(
"MySectionName/MyStuff")
as NameValueCollection;

No comments: