Here is another update to the XmlSerializerSectionHandler that Craig
Andera introduced. The code below is essentially the same:
public
class XmlSerializerSectionHandler : IConfigurationSectionHandler
{
public
object Create(object p_oParent, object p_oConfigContext, System.Xml.XmlNode
p_oSection) {
XPathNavigator oNav =
p_oSection.CreateNavigator ();
string sTypeName =
oNav.Evaluate(“string(@type)”).ToString();
Type oType =
Type.GetType(sTypeName);
XmlSerializer oSer = new XmlSerializer(oType);
XmlNodeReader oReader = new XmlNodeReader(p_oSection);
object oRetValue =
oSer.Deserialize(oReader);
oReader.Close();
return oRetValue;
}
}
I wanted to demonstrate how powerful this really is. Not only can we now use
this to strongly-type our configuration keys as elements, but we can configure
arrays as well. Here is my config section:
<configSections>
<section name=”MyConfig” type =”Dell.Titans.Framework.Configuration.XmlSerializerSectionHandler,
Dell.Titans.Framework”/>
</configSections>
<MyConfig type=”ConsoleTestHarness.MyConfig,ConsoleTestHarness”>
<List>
<int>1</int>
<int>2</int>
<int>4</int>
</List>
<Foo>1.234</Foo>
<Bar>A bunch of
information</Bar>
<ConnectionString>my string</ConnectionString>
</MyConfig>
Now the section name must be the same as the type name, but see how we can
configure an array of int object as the “List” property. Here is my type:
public
class MyConfig {
private
float foo;
private
string bar;
private
string connectionString;
public
float Foo {
get { return foo ; }
set { foo = value ; }
}
public
string Bar {
get { return bar; }
set { bar = value; }
}
public
string ConnectionString {
get { return connectionString; }
set { connectionString = value; }
}
public
int[] List = new int[]{1, 2, 4};
}
Note how I have added one more property as well as the List array. Another
thought is: What if I add a method to the getter of ConnectionString to
unencrypt the value before returning it? Then I could encrypt sensitive keys
without much effort.
The <appSettings> configuration section offers basic functionality, but
the configuration architecture is so flexible that we are able to customize
configuration to our exact needs. Happy programming.