In. NET, a tutorial is provided to facilitate the operation of configuration items, and. net is more convenient.

Source: Internet
Author: User

In. NET, a tutorial is provided to facilitate the operation of configuration items, and. net is more convenient.
During application development, we often provide some configuration items for the software to allow the software to do things flexibly according to the configuration items, such as configuring the log file path. In addition, we can also use configuration items to store user preference settings.

. NET provides the configuration mechanism and configuration file by default. The app. config or web. config file in the project (if not, you can add it) is the configuration file provided by. NET for us. Under the configuration of the root node in this configuration file, create the deleteworker node. In this node, we can add custom configuration items. The ConfigurationManager class also provides methods for accessing and operating the Configuration file (represented by the Configuration class. Note that this class is in the System. Configuration. dll file and must be added to the reference of the project before it can be used.

This article mainly introduces a more convenient way to access/store configuration items. Of course, it is essentially completed using the ConfigurationManager class. Its main feature is to solve this problem in an object-oriented way. More specifically, we create a class that contains some attributes used to represent configuration items and access or set these attributes, you can obtain or update the corresponding configuration item.

I. Implementation

First, we add an extension method AddOrUpdateAppSettingItem for the Configuration class, as shown below:

///

 

/// Add (if not exist) or update (if existing) the given key and value to the configured paietings Section

///

 

///

///

///

Public static void AddOrUpdateAppSettingItem (this Configuration config, string key, string value)

{

If (config. AppSettings. Settings. AllKeys. Contains (key ))

{

Config. etettings. Settings [key]. Value = value;

}

Else

{

Config. AppSettings. Settings. Add (key, value );

}

}

}

This method is mainly used to add (the configuration item does not exist) to the appSettings node or update (the configuration item already exists) The configuration. Next we will use this method.

Next, we define the abstract base class ConfigSetting as follows:

Public abstract class ConfigSetting

{

///

 

/// Configuration class

///

 

///Configuration

Public ConfigSetting (Configuration configuration)

{

Configuration = configuration;

}

///

 

/// Current configuration

///

 

Public Configuration

{

Get;

}

///

 

/// Obtain the current program Configuration

///

 

///

///

Public static Configuration GetCurrentConfiguration ()

{

Return ConfigurationManager. OpenExeConfiguration (ConfigurationUserLevel. None );

}

///

 

/// Return the value of the specified configuration item

///

 

///

///

Protected virtual string GetSettingValue ([CallerMemberName] string settingKey = null)

{

Return Configuration ?. Ettings ?. Settings [settingKey]?. Value;

}

///

 

/// Return the value of the specified configuration item

///

 

/// Value Type

///

///

Protected virtual T GetSettingValue ([CallerMemberName] string settingKey = null)

{

Var value = GetSettingValue (settingKey );

If (string. IsNullOrWhiteSpace (value ))

{

Return default (T );

}

Else

{

Return (T) Convert. ChangeType (value, typeof (T ));

}

}

///

 

/// Set the value for the specified configuration item

///

 

///

///

Protected virtual void SetSettingValue (object value, [CallerMemberName] string settingKey = null)

{

Configuration. AddOrUpdateAppSettingItem (settingKey, value ?. ToString ());

Configuration. Save ();

}

}

It mainly includes a static method and three protected virtual methods, which are described as follows:

1. The static method GetCurrentConfiguration returns the configuration class of the current application;

2. The GetSettingValue and SetSettingValue methods are responsible for reading and setting the values of the specified configuration item respectively;

3. GetSettingValue has two reloads, one of which is used to support generics;

4. The CallerMemberName feature is included in their method signatures. You can use this attribute to obtain the name of the method or attribute that calls this access.

Then, create a class named AppConfigSetting, which includes some attributes that represent configuration items and inherit from ConfigSetting, as shown below:

Public class AppConfigSetting: ConfigSetting

{

Public AppConfigSetting (Configuration configuration): base (configuration)

{

}

Public DateTime InstallDateTime

{

Get {return GetSettingValue ();}

Set {SetSettingValue (value );}

}

Public string LogFileName

{

Get {return GetSettingValue ();}

Set {SetSettingValue (value );}

}

Public int ReadBlockSize

{

Get {return GetSettingValue ();}

Set {SetSettingValue (value );}

}

}

Note:

1. We can see that three attributes are added in it. In their get and set segments, two methods corresponding to the base class are called. For non-string-type configuration items, GetSettingValue is called. .

2. Through the CallerMemberName feature we mentioned earlier, we can get the attribute name here and get the corresponding configuration items, so that we do not need hard encoding. Therefore, this attribute name is essentially the name of the configuration item.

In this way, we put all the configuration items to be used as attributes in the AppConfigSetting class, and then perform all the operations on the configuration items by operating these attributes.

Ii. How to Use

It is also very simple to use. The Code is as follows:

Var config = ConfigSetting. GetCurrentConfiguration ();

AppConfigSetting setting = new AppConfigSetting (config );

// When not set

MessageBox. Show ($ "LogFileName: {setting. LogFileName }");

// Read the data after setting

Setting. LogFileName = "log.txt ";

MessageBox. Show ($ "LogFileName: {setting. LogFileName }");

Iii. Supplement

To meet the need to access/store the specified configuration item without adding the configuration item attribute to AppConfigSetting, we can add the following three methods to the base class ConfigSetting:

//

/// Return the value of the specified configuration item

///

///

///

Public string GetSettingValueByKey (string settingKey)

{

Return GetSettingValue (settingKey );

}

///

/// Return the value of the specified configuration item

///

///

///

Public T GetSettingValueByKey (String settingKey)

{

Return GetSettingValue (SettingKey );

}

///

/// Set the value for the specified configuration item

///

 

///

///

Public void SetSettingValueByKey (string settingKey, object value)

{

SetSettingValue (value, settingKey );

}

Using these methods, you can freely access/store configuration items. Unlike adding properties above, you need to pass the configuration item key as the parameter.

Usage:

// When not set

MessageBox. Show ($ "LogLevel: {setting. GetSettingValueByKey (" LogLevel ")}");

// Read the data after setting

Setting. SetSettingValueByKey ("LogLevel", 5 );

MessageBox. Show ($ "LogLevel: {setting. GetSettingValueByKey (" LogLevel ")}");

Summary

This article mainly introduces a more convenient way to access the application configuration, the main idea is to use the GetSettingValue/SetSettingValue methods in the base class to obtain the name of the attribute in the derived class by using the CallerMemberName feature and operate the corresponding configuration item. Of course, this not only provides a method, but also provides a way of thinking. Based on this, you can also adjust and expand to meet your actual needs.

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.