. NET Configuration System-Analysis of ettings implementation

Source: Internet
Author: User
Tags mscorlib

 

1. Browse ettings

AppSettings provides convenient and concise configuration storage for programmers. The following is a typical configuration file for AppSettings in applications:

 

<? Xml version = "1.0" encoding = "UTF-8"?>

 

<Configuration>

 

<Deleetask>

 

<Clear/>

 

<Add key = "key1" value = "value1"/>

 

<Add key = "key2" value = "value2 A"/>

 

<Add key = "key2" value = "value2 B"/>

 

</AppSettings>

 

 

 

</Configuration>

 

 

 

<Configuration> yes.. NET: configure the XML root node of the system, and then delete the inherited appsing ettings value (if any) in <deleettings> <clear/> ), use <add> to add a key value. If the two keys are the same, for example, two key2 In the example, the previous key value will be rewritten later, in this configuration file, the key2 key value in the deleetaskis value2 B.

 

 

 

AppSettings is a ConfigurationSection. First, you can use the GetSection of Configuation to browse its content. Of course, the Configuration class provides a configurettings attribute to help you view its source code, actually, GetSection is used to return the "deleetask" ConfigurationSection;

 

// Source code of the configurettings attribute of the Configuration class

 

Public AppSettingsSection extends ettings

 

{

 

Get

 

{

 

Return (AppSettingsSection) this. GetSection ("appSettings ");

 

}

 

}

 

 

 

Then, you can use the Configuration class to browse the ettings as follows:

 

(Code 1: browse through Configuration. GetSection)

 

Configuration conf =

 

ConfigurationManager. OpenExeConfiguration (ConfigurationUserLevel. None );

 

AppSettingsSection appSet = conf. AppSettings;

 

Foreach (KeyValueConfigurationElement ele in appSet. Settings)

 

Console. WriteLine ("Key: {0} Value: {1}", ele. Key, ele. Value );

 

 

 

 

 

Here, some readers may find that this is not the most commonly used browsing method. Yes, the above method is browsing. NET configuration file is the most primitive method, the advantage is flexible and readable and writable, the disadvantage is a bit complicated, for the convenient and concise configuration storage of AppSettings, we can also use another more common method, is to use the ConfigurationManager class. This class returns a NameValueCollection (this class is in the System. Collections. Specialized namespace) for users to query directly.

 

(Code 2: browse through ConfigurationManager)

 

System. Collections. Specialized. NameValueCollection nvc =

 

ConfigurationManager. deleettings;

 

Foreach (string key in nvc. AllKeys)

 

Console. WriteLine ("key: {0} value: {1}", key, nvc [key]);

 

 

 

Both methods have the same output:

 

Key: key1 value: value1

 

Key: key2 value: value2 B

 

 

 

 

 

 

 

2. Search for the root cause of ettings

Let's say that etettings is essentially a ConfigurationSection. Next we will explore this ConfigurationSection. Let's take a look at all the configurationsections inherited from the local application configuration file.

 

Here, we use the Sections and SectionGroups attributes of the Configuration class to enumerate

 

Configuration conf = ConfigurationManager. OpenExeConfiguration (ConfigurationUserLevel. None );

 

Console. WriteLine ("local configuration file: {0} \ n", conf. FilePath );

 

Console. WriteLine ("=== all SectionGroup ");

 

Foreach (ConfigurationSectionGroup grp in conf. SectionGroups)

 

Console. WriteLine (grp. SectionGroupName );

 

 

 

Console. WriteLine ();

 

Console. WriteLine ("= all sections ");

 

 

 

Foreach (ConfigurationSection sec in conf. Sections)

 

Console. WriteLine (sec. SectionInformation. SectionName );

 

Output result:

 

Local configuration file: E: \ My Documents ents \ Visual Studio 2008 \ Projects \ TTC \ bin \ Release \ Mg

 

En.exe. Config

 

 

 

=== All sectiongroups

 

System. serviceModel

 

System.net

 

System. transactions

 

System. web

 

System. runtime. serialization

 

System. serviceModel. activation

 

System. xml. serialization

 

 

=== All sections

 

System. data

 

Windows

 

System. webServer

 

Mscorlib

 

System. data. oledb

 

System. data. oracleclient

 

System. data. sqlclient

 

ConfigProtectedData

 

Satelliteassemblies

 

System. data. dataset

 

Startup

 

System. data. odbc

 

System. diagnostics

 

Runtime

 

System. codedom

 

System. runtime. remoting

 

ConnectionStrings

 

AssemblyBinding

 

AppSettings

 

System. windows. forms

 

 

 

AppSettings must be in it (marked in yellow)

 

 

 

Our local application configuration file does not have a region defined, but can be used directly. This is because the region ettings is the configuration option inherited by the local application configuration file. More accurately, inherited from. NET Configuration System top configuration file machine. config

 

 

 

The file path of machine. config can be obtained in the following two ways, and the results are the same

 

Var path1 = ConfigurationManager. OpenMachineConfiguration (). FilePath;

 

Var path2 = new ConfigurationFileMap (). MachineConfigFilename;

 

 

 

Open machine. config and you can find the definition of AppSettings at the beginning (of course, there is another common ConfigurationSection: ConnectionStrings region definition)

 

<Configuration>

 

<ConfigSections>

 

<Section name = "etettings"

 

Type = "System. Configuration. etettingssection, System. Configuration, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a"

 

RestartOnExternalChanges = "false"

 

RequirePermission = "false"/>

 

<Section name = "connectionStrings"

 

Type = "System. Configuration. ConnectionStringsSection, System. Configuration, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a"

 

RequirePermission = "false"/>

 

<Section name = "mscorlib"

 

Type = "System. Configuration. IgnoreSection, System. Configuration, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a"

 

AllowLocation = "false"/>

 

 

 

Subsequent content omitted ......

 

 

 

Okay. Now, everything is "very clear". AppSettings is actually an ordinary Configuration file definition of System. Configuration. etettingssection! Next let's take a look at this etettingssection class!

 

 

 

 

 

 

 

3. Explore AppSettingsSection

AppSettings is predefined by Microsoft in. NET Framework, but does not enjoy any special services. It is a general ConfigurationSection represented by AppSettingsSection. Let's take a look at this class.

 

First, do not forget that the ConfigurationSection is inherited from the ConfigurationElement. The latter has the Properties attribute of the ConfigurationPropertyCollection type, which is used to add user-defined attributes (this attribute is the node attribute in the configuration file and is also used for implementation. NET ).

 

AppSettingsSection has only two attributes: File and Settings. The File attribute is also described on MSDN, but the Settings attribute is hardly seen, because the Settings attribute is the default container attribute (IsDefaultCollection = true), and its ConfigurationProperty name is a null string.

 

The Settings property is initialized as follows:

 

// The EnsureStaticPropertyBag method code of the deleettingssection

 

// This method will be called in get of Properties

 

S_propAppSettings =

 

New ConfigurationProperty (

 

Null,

 

Typeof (KeyValueConfigurationCollection ),

 

Null,

 

ConfigurationPropertyOptions. IsDefaultCollection );

 

 

 

 

 

In this case, adding data directly to the AppSettingsSection is actually adding data to the KeyValueConfigurationCollection set in AppSettingsSection.

 

 

 

 

 

 

 

4. Explore KeyValueConfigurationCollection

KeyValueConfigurationCollection is inherited from ConfigurationElementCollection, and is the default AddRemoveClearMap type container. The ThrowOnDuplicate attribute of ConfigurationElementCollection must be described here.

 

ThrowOnDuplicate of ConfigurationElementCollection returns true for AddRemoveClearMap and addremoveclearmapalterate.

 

You can refer to its source code:

 

Protected virtual bool ThrowOnDuplicate

 

{

 

Get

 

{

 

If (this. CollectionType! = ConfigurationElementCollectionType. AddRemoveClearMap) & (this. CollectionType! = ConfigurationElementCollectionType. AddRemoveClearMapAlternate ))

 

{

 

Return false;

 

}

 

Return true;

 

}

 

}

 

 

 

However, it is very important to rewrite KeyValueConfigurationCollection to false. In this way, the key value in the deleteconfigurationcollection can be added repeatedly. If the same key exists, the value will be overwritten!

 

 

 

In addition, because the container operation functions of ConfigurationElementCollection are only visible to inheritance classes, KeyValueConfigurationCollection also defines the Add, Remove, Clear public functions, the three functions use the class-visible BaseAdd, BaseRemove, and BaseClear inheritance functions within the ConfigurationElementCollection. You can use these three functions to dynamically modify the deleettings. As mentioned above, only the Configuration class can be used, while the ConfigurationManager's deleteworkflow is read-only.

 

 

 

 

For example, you can remove the key1 key at the top of the article and save the config file:

 

Configuration conf = ConfigurationManager. OpenExeConfiguration (ConfigurationUserLevel. None );

 

Etettingssection appsetSection = conf. AppSettings;

 

 

 

KeyValueConfigurationCollection collec = deleetsection. Settings;

 

Collec. Remove ("key1 ");

 

Conf. Save ();

 

 

 

 

 

In addition, KeyValueConfigurationCollection has not changed the Add/Remove/ClearElementName of ConfigurationElementCollection. The three values are kept by default, that is, add, remove, and clear.

 

 

 

Finally, KeyValueConfigurationCollection stores KeyValueConfigurationElement, which is defined in the ConfigurationElementCollectionAttribute feature.

 

[ConfigurationCollection (typeof (KeyValueConfigurationElement)]

 

Public class KeyValueConfigurationCollection: ConfigurationElementCollection

 

This KeyValueConfigurationElement is also a common ConfigurationElement. Two data attributes are defined here. Key and Value represent the Key and Value respectively.

 

 

 

 

 

 

 

Overview

Finally, let's take a look at the ettings at the beginning of the article. At this time, you should have a new understanding of ettings. I will comment on the Principles:

 

<? Xml version = "1.0" encoding = "UTF-8"?>

 

 

 

<! -- This is the root node of the. NET configuration file -->

 

<Configuration>

 

 

 

<! -- Define the ettings region in machine. config -->

 

 

 

<! -- Represents the ConfigurationSection of AppSettingsSection -->

 

 

 

<Deleetask>

 

 

 

<! -- Set the Settings attribute in AppSettingsSection -->

 

 

 

<! -- Because the Settings property has the default container property, you do not need to specify the name -->

 

 

 

<! -- Operate KeyValueConfigurationCollection (the type represented by the Settings attribute) -->

 

 

 

 

 

<! -- This is ClearElementName in ConfigurationElementCollection -->

 

 

 

<! -- KeyValueConfigurationCollection does not rewrite this value. Keep the default value -->

 

 

 

<! -- Delete all values that may inherit the ettings -->

 

 

 

<Clear/>

 

 

 

 

 

<! -- Add KeyValueConfigurationElement in KeyValueConfigurationCollection -->

 

 

 

<! -- Add is the default value of AddElementName of ConfigurationElementCollection -->

 

 

 

<! -- Key and value are the attributes of KeyValueConfigurationElement -->

 

 

 

<Add key = "key1" value = "value1"/>

 

 

 

 

 

<! -- Same as above -->

 

 

 

<Add key = "key2" value = "value2 A"/>

 

 

 

 

 

<! -- The KeyValueConfigurationCollection rewrite ThrowOnDuplicate to false -->

 

 

 

<! -- Therefore, the same key will be rewritten. In this case, the key2 key value in the ettings is changed to value2 B -->

 

 

 

<Add key = "key2" value = "value2 B"/>

 

 

 

</AppSettings>

 

 

 

</Configuration>

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.