Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with using ConfigurationSection to properly read from a config file

I'm trying to create classes to read from my config file using ConfigurationSection and ConfigurationElementCollection but am having a hard time.

As an example of the config:


<PaymentMethodSettings>
  <PaymentMethods>
    <PaymentMethod name="blah blah" code="1"/>
    <PaymentMethod name="blah blah" code="42"/>
    <PaymentMethod name="blah blah" code="43"/>
    <Paymentmethod name="Base blah">
      <SubPaymentMethod name="blah blah" code="18"/>
      <SubPaymentMethod name="blah blah" code="28"/>
      <SubPaymentMethod name="blah blah" code="38"/>
    </Paymentmethod>
  </PaymentMethods>
</PaymentMethodSettings>
like image 317
Little Larry Sellers Avatar asked Mar 02 '23 05:03

Little Larry Sellers


2 Answers

The magic here is to use ConfigurationSection classes.

These classes just need to contain properties that match 1:1 with your configuration schema. You use attributes to let .NET know which properties match which elements.

So, you could create PaymentMethod and have it inherit from ConfigurationSection

And you would create SubPaymentMethod and have it inherit from ConfigurationElement.

PaymentMethod would have a ConfigurationElementCollection of SubPaymentMethods in it as a property, that is how you wire up the complex types together.

You don't need to write your own XML parsing code.

public class PaymentSection : ConfigurationSection
{
   // Simple One
   [ConfigurationProperty("name")]]
   public String name
   {
      get { return this["name"]; }
      set { this["name"] = value; }
   }

}

etc...

See here for how to create the ConfigurationElementCollections so you can have nested types:

http://blogs.neudesic.com/blogs/jason_jung/archive/2006/08/08/208.aspx

like image 78
FlySwat Avatar answered Apr 28 '23 01:04

FlySwat


This should help you figure out how to create configuration sections correctly, and then read from them.

like image 29
DOK Avatar answered Apr 28 '23 01:04

DOK