When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Friday, May 31, 2002

Specifying Configuration Settings in Web.config
By Scott Mitchell


Introduction
There are often times when you need to store some globally accessbile bit of information that will be used on (nearly) every page on the Web site. Ideally this bit of information would be stored once in some centralized repository rather than being replicated on each and every Web page. For example, a database connection string is one such bit of information. If such information is not stored in a centralized location, instead typed in by hand on every page that needs to connect to the database, imagine what a headache it would be if the connection string changed - you would have to go through each data-driven page on the site and make the needed changes!

- continued -

In classic ASP such global information was typically stored as an application variable. (Keep in mind it was never smart to store an open connection object in application scope, but storing the connection string is fine.) In ASP.NET there is still the notion of application variables, which can be accessed in the same fashion as they were in classic ASP. However, there's also the capability to specify application-wide settings in the Web.config file. In this article we'll examine how to specify application-wide settings in Web.config, and how to read such settings from an ASP.NET Web page. We'll also look at how to specify custom settings in Web.config.

What is Web.config
In classic ASP all Web site related information was stored in the metadata of IIS. This had the disadvantage that remote Web developers couldn't easily make Web-site configuration changes. If you host a Web site with a company you're probably aware of this; for example, if you want to add a custom 404 error page, a setting needs to be made through the IIS admin tool, and you're Web host will likely charge you a flat fee to do this for you. (For more information on creating custom 404 error pages in classic ASP, see: Creating a Custom 404 Error Page.)

With ASP.NET, however, these settings are moved into an XML-formatted text file (Web.config) that resides in the Web site's root directory. Through Web.config you can specify settings like custom 404 error pages, authentication and authorization settings for the Web site, compilation options for the ASP.NET Web pages, if tracing should be enabled, etc. For more on ASP.NET configuration, be sure to read: ASP.NET Configuration.

Specifying Application-Wide Settings in Web.config
The Web.config file, as aforementioned, is an XML-formatted file. At the root level is the <configuration> tag. Inside this tag you can add a number of other tags, the most common and useful one being the system.web tag, where you will specify most of the Web site configuration parameters. However, to specify application-wide settings you use the <appSettings> tag. Inside of this tag you can specify zero to many settings by using the <add ... /> tag. For example, if we wanted to add a database connection string parameter we could have a Web.config file like so:

<configuration>
  <!-- application specific settings -->
  <appSettings>
      <add key="connString" value="connection string" />
  </appSettings>

  <system.web>
     ...
  </system.web>
</configuration>

The above code adds an application-wide setting named connString with the connection string value provided by connection string. Now, in any of your ASP.NET Web pages in this Web site you can read the value of the connString parameter like so:

ConfigurationSettings.AppSettings("connString")

In fact, if you examine any one of the DataGrid demos from the previous article A Thorough Examination of the DataGrid, you'll see that they all use this technique when needing to make a connection to the database. Specifically, the code looks like:

Dim myConnection as New SqlConnection(ConfigurationSettings.AppSettings("connString"))

Specifying Classes of Application-Wide Settings
If you are creating a large ASP.NET application you may (wisely) decide to specify a number of Web master-adjustable properties as application-wide parameters. While you can use the appSettings tag as we have done in the article thus far, if you intend to sell this Web application or have it be used on other people's Web sites, placing such parameters in the appSettings tag may lead to problems. For example, imagine that you have a connection string parameter named connString that you want to let be configurable, so you create a key in the appSettings tag named connString, as we did above. Well, imagine that the person who's installing your application is trying to integrate with his already-existing Web site. She might already have such configuration settings, which means she'll have to change her setting and all the pages that reference it, to some name that doesn't conflict with any of your setting names.

Ideally you'd like not to present your end user with this headache. To avoid this complication you can "group" your application's settings into a unique tag in the Web.config file. That is, you can create a tag named: <MyAppSettings> in Web.config and then use the as we did earlier to add application-wide settings. To add a custom tag to Web.config you need to first explicitly specify the new tag name in Web.config via the <configSections> tag, like so:

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

   ...
</configuration>

Note that the value of the type attribute of the <section ... /> tag must all appear on one line... the line breaks are in there for better formatting.

This <section ... /> tag indicates that we are going to be adding a custom tag named MyAppSettings. Now we can add a <MyAppSettings> tag to our Web.config file and add <add ... /> tags to add application-wide parameters, like so:

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

  <MyAppSettings>
    <add key="connString" value="connection string" />
  </MyAppSettings>


   ...
</configuration>

Finally, to read this custom value from an ASP.NET Web page we use the following syntax:

ConfigurationSettings.GetConfig("MyAppSettings")("connString")

More generally, replace MyAppSettings with whatever name you chose to give your custom settings tag, and replace connString with whatever name of the parameter in the custom settings tag you wish to read. This way, when shipping your ASP.NET Web application, the person installing it won't run into any naming conflicts (unless, of course, they also have created a custom settings tag with the exact same name as you had chosen).

Creating Richer Custom Configuration Sections
Using a "group" of application settings works well to disambiguate your custom configuration settings from other application settings, but is limiting in the way that it only allows for scalar name/value pairs for configuration information. But what if your configuration information needs a collection of settings, where there may be an arbitrary number of values in the collection?

To enjoy a more readable and richer custom configuration experience you can create custom configuration sections in Web.config, resulting in configuration settings like the following:

<ScottsSettings
     message="Hello, World!"
     showMessageInBold="true">
   <favoriteColors>
      <color>Red</color>
      <color>Yellow</color>
      <color>Brown</color>
   </favoriteColors>
</ScottsSettings>

To accomplish this you need to create a couple of classes to model the configuration information and to pump the custom configuration markup to a method that deserializes it. For more information on this topic, see: Creating Custom Configuration Sections in Web.config.

Happy Programming!

  • By Scott Mitchell


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES