AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=705&pId=-1
Create and Use a Custom Config File
page
by Steven Archibald
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 43324/ 61

Background Information

When you create a web project in Visual Studio, a standard configuration file, named Web.config, is automatically created for you. This file is actually an XML document file. For a greater understanding regarding the format of this file, read the Microsoft reference titled Format of ASP.NET Configuration Files. If you want to store application-wide configuration information in an external file, such as an SQL Server connection string, it is usually recommended that you add an <appSettings> section to your Web.config file and store your information in this ‘additional’ section. This works well if the information is fairly static, and is not subject to change outside of your control.

One of my clients wanted to have some application-wide information available for their website, namely release information in text format, but did not wish to put it in the web.config file. They have a separate department that is responsible for doing builds and releasing them to QA and Production. The one thing this department wanted to do was to place a simple text file in the root web directory that any page could then have available. I suggested using a custom .config file, named Release.config. Below, I document what goes in this custom .config file and then how to access its values using a simple static method in a utility class.

Most samples of custom application configuration processing that you find on the web document how to add sections to an existing Web.config file. That particular solution was not appropriate here since the department responsible for producing the information was not a development department.

The steps are fairly simple:

  1. Create our own custom .config file which is itself an XML document.
  2. Modify the standard Web.config file to reference our custom .config file.
  3. Create a utility method to extract the desired values from the custom .config file.
  4. Modify our application code to utilize the utility method.
Create the Custom .config File

We’ll name the custom file Release.config. It will be placed in the same directory in which the standard Web.config file is found. The structure of this XML document is simple. The root element of this document is simply a name of a section that we will add to the standard Web.config file, following some rules described below. The name doesn’t really matter--we make it up. It would be nice to have it reflect the data and purpose of the section. We’ll call our section appReleaseSection.  It is within this element that we add the code to define the names of our data elements and their values.

Listing 1 -The Custom .config File

<?xml version="1.0" encoding="utf-8" ?>
<appReleaseSection>
      <add key="ReleaseNumber" value="10.01.12.09" />
      <add key="ReleaseDate" value="08/03/2005" />
</appReleaseSection>

Seems simple so far. Note that we are using the same simple <add key> mechanism used in the normal <appSettings> section of the standard Web.config file. That means we can use the same handler in the next step.

Change the Standard Web.config File

We need to modify Web.config in two different areas; near the top, and near the bottom.

Listing 2 – Change the Top Area

<?xml version="1.0" encoding="utf-8" ?>
<configSections>
 <section name="appReleaseSection" type="System.Configuration.NameValueFileSectionHandler, 
 System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</configSections>

Note that this code goes between the <configuration> opening tag and the <system.web> opening tag. You really do need all the gobbledy-gook in the type attribute. I’ve tried taking parts of it out, and it just stops working without it. Note that here we are referencing the NameValueFileSectionHandler alluded to earlier. There is a useful Microsoft reference on creating new configuration sections that you should take a moment to read. The most useful part of this reference is how to use the same configuration section handler that is used for the <appSettings> section. That is what we are doing here. The tag <section> above was merely lifted from similar code. The code sample in the link has some additional section tags that aren’t required, so I’ve eliminated them. You can also create your own IConfigurationSectionHandler object, but it’s just simpler to use one that already exists, particularly since our data is so simple.

If you are not familiar where to locate the Version, Culture, and PublicKeyToken values for the NameValueFileSectionHandler, all you have to do is look at the machine.config file on server.

The following code goes just below the closing </appSettings> or </system.web> depending on whether you have an <appSettings> section or not. In my example, we do.

Listing 3 – Change the Bottom Area

</appSettings>
<appReleaseSection file="Release.config">
</appReleaseSection>

Note that the file attribute is a relative path assignment. You can probably place your custom file lower down from the root, say in a special "config" directory if you want to be clever, but this suffices for the example.

Create a Static Utility Method to Extract the Values

I have a utility class, cleverly named Utility.cs, that is present in all my websites. I’ll present a sample as though this were the only method in the class (don’t want to give away too many secrets all at once, eh?). In my example, I exclude the constructor and remove some tabs to conserve valuable web page space and protect the environment.

Listing 4 – The utility method

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;


namespace MyWebSite
{
public class Utility
{
      public static string GetCustomConfigValue(string SectionName,string KeyName)
      {
  NameValueCollection myData = (NameValueCollection)
  System.Configuration.ConfigurationSettings.


  GetConfig(SectionName);


    if (myData == null)
   {
    throw(new NullReferenceException("Section Name not found: " + SectionName));
            }
            string myValue = myData.Get(KeyName);


            if (myValue == null)
            {
                  throw(new NullReferenceException("Key Name not found: " + KeyName));
            }
            return myValue;
      }
}

Note that we are raising exceptions here. It’s recommended, but you could just return a value like “Key name not found” so you present some value that indicates to you (when you are testing) that something didn’t work. Note the System namespaces imported at the top of the file. You need them.

Now, we go get those valuable little puppies of information!

Retrieving Our Valuable Data

To demonstrate retrieving the separated information, create a new webform named TestNewConfigurationFile. I could have used a longer name, but brevity is considered a virtue. Don’t bother to put any controls on it.

Enter the following code in the Page_Load method of your .aspx.cs file.

Listing 5 – The Web Form Code

private void Page_Load(object sender, System.EventArgs e)
{
      string myNumber = Utility.GetCustomConfigValue("appReleaseSection", "ReleaseNumber");
      string myDate = Utility.GetCustomConfigValue("appReleaseSection", "ReleaseDate");
      Response.Write("Release: " + myNumber + "<br />Date: " + myDate);
}

Build and run!

Bing, Bam, Boom – we be done!

Benefits

This methodology provides several benefits:

  1. We are using standard .NET configuration processing for custom work.
  2. It probably meets “Best Practices” standards.
  3. It is extremely simple to add new custom configuration files and data in the future.
  4. By having the section name as a parameter of our utility method, we don’t have to write methods for each new file in the future.
Caveats & Limitations

The biggest limitation is we are limited to using the name/value pair type of data in our custom configuration file. One work-around would be to have the utility method figure out what type of handler was expected for the section name. Another is to have a separate method for each section name, i.e., custom .config file. I’ll leave those exercises to the clever reader. Finally, take the time to read the following Microsoft dissertation the format of ASP.NET configuration files.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 12:02:53 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search