DCSIMG
Configuration Weirdness - Doron's .NET Space

Configuration Weirdness

Lately I've encountered a rather weird behavior when using .NET 2.0's configuration model.

Let's say I have the following custom configuration section:

public class TestConfigSection: ConfigurationSection { public TestConfigSection() { } public TestConfigSection(string testAttrib) { TestAttrib = testAttrib; } [ConfigurationProperty("testAttrib", IsRequired=true)] public String TestAttrib { get { return (String)this["testAttrib"]; } set { this["testAttrib"] = value; } } }

Rather straightforward: Its a config section with one required string attribute. Now, let's use it in a config file:

<configuration> <configSections> <section name="testConfigSection" type="CodeLikeHell.Configuration.TestConfigSection, CodeLikeHell, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c211d86e3b9c35ff" /> </configSections> <testConfigSection testAttrib="testValue"/> </configuration>

Nice and easy, I can get the configuration section with this code:

ConfigurationManager.GetSection("testGroup/testConfigSection") as TestConfigSection;

Now, a question: what will GetSection return for the following configuration file?

<configuration> <configSections> <section name="testConfigSection" type="CodeLikeHell.Configuration.TestConfigSection, CodeLikeHell, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c211d86e3b9c35ff" /> </configSections> </configuration>

As you can see, I didn't actually state the config section in my configuration file, only the declaration for it. You would expect that in this case, GetSection will return null, no? Well, at least I would. But it actually returns a TestConfigSection object, with an empty string as the value for testAttrib. Also, there won't be any runtime exception for the missing required attribute (note that I marked testAttrib as IsRequired=true above). The error will show up only if you explicitly state the configSection in your configuration file without the attribute, as follows:

<configuration> <configSections> .... </configSections> <testConfigSection /> </configuration>

Trying to call GetSection("testConfigSection") will now throw a ConfigurationErrorsException("Required attribute 'testAttrib' not found").

This means that you can't count on the fact that GetSection will return null if the custom config section is not stated in the configuration file, and you can't count on the fact that your "IsRequired" validation will do anything at all.

I didn't find a decent solution for this, although one approach can be to use the DefaultValue property of the ConfigurationProperyAttribute in order to see if the property was initialized or not. Whatever solution you choose, you should be aware of this issue when you test any code that uses custom configuration sections.

Published Saturday, March 10, 2007 11:08 AM by dorony
תגים:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: