". Net deep Breathing" Custom application configuration section

Source: Internet
Author: User

Tags: Configuring the str ORM derived class to access sys bug COM MSSQL

In fact, the application configuration file, App. config, is made up of individual sections (configuration sections), which are typically grouped by function, such as appSettings, ConnectionStrings, startup, System. ServiceModel ...

In real-world development, our application should also need a configuration section where our programs are dedicated and functional, so that we can read through the relevant APIs in our code instead of using normal XML file reading methods.

In fact, implementing a custom configuration section is not difficult, but there are a few issues to be aware of.

Old week on the side to show the big friends to explain, this will be more emotional.

To customize the application configuration section, you must derive from the ConfigurationSection class, which is an abstract class, so we must define our own configuration section as a base class. Although it is an abstract class, however, the function is very perfect, in most cases we do not need to rewrite its members (special needs, can be rewritten on demand), to show you a look at my class.

     Public class mydemosection:configurationsection    {            ...    }

So, what are we going to do in this class? We're going to add the attributes we need to it. For example, I need two properties-a User, a string type, and another age, type int.

     Public class mydemosection:configurationsection    {        publicstring  User        {            get  {...}             Set {...}        }  Public int Age        {            get  {...}             Set {...     }}}

At this point, you must think of a question: How is the profile API recognized when it is saved to a configuration file? In fact, the base class of this ConfigurationSection class is configurationelement. ConfigurationElement is the common base class for all configuration file elements. The configuration section is actually a special configuration element, which differs from normal configuration elements in that the configuration section is usually the primary node for a class of functions. The child element of the configuration section is the normal configuration element, and the configuration section must be declared under the configsections node before it can be used in the configuration file. We'll talk about this later.

The ConfigurationElement class exposes the following two versions of indexers:

protected Internal Object  This [stringgetset;} protected Internal Object  This Get set; }

We typically use a version with a string parameter that can only be accessed in a derived class and not externally exposed. The ConfigurationSection class is derived from the ConfigurationElement class and will naturally inherit the indexer.

So, in the property wrapper of the Custom configuration section, we can access the content through this indexer, which is similar to a dictionary.

     Public classmydemosection:configurationsection { Public stringUser {Get{return(string) This["User"]; }            Set{ This["User"] =value;} }         Public intAge {Get{return(int) This[" Age"]; }            Set{ This[" Age"] =value;} }    }

Code to write here, it seems to be completed, in fact, in the bud. At this point, if you want to write the custom node to the configuration file in code, you will receive the following exception.

Because our custom configuration section class is not finished yet, one Attribute is not applied. It should be written like this.

[ConfigurationProperty ("User")]         Public stringUser {Get{return(string) This["User"]; }            Set{ This["User"] =value;} } [ConfigurationProperty (" Age")]         Public intAge {Get{return(int) This[" Age"]; }            Set{ This[" Age"] =value;} }

Attention, serious to pay attention!! The name specified in the application's configurationpropertyattribute must be the same as that used in the indexer (this["..."]) , such as the code above, age is consistent, and if you change it, you will get an error.

 [ConfigurationProperty ( number  Span style= "color: #800000;" > " )]  public  int   age { get  {return  (int ) this  [ " age  "   set  {this  [ " age  " ] =

Because number and age do not match, however, the property name of the type is not required, for example, the age attribute can be changed to Num.

 [ConfigurationProperty ( age  Span style= "color: #800000;" > " )]  public  int   Num { get  {return  (int ) this  [ " age  "   set  {this  [ " age  " ] =

Changing the attribute name to Num will not give an error. as long as the name parameter in Configurationpropertyattribute matches the name in the indexer .

Next, let's try this custom configuration section, which we configure in code and then save in App. Config.

Configuration config =configurationmanager.openexeconfiguration (Configurationuserlevel.none); Mydemosection Sect=Newmydemosection (); Config. Sections.add ("MyInfo", sect); //sect. Sectioninformation.forcesave = false;Sect. User ="Ben Dan"; Sect. Age= -; //SaveConfig. Save (configurationsavemode.modified);

Pass.... The Sections.add method adds a custom configuration section to the configuration file, where there is a name parameter that specifies the name of the XML element when the configuration is used. If you do not understand this, do not worry, you first remember our code written in the name of MyInfo.

Then execute the above code, and then open the application-related app. config file, note that the config file in the project is not in the bin\\ directory. When you open it, you'll see something like that.

<Configuration>    <configsections>         < section name= "MyInfo"  type= "Custconfigs.mydemosection, Caidemo, version=1.0.0.0, Culture=neutral, publickeytoken=null " />     </configsections>
<MyInfo user= "Ben Dan" age= "/>"
...</Configuration>

How, you see now understand no, know that myinfo how to use it.

First, to configure the type of the custom configuration section with the section element in configsections, type specifies the Mydemosection class that we just defined, but only the type name and assembly name are required. Name specifies a name, which is the XML element name that you then use in the configuration file, such as MyInfo in this example.

In the above code, you may notice that a line of code is commented out,

false;

On MSDN, this property indicates whether you want to force the contents of the configuration section to be persisted, even if it has not been modified, and I'm not using it, because the example on MSDN has this line, and I deliberately add it to the force.

Just now, we used the code to apply my custom configuration section, the content has been written to the App. Config file, and if we run the above code again, you will find an error.

The original configuration section can not be repeated Add, so we change the code, the first judgment.

Configuration config =configurationmanager.openexeconfiguration (Configurationuserlevel.none); Mydemosection Sect = config. sections["myinfo"]  as mydemosection;  if(sect = = null) {Sect = new  Mydemosectio N (); Config. Sections.add ("myinfo"  , sect); } sect. User="Ben Dan"; Sect. Age= -; //SaveConfig. Save (configurationsavemode.modified);

OK, so you can avoid the error.

Next, I'll give you another example this time, instead of writing the configuration file with code, we edit the configuration file directly and then read the configuration information in the code. This should be the most common practice.

Still, we customize a configuration section type.

     Public classdbsection:configurationsection {[ConfigurationProperty ("DbName", DefaultValue ="Db.mdf")]         Public stringDBName {Get{return(string) This["DbName"]; }            Set{ This["DbName"] =value;} } [ConfigurationProperty ("LoginName", DefaultValue ="SA")]         Public stringLoginName {Get{return(string) This["LoginName"]; }            Set{ This["LoginName"] =value;} }    }

Assuming that DBName represents the name of the database file, LoginName indicates the name of the login MSSQL (the default is SA).

Then, we open \bin\debug the following app. Config, note that it is not a configuration file in the project. The Custom configuration section is declared first.

  < configsections >    <name= "db"  type= "custconfigs.dbsection, Caidemo"  />  </configsections>

At this point, the XML element is named DB if it is to be configured.

<dbName= "App.mdf"  loginName= "admin"/>

Note that the property name set here is not the property name on the class, but the name specified by Configurationpropertyattribute.

Now, let's read out these configuration parameters in the code.

            Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none);             = Config. sections["db" as dbsection;             if NULL             {                string s = $" database: {sect. DBName}, Login name: {sect. LoginName}. ";                Console.WriteLine (s);            }

Note that just as we declared in the configuration file, the elements of the custom section are named DB.

<name= "db"   type= "custconfigs.dbsection, Caidemo" />

So, when we read, we also use DB as the name to remove the configuration section instance, and then read the value of the property.

Finally, the output is as follows:

Well, today's content is pulled here, this thing, we learned, still have real combat value, and it is not difficult.

". Net deep Breathing" Custom application configuration section

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: