- 自定義配置節點中相關類的介紹 (返回)
- 自定義配置單節點 (返回)
- 向項目中添加System.Configuration引用。ConfigurationSection、ConfigurationElement、ConfigurationElementCollection這幾個類都是在System.Configuration中定義的,而該dll默認並不是新建一個項目就有的,需要添加該dll引用。
- 假如我們要配置的節點格式如下:
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <configSections>
- <section name="SingleSectionHandler" type="CustomSingleSection.SingleSectionHandler, CustomSingleSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
- </configSections>
- <SingleSectionHandler myAttrib1="lastBeachhead">
- <MySingleSection MyAttribute1="softwarezxj" MyAttribute2="epms"/>
- </SingleSectionHandler>
- </configuration>
具體的實現代碼如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Configuration;
- namespace CustomSingleSection
- {
- public class SingleSectionHandler : ConfigurationSection
- {
- public SingleSectionHandler()
- {
- }
- public SingleSectionHandler(String attribVal)
- {
- MyAttrib1 = attribVal;
- }
- [ConfigurationProperty("myAttrib1", DefaultValue = "默認值", IsRequired = true)]
- [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'/"|//", MinLength = 1, MaxLength = 60)]
- public String MyAttrib1
- {
- get { return (String)this["myAttrib1"]; }
- set { this["myAttrib1"] = value; }
- }
- [ConfigurationProperty("MySingleSection")]
- public MySingleSection MySingleSection
- {
- get
- {
- return (MySingleSection)this["MySingleSection"];
- }
- set
- {
- this["MySingleSection"] = value;
- }
- }
- }
- public class MySingleSection : ConfigurationElement
- {
- public MySingleSection()
- {
- }
- public MySingleSection(String a1, String a2)
- {
- MyAttribute1 = a1;
- MyAttribute2 = a2;
- }
- [ConfigurationProperty("MyAttribute1", DefaultValue = "默認屬性1", IsRequired = true)]
- [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'/"|//", MinLength = 1, MaxLength = 60)]
- public String MyAttribute1
- {
- get{ return (String)this["MyAttribute1"]; }
- set{ this["MyAttribute1"] = value; }
- }
- [ConfigurationProperty("MyAttribute2", DefaultValue = "默認屬性2", IsRequired = true)]
- [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'/"|//", MinLength = 1, MaxLength = 60)]
- public String MyAttribute2
- {
- get{ return (String)this["MyAttribute2"]; }
- set{ this["MyAttribute2"] = value; }
- }
- }
- }
使用該配置的代碼如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Configuration;
- namespace CustomSingleSection
- {
- class Program
- {
- static void Main(string[] args)
- {
- LookCustomSingleSection();
- Console.ReadLine();
- }
- private static void LookCustomSingleSection()
- {
- SingleSectionHandler mySingleSection = ConfigurationManager.GetSection("SingleSectionHandler") as SingleSectionHandler;
- StringBuilder sb = new StringBuilder();
- sb.Append("該自定義配置節的屬性MyAttrib1的值是:");
- sb.Append(mySingleSection.MyAttrib1.ToString());
- sb.Append("/n");
- sb.Append("該自定義配置節的MySingleConfigElement節點的MyAttribute1屬性的值是:");
- sb.Append( mySingleSection.MySingleSection.MyAttribute1.ToString() );
- sb.Append("/n");
- sb.Append("該自定義配置節的MySingleConfigElement節點的MyAttribute2屬性的值是:");
- sb.Append(mySingleSection.MySingleSection.MyAttribute2.ToString());
- sb.Append("/n");
- Console.WriteLine( sb.ToString() );
- }
- }
- }
舉例說明,假如我們需要實現一個如下的配置:
- <customMulSectionDemo>
- <regexUrlMapping enable="true" rebaseClientPath="true">
- <add url="(/d+)$" mappedUrl="default.aspx?id=$1"></add>
- <add url="/$" mappedUrl="default.aspx?id=0"></add>
- </regexUrlMapping>
- </customMulSectionDemo>
首先需要定義一個配置節元素,如下:
- <configSections>
- <section name="customMulSectionDemo" type="CustomMulSection.RegexUrlMappingConfig,CustomMulSection" allowDefinition="Everywhere" restartOnExternalChanges="true" allowLocation="true"/>
- </configSections>
Ok,我們已經把目的明確了,下面的工作就是要實現RegexUrlMappingConfig這個類。要想此類擁有處理配置節的能力,就必須裝飾一下這個類,裝飾完成後,此類的代碼如下:
- class RegexUrlMappingConfig : ConfigurationSection
- {
- [ConfigurationProperty("regexUrlMapping")]
- public UrlMappingCollection UrlMappings
- {
- get{return this["regexUrlMapping"] as UrlMappingCollection;}
- }
- }
下一步,就是實現UrlMappingCollection類。由名字可以得知,這是一個集合類,它一般用來處理包含add元素的元素。實現此類也需要使用自定義屬性對此類進行裝飾。如下:
- class UrlMappingCollection : ConfigurationElementCollection
- {
- protected override ConfigurationElement CreateNewElement()
- {
- return new UrlMapping();
- }
- protected override object GetElementKey(ConfigurationElement element)
- {
- return ((UrlMapping)element).Url;
- }
- [ConfigurationProperty("enable")]
- public bool Enable
- {
- get
- {
- return bool.Parse(this["enable"].ToString());
- }
- }
- [ConfigurationProperty("rebaseClientPath")]
- public bool RebaseClientPath
- {
- get
- {
- return bool.Parse(this["rebaseClientPath"].ToString());
- }
- }
- //寫一個索引器,方便的訪問該集合中的元素。
- //如果不寫,則只有foreach來訪問。
- public UrlMapping this[int index]
- {
- get
- {
- return this.BaseGet(index) as UrlMapping;
- }
- }
- }
現在,我們已經實現了需要重寫的方法。看到regexUrlMapping元素還包括兩個屬性,實現這兩個屬性的代碼與已講過的內容類似。在此不做贅述。
還差最後一步,就是實現表示add元素的類。如下:
- class UrlMapping : ConfigurationElement
- {
- [ConfigurationProperty("mappedUrl")]
- public string MappedUrl
- {
- get
- {
- return (string)this["mappedUrl"];
- }
- }
- [ConfigurationProperty("url")]
- public string Url
- {
- get
- {
- return (string)this["url"];
- }
- }
- }
至此,我們已經完成了配置的映射工作。
完整的代碼如下所示:
app.config:
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <configSections>
- <section name="customMulSectionDemo" type="CustomMulSection.RegexUrlMappingConfig,CustomMulSection" allowDefinition="Everywhere" restartOnExternalChanges="true" allowLocation="true"/>
- </configSections>
- <customMulSectionDemo>
- <regexUrlMapping enable="true" rebaseClientPath="true">
- <add url="(/d+)$" mappedUrl="default.aspx?id=$1"></add>
- <add url="/$" mappedUrl="default.aspx?id=0"></add>
- </regexUrlMapping>
- </customMulSectionDemo>
- </configuration>
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Configuration;
- namespace CustomMulSection
- {
- class RegexUrlMappingConfig : ConfigurationSection
- {
- [ConfigurationProperty("regexUrlMapping")]
- public UrlMappingCollection UrlMappings
- {
- get{return this["regexUrlMapping"] as UrlMappingCollection;}
- }
- }
- class UrlMappingCollection : ConfigurationElementCollection
- {
- protected override ConfigurationElement CreateNewElement()
- {
- return new UrlMapping();
- }
- protected override object GetElementKey(ConfigurationElement element)
- {
- return ((UrlMapping)element).Url;
- }
- [ConfigurationProperty("enable")]
- public bool Enable
- {
- get
- {
- return bool.Parse(this["enable"].ToString());
- }
- }
- [ConfigurationProperty("rebaseClientPath")]
- public bool RebaseClientPath
- {
- get
- {
- return bool.Parse(this["rebaseClientPath"].ToString());
- }
- }
- //寫一個索引器,方便的訪問該集合中的元素。
- //如果不寫,則只有foreach來訪問。
- public UrlMapping this[int index]
- {
- get
- {
- return this.BaseGet(index) as UrlMapping;
- }
- }
- }
- class UrlMapping : ConfigurationElement
- {
- [ConfigurationProperty("mappedUrl")]
- public string MappedUrl
- {
- get
- {
- return (string)this["mappedUrl"];
- }
- }
- [ConfigurationProperty("url")]
- public string Url
- {
- get
- {
- return (string)this["url"];
- }
- }
- }
- }
測試代碼:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Configuration;
- namespace CustomMulSection
- {
- class Program
- {
- static void Main(string[] args)
- {
- DealMulSection();
- Console.ReadLine();
- }
- private static void DealMulSection()
- {
- RegexUrlMappingConfig myCustomMulSection = ConfigurationManager.GetSection("customMulSectionDemo") as RegexUrlMappingConfig;
- StringBuilder sb = new StringBuilder();
- sb.Append("myCustomMulSection對象的regexUrlMapping屬性(實際是個集合)的enable:");
- sb.Append(myCustomMulSection.UrlMappings.Enable.ToString());
- sb.Append("/n");
- sb.Append("myCustomMulSection對象的regexUrlMapping屬性(實際是個集合)的rebaseClientPath:");
- sb.Append(myCustomMulSection.UrlMappings.RebaseClientPath.ToString());
- sb.Append("/n");
- for (int i = 0; i < myCustomMulSection.UrlMappings.Count; i++ )
- {
- sb.Append("UrlMappings[");
- sb.Append(i.ToString());
- sb.Append("].url:");
- sb.Append(myCustomMulSection.UrlMappings[i].Url.ToString());
- sb.Append("/n");
- sb.Append("UrlMappings[");
- sb.Append(i.ToString());
- sb.Append("].mappedUrl:");
- sb.Append(myCustomMulSection.UrlMappings[i].MappedUrl.ToString());
- sb.Append("/n");
- }
- Console.WriteLine(sb.ToString());
- }
- }
- }