[Gadgets] use the "anemia model" of C # To quickly configure the component quickconfig

Source: Internet
Author: User

One thing that is inevitable for a program is to configure runtime .. NET platform native configuration is to use app. config. However, this configuration method is not very flexible and is a text file and is not suitable for storing sensitive information.

Many bloggers in the garden have published articles on "quick configuration files" using "serialization" and "deserialization. However, a simple implementation is provided and cannot be reused. Because I often encounter the problem of adding a configuration file to the software, I spent a little time creating a quickconfig component and sharing it with you. If there is something wrong with the code, you are welcome to point it out.

First, let's talk about the features of quickconfig:

  1. Anemia-based model: If your program already has a configuration file and an entity class for this configuration for ease of management, If you want quickconfig, you only need to make a few changes.
  2. Real-time configuration update: If you manually modify the configuration file when the software is running, the modification will be immediately reflected in the program.
  3. Supported by default configuration: a default value exists for any configuration, right?
  4. Configuration File Fault Tolerance: if the customer accidentally loses or breaks the configuration file, will the software be unable to run? No, no, no. The software can continue to run based on the default configuration.
  5. Easy configuration: you can read the configuration from the file at any time, save the configuration, or reset it to the default value. (Call the corresponding method ).
  6. Custom serialization mode: The component provides XML serialization by default. You can customize the serialization mode by yourself. For example, JSON.
  7. Configuration Encryption support: You can encrypt the configuration file by using custom serialization.
  8. Custom configuration file name: the configuration file is saved in the program running directory. By default, it is an XML file named after the full name of the configuration class. You can also customize the file name.

Is it a bit exciting? Let's start with an instance!

First, create a configuration entity. After defining the attributes, write the default configuration values in the constructor: (remember to add the serializable feature)

Appconfig. CS

1 [serializable] 2 public class appconfig 3 {4 Public appconfig () 5 {6 this. appname = "brain burst"; 7 This. updateinterval = 1; 8 This. mainwindowsize = new size (800,600); 9} 10 /// <summary> 11 /// Application name 12 /// </Summary> 13 Public String appname {Get; set;} 14 // <summary> 15 // Update Interval unit: 16 hours /// </Summary> 17 Public int32 updateinterval {Get; set ;} 18 /// <summary> 19 /// main form size 20 /// </Summary> 21 public size mainwindowsize {Get; set;} 22}

Introduce the quickconfig component to the project. All the preparations are complete, and then you can use them. How to use it? Very simple...

Program. CS

 1     class Program 2     { 3         static void Main(string[] args) 4         { 5             var cfm = QuickConfigManagement<AppConfig>.Create(); 6             Console.Write(cfm.ConfigModel.AppName); 7             Console.WriteLine(cfm.ConfigModel.MainWindowSize.ToString()); 8             Console.ReadLine(); 9         }10     }

Is it really easy? It's as simple as getting rid ?.. Hey, what's more amazing. We can use the quickconfigargumentattribute feature to set the file name and serialization method of the configuration file.

First, we first implement JSON serialization (implementing the iquickconfigprovider Interface) :( referencing JSON. net)

Jsonquickconfigprovider. CS

 1     public class JsonQuickConfigProvider : QuickConfig.IQuickConfigProvider 2     { 3         public Type ConfigType { get; set; } 4  5         public object Deserialize(System.IO.Stream stream) 6         { 7             JsonSerializer js = new JsonSerializer(); 8             return js.Deserialize(new System.IO.StreamReader(stream), this.ConfigType); 9         }10 11         public void Serialize(System.IO.Stream stream, object config)12         {13             JsonSerializer js = new JsonSerializer();14             var sw = new System.IO.StreamWriter(stream);15             js.Serialize(sw, config);16             sw.Flush();17         }18     }

Then, add the quickconfigargumentattribute feature to the appconfig class, which will be like this:

Appconfig. CS

1 [serializable] 2 [quickconfigargument ("config. JSON ", typeof (jsonquickconfigprovider)] 3 Public class appconfig 4 {5 Public appconfig () 6 {7 This. appname = "brain burst"; 8 This. updateinterval = 1; 9 this. mainwindowsize = new size (800,600); 10} 11 /// <summary> 12 // Application name 13 /// </Summary> 14 Public String appname {Get; set;} 15 // <summary> 16 // Update Interval unit: 17 hours /// </Summary> 18 public int32 updateinterval {Get; set ;} 19 /// <summary> 20 /// main form size 21 /// </Summary> 22 public size mainwindowsize {Get; set;} 23}

In this case, the program will generate a config. JSON file:

Now let's modify the code in program. CS so that it can continuously get the Configuration:

Program. CS

 1     class Program 2     { 3         static void Main(string[] args) 4         { 5             var cfm = QuickConfigManagement<AppConfig>.Create(); 6             while (true) 7             { 8                 Console.Write(cfm.ConfigModel.AppName); 9                 Console.WriteLine(cfm.ConfigModel.MainWindowSize.ToString());10                 var key = Console.ReadLine();11                 if (String.Equals(key, "exit")) break;12             }13         }14     }

Next, run the program:

Use Notepad ++ to open the config. JSON file. Modify the content:

We can see that we changed the value of appnamde to soar brain burst. Now, go back to the program and press Enter:

We can see that the value read by the program has been refreshed. (I promise you that the configuration file will not be read again every time you access the properties of the configuration object)

Let's try "reload" and "Restore Default Value:

Reload

1 class Program 2 {3 static void main (string [] ARGs) 4 {5 var CFM = quickconfigmanagement <appconfig>. create (); 6 console. writeline (CFM. configmodel. appname); // soar brain burst 7 CFM. configmodel. appname = "new app name"; // set the new value to 8 CFM. load (); // reload the configuration file 9 console. writeline (CFM. configmodel. appname); // soar brain burst10} 11}
Restore Default Value

1 class Program 2 {3 static void main (string [] ARGs) 4 {5 var CFM = quickconfigmanagement <appconfig>. create (); 6 console. writeline (CFM. configmodel. appname); // soar brain burst 7 CFM. reset (); // The default value is 8. writeline (CFM. configmodel. appname); // brain burst 9/* 10 * after calling reset, 11 * entity configurations are not written into the configuration file. 12 * To write a configuration file, you must call the Save method. 14 */15 CFM. Save (); 16} 17}

A sigh of relief. Finally. This is the first time I have shared my own components in my blog. If you have any comments, please submit them. Quickconfig is: http://files.cnblogs.com/Soar1991/QuickConfig.7z

For some reason, there are only components in the file, and there are no examples. Please try again. (* ^__ ^. If you like it, you can give us support. Thank you ~!

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.