Creating a custom configuration section can be done in 3 easy steps. However, accessing section with a ConfigurationElementCollection can be tedious. Let me explain.
Let’s pretend you have a section that looks like this:
<namedUrlSection favoriteUrl="CodeHarder">
<namedUrls>
<add name="Twitter" url="http://twitter.com"/>
<add name="CodeHarder" url="http://codeharder.com"/>
<add name="Stackoverflow" url="http://www.stackoverflow.com"/>
</namedUrls>
</namedUrlSection>
And the accompanying code to read it:
public class UrlConfigSection : ConfigurationSection
{
public static UrlConfigSection ConfigSection = ConfigurationManager.GetSection("namedUrlSection") as UrlConfigSection;
[ConfigurationProperty("favoriteUrl")]
public string Favorite
{
get
{
return this["favoriteUrl"].ToString();
}
}
[ConfigurationProperty("namedUrls")]
public NamedUrlCollection Urls
{
get
{
return this["namedUrls"] as NamedUrlCollection;
}
}
}
If you wanted to get the name of your favorite URL, it is very simple syntax.
string favUrlName = UrlConfigSection.ConfigSection.Favorite;
But, when you want to access one of the child namedUrl elements, it just doesn’t look very nice. Not ugly, just verbose. Wouldn’t you agree?
UrlConfigSection.ConfigSection.Urls["CodeHarder"].Url
I always wished I could just flatten it out to something like .CodeHarder. I don’t know why I didn’t think of this before, but with the new DynamicObject in .net4 I can! Creating a wrapper to give me that syntax is ~10 lines of code.
public class DynamicUrlConfig:DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
NamedUrl url = UrlConfigSection.ConfigSection.Urls[binder.Name];
if (url != null)
{
result = url.Url;
return true;
}
return false;
}
}
Now, when I want to get anything from the namedUrls section, I can use the syntax I always wanted.
dynamic urlSection = new DynamicUrlConfig();
string favUrl = urlSection.CodeHarder;
I know this isn’t new, and a quick google would probably give me several people who have done it before, but I was quite pleased and thought I would share.
short link to this post:
.net, Fun with .net
programming, dynamic, configuration, .net4