Recipe 12.3. Adding Custom Application Settings in web.config


Problem

You have custom configuration information for your application that you would like to store in its web.config file.

Solution

Modify the web.config file for your application by adding an <appSettings> element to contain the custom configuration settings:

  1. Locate the web.config file in the root directory of your application (or create one if it does not already exist).

  2. Add an <appSettings> element.

  3. Add <add> child elements along with key/value pairs to the <appSettings> element as required.

  4. In the code-behind class for your ASP.NET page, use the .NET language of your choice to access the <appSettings> key/value collection through the ConfigurationManager object.

Examples 12-1, 12-2, 12-3 through 12-4 show the sample code we've written to implement this solution. Example 12-1 shows our web.config file with some key/value pairs. Example 12-2 shows the .aspx file for a web form that displays the configuration settings. Examples 12-3 (VB) and 12-4 (C#) show the code-behind class that accesses the configuration settings using the ConfigurationManager object.

Discussion

ASP.NET lets you add and then access configuration information specific to your application to the web.config file by means of a special <appSettings> element. You can add application configuration information by adding an <add> child element for each parameter, setting the key attribute to the name of the configuration parameter, and setting the value attribute to the value of the configuration parameter, as shown in Example 12-1.

The <appSettings> element is not a child of <system.web>, like some of the other web.config elements we discuss in this chapter. Rather, it is a subsection all its own within the <configuration> section.

When your application is started, ASP.NET creates a NameValueCollection from the key/value pairs in the <appSettings> section. You can access this NameValueCollection anywhere in your application through the ConfigurationManager object. Any data that can be represented as a string can be stored in the <appSettings> section, but anything other than a string will need to be cast to the appropriate data type for use in your application.

web.config allows any string for the value of a key/value pair. If the data is any nonstring data type, your code needs to include the appropriate exception handling for invalid data in the web.config file.


See Also

Recipe 12.6 for how to store an application's configuration information in its own custom section in web.config

Example 12-1. Application settings in web.config

 <?xml version="1.0"?> <configuration>   <appSettings> <!-- Keys/Values used in chapter 12 --> <add key="defaultSortField" value="Title" /> <add key="defaultSortOrder" value="Ascending" /> <add key="defaultResultsPerPage" value="25" />   </appSettings> </configuration> 

Example 12-2. Accessing application settings in web.config (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"   AutoEventWireup="false"   CodeFile="CH12GetAppSettingsVB.aspx.vb"   Inherits="ASPNetCookbook.VBExamples.CH12GetAppSettingsVB"   Title="Get Application Settings" %> <asp:Content  runat="server" ContentPlaceHolder>   <div align="center" >      Application Configuration In web.config (VB)   </div>   <table width="60%" align="center" border="0">     <tr>    <td >Sort Field: </td>    <td >       <asp:Label  Runat="server" /></td> </tr> <tr>        <td >Sort Order: </td>    <td >           <asp:Label  Runat="server" /></td> </tr> <tr>        <td >Number of Pages: </td>    <td >       <asp:Label  Runat="server" /></td> </tr>   </table> </asp:Content> 

Example 12-3. Accessing application settings in web.config code-behind (.vb)

 Option Explicit On Option Strict On Imports System Imports System.Configuration Namespace ASPNetCookbook.VBExamples  ''' <summary>  ''' This class provides the code behind for  ''' CH12GetAppSettingsVB.aspx  ''' </summary>  Partial Class CH12GetAppSettingsVB  Inherits System.Web.UI.Page  '''***********************************************************************  ''' <summary>  ''' This routine provides the event handler for the page load event. It  ''' is responsible for initializing the controls on the page.  ''' </summary>  '''  ''' <param name="sender">Set to the sender of the event</param>  ''' <param name="e">Set to the event arguments</param>  Private Sub Page_Load(ByVal sender As Object, _    ByVal e As System.EventArgs) Handles Me.Load    Dim resultsPerPage As Integer     'initialize labels on form from values in web.config     labSortField.Text = ConfigurationManager.AppSettings("defaultSortField")     labSortOrder.Text = ConfigurationManager.AppSettings("defaultSortOrder")     'get an integer value from web.config and do a little calculating     resultsPerPage = _       CInt(ConfigurationManager.AppSettings("defaultResultsPerPage"))     labNumberOfPages.Text = Math.Ceiling(1234.0 / resultsPerPage).ToString()   End Sub 'Page_Load  End Class 'CH12GetAppSettingsVB End Namespace 

Example 12-4. Accessing application settings in web.config code-behind (.cs)

 using System; using System.Configuration; namespace ASPNetCookbook.CSExamples {  /// <summary>  /// This class provides the code behind for  /// CH12GetAppSettingsCS.aspx  /// </summary>  public partial class CH12GetAppSettingsCS : System.Web.UI.Page  {   ///***********************************************************************   /// <summary>   /// This routine provides the event handler for the page load event.   /// It is responsible for initializing the controls on the page.   /// </summary>   ///   /// <param name="sender">Set to the sender of the event</param>   /// <param name="e">Set to the event arguments</param>   protected void Page_Load(object sender, EventArgs e)   { int resultsPerPage; // initialize labels on form from values in web.config labSortField.Text = ConfigurationManager.AppSettings["defaultSortField"]; labSortOrder.Text = ConfigurationManager.AppSettings["defaultSortOrder"];         // get an integer value from web.config and do a little calculating     resultsPerPage =    Convert.ToInt32(ConfigurationManager.AppSettings["defaultResultsPerPage"]);     labNumberOfPages.Text = Math.Ceiling(1234.0 / resultsPerPage).ToString();  } // Page_Load    } // CH12GetAppSettingsCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net