M.R.
M.R.

Reputation: 4837

Configuration settings properties read in dynamically

I have an application where I need to have configuration settings for specific business entities (namely countries). The config will go something like this:

<country value="US">
   <metadata>
      <key name="filePath" value="c:\blah">
      <key name="wsPath" value="http://blah.com">
   </metadata>
   <sublayouts>
     <template value="division">
       <key name="path" value="c:\blah\file.txt">
     </division>
   </sublayouts>
</country>
<country value="FR">
   <metadata>
      <key name="filePath" value="c:\blah">
      <key name="wsPath" value="http://blah.com">
   </metadata>
   <sublayouts>
     <template value="division">
       <key name="path" value="c:\blah\file.txt">
     </division>
   </sublayouts>
</country>

What I want is to be able to read this into a static object for the site I am in. So, for the US site, it will load in the entire country node that has value="US". Once loaded, I want to be able to read it like:

string var = Config.metaData.filePath

OR

string var = Config.sublayouts.template["division"].path;

Is this even doable? Is there a good design pattern (not too difficult) that does this? I am fully willing to change the structure of the XML as long as it makes sense. I want to be able to add in new sections when I want. Basically, the idea is to have a flexible configuration system that is not too hard to maintain programmatically.

Upvotes: 0

Views: 1355

Answers (2)

cuongle
cuongle

Reputation: 75316

You can take advantage of Dynamic in C# 4.0 with ExpandoObject. Data can be loaded from Xml into ExpandoObject dynamically by casting ExpandoObject to IDictionary, something like:

 dynamic country = new ExpandoObject();
 var countryDic = country as IDictionary<string, object>;

 dynamic metadata = new ExpandoObject();
 var metadataDic = metadata as IDictionary<string, object>;
 metadataDic["filePath"] = "your file path";

 countryDic["metadata"] = metadata;
 var filePath = country.metadata.filePath;

More information: Introducing the ExpandoObject

Upvotes: 1

Brannon
Brannon

Reputation: 5424

What you want to do is design your data containers first. In other words, you will end up with a class for each XML node type: Country and Template. You'll get something like this:

class Country {
  IList<KeyValuePair<string, string>> MetaData {get;set;}
  IList<Template> Sublayouts {get;set;}
}

Once you've got that data you've got several options for serializing it to and from XML: DataContractSerializer, BinaryFormatter, XmlSerializer, etc.

Upvotes: 0

Related Questions