C # Learning Diary 2017-02-14 configuration file AppConfig issues

Source: Internet
Author: User
Tags connectionstrings

problem Description : Read the value of a node in the AppConfig file and initialize some values using the values in the configuration file

Workaround: use ConfigurationManager's appsettings["a field name to get" method to get the value in the configuration file.

  private void Normalform_load (object sender, EventArgs e)
        {
            string workunitname = configurationmanager.appsettings["Workunitname"]. ToString (). Trim (); The work station uses
            string procedurename = configurationmanager.appsettings["ProcedureName"]. ToString (). Trim ()//operation
            Workunitno = configurationmanager.appsettings["Workunitno"]. ToString (). Trim (); Position code
            Procedureno = configurationmanager.appsettings["Procedureno"]. ToString (). Trim ()//Process code
            Tosslaboperater.text = "    operator:" + operatername;
            Tosslabstationno.text = "    Current work unit:" + workunitname;
            Tosslabcurrentprocedure.text = "    Current process:" + procedurename;
            Mshowchart ();    Statistics number of initial loading station
            mshowconfig ();//Determine if configuration button is displayed
        


Learning content:

1. You must refer to the System.Configuration namespace (DLL) when using the ConfigurationManager object, or you may receive an error that cannot be referenced. NET provides System.Configuration.dll, the classes provided under this namespace can easily be configured to read and write these parameters to an XML file.


2. Some of the configuration file-related classes:

ConfigurationManager: Opens the configuration file for the current program as a configuration object.

ConfigurationSection: Represents a Zone object in a configuration file.

ConfigurationElement: Represents an Element object in a configuration file.

ConfigurationElementCollection: A collection of configuration file element objects

3. You can add a profile directly to the application, click on the item-Add class-application configuration file-filename app.config xml file.


4.Section Zone: It is a child node outside the root node of the XML file, and it can have other child nodes and elements underneath it

Element elements: It is the most basic element in an XML file, and there is no other element underneath it.

Both of these elements can have attributes, and their properties are the tags within their XML.

[HTML] View plain copy on the code to see the snippet derived from my Code slice <?xml version= "1.0" encoding= "Utf-8"?> <configuration> ;configsections> <section name= "Section1" type= "Oracledataconverttxt.appsectiona, Oracledataconverttxt, Ve rsion=1.0.0.0, culture=neutral, publickeytoken=null "/> <section name=" Sectiona "type=" OracleDataConvertTx T.APPSECTIONB, Oracledataconverttxt, version=1.0.0.0, culture=neutral, publickeytoken=null "/> <section na Me= "Sectionb" type= "oracledataconverttxt.appsectionb, Oracledataconverttxt, version=1.0.0.0, Culture=neutral, Publickeytoken=null "/> </configSections> <appSettings> <add key=" Huangbo "value=" 1234567890 "/> </appSettings> <connectionStrings> <add name=" The name of the connection, which is similar to the key "Connec Tionstring= the name of the provider that is used with the connection string for the specific connection string "Providername=".  
      This can sometimes be without "/> </connectionStrings> <section1 keyname=" "Keyvalue=" ">  <appelement keyname= ' This is key ' keyvalue= ' This is value ' keyvalue2= ' This is value2 '/> </section1>  <sectiona keyname= "hahahaha" keyvalue= "1234567"/> <sectionb keyname= "This is key name" Keyvalue= " is key value > <ElementCollection> <add keyname= "E1 key" keyvalue= "E1 value" keyvalue 2= "E1 value2"/> <add keyname= "E2 key" keyvalue= "E2 value" keyvalue2= "E2 value2"/> & Lt;add keyname= "E3 key" Keyvalue= "E3 value" keyvalue2= "E3 value2"/> </ElementCollection> </se   Ctionb> </configuration>

5.

Structural analysis of general XML files:

1, the entire XML configuration file with the <?xml version= "1.0" encoding= "Utf-8"?> for the head declaration indicates that the version of the 1.0 character encoding for Utf-8
2, there is a root node <configuration>. All content must be in this root node.
3, there is a custom area of the declaration block <configSections>. All custom areas must be declared in this block.
4, there are two predefined regions <appSettings> and <connectionStrings>. They are. NET predefined areas, if they are not used, the two areas will not appear in the file.
5, a number of other custom areas such as above:<section1>, <sectiona>, <SectionB>. The label names for these zones must be consistent with the section name declared in the custom zone declaration.
6, in each custom area can have a number of child nodes, element collection, and basic elements.
7. All custom regions, collections, can have a number of properties, such as <sectiona keyname= "Hahahaha" keyvalue= "1234567"/> keyname= "Hahahaha" 1234567 "is a two attribute.
8. All elements under the custom area can have several properties, but must begin with the add identity, and the first property is a key value, and the key value cannot be the same in the same group of elements.
The element properties under 9, two predefined areas are fixed and no other attributes other than the specified attribute can appear.

7. Define each area collection, and element

Using System;  
Using System.Collections.Generic;  
Using System.Linq;  
Using System.Text;  
  
Using System.Configuration; Namespace Oracledataconverttxt {//appsectiona,appsectionb: Zone node class, in XML as a child node second to the root node.  
    Inherited from ConfigurationSection. Appelementcollection: An element collection class that is a child node under an area node in XML.  
    Inherited from ConfigurationElementCollection. Loadsettingselement: The element class, in XML, is a basic element.  
    Inherited from ConfigurationElement. Appsectiongroup: An area node collection class that is a set of regions in XML. Inherit from Configurationsectiongroupcollection public sealed class Appsectiona:configurationsection {//a simple appse  The Ctiona area contains only two attributes and a fixed element//First attribute [ConfigurationProperty ("KeyName", IsRequired = true)] Public  
            String KeyName {get {return (string) base["KeyName"];}  
        set {base["keyname"] = value;}  
        }//Second property [ConfigurationProperty ("keyvalue", IsRequired = True)] public string keyvalue {get {return (string) base["K"Eyvalue "];  
        set {base["keyvalue"] = value;} }//an element [ConfigurationProperty ("appelement", IsRequired = True)] public appelement Appeleme  
        NT {get {return (appelement) base["Appelement"];} } public sealed class Appsectionb:configurationsection {//complex a little appsectionb area, contains two properties and a acountelemen TCollection Elements Collection (the benefit of an element collection is that you can dynamically add and delete elements in a collection)//The first property [ConfigurationProperty ("KeyName", isrequired = True)  
            ] public string KeyName {get {return (string) base["KeyName"];}  
        set {base["keyname"] = value;}  
        }//Second property [ConfigurationProperty ("keyvalue", IsRequired = True)] public string keyvalue  
            {get {return (string) base["KeyValue"];}  
        set {base["keyvalue"] = value;} }//an element [ConfigurationProperty ("ElementCollection", IsreQuired = true]] public appelementcollection elementcollection {get {return (appelement Collection) base["ElementCollection"];  
    }} public sealed class Appelementcollection:configurationelementcollection {//define a APPELEMENTCOLLECTION element collection class//In fact, the key is the two indexers, but it is also called the implementation of the base class, just do the next type conversion on the line///These two indexers one is a string version, one is a digital version. Because these members are declared by the base class for protected purposes, these methods are exposed to external use. Indexers cannot be inherited, all to new new public appelement this[string name] {getting {return (appelement) BA Se. Baseget (name); //set can be set without setting.  
            Since it can be returned through get, it is OK to directly modify the returned objects, which are reference types. set {appelement app = ((appelement) baseget (name)); KeyName = value. KeyName; App. KeyValue = value. KeyValue; App. KeyValue2 = value. KeyValue2; } new public Appelement This[int index] {get {return (appelement) base. Baseget (index); //set can be set without setting. Because it can be returned through get, you can directly modify the returned objects, which are reference types。 set {appelement app = ((appelement) baseget (index)); app. KeyName = value. KeyName; App. KeyValue = value. KeyValue; App. KeyValue2 = value. KeyValue2;  
        The protected override ConfigurationElement Createnewelement () that must be implemented in the abstract class in the following two methods.              
        {return new appelement (); } protected Override Object Getelementkey (configurationelement Element) {return (Ap pelement) Element).  
        KeyName;  
            }//Description: If you do not need to modify the collection in your code, you may not implement Add,clear,remove public void Add (appelement setting) { This.  
        Baseadd (setting); public void Clear () {this.  
        Baseclear (); ConfigurationElement get (String keyname) {return this.  
        Baseget (KeyName); public void Remove (string keyname) {this.          Baseremove (KeyName);    
        } public sealed class Appelement:configurationelement {//This is the definition base This is the element class that has three properties, and the default first property for its Key,key value cannot be repeated [ConfigurationProperty ("KeyName", IsRequired = True)] public Strin G KeyName {get {return this["KeyName"]. ToString ();  
        set {base["keyname"] = value;}  
            [ConfigurationProperty ("keyvalue", IsRequired = False)] public string KeyValue { get {return this["KeyValue"]. ToString ();  
        set {this["keyvalue"] = value;}  
            [ConfigurationProperty ("KeyValue2", IsRequired = False)] public string KeyValue2 { get {return this["KeyValue2"]. ToString ();  
        set {this["KeyValue2"] = value;}   }  
    }  
  
}


8. Application in the procedure:


  private void Button1_Click (object sender, EventArgs e) {//Get a Configuration object Configuration cfg

            = Configurationmanager.openexeconfiguration (Configurationuserlevel.none); //--------------. NET provides two predefined areas AppSettings and connectionstrings-----------//using predefined AppSettings zone configuration nodes, adding elements inside, elements must be a keyvalue  
            The object of the ConfigurationElement class.  
            This object is a key, value pair.
            Keyvalueconfigurationelement Element = new Keyvalueconfigurationelement ("Huangbo", "1234567890"); Cfg.  APPSETTINGS.SETTINGS.ADD (Element); It can also be written directly as a cfg.              

            APPSETTINGS.SETTINGS.ADD ("Huangbo", "1234567890"); Using the predefined connectionstrings zone configuration node, add elements inside, the element must be an object of a connectionstringsettings class connectionstringsettings Constrs etting = new Connectionstringsettings ("Connection name, same as key", "specific connection string", "the name of the provider to use with the connection string.)
            This can sometimes be without "); Cfg.

            CONNECTIONSTRINGS.CONNECTIONSTRINGS.ADD (constrsetting); -------------The following is a custom area------------  

            Declare an area Section1 and add it to the CFG.
            Appsectiona Section1 = new Appsectiona (); Section1.
            Appelement.keyname = "This is key"; Section1.
            Appelement.keyvalue = "This is value"; Section1.
            Appelement.keyvalue2 = "This is value2"; Cfg.

            Sections.add ("Section1", Section1);  
            Declare an area Sectiona and add it to the CFG.
            Appsectionb Sectiona = new Appsectionb ();
            Sectiona.keyname = "Hahahaha";
            Sectiona.keyvalue = "1234567"; Cfg.

            Sections.add ("Sectiona", Sectiona);  
            Declare an area SECTIONB and add it to the CFG.
            Appsectionb sectionb = new Appsectionb ();
            Sectionb.keyname = "This is key name";
            Sectionb.keyvalue = "This is key value";
            Appelement e1 = new Appelement ();
            appelement e2 = new Appelement ();
            Appelement E3 = new Appelement (); E1.
            KeyName = "E1 key"; E1.
            KeyValue = "E1 value"; E1. KeyvaluE2 = "E1 value2"; E2.
            KeyName = "E2 key"; E2.
            KeyValue = "E2 value"; E2.
            KeyValue2 = "E2 value2"; E3.
            KeyName = "E3 key"; E3.
            KeyValue = "E3 value"; E3.
            KeyValue2 = "E3 value2";
            SECTIONB.ELEMENTCOLLECTION.ADD (E1);
            SECTIONB.ELEMENTCOLLECTION.ADD (E2);
            SECTIONB.ELEMENTCOLLECTION.ADD (E3); Cfg.

            Sections.add ("Sectionb", sectionb); Delete an element delete sectionb the first key value in the ElementCollection element set below is called the element of the E1 key. (The key value is the first property value of the element)//must be an element under ElementCollection to be deleted, because ElementCollection is a collection in which items in the collection can be deleted.  
            Elements that are directly below the zone cannot be deleted because they are defined as properties of the class.  

            SectionB.ElementCollection.Remove ("E1 key"); Deletes a region Sectiona//cfg.  

            Sections.remove ("Sectiona"); Updates an element//sectionb.elementcollection["E2 key"].  

            KeyValue = "E2 new value"; Writes the configuration of the configuration object cfg to the current XML file to the CFG.

            Save (); Refreshes the named node so thatIt will be read again from disk the next time it is retrieved.

            Configurationmanager.refreshsection ("sectionb");  
            Directly to the assigned value//appelement tmpelement = new Appelement (); Tmpelement.  
            KeyName = "Bob"; Tmpelement.  
            KeyValue = "Bobvalue"; Tmpelement.  
            KeyValue2 = "Bobvalue2"; Appsectionb appsection2 = cfg.  
            GetSection ("Sectionb") as APPSECTIONB; Appsection2.  
            elementcollection["E3 key"] = Tmpelement; Cfg.  



        Save ();  
         }





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.