Blue Theme Orange Theme Green Theme Red Theme
 
Dundas Dashboard
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting - 3 Month Free Hosting, Click Here!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Configuration Sections-Create a customized section using ConfigurationSection class: Part II

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

This article extends the custom configuration section concept.

Author Rank:
Technologies: .NET 1.0/1.1, XML,Visual C# .NET
Total downloads : 139
Total page views :  8129
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ConfigSection.zip
 
Become a Sponsor


Related EbooksTop Videos

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"


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Bechir Bejaoui
The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ConfigSection.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Nice Work by Patrick On January 8, 2009
I liked the thoroughness of the article. I posted a blog on custom ConfigurationSection classes myself, but didn't go into as much depth. Out of curiosity, do you see the need for IConfigurationSection anymore? Ever since ConfigurationSection came out with .NET 2.0, I never looked back to the manual XML parsing of the old interface.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved