Configuring Applications in VB.NET

Introduction

The .Net Framework provides a very convenient and flexible way to configure applications at run time. Using Configuration files developers and administrators can modify settings for applications without having to recompile the application, avoiding many of the redistribution/re-deployment hassles. For example, if you specify the connection string to be used for database connectivity to an application in the configuration files or an update path for the latest version, you will find configuration files make your application more adaptable. Configuration files contain settings for ASP.Net, built-in remoting channels, assembly binding, custom settings for applications, etc.

Configuration Files

Configuration files are XML files that contain the configuration settings. There are three types of configuration files as described below

  • Machine configuration file: The machine.config file contains settings that apply to the entire computer. This file is located in the %runtime install path%\Config directory. There is only one machine.config file on a computer.
     
  • Application Configuration file: The name of this file depends on the application's host. For ASP.Net applications, this file is called web.config and is located in the bin folder of the application root. An ASP.Net application can contain more than one web.config files at sub-directory level.

    For applications hosted by the executable host, the config file has the same name as the application, with a. config extension and is located in the same directory as the application. Internet Explorer hosted applications specify the name and location of the config file in a link tag.

  • Security Configuration file: These configuration files contain information about the code group hierarchy and permission sets for policy levels. There are three levels of security configuration files: Enterprise policy configuration file (Enterprisesec.config), Machine policy configuration file (Security.config) and User policy configuration file (Security.config). Note that you have to be extra careful while editing these files as changes might corrupt the security configurations.

In this article, we will focus on including custom settings in our machine.config or web.config configuration file.

Application-specific Custom Configuration Settings Using AppSettings

Step 1: Define and Specify:

Configuration files consists of section declarations and configuration settings. ASP.Net provides a default section "AppSettings" in the config file to allow for custom application settings. Shown below is the configuration section declaration for the AppSettings section in machine.config. Add the xml snippet for the configuration setting in the AppSetting node, after the <system.web> node and within the <configuration> node in the default web.config that is created by default in an ASP.Net project in Visual Studio:

<configuration>
<
configSections>
<
section name="appSettings"
type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</
configSections>
</
configuration>

XML Listing: Section of existing machine.config containing the declaration for the AppSettings Section (No changes required - this section is created by default)

(The PublicKeyToken value may vary on your machine)

Now we define a custom setting in the ASP.Net application's web.config file for the connection string to be used for database connections for our application. We add our custom setting in the AppSettings section. Shown below is the complete web.config after our modification.

<?xml version="1.0" encoding="utf-8" ?>
<
configuration>
<
system.web>
<
compilation defaultLanguage="VB" debug="true" />
<
customErrors mode="RemoteOnly" /> 
<authentication mode="Windows" /> 
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime"localOnly="true" />
<
sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false"timeout="20" />
<
globalization requestEncoding="utf-8" responseEncoding="utf-8" />
</
system.web>
<
appSettings>
<
add key="connstring" value="data source=dbserver;initialcatalog=DevelopmentDB;persist security info=False;user id=DBUser" />
</
appSettings>
</
configuration>

XML Listing: Modified web.config for adding custom settings in web.config. Add the code in bold to the web.config file created by default in your VS.Net application.

Step 2: Retrieve

We will now retrieve the configuration value at run-time the application in order to determine the settings to be applied. Following is the code to retrieve the value of the custom setting that was specified in the config file:

Dim strConn As String
strConn = ConfigurationSettings.AppSettings("connstring")
Try
sqlConnection1.ConnectionString = strConn
sqlConnection1.Open()
End Try
...

We need to import the namespace System.Configuration for this example. To retrieve the value of a configuration setting in the AppSettings section, we need a single line of code. The "ConfigurationSettings" object's static property "AppSettings" points to a NameValueCollection object which is indexed on the key name of the configuration.

Custom Sections in the web.config file

You are not restricted to using the predefined AppSettings section. Instead of using AppSettings, you can define your custom configuration section in the web.config file. 

Declaring a section defines a new element in the configuration file. 

Step 1: Define a Custom Section in the web.config file and specify the values within the newly defined section:

<?xml version="1.0" encoding="utf-8" ?>
<
configuration>
<
configSections>
<
section name="MyAppSection"
type="System.Configuration.SingleTagSectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</
configSections>
<
system.web>
<
compilation defaultLanguage="VB" debug="true" />
<
customErrors mode="RemoteOnly" /> 
<authentication mode="Windows" /> 
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime"localOnly="true" />
<
sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false" timeout="20"/>
<
globalization requestEncoding="utf-8" responseEncoding="utf-8" />
</
system.web>
<
appSettings>
<
add key="connstring" value="data source=dbserver;initialcatalog=DevelopmentDB;persist security info=False;user id=DBUser" />
</
appSettings>
<
MyAppSection ListLimit="1000" TableLimit="500" PageLimit="10" />
</
configuration>

XML Listing: Modified web.config for adding custom sections in web.config

The section declaration contains the section name and type. The section can be of type "SingleTagSectionHandler", "NameValueSectionHandler" or "DictionarySectionHandler". We will explore these different types a little later in this article.

The configSections node in the web.config XML configuration file listed above defines a custom configuration section called "MyAppSection". The PublicKeyToken varies on different machine and the best way to get the appropriate value is by searching in the existing machine.config file for a similar section handler. In this case, we can lookup the PublicKeyToken for an existing section of type SingleTagSectionHandler.

Step 2: Retrieve the configuration values in the application at run time.
...
...
Dim sampleTable As IDictionary = CType(ConfigurationSettings.GetConfig("MyAppSection"), IDictionary)
Dim strValue1 As String = CStr(sampleTable("ListLimit"))
Dim strValue2 As String = CStr(sampleTable("TableLimit"))
Dim strValue3 As String = CStr(sampleTable("PageLimit"))
...

Code Snippet: Retrieve values from custom section from web.config

The ConfigurationSettings object's static method "GetConfig" is used to retrieve the values of the custom section, which are typecast to the appropriate Collection class based on the configuration section declaration.

The child attributes and nodes you define depend on the Section Handler you use for the setting. Sections that are defined using the SingleTagSectionHandler class specify the configuration settings as key value pairs using XML Attributes. Section declarations using the NameValueSectionHandler class allow the configuration information to be specified as name value pairs in XML nodes. The DictionarySectionHandler is similar to the NameValueSectionHandler in storing the configuration information in the xml config file but returns the configuration information as a Dictionary object.

Shown below is the code xml snippet to define and specify a custom section using DictionarySectionHandler class

<configuration>
<
configSections>
<
section name="dictAppUpdate"
type="System.Configuration.DictionarySectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
</
configSections>
...
<dictAppUpdate>
<
add key="updatePath" value="f:\\"/>
</
dictAppUpdate>
...

</configuration>

XML Listing: Adding custom sections in web.config using DictionarySectionHandler class

Dim sampleTable As IDictionary = CType(ConfigurationSettings.GetConfig("dictAppUpdate"), IDictionary)
Dim strPath As String = CStr(sampleTable("updatePath"))

Code Lising: Retrieve the Value of the custom section defined using DictionarySectionHandler

We will view an example of a section defined using the NameValueSectionHandler class in the next part of the article. 

Sections Groups in the web.config file

Using Custom sections to define custom application settings helps in avoiding naming conflicts with other developers' section settings in a multi-user development environment or sytems integration projects. Here is the xml snippet to define the custom section and include the section in the configuration file. The technique is very similar to adding custom sections.

...
<
configSections>
<
sectionGroup name="myDepartmentGroup">
<
section name="mySection"
type="System.Configuration.NàmeValueSectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" />
</
sectionGroup>
</
configSections>
...
<myDepartmentGroup>
<
mySection>
<
add key="myKey" value="myKeyValue" />
</
mySection>
</
myDepartmentGroup>
...

XML Listing: Adding custom sections in web.config using DictionarySectionHandler class

Dim sampleConfig As NameValueCollection =CType(ConfigurationSettings.GetConfig("myDepartmentGroup/mySection"), NameValueCollection)
Dim strKeyValue As String = CStr(sampleConfig("myKey"))

Code Listing: Retrieve the Value of the configuration setting defined within a SectionGroup element.

Conclusion

The previous approach for specifying application settings was using registry values and global.asa file in ASP applications. This article discussed the alternatives available for specifying configuration values at run-time. This helps in the making the application configurable and allows administrators to customize the application as required for the environment.

Up Next
    Ebook Download
    View all
    Learn
    View all