Software Development

Working with configuration files in ASP.NET 2.0


The second iteration of ASP.NET includes a number of enhancements for working with configuration files. Configuration files include a variety of ASP.NET settings, as well as facilitate the use of custom data elements. While it isn't a difficult process to retrieve data values using ASP.NET 1.1, the improvements in 2.0 make it easier and add more features. I'll show you how to access data values stored in web.config files.

New approach

ASP.NET 2.0 introduced a number of improvements to the way data elements are stored and retrieved in configuration files. These improvements include several new configuration sections for the web.config file, along with a simplified approach to encrypting and decrypting data values stored in configuration files.

A major enhancement is the ability to develop and manage configuration data programmatically, so manually editing sometimes cryptic XML is no longer necessary. The configuration API provides this ability; it also includes a set of classes to interact with configuration files.

The base class

The configuration API's base class is the Configuration class. This class represents the merged view of the configuration settings that apply to a specific physical entity, such as a computer, or to a logical entity, such as an application or a Web site. If no configuration file exists, the Configuration class uses the default settings defined in the machine.config file.

The Configuration class includes two methods for accessing data contained in a configuration file by its section name: GetSection and GetSectionGroup. (A list of section names is available on MSDN.)

  • GetSection: Retrieves a configuration section by its name. It returns the specified ConfigurationSection object.
  • GetSectionGroup: Retrieves a ConfigurationSectionGroup object for the path specified.

The two methods allow you to specify the path to the section within the configuration file using XPath. For example, the following XPath expression returns the authentication section of a web.config file:

system.web/authentication

When working with ASP.NET applications, the WebConfigurationManager class is used. It includes open methods that return an instance of the Configuration class, which provides methods and properties for working with the files.

WebConfigurationManager class

The WebConfigurationManager class provides access to configuration files as they apply to Web applications. The class is contained in the System.Web.Configuration namespace. The class includes a number of classes that correspond to the pre-defined sections that may appear in the configuration file. Listing A includes a basic web.config for an ASP.NET project.

<?xml version="1.0"?>

<configuration>

<appSettings>

<add key="site" value="TechRepublic.com"/>

</appSettings>

<connectionStrings>

<add name="db" connectionString="connection details"/>

</connectionStrings>

<system.web>

<compilation debug="false" />

<authentication mode="Windows" />

<authorization>

<allow users="tester"/>

</authorization>

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">

<error statusCode="403" redirect="NoAccess.htm" />

<error statusCode="404" redirect="FileNotFound.htm" />

</customErrors>

</system.web>

</configuration>

The file includes the following standard sections: appSettings, connectionStrings, compilation, authentication, and customErrors. The WebConfigurationManager class includes methods for working with these sections as objects. The following list includes a subset of this list; you can see a more comprehensive list in the full details of the System.Web.Configuration namespace.

  • CustomErrorsSection: Provides access to the Custom Errors section of the web.config where error handling may be defined.
  • AuthenticationSection: Allows you to define how the applications handle the authentication of users.
  • AuthorizationSection: Allows and denies access to users or groups.
The C# code in Listing B accesses these sections and displays values form each.

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Web.Configuration" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void Page_Load(object sender, EventArgs e) {

AuthenticationSection asec;

AuthorizationSection auth;

CustomErrorsSection cerr;

asec = (AuthenticationSection) WebConfigurationManager.GetSection("system.web/authentication");

auth = (AuthorizationSection) WebConfigurationManager.GetSection("system.web/authorization");

cerr = WebConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;

if (asec != null) {

Response.Write("<br>Authentication Mode: " + asec.Mode.ToString());

}

if (auth != null) {

for (int i = 0; i < (auth.Rules.Count - 1); i++) {

Response.Write("<br>Customer Errors mode: " + auth.Rules[i].Action.ToString() + " - " + auth.Rules[i].Users.ToString());

} }

if (cerr != null) {

Response.Write("<br>Customer Errors mode: " + cerr.Mode.ToString());

} }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Configuration Class</title>

</head><body></body></html>

You can also access the new connectionString section added in ASP.NET 2.0 and the appSettings section, which allows you to store custom data elements. The ASP.NET page (which is written in C#) in Listing C accesses these sections and uses a couple of approaches. It accesses the connectionString using both its class (connectionStringSection) and directly using the index value of the connection string within the list in the configuration file.

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Web.Configuration" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void Page_Load(object sender, EventArgs e) {

ConnectionStringsSection connectionStringsSection = WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection;

string connString = WebConfigurationManager.ConnectionStrings["db"].ToString();

string dvalue = WebConfigurationManager.AppSettings["site"].ToString();

Response.Write("<br />Connection String: " + connectionStringsSection.ConnectionStrings[1].ToString());

Response.Write("<br />Connection String: " + connString);

Response.Write("<br />Site value: " + dvalue);

}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Configuration Class</title>

</head><body></body></html>

You can also access sections and their values as collections. The C# snippet in Listing D demonstrates looping through all values contained in the connectionString section.

ConnectionStringsSection cStringsSection = WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection;

ConnectionStringSettingsCollection cStrings = cStringsSection.ConnectionStrings;

IEnumerator cStringsEnum = cStrings.GetEnumerator();

int j = 0;

while (cStringsEnum.MoveNext()) {

string name = cStrings[j].Name;

Response.Write("<br>Name: " + name + " Value: " + cStrings[name]);

j += 1;

}

Conclusion

The ASP.NET web.config file makes it easy for developers to store application settings alongside the application. The improvements introduced in ASP.NET 2.0 simplify retrieval, storage, and encryption of configuration data. Although this article focuses on ASP.NET Web applications, all of the improvements introduced by the configuration API are available in Windows forms applications.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

---------------------------------------------------------------------------------------

Get weekly .NET tips in your inbox TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically subscribe today!

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

5 comments
pareshm
pareshm

useful article. Thanks!!

aspatton
aspatton

The other sections are accessible via the numerous methods. For example, the section name may be used with the GetSection method to access sections within the configuration file.