Blue Theme Orange Theme Green Theme Red Theme
 
Ads by Lake Quincy Media
Home | Forums | Videos | Photos | Downloads | Blogs | 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
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » 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:
Total page views :  9678
Total downloads :  109
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ConfigurationSectionGroup.zip
 
Become a Sponsor

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);

}


Login to add your contents and source code to 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 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ConfigurationSectionGroup.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Feedback by Saliya On January 25, 2010
nice work!!!
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
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.