Customizing SectionGroups and Sections in Web.config






2.77/5 (21 votes)
Jun 2, 2004

128319

645
To add our own SectionGroups and Sections in the Configuration sections of web.config.
Introduction
This article deals with how to customize web.config file in our application.
Already, we have facility to access Appsettings
in web.config. In certain situations, we need to declare our own SectionGroup
s and Section
s in web.config depending upon our application's needs. This will help the developer to access these values from the section
s across the application.
Here, I have created two Section
s under one SectionGroup
.
Hope this article will help whenever you want to handle SectionGroup
s in your web.config.
Code
'write the following in the web.config
<configuration>
<configSections>
<!--Config section Group and Sections Declaration-->
<sectionGroup name="Company">
<section name="AssociatedCompany"
type="System.Configuration.NameValueSectionHandler,System"/>
<section name="Subsidiary"
type="System.Configuration.NameValueSectionHandler,System"/>
</sectionGroup>
</configSections>
.
.
.
.
.
.
<!--This For Section Declaration-->
<Company>
<AssociatedCompany>
<add key="A1" value="AWCompany"/>
<add key="A2" value="AXCompany"/>
<add key="A3" value="AYCompany"/>
<add key="A4" value="AZWCompany"/>
</AssociatedCompany>
<Subsidiary>
<add key="S1" value="AWCompany"/>
<add key="S2" value="AXCompany"/>
<add key="S3" value="AYCompany"/>
<add key="S4" value="AZWCompany"/>
</Subsidiary>
</Company>
</configuration>
Now, write the following into the code behind (VB):
Imports System.Collections.Specialized
'This Code will populate the Company Details into dropdownlist
Dim config As New NameValueCollection
'Getting Associated Company code from web.config
config = ConfigurationSettings.GetConfig("Company/AssociatedCompany")
If Not IsNothing(config) Then
Dim inKeyCnt As Integer
'Loop to populate all the company code in the dropdown list
For inKeyCnt = 0 To config.Keys.Count - 1
'DropDown List ID is ddlAssociation
ddlAssociation.Items.Add(config(inKeyCnt).ToString)
Next
End If
'Similary for Subsidiary also.
Note: if you' get any error while calling GetCOnfig()
function then provide the public key and version in the Section
declaration of web.config. Check the public key and version information from your machine.config file in your framework. For example:
<section name="AssociatedCompany"
type="System.Configuration.NameValueSectionHandler,
System,Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"/>
<section name="Subsidiary"
type="System.Configuration.NameValueSectionHandler,
System,Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"/>
Drop me, in case if you have, any suggestions.
Thank you once again.