public void
ReadConfig(object o)
{
//discover
which items we need to retrieve.
//Get
all public and non-public members
MemberInfo[]
mia=o.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic);
//get
the XML document
XmlDocument
doc=new XmlDocument();
try
{
doc.Load(_configFile);
}
catch(FileNotFoundException)
{
//file
doesn't exist...
return;
//there is no config data
}
foreach(MemberInfo
mi in mia)
{
if(mi.MemberType==MemberTypes.Field)
{//check
to see if it's declared as configurable
object[]
ca=mi.GetCustomAttributes(typeof(ConfigurableAttribute),false);
if(ca.Length>0)
{//there
will be only one really...
//so
get all the configurable properties of the current object
object[]
properties=mi.GetCustomAttributes(typeof(ConfigurablePropertyAttribute),false);
foreach(ConfigurablePropertyAttribute
cpa in properties)
{
//read the value into the field
FieldInfo fi=mi as FieldInfo;
//get the instance of the private field..
(scary stuff!)
object obj=fi.GetValue(o);
//get the member info for the property of
the private field we're interrogating
MemberInfo[] pa=obj.GetType().GetMember(cpa.PropertyName,MemberTypes.Property,BindingFlags.Public
| BindingFlags.Instance);
if(pa.Length>0)
{
//make sure it's a propertyinfo
PropertyInfo po=pa[0] as
PropertyInfo;
//if it is..
if(po!=null)
{
//get the TypeConverter.
TypeConverter tc=TypeDescriptor.GetConverter(po.PropertyType);
if(tc!=null
&& tc.CanConvertFrom(typeof(string)))
{
//get the value using the xpath of
the current tree of nodes
XmlNode node=doc.SelectSingleNode(string.Format("EasyConfig/{0}/{1}/{2}",_sectionName,mi.Name,po.Name));
if(node!=null)
po.SetValue(obj,tc.ConvertFrom(node.InnerText),null);
}
}
}
}
}
}
}
//now
for the configurable properties of the owner class
object[]
props = o.GetType().GetCustomAttributes(typeof(ConfigurablePropertyAttribute),false);
if(props.Length>0)
{
foreach(ConfigurablePropertyAttribute
cpa in props)
{
//get
the property.
PropertyInfo
pi=o.GetType().GetProperty(cpa.PropertyName);
if(pi!=null)
{
TypeConverter
tc=TypeDescriptor.GetConverter(pi.PropertyType);
if(tc!=null
&& tc.CanConvertFrom(typeof(string)))
{
//Construct the XPath
XmlNode node=doc.SelectSingleNode(string.Format("EasyConfig/{0}/{1}/{2}",this._sectionName,o.GetType().Name,cpa.PropertyName));
pi.SetValue(o,tc.ConvertFrom(node.InnerText),null);
}
}
}
}
}