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. 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 <system.web> element in the web.config file. |
|
Property\Method |
Description |
|
AppSettings |
This property gets the appropriate data from the <appSettings> section of the current application's configuration file. |
|
ConnectionStrings |
This property gets the appropriate data from the <ConnectionStrings> 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. |
<connectionStrings>
<add name="pubs"
connectionString="localhost;integrated
security=true;database=pubs;" />
</connectionStrings>
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" %>
<script runat=server language=C# >
public void Page_Load(object source,
EventArgs e)
{
Response.Write("Connection String:"
+ ConfigurationManager.
ConnectionStrings["pubs"].
ConnectionString);
}
</script>
<html>
<head>
<title>Retrieving Connection Strings</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
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.
<connectionStrings>
<add name="pubs"
connectionString="localhost;integrated
security=true;database=pubs;" />
</connectionStrings>
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. |
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. |
<protectedData>
<protectedDataSections>
<add name="connectionStrings"
provider="DataProtectionConfigurationProvider"
inheritedByChildren="False"/>
</protectedDataSections>
</protectedData>
<connectionStrings>
<EncryptedData>
<CipherData>
<CipherValue>AQA------------
FnvpHa1iy4Oww=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
![]() | |
| 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. |
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" %>
<script runat=server language=C# >
public void Page_Load(object source,
EventArgs e)
{
Configuration config =
ConfigurationManager.OpenWebConfiguration(
Request.ApplicationPath, "Configuration");
//Enumerate the connection strings
//and display them
Response.Write("<b>Connection " +
"strings in Web.config:</b><br>");
foreach (ConnectionStringSettings connection in
config.ConnectionStrings.ConnectionStrings)
{
Response.Write("Name: " +
connection.Name + "<br>");
Response.Write("Connection String: " +
connection.ConnectionString + "<br><br>");
}
}
</script>
<html>
<head>
<title>Enumerating Configuration Settings</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
![]() | |
| 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. |
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.
| DevX is a division of Internet.com. © Copyright 2010 Internet.com. All Rights Reserved. Legal Notices |