Configuration Sections-Create a customized section using ConfigurationSection class: Part II

Introduction:

This article extends the custom configuration section concept introduction. Therefore, it is strongly advised to read the previous article witch is "Part I: Introducing the custom configuration section concept" for well understanding purposes.

Suppose that the "Application F" is used by the financial department and the "Application A" is by the Account department as a part of the enterprise resource planning ERP. The first one listens to the second one. The listening procedure is done periodically for update operations purposes. Suddenly, the information system department decides to make some changes concerning the access privilege via some ports for a security issues, so that it will be not possible that F can listen to A. In this case, you have to rectify the port values from the F code source for each time the situation of access via this port is going to be changed. The second alternative is to convince the information department does not change the port access privilege so that F can listen to A without any interruptions. It is not practical at all to adopt such alternatives. In order to avoid this trouble, we can create a custom section in the application configuration file that enables us change parameters according to a given port at any time. There is two ways to do that. The first way is to define a custom section by extending it from the ConfigurationSection class witch is an abstract class and that means that it is not possible to define a direct instantiated object from it, in other means, it must be inherited. The second way is to use the IConfigurationSection interface witch is out of the scope of this part and witch constitutes the subject of a subsequent article.

Imagine that there is a partially centralized information system designed as follow:



This is a quick representation of the ConfigurationSection class witch constitute our section class handler:*

The class



The members



Step by step I will show how to deal:

  • Add a class to your project and name it PortsSectionHandler. Click Ok. Remember that each section element needs a section handler class to be set.
  • Replace class by namespace as shown bellow




  • Create a new section handler class by extending it from the Configuration section class. We assume that there are not other sub elements that should be added.
  • We consider that a port section has some attributes witch are:

    Key
    Serial

  • Add a new class within the namespace PortsSectionHandler and name it PortsSectionHandler

    public class PortSectionHandler : ConfigurationSection

    {}

As shown, this class inherits from Configuration section abstract class. The next step consists on adding two constructors and three properties to this above class.

public class PortSectionHandler : ConfigurationSection

{

    //First constructor

    public PortSectionHandler() { }

    //Second constructor

    public PortSectionHandler(string SectionName,string Key, string Serial)

    {

        this.SectionName = SectionName; this.Key = Key; this.Serial = Serial;

    }

    //First property: SectionName

    private string _SectionName;

    public string SectionName

    {
        get
      
 {
            return _SectionName;
        }
        
set
      
 {
            _SectionName = value;
        }
    }

    //Second property: The port Key

    [ConfigurationProperty("key", DefaultValue = "Account", IsRequired = true)]

    [StringValidator(InvalidCharacters = "|~!@#$%^&*()[]{}/;'\\",MinLength = 1)]

    public string Key

    {
       
get
   
    {
            return (string)this["key"];
        }

        set
        {
            this["key"] = value;
        }
    }

    //Third property: The port serial

    [ConfigurationProperty("serial", DefaultValue = "9000",IsRequired = true)]

    [StringValidator(InvalidCharacters = "|~!@#$%^&*()[]{}/;'\\", MinLength = 1)]

    public string Serial

    {
       
get
  
     {
            return this["serial"] as string;
        }
       
set
 
      {
            this["serial"] = value;
        }
    }
}

  • Switch to a form, for example the Form 1, view its code, add a method, name it AddNewSection( ) and implement it as bellow:

    private static void AddNewSection()

    {

        /* This code provides access to configuration files using OpenMappedExeConfiguration, method. You can use the OpenExeConfiguration method instead. For further informatons, consult the MSDN, it gives you more inforamtions about config files access methods*/           

        ExeConfigurationFileMap oConfigFile = new ExeConfigurationFileMap();

        oConfigFile.ExeConfigFilename = Application.StartupPath + "\\AppConfig.exe.config";

        Configuration oConfiguration = ConfigurationManager.OpenMappedExeConfiguration(oConfigFile, ConfigurationUserLevel.None); 

        //Define a new section handler

        PortsSectionHandler.PortSectionHandler oCostomSection;

        oCostomSection = new PortsSectionHandler.PortSectionHandler();

        if (oConfiguration.Sections[oCostomSection.SectionName] == null)

        {

            // Set its name

            oCostomSection.SectionName = "Port1";

              

            //Add it to the configuration's sections

            oConfiguration.Sections.Add(oCostomSection.SectionName, oCostomSection);

     

            //Save the given section in the configuration file

            oCostomSection.SectionInformation.ForceSave = true;

            oConfiguration.Save(ConfigurationSaveMode.Full);

               

            //The application should be restarted to visualize the new adding settings

            Application.Restart();

        }

    }

  • Call the method at the run time.

  • Open the Configuration file and observe the changes.

    <?
    xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections
    >
        <section name="Port1" type="F.PortsSectionHandler.PortSectionHandler, 
    F, 
                    
         Version=1.0.0.0,

                 Culture=neutral,

                 PublicKeyToken=null"

                 allowLocation="true"

                 allowExeDefinition="MachineToApplication"

                 restartOnExternalChanges="false"/>
    </configSections> 

      <Port1 key="Account" serial="9000"/>

    </configuration>

As we observe, the section parameters are added within the <configSections></configSections> tags with some precisions witch are:

Attribute Description
name="Port1" The name of the new customized section

type="F.PortsSectionHandler.PortSectionHandler,

             F,

             Version=1.0.0.0,

             Culture=neutral,

             PublicKeyToken=null"
The first element indicates the complete name of the section handler classThe second one indicates the assembly or the namespace in witch the configuration handler class is added. The third one indicates the culture and the last one indicates the public key token witch is null in our case.
allowLocation="true" This attribute indicate that the current section can be used within a location element.
allowExeDefinition="MachineToApplication This section can be configured in the application configuration file or in the machine configuration file.
restartOnExternalChanges="true" The application should not be restarted after any configuration changes.

In addition, the section attributes with default values are added outside of the <configuration></configSections tags witch are:

<Port1 key="Sales" serial="9000"/>

The attributes values are exactly the same as precised in the default value within the porperties attribute in section handler class.

We can add more elements according to this section programmatically by instantiating a new object from the section handler class, setting its values, adding it to the configuration sections collection and saving its changes by using the save method of the Configuration class.

We can add elements directly with manual manner in the configuration file it self, but don’t forget to give a distinct name to each section.

Now, we want to access to an existent section and retrieve its key and its serial programmatically, assume that we need them to configure the financial application, so we do as follow:

Create a new method and implement it as follow:

private static void GetSectionParameters()

{

    /* This code provides access to configuration files using OpenMappedExeConfiguration,method. You can use the OpenExeConfiguration method instead. For further informatons,consult the MSDN, it gives you more inforamtions about config files access methods*/

    ExeConfigurationFileMap oConfigFile = new ExeConfigurationFileMap();

    oConfigFile.ExeConfigFilename = Application.StartupPath + "\\AppConfig.exe.config";

    Configuration oConfiguration = ConfigurationManager.OpenMappedExeConfiguration(oConfigFile,ConfigurationUserLevel.None);

    /* create a PortSectionHandler object and use oConfiguration.GetSection method to get the targeted section  */

    try

    {

        PortsSectionHandler.PortSectionHandler oSection = oConfiguration.GetSection("Port1") as PortsSectionHandler.PortSectionHandler; 

        MessageBox.Show(oSection.Key);

        MessageBox.Show(oSection.Serial);

    } 

    // If there is not a corresponding section, then the exception is raised

    catch (NullReferenceException caught) { MessageBox.Show(caught.Message);
}

You can use the oSection.Key and oSection.Serial to configure the application settings. If the access privilege is changed from time to time, you simply access to the configuration file and change the given port attributes values and all things will be OK.

To know how to do the same thing but using the IConfigurationSection interface, please refer to the article which is
"Part III: Add and handle a customized configuration section using IConfigurationSection interface"


Similar Articles