C# 配置文件 自定義結點

  1.  對於配置自定義結點,需要繼承ConfigurationSection類。

  UrlsSection : ConfigurationSection

  2.  配置文件中,需要如下引用:    

View Code
  <configSections>
          <section name="orders" type="WebApplication4.UrlsSection, WebApplication4"/>
          <section name="MyUrls" type="WebApplication4.UrlsCollectionSection,WebApplication4"/>
    </configSections>
  <MyUrls>
    <urls>
      <remove name="Contoso" />
      <add name="Contoso" url="http://www.contoso.com" port="0" />
    </urls>
  </MyUrls>
      <orders companyID="2001">
        <myChildSection
         myChildAttrib1="Zippy"
         myChildAttrib2="Michael Zawondy "/>
        <order number="100001" amount="222.22">
          <lineItems warehouseNumber="02">
            <lineItem number="00-000-001" description="wii"/>
    
        </lineItems>
       
      </order>
          <order number="300001" amount="33.33">
              <lineItems warehouseNumber="99">
                  <lineItem number="00-000-001" description="xbox 360"/>
                  <lineItem number="00-000-003" description="playstation 3"/>
          
        </lineItems>
        
      </order>
      
    </orders>

    上面的配置文件,定義了2個結點,一個是UrlsSection,另一是UrlsCollectionSection。

      <configSections>
          <section name="orders" type="WebApplication4.UrlsSection, WebApplication4"/>
          <section name="MyUrls" type="WebApplication4.UrlsCollectionSection,WebApplication4"/>
    </configSections>

 3.  在定義好ConfigurationSection中,可以定義屬性,屬性包括:簡單屬性 複雜屬性 集合屬性 如下:

View Code
public class UrlsSection : ConfigurationSection
    {
        [ConfigurationProperty("companyID", IsRequired = true)]
        public string CompanyID
        {
            get
            {
                return (string)base["companyID"];
            }
            set
            {
                base["companyID"] = value;
            }

        }
    
        [ConfigurationProperty("", IsDefaultCollection = true)]
        public OrderElementCollection Orders
        {
            get
            {
                return (OrderElementCollection)base[""];
            }
        }



        [ConfigurationProperty("myChildSection")]
        public MyChildConfigElement MyChildSection
        {
            get
            { return (MyChildConfigElement)this["myChildSection"]; }
            set
            { this["myChildSection"] = value; }

        }
    }

  簡單屬性,就是c#提供的一些默認類型,int string 等。

  複雜屬性,其實就是定義一個類,其中集合屬性頁可以認為是其中的一種。

   上面CompanyID就是簡單類型,是string。對應所有屬性,需要指定 [ConfigurationProperty("companyID", IsRequired = true)]屬性

在ConfigurationProperty屬性中,可以指定配置文件中的名稱等,如果是集合類型需要這樣定義這個屬性

[ConfigurationProperty("", IsDefaultCollection = true)]

 4. 對應複雜類型,如果不是集合類型,需要繼承ConfigurationElement

View Code
public class MyChildConfigElement : ConfigurationElement
    {
        public MyChildConfigElement()
        {
        }

        public MyChildConfigElement(String a1, String a2)
        {
            MyChildAttribute1 = a1;
            MyChildAttribute2 = a2;
        }

        [ConfigurationProperty("myChildAttrib1", DefaultValue = "Zippy", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
        public String MyChildAttribute1
        {
            get
            { return (String)this["myChildAttrib1"]; }
            set
            { this["myChildAttrib1"] = value; }
        }

        [ConfigurationProperty("myChildAttrib2", DefaultValue = "Michael Zawondy", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
        public String MyChildAttribute2
        {
            get
            { return (String)this["myChildAttrib2"]; }
            set
            { this["myChildAttrib2"] = value; }
        }

    }

   上面的代碼中,有2個構造函數,構造函數的作用,是為了在配置文件中,能直接設置屬性,下面是2個參數的構造函數。

      <myChildSection
         myChildAttrib1="Zippy"
         myChildAttrib2="Michael Zawondy "/>

 5. 如果是集合類型,需要繼承ConfigurationElementCollection,對應集合類型,由於ConfigurationElementCollectionType類型不同,有不同的實現。

   5.1 ConfigurationElementCollectionType.AddRemoveClearMap

        這種方式,配置文件中,需要這樣寫:

    <urls>
      <remove name="Contoso" />
      <add name="Contoso" url="http://www.contoso.com" port="0" />
    </urls>

實現代碼如下:

   

View Code
public class UrlsCollection : ConfigurationElementCollection
{
    public UrlsCollection()
    {
        UrlConfigElement url = (UrlConfigElement)CreateNewElement();
        Add(url);
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get
        {
            return ConfigurationElementCollectionType.AddRemoveClearMap;
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new UrlConfigElement();
    }

    protected override Object GetElementKey(ConfigurationElement element)
    {
        return ((UrlConfigElement)element).Name;
    }

    public UrlConfigElement this[int index]
    {
        get
        {
            return (UrlConfigElement)BaseGet(index);
        }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    new public UrlConfigElement this[string Name]
    {
        get
        {
            return (UrlConfigElement)BaseGet(Name);
        }
    }

    public int IndexOf(UrlConfigElement url)
    {
        return BaseIndexOf(url);
    }

    public void Add(UrlConfigElement url)
    {
        BaseAdd(url);
    }
    protected override void BaseAdd(ConfigurationElement element)
    {
        BaseAdd(element, false);
    }

    public void Remove(UrlConfigElement url)
    {
        if (BaseIndexOf(url) >= 0)
            BaseRemove(url.Name);
    }

    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);
    }

    public void Remove(string name)
    {
        BaseRemove(name);
    }

    public void Clear()
    {
        BaseClear();
    }
}

同時 在ConfigurationSection 中的定義也不一樣,如下:

     [ConfigurationProperty("urls", IsDefaultCollection = false)]
        [ConfigurationCollection(typeof(UrlsCollection),
            AddItemName = "add",
            ClearItemsName = "clear",
            RemoveItemName = "remove")]
        public UrlsCollection Urls
        {
            get
            {
                UrlsCollection urlsCollection =
                    (UrlsCollection)base["urls"];
                return urlsCollection;
            }
        }

    5.2 ConfigurationElementCollectionType.BasicMap

     配置文件如下寫:

        <order number="100001" amount="222.22">
          <lineItems warehouseNumber="02">
            <lineItem number="00-000-001" description="wii"/>
    
        </lineItems>
       
      </order>
          <order number="300001" amount="33.33">
              <lineItems warehouseNumber="99">
                  <lineItem number="00-000-001" description="xbox 360"/>
                  <lineItem number="00-000-003" description="playstation 3"/>
          
        </lineItems>
        
      </order>

實現類如下:

View Code
public class OrderElementCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new OrderElement();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((OrderElement)element).Number;
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }
        protected override string ElementName
        {
            get
            {
                return "order";
            }
        }

        public OrderElement this[int index]
        {
            get
            {
                return (OrderElement)BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }
    }

在ConfigurationSection中定義的屬性,與一般的屬性是一樣的,如下:

        [ConfigurationProperty("", IsDefaultCollection = true)]
        public OrderElementCollection Orders
        {
            get
            {
                return (OrderElementCollection)base[""];
            }
        }

 

 

 

 

 

 

posted @ 2012-04-29 10:32  無限遐想  阅读(2096)  评论(1编辑  收藏  举报