Monday, November 19, 2007 8:05 AM
Geoff
Configuration section fun and games
I've been pulling my hair out all weekend over a configuration issue that still doesn't make sense to me.
I've created a custom configuration file section in order to simplify the configuration of one application I work on and was following along the source code in log4net. I had setup my configuration section just so:
1: <configSections>
2: <section name="mySection" type="System.Configuration.IgnoreSectionHandler" />
3: </configSections>
This is exactly how I've been setting up my log4net since day one. The purpose of the IgnoreSectionHandler is to force the .NET configuration API to not throw an error when it encounters the mySection configuration section in the configuration file.
Then, at some point later on (I do it in the Global.asax session start event handler) you load your configuration into an XmlElement using code something like this:
1: protected void Page_Load(object sender, EventArgs e)
2: { 3: XmlElement section = ConfigurationManager.GetSection("mySection") as XmlElement; 4: if (section == null) throw new InvalidOperationException("No config section."); 5: XmlNode testNode = section.SelectSingleNode("test"); 6: if (testNode == null) throw new InvalidOperationException("No test node."); 7: XmlAttribute idAtr = testNode.Attributes.GetNamedItem("id") as XmlAttribute; 8: if (idAtr == null) throw new InvalidOperationException("No id attribute."); 9: idTextBox.Text = idAtr.Value;
10: valueTextBox.Text = testNode.InnerText;
11: }
- assuming you have a configuration section that looks something like this:
1: <mySection>
2: <test id="1">value</test>
3: </mySection>
- which I do. And what do you think would happen at this point? If you said that the configuration section would not be returned, then you'd be right.
Now the MSDN documentation clearly states that the IgnoreSectionHandler provides a legacy section-handler definition for configuration sections that are not handled by the System.Configuration types. Nowhere does it say it completely skips over the section and doesn't parse it. Based on how I configure log4net, I thought it would work. But it didn't.
In the end I carved up my very own section handler implementation:
1: public class MyConfigurationSectionHandler : IConfigurationSectionHandler
2: { 3: public object Create(object parent, object configContext, XmlNode section)
4: { 5: return section;
6: }
7: }
and changed the configuration section declaration to look like this:
1: <configSections>
2: <section name="mySection" type="WebApplication1.MyConfigurationSectionHandler" />
3: </configSections>
and now it works.
I am still extremely confused as to how on Earth log4net manages to pick up it's configuration under the exact same circumstances. I'll have to step through the code one day when I'm completely bored.