Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Programming Best Practices » Configuration Sections- Create a configuration section group and retrieve configuration information from it: Part IV

Configuration Sections- Create a configuration section group and retrieve configuration information from it: Part IV

In the previous article , we demonstrate how to create a custom section with custom attributes using the ConfigurationSection class and IConfigurationSectionHandler interface.

Author Rank :
Page Views : 20072
Downloads : 219
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ConfigurationSectionGroup.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

In the previous article
Part III , we demonstrate how to create a custom section with custom attributes using the ConfigurationSection class and IConfigurationSectionHandler interface. And our goal was to create a customized section that represents ports and enable developer rectify the listen ports after the application deployment. Assuming that we develop an enterprise planning resource for a given firm in witch an application F used by the financial department listens to the application A used by the account department. In the current article we will achieve the same goal with different manner, I mean; we will use a section group to set sections within the same characteristics.

Section group representation

It simply represents a group of specified sections within a configuration file, I mean, it is a group of sections container and this is very useful for organizational purposes, moreover, it avoids a certain naming conflicts. A section group has some arguments witch are:

Element Description
name The section group name, it is required to specify the name of the section group
type The section group type precise the configuration section group handler class, the assembly, the version, the culture and the public key token

Remember that in Part II article, we treated the case of none centralized information system, Imagine now a strongly centralized information system conforming to this hierarchy:



In such situation, the general department solution will listen to more than one application. The best manner to organize the ports sections is to group them in one section group instead of adding them separately. To achieve this goal we take the following steps:

  • Add the custom configuration class to the project.

public class PortSectionHandler : ConfigurationSection<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

{

    //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;} 

    }

}

  • Add the method that handles the configuration section group

private static void AddNewSectionGroup()

{

    /* 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 + "\\" + Application.ProductName + ".exe.config";

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

    // Create a configuration section group

    ConfigurationSectionGroup oSectionGroup = new ConfigurationSectionGroup();
 

    //This string array contains the departments names

    string[] Departement = { "Acount", "Financial", "Logistic", "Stocks", "Sales", "Technical" };

    /* As we are in not real case,we generate a serial port number using a random object*/

    Random oRandom = new Random();
 

    // Add the section group to the configuration object

    oConfiguration.SectionGroups.Add("Ports", oSectionGroup);
 

    //Create a new port section, do not initialise it

    PortsSectionHandler.PortSectionHandler oSection;
 

    //Five ports sections will be added

    for (int i = 0; i < 6; i++)

    {

        oSection = new PortsSectionHandler.PortSectionHandler();

        oSection.SectionName = "Port" + i.ToString();

        oSection.Key = Departement[i] + "_department";

        oSection.Serial = oRandom.Next(9000, 14000).ToString();

        oSection.SectionInformation.ForceSave = true;

        oSectionGroup.Sections.Add(oSection.SectionName, oSection);

    }
 

    //Save changes

    oConfiguration.Save(ConfigurationSaveMode.Full);

    MessageBox.Show("Ports section group is added");

    Application.Restart();

}

  • Call it from the code, switch to the configuration file and observe changes:

<?xml version="1.0" encoding="utf-8" ?>

<configuration><configSections>

<sectionGroup name="Ports" type="System.Configuration.ConfigurationSectionGroup,   System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" >

<section name="Port0" type="AppConfig.PortsSectionHandler.PortSectionHandler,

<section name="Port1" type="AppConfig.PortsSectionHandler.PortSectionHandler,

<section name="Port2" type="AppConfig.PortsSectionHandler.PortSectionHandler,
<
section name="Port3" type="
AppConfig.PortsSectionHandler.PortSectionHandler,
<
section name="Port4" type="AppConfig.PortsSectionHandler.PortSectionHandler,

<section name="Port5" type="AppConfig.PortsSectionHandler.PortSectionHandler,
</
sectionGroup></configSections>

  <Ports>

    <Port0 key="Acount_department" serial="13339" />

    <Port1 key="Financial_department" serial="9427" />

    <Port2 key="Logistic_department" serial="13420" />

    <Port3 key="Stocks_department" serial="12932" />

    <Port4 key="Sales_department" serial="11599" />

    <Port5 key="Technic_department" serial="13474" />

  </Ports>

</configuration>

Now, suppose that we want to retrieve information about a given port, the port 5 for example. We can do that using this method:

private static void RetriveKeySerial()

{

    /* 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 configuration section group and set is as follow don’t miss to cast it

    ConfigurationSectionGroup oSectionGroup = oConfiguration.GetSectionGroup(“Ports”) as ConfigurationSectionGroup;

    //Create a new port section handler object and set it as follow

    PortsSectionHandler.PortSectionHandler oSection = oSectionGroup.Sections[“Port5”] as PortsSectionHandler.PortSectionHandler;

    //Display targeted informations

    MessageBox.Show(oSection.Key);

    MessageBox.Show(oSection.Serial);

}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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 also holds:

MCPD enteprise solutions developement 3.5 certification and MCTS distibuted application developement 2.0

 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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Feedback by Saliya On January 25, 2010
nice work!!!
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.