Angry! Accidentally click full screen mode, and everything you just wrote is lost !! Start from scratch !!!
Configuration files are indispensable for web programs, windows programs, and windows service programs. We are used to placing the connection string in the ConnectionString node and setting the program in the appSetting node. The Configuration File Management Program provides us with a convenient management method, so how do we customize the configuration node?
There are two methods. One is to inherit IConfigurationSectionHandler and implement the Create method. The flexibility of this method is very high. We need to parse the XmlNode of the custom node, so the implementation is complicated. Second, inherit the ConfigurationSection. This method is much simpler. You only need to specify the corresponding attribute name.
This article aims to use the least code to implement custom configuration nodes, so we will discard the first method and use the second method to implement custom configuration nodes.
Simply put, do not exercise fake scripts. Next we will use the second method to implement custom configuration nodes. The procedure is as follows:
1. Define custom configuration node information in configSections Node
<ConfigSections> <section name = "custom" type = "SampleWebConfigSection. Configuration. customSection, SampleWebConfigSection"/> </configSections>
Name: name of the custom configuration Node
Type: type. The data type corresponding to the custom configuration node.
2. Complete the structure of the custom configuration Node
<Custom fileName = "Default.txt" maxUsers = "2500" maxIdleTime = "00:10:00"/> 3. Implement node access by programming
CustomSection code
Using System. configuration; using System; namespace SampleWebConfigSection. configuration {public class customSection: ConfigurationSection {[ConfigurationProperty ("fileName", DefaultValue = "default.txt", IsRequired = true, IsKey = false)] [StringValidator (InvalidCharacters = "~! @ # $ % ^ & * () [] {}/; '\ "| \", MinLength = 1, MaxLength = 60)] public string FileName {get {return (string) this ["fileName"];} set {this ["fileName"] = value ;}} [ConfigurationProperty ("maxUsers ", defaultValue = (long) 10000, IsRequired = false)] [LongValidator (MinValue = 1, MaxValue = 10000000, ExcludeRange = false)] public long MaxUsers {get {return (long) this ["maxUsers"];} set {this ["maxUsers"] = Value ;}} [ConfigurationProperty ("maxIdleTime", DefaultValue = "", IsRequired = false)] [TimeSpanValidator (MinValueString = "", MaxValueString = ", excludeRange = false)] public TimeSpan MaxIdleTime {get {return (TimeSpan) this ["maxIdleTime"] ;}set {this ["maxIdleTime"] = value ;}}}} configurationProperty flag: indication. NET Framework instantiates the field value of an object through the attributes of the custom node. For each property marked with this property,. NET Framework uses reflection to read and modify parameters and create related ConfigurationProperty instances.
StringValidator flag: Declares the method to instruct. NET Framework to perform string verification on the configuration attribute.
LongValidator flag: declares a way to instruct. NET Framework to perform integer verification on the configuration attribute.
TimeSpanValidator flag: Declares the method to instruct. NET Framework to perform time verification on the configuration attribute.
4. Use custom configuration nodes
CustomSection custom = (customSection) System. configuration. configurationManager. getSection ("custom"); Response. write (custom. fileName + "|" + custom. maxUsers. toString () + "|" + custom. maxIdleTime); in the first code, we use ConfigurationManager. getSection obtains the M node and forcibly converts the type to the custom node. This makes it easy to use.
OK. The first example is complete. In fact, this example is in MSDN. I just took it down and explained it a bit.
Of course, the above content is not enough for the home page. The above example does not fully meet our general needs. We can even put these configurations in the appSetting to replace our custom configuration nodes. The following describes an actual requirement:
During website construction, we want to put the website title, subtitle, and URL in one configuration. Because the website has the file upload function, we want to limit the size of the uploaded files in the configuration, files are stored in different directories for different upload types. The node structure is as follows:
<WebSetting> <base title = "Cottage & amp; pickup "subTitle =" 7 km deep blue blog "url =" http://youring2.cnblogs.com "> </base> <fileUpload> <file name =" headPhoto "path =" upload/image/headPhoto "size = "200"> </file> <file name = "album" path = "upload/image/album" size = "1024"> </file> </fileUpload> </webSetting> to complete this custom configuration node, follow the steps in the first example to configure the custom node information in configSections:
<Section name = "webSetting" type = "SampleWebConfigSection. Configuration. webSettingSection, SampleWebConfigSection"/> do not explain. Next we need to complete four classes:
WebSettingSection
BaseSection
FileUploadSection
FileSection
These four classes correspond to the four nodes in this configuration: webSetting, base, fileUpload, and file.
WebSettingSection code
Using System. configuration; namespace SampleWebConfigSection. configuration {public class webSettingSection: ConfigurationSection {// base node [ConfigurationProperty ("base")] public baseSection BaseSetting {get {return (baseSection) base ["base"] ;}} // fileUpload node [ConfigurationProperty ("fileUpload")] public fileUploadSection FileUploadSetting {get {return (fileUploadSection) base ["fileUpload"];} }}} Is derived from ConfigurationSection and contains two attributes: BaseSetting and FileUploadSetting, which correspond to the two subnodes base and fileUpload in the configuration file respectively.
BaseSection code
Using System. configuration; namespace SampleWebConfigSection. configuration {public class baseSection: ConfigurationElement {// title attribute [ConfigurationProperty ("title", IsKey = true, IsRequired = true)] public string title {get {return (string) base ["title"] ;}set {title = value ;}// subTitle attribute [ConfigurationProperty ("subTitle", IsRequired = false, DefaultValue = "")] public string subTitle {get {Return (string) base ["subTitle"] ;}set {subTitle = value ;}// url attribute [ConfigurationProperty ("url", IsRequired = true)] public string url {get {return (string) base ["url"] ;}set {url = value ;}}} is derived from ConfigurationElement because it is a child element, is included in the webSettingSection class. Its Attributes are not explained.
FileUploadSection code
Using System. configuration; namespace SampleWebConfigSection. configuration {[ConfigurationCollection (typeof (fileSection), AddItemName = "file")] public class fileUploadSection: ConfigurationElementCollection {protected override ConfigurationElement CreateNewElement () {return new fileSection ();} protected override object GetElementKey (ConfigurationElement element) {return (fileSection) element ). Name;} public fileSection this [int index] {get {return (fileSection) base. baseGet (index) ;}} new public fileSection this [string name] {get {return (fileSection) base. baseGet (name) ;}}} is derived from ConfigurationElementCollection because it is a collection of child elements and contains a collection of filesections.
This class uses the following tag:
[ConfigurationCollection (typeof (fileSection), AddItemName = "file")] This is a description of a child element set. The first type parameter is required and specifies the type that contains the subset. The second parameter is optional. It specifies the node name of the subnode to be added to the set. The default value is add. Instead of the default value, file is used ", therefore, this parameter is specified.
In addition, this class also implements the method of getting a fileSection through index and name, which are this [int index] And this [string name]. The base class itself has a method to obtain sub-elements through strings, so the new keyword is used here.
FileSection code
Using System. configuration; namespace SampleWebConfigSection. configuration {public class fileSection: ConfigurationElement {// name attribute [ConfigurationProperty ("name", IsKey = true, IsRequired = true)] public string name {get {return (string) this ["name"] ;}set {name = value ;}// path attribute [ConfigurationProperty ("path", IsRequired = true)] public string path {get {return (string) this ["path"];} se T {path = value ;}// size attribute [ConfigurationProperty ("size", IsRequired = true, DefaultValue = 1024)] public int size {get {return (int) this ["size"] ;}set {size = value ;}}} is derived from ConfigurationElement. Its Attributes are simple and not explained.
We can use this configuration node as in the first example using the custom configuration Node Method. However, we usually do not want to re-load a configuration item every time we use it. Therefore, we use a static object to access this configuration node:
Namespace SampleWebConfigSection. configuration {public class WebSettingManager {public static webSettingSection WebSetting = (webSettingSection) System. configuration. configurationManager. getSection ("webSetting") ;}test whether custom configuration nodes are easy to use. Add the following code to the website page:
<Asp: Content ID = "BodyContent" runat = "server" ContentPlaceHolderID = "MainContent">
Protected void Page_Load (object sender, EventArgs e) {this. title = WebSettingManager. webSetting. baseSetting. title + "-" + WebSettingManager. webSetting. baseSetting. subTitle; this. lblTitle. text = WebSettingManager. webSetting. baseSetting. title; this. lblSubTitle. text = WebSettingManager. webSetting. baseSetting. subTitle; this. lblUrl. text = WebSettingManager. webSetting. baseSetting. url; this. gvFileUploadSetting. dataSource = WebSettingManager. webSetting. fileUploadSetting; this. gvFileUploadSetting. dataBind ();}
When running the website, we can see the following interface, indicating that our configuration node is available:
We can rest, haha, with source code: http://files.cnblogs.com/youring2/SampleWebConfigSection.rar