|
This was originally posted in February of 2006 on my other blog. Recent interest in the subject prompted me to repost it here.
I have been working on this one for a little while and I have to thank Brian and Dmitryr for helping me get this working. I am developing a web site where I wanted to get a list of items from a custom configuration section. Unfortunately this is a subject that seems to be a very closely guarded secret since almost no one has posted anything about it. Either that or I am the only person silly enough to try it.
What I wanted to end up with is a collection that I could manipulate and conceivably bind to. Below is an example of the XML layout. The "add" element will be repeated several times similar to the way it is in the appSetting section of the web.config file.
So how do you load this information into an application without having to get each item one at a time? The answer is a custom configuration section handler. There are several classes that are involved in creating a handler. These include:
- ConfigurationSection
- ConfigurationElement
- ConfigurationElementCollection
There are also some attributes that you will need to be aware of including ConfigurationProperty and ConfigurationCollectionAttribute.
The ConfigurationProperty attribute defines the relationship between a class property and an attribute within the XML element. So the name attribute of the add element maps to the Name property of the ListItemsElement class.
So now lets see what the code looks like. The first class you need to create is derives from ConfigurationElement. This will contain the actual data of your list. Based on the XML above the code should resemble the listing below.
Next you will need to define a collection class to hold the elements. I modified the collection that was produced by Dmitryr's SCDL application so that it has a default property so that elements can be retrieved by their index.
We almost have all the pieces we need now. The final class of the section handler is the section itself. As with the ListItemsElement class, the ConfigurationSection derived class uses the ConfigurationProperty attribute to define the element that it is meant to handle. In this case it is listItems which contains our list of add elements.
We now need to create our elements within our configuration file. The type attribute contains two parameters. The first is the fully qualified class name of your new section handler. The second is the name of the assembly.
The last task is to add code to the application to retrieve the collection.
As with any solution there are always alternative. It may have been easier to use a separate XML file or possibly a database, but then what fun would that be.
|