devxlogo

Configuration API Improvements in ASP.NET 2.0

Configuration API Improvements in ASP.NET 2.0

icrosoft has greatly enhanced the management tasks for your .NET 2.0 applications by providing a set of configuration APIs that you can use to programmatically access, modify, and save the configuration of an application using minimal code. This article explores the new and enhanced configuration API that ships with .NET Framework 2.0 by providing examples on how to use them from an ASP.NET Web application.

Introducing the ConfigurationManager Class
One important new configuration-related class is the ConfigurationManager class, which provides seamless programmatic access to configuration files and configuration sections. Using the methods and properties of this class, you can open configuration files and retrieve configuration sections from within your application. The ConfigurationMangager class’s major functionality falls into three categories.

  • Quick access to the appSettings and connectionStrings sections of the current application’s default configuration file, which you access through properties such as AppSettings and ConnectionStrings.
  • Access to a specific configuration section from the current application’s default configuration file, using methods such as GetSection, GetWebAppSection, and RefreshSection.
  • The ability to open different types of configuration files such as .exe.config, machine.config, and web.config so you can update them programmatically through methods such as OpenMachineConfiguration, OpenMappedMachineConfiguration, OpenExeConfiguration, OpenMappedExeConfiguration, OpenWebConfiguration, and OpenMappedWebConfiguration.

You’ll see examples of all of these ConfigurationManager class capabilities. Table 1 shows the most important methods and properties of the class.

Author’s Note: For all the examples shown in this article, the ASP.NET process account needs sufficient permissions to be able to read and write into the specified configuration file. For simplicity, to run the samples, enable Integrated Windows authentication through IIS and enable impersonation at the Web site level using the following configuration settings under the element in the web.config file.

Table 1. ConfigurationManager Properties and Methods: The table shows some important properties and methods of the Configuration Manager class.

PropertyMethod

Description

AppSettings

This property gets the appropriate data from the section of the current application’s configuration file.

ConnectionStrings

This property gets the appropriate data from the section of the current application’s configuration file.

OpenExeConfiguration

This property opens the specified client configuration file as a configuration object.

OpenMachineConfiguration>

This property opens the specified machine configuration file as a configuration object.

OpenWebConfiguration

This property opens the specified Web application’s configuration file as a configuration object.

RefreshSection

This method allows you to refresh the named configuration section so that it is retrieved from the configuration file next time.

Retrieving Connection Strings
One of the most common questions ASP.NET developers have is how and where to store connection strings. .NET 2.0 introduces a new configuration section called that lets you store connection strings securely in a .NET application. This section will show you how to read the connection string that is stored inside the section in a web.config file.

First, you need to prepare your web.config file. For example, here’s a portion of a web.config that contains a entry.

   

The following code retrieves that connection string from the web.config file using the ConnectionStrings property of the ConfigurationManager class. Then it simply displays the retrieved connection string in the browser using the Response.Write statement. Here’s the code:

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

Encrypting and Decrypting Connection Strings
Keeping unencrypted connection strings in your web.config file isn’t ideal. Fortunately, in addition to reading connection strings from a configuration file, you can also use the Configuration APIs to encrypt individual sections so that confidential information such as connections to your databases are not stored in plain text. To encrypt a configuration section, you invoke the ProtectSection() method of the SectionInformation object.

The NET 2.0 Framework ships with two types of providers: DataProtectionConfigurationProvider and RSAProtectedConfigurationProvider. You supply the ProtectSection() method with the encryption algorithm to use. The example shown in Listing 1 uses the built-in DataProtectionConfigurationProvider, and displays a form containing two buttons that you can use to encrypt or decrypt the connection string stored in the web.config file.

Before viewing the output of Listing 1 in a browser, place the following connection string section in your web.config file.

    

As you can see from Listing 1, you can access the configuration file for any location in the config hierarchy using the ConfigurationManager’s OpenWebConfiguration method, passing a virtual path to retrieve the configuration file for that location. The method returns a Configuration object that you can use to view the combined configuration (inherited across all configuration files starting from machine.config file) for that location. You use the SectionInformation class to access, protect (encrypt), and unprotect (decrypt) specific sections. Table 2 shows the important methods and properties of the SectionInformation class.

Table 2. SectionInformation Properties and Methods: The table shows some important properties and methods of the SectionInformation class

Property or Method

Description

GetRawXml

This method returns an XML node object containing the XML representation for the associated configuration section object.

ProtectSection

This method encrypts a specific configuration section by using the supplied provider.

UnProtectSection

This method decrypts a specific configuration section that is already encrypted using the ProtectSection method

IsProtected

This property returns a value indicating whether the associated configuration section is locked.

Name

This property returns the name of the configuration section.

SectionName

This property returns the name of the associated configuration section.

When you run the code in Listing 1 and click on the Encrypt button (see Figure 1), you’ll find that it modifies the web.config file, adding a section named protectedData as shown below.

                       AQA------------          FnvpHa1iy4Oww=         
Figure 1. Output Produced by Clicking the Encrypt Button: When you click the Encrypt button, the application encrypts the connection string from the web.config, then retrieves and decrypts it and displays the decrypted string in the browser.

Clicking the Encrypt button also results in the connection string being displayed in the page. This is shown in Figure 1. Note that even though the connection string is encrypted in the web.config file, when you retrieve the connection string programmatically, ASP.NET automatically does the decryption for you.

In Listing 1, note that the UnProtectSection() method, unlike ProtectSection(), does not require a provider name. When a section is encrypted, ProtectSection () stores information regarding the provider used to perform the encryption in the web.config file. You can see information about the provider from the web.config file entries shown above. The UnProtectSection() method uses that information to determine which provider to use to decrypt the data.

When you click on the Decrypt button shown in Figure 1, you’ll see a message indicating that the connection string is decrypted and stored in the web.config file.

Enumerating Stored Connection Strings
You’re not limited to interacting with single entries in web.config sections; you can enumerate the contents of any specific section in a configuration file. The following example shows you how to enumerate the built-in connectionStrings section by looping through all the connection strings stored in that section.

Like the previous examples, this example also uses the OpenWebConfiguration() method of the ConfigurationManager class to get a reference to the configuration element in the web.config file. Having done that, you can then easily get a reference to the connectionStrings section through the ConnectionStrings property of the Configuration object. The following example uses a foreach loop, to enumerate all the connection strings in that section and write them to a browser one at a time.

 <%@ Import Namespace="System.Configuration" %><%@ Import Namespace="System.Web.Configuration" %>  Enumerating Configuration Settings  
Figure 2 Enumerating Connection Strings: The figure shows the result of enumerating all the connection strings in a web.config file and writing them to a browser.

When you navigate to the page created by that code from a browser you’ll see the output shown in Figure 2.

Adding Custom Configuration Sections
There are times where you may have to programmatically create a custom section and add it to a configuration file at runtime. For example, modifying configuration files programmatically is useful if you are creating a Windows installer for deploying a Web application and you need to create sections of the web.config file dynamically. You can do this by going through the following steps:

  • Create a custom class that derives from the ConfigurationSection class. This class represents the custom section you want to add to the configuration file.
  • Populate that object with the right values.
  • Add the custom object to the ConfigurationSectionCollection using the Add() method.
  • Persist the configuration changes by calling the Save() method of the Configuration class.

The following code shows an implementation of a custom class that represents a custom section in the Configuration file.

 using System.Configuration;public class CustomSection : ConfigurationSection{   public CustomSection()   {   }	   [ConfigurationProperty("name",       RequiredValue = true,       DefaultValue = "")]   public string Name   {      get      {         return (string)base["name"];      }      set      {         base["name"] = value;      }   }} 

As you can see the preceding code, implementing such a custom class is very simple and straightforward. The custom class inherits from the ConfigurationSection class and exposes a Name property decorated with the ConfigurationProperty attribute. The ConfigurationProperty class represents a configuration property, attribute, or child element contained within an element of a configuration file. You supply the name of the attribute as an argument (which is “name,” in this example) to the constructor of the ConfigurationProperty class, as well as a Boolean value indicating whether the attribute is required and the default value for that attribute.

Now that you have seen the implementation of the custom class, Listing 2 demonstrates how to serialize the contents of a custom class to a web.config file.

Just like the previous examples, you start by obtaining a reference to the web.config file. Then you create an instance of the CustomSection class. If you want to replace any existing custom configuration sections, you can use the Clear() method, as the preceding code does, which erases all of the custom configuration sections currently in the file. To store the modifications to disk, invoke the Save() method. The rest of the code in Listing 2 verifies whether the newly added section is actually present in the configuration file by looping through all the sections using the AllKeys property. While looping through the collection, if it finds a section named “CustomSection,” the code simply displays a message indicating that the section was found.

ASP.NET contains many architectural enhancements designed to improve the manageability of deployed applications. For example, now that you can programmatically modify a configuration file using native .NET class methods, you write interfaces that let administrators modify configuration files easily and safely. In addition, the new features let you create sophisticated installers that can do everything from creating configuration files at deployment time to encrypting connection strings at runtime.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist