In. NET, a more convenient way to manipulate configuration items

Source: Internet
Author: User

Tag: Derive this RAM Lda value problem extension method base class txt

In the application development process, we often provide some configuration items for the software to allow the software to do things according to the configuration items, such as configuration log file path, in addition, we can also use configuration items to store their preferences for users, and so on.

. NET provides us with the configuration mechanism and configuration files, and the app. Config or Web. config file in the project (if not, can be added) is the configuration file provided to us by. Net. In this configuration file, under the root node configuration, create the AppSettings node, in which we can add custom configuration items. At the same time, the ConfigurationManager class provides access to and manipulation of the methods configured in this configuration file (represented by a configuration Class). It is important to note that this class is in the System.Configuration.dll file and needs to be added to the project reference before it can be used.

This article focuses on a more convenient way to access/store configuration items, which, of course, is done using the ConfigurationManager class in essence. Its main feature is to solve this problem in an object-oriented manner , and more specifically, we create a class that includes properties to represent the configuration items that can be obtained or updated by accessing or setting these properties.

First, to achieve

First, we add an extension method Addorupdateappsettingitem for the Configuration class, as follows:

        /// <summary>        ///adds to the configured appsetings section (if it does not exist) or updates (if it already exists) the given key and value/// </summary>        /// <param name= "config" ></param>        /// <param name= "key" ></param>        /// <param name= "value" ></param>         Public Static voidAddorupdateappsettingitem ( ThisConfiguration Config,stringKeystringvalue) {            if(config. AppSettings.Settings.AllKeys.Contains (key)) {config. Appsettings.settings[key]. Value=value; }            Else{config.            APPSETTINGS.SETTINGS.ADD (key, value); }        }    }

This method mainly implements the configuration of adding to the AppSettings node (the configuration item does not exist) or updating (the configuration item already exists), which we will use next.

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

     Public Abstract classconfigsetting {/// <summary>        ///Configuration Class/// </summary>        /// <param name= "Configuration" >Configuration</param>         Publicconfigsetting (Configuration configuration) {Configuration=configuration; }        /// <summary>        ///Current Configuration/// </summary>         Publicconfiguration Configuration {Get; }        /// <summary>        ///Get Current program configuration/// </summary>        /// <param name= "config" ></param>        /// <returns></returns>         Public StaticConfiguration getcurrentconfiguration () {returnconfigurationmanager.openexeconfiguration (Configurationuserlevel.none); }        /// <summary>        ///returns the value of the specified configuration item/// </summary>        /// <param name= "Settingkey" ></param>        /// <returns></returns>        protected Virtual stringGetsettingvalue ([Callermembername]stringSettingkey =NULL)        {            returnConfiguration?. AppSettings?. Settings[settingkey]?.        Value; }        /// <summary>        ///returns the value of the specified configuration item/// </summary>        /// <typeparam name= "T" >value type</typeparam>        /// <param name= "Settingkey" ></param>        /// <returns></returns>        protected VirtualT getsettingvalue<t> ([Callermembername]stringSettingkey =NULL)        {            varValue =Getsettingvalue (Settingkey); if(string. Isnullorwhitespace (value)) {return default(T); }            Else            {                returnT Convert.changetype (Value,typeof(T)); }        }        /// <summary>        ///set a value for the specified configuration item/// </summary>        /// <param name= "value" ></param>        /// <param name= "Settingkey" ></param>        protected Virtual voidSetsettingvalue (ObjectValue, [Callermembername]stringSettingkey =NULL) {Configuration.addorupdateappsettingitem (Settingkey, Value?.            ToString ());        Configuration.save (); }    }

This includes a static method and three protected virtual methods, which illustrate:

1. Static method Getcurrentconfiguration Returns the currently applied configuration class;
2. The Getsettingvalue and Setsettingvalue methods are respectively responsible for reading and setting the value of the specified configuration item;
3. The Getsettingvalue has two overloads, one of which is used to support generics;
4. Include the Callermembername attribute in their method signature, which allows you to get the name of the method or property that called the access.

Then, create a class named Appconfigsetting, which will include some properties that represent the configuration item, and it will inherit from Configsetting, as follows:

     Public classappconfigsetting:configsetting { PublicAppconfigsetting (configuration):Base(configuration) {} PublicDateTime Installdatetime {Get{returnGetsettingvalue<datetime>(); } Set{setsettingvalue (value);} }         Public stringLogFileName {Get{returngetsettingvalue ();} Set{setsettingvalue (value);} }         Public intReadblocksize {Get{returngetsettingvalue<int>(); } Set{setsettingvalue (value);} }    }

Description

1. You can see that we have added three properties to it. In their get and set segments, the corresponding two methods in the base class are called, where we call getsettingvalue<t> for configuration items that are not of type string.
2. With the Callermembername feature we mentioned earlier, we can get the property name here and get the corresponding configuration item so that we don't have to hardcode it. So, this property name is essentially the name of the configuration item.

In this way, we put all the configuration items we want to use as attributes into the Appconfigsetting class, and then we can do all of the configuration items by manipulating the properties.

Second, how to use

Using it is also very simple, the code is as follows:

            varConfig =configsetting.getcurrentconfiguration (); Appconfigsetting setting=Newappconfigsetting (config); //When not setMessageBox.Show ($"LogFileName: {setting. LogFileName}"); //after setting, then readSetting. LogFileName ="Log.txt"; MessageBox.Show ($"LogFileName: {setting. LogFileName}");
Third, supplementary

To satisfy the need to add configuration item properties to appconfigsetting without having to access/store the specified configuration items, we can add the following three methods to the base class Configsetting:

        /// <summary>        ///returns the value of the specified configuration item/// </summary>        /// <param name= "Settingkey" ></param>        /// <returns></returns>         Public stringGetsettingvaluebykey (stringSettingkey) {            returnGetsettingvalue (Settingkey); }        /// <summary>        ///returns the value of the specified configuration item/// </summary>        /// <param name= "Settingkey" ></param>        /// <returns></returns>         PublicT getsettingvaluebykey<t> (stringSettingkey) {            returnGetsettingvalue<t>(Settingkey); }        /// <summary>        ///set a value for the specified configuration item/// </summary>        /// <param name= "value" ></param>        /// <param name= "Settingkey" ></param>         Public voidSetsettingvaluebykey (stringSettingkey,Objectvalue)        {Setsettingvalue (value, Settingkey); }

Using these methods, you have the freedom to access/store configuration items, unlike the way you add attributes above, it needs to pass the configuration key itself as a parameter.

Use:

            //When not setMessageBox.Show ($"LogLevel: {setting. Getsettingvaluebykey ("LogLevel")}"); //after setting, then readSetting. Setsettingvaluebykey ("LogLevel",5); MessageBox.Show ($"LogLevel: {setting. Getsettingvaluebykey ("LogLevel")}");
Summarize

This paper introduces a more convenient way to access application configuration, the main idea is to use the Getsettingvalue/setsettingvalue two methods in the base class with the help of Callermembername attribute to get the name of the property in the derived class and manipulate the corresponding configuration item. Of course, there is not only a way to provide a method, but also a kind of idea, based on which you can adjust and expand to meet your actual needs.

SOURCE download

In. NET, a more convenient way to manipulate configuration items

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.