Recipe 12.6. Accessing Other web.config Configuration Elements


Problem

You want to be able to read application information from a web.config file that is unavailable as an <appSettings> key/value pair but present as an attribute or child element of some other element of the file.

Solution

Use the OpenWebConfiguration method of the WebConfigurationManager object to read the web.config file into a Configuration object, and use the GetSection method to access the desired section.

In the code-behind class for your ASP.NET page, use the .NET language of your choice to:

  1. Use the OpenWebConfiguration method of the WebConfigurationManager object to read the web.config file into a Configuration object.

  2. Use the GetSection method to access the desired section.

  3. Cast the returned ConfigurationSection object to the type of the object for the section being accessed.

  4. Use the properties of the object to access the desired information.

Examples 12-6, 12-7 through 12-8 show an application we've written that implements this solution and retrieves attribute settings from the <trace> element of a web.config file. Example 12-6 shows the .aspx file that displays the information. Examples 12-7 (VB) and 12-8 (C#) show the code-behind class for the page that does the work of reading the settings from the <trace> element.

Discussion

In ASP.NET 1.x, you had to resort to opening the web.config file using an XmlDocument object to access many of the configuration elements. In ASP.NET 2.0, new classes have been introduced to read and access web.config. The new classes provide the ability to change the contents of the configuration file and save it back to the filesystem. In addition, the new classes are strongly typed, which avoids the problem of storing data of the wrong type in the web.config file.

The first step is to open the web.config file by using the OpenWebConfiguration method of the WebConfigurationManager object. The relative path within your web site to the web.config file is passed to OpenWebConfiguration and a Configuration object containing the contents of the web.config file is returned.

 

Dim config As Configuration Dim path As String path = Request.ApplicationPath config = WebConfigurationManager.OpenWebConfiguration(path)

Configuration config = null; String path = null; path = Request.ApplicationPath; config = WebConfigurationManager.OpenWebConfiguration(path);

Any web.config file contained in your application can be accessed by passing the file's relative path to OpenWebConfiguration.


Next, use the GetSection method of the Configuration object to access the desired section. Since the GetSection method returns a ConfigurationSection object, you will need to cast it to the type of the section you are accessing. In our example, we are accessing the trace section, so we cast the ConfigurationSection object to a traceSection object. This allows us to access the data in the trace section using strongly typed properties.

 

Dim traceSettings As TraceSection traceSettings = CType(config.GetSection("system.web/trace"), _ TraceSection)

TraceSection traceSettings = null; traceSettings = (TraceSection)(config.GetSection("system.web/trace"));

Finally, use the properties of the object to access the desired information. In our example, we are displaying the values of a few of the attributes in the trace section.

 

labEnabled.Text = traceSettings.Enabled.ToString() labRequestLimit.Text = traceSettings.RequestLimit.ToString() labPageOutput.Text = traceSettings.PageOutput.ToString() labTraceMode.Text = traceSettings.TraceMode.ToString() labLocalOnly.Text = traceSettings.LocalOnly.ToString()

labEnabled.Text = traceSettings.Enabled.ToString(); labRequestLimit.Text = traceSettings.RequestLimit.ToString(); labPageOutput.Text = traceSettings.PageOutput.ToString(); labTraceMode.Text = traceSettings.TraceMode.ToString(); labLocalOnly.Text = traceSettings.LocalOnly.ToString();

If you need to modify the contents of the web.config file, you can change the values of the desired properties and use the Save method of the Configuration object:

 

traceSettings.Enabled = Not traceSettings.Enabled traceSettings.PageOutput = Not traceSettings.PageOutput config.Save()

traceSettings.Enabled = !traceSettings.Enabled; traceSettings.PageOutput = !traceSettings.PageOutput; config.Save();

You should not design your application to change the contents of the web.config file routinely. The reason is that changing the web.config file's contents may cause the application to restart. Restarting the application can lead to a significant delay for page requests and can cause undesirable effects for users when their sessions are restarted.


Example 12-6. Access system configuration information in web.config (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"   AutoEventWireup="false"   CodeFile="CH12AccessSystemConfigVB.aspx.vb"   Inherits="ASPNetCookbook.VBExamples.CH12AccessSystemConfigVB"   Title="Access web.config" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" >    Accessing System Configuration Information In web.config (VB) </div> <table width="40%" align="center" border="0">    <tr>       <td align="center"  colspan="2>      Trace Section Attributes   </td>    </tr>    <tr>   <td align="right" width="50%" >enabled = </td>   <td width="50%" >  <asp:Label  runat="server" />   </td>    </tr>    <tr>   <td align="right" >requestLimit = </td>   <td >      <asp:Label  runat="server" />   </td>    </tr>    <tr>   <td align="right" >pageOutput = </td>   <td >  <asp:Label  runat="server" />   </td>    </tr>    <tr>   <td align="right" >traceMode = </td>   <td >  <asp:Label  runat="server" />   </td>    </tr>    <tr>   <td align="right" >localOnly = </td>   <td >  <asp:Label  runat="server" />   </td>    </tr>    <tr>   <td align="center" colspan="2">  <br/>  <input  runat="server"    type="button" value="Toggle Enable"    onserverclick="btnToggleEnable_ServerClick" />   </td>    </tr>   </table> </asp:Content> 

Example 12-7. Access system configuration information in web.config code-behind (.vb)

 Option Explicit On Option Strict On Imports System Imports System.Configuration Imports System.Web.Configuration Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH12AccessSystemConfigVB.aspx ''' </summary> Partial Class CH12AccessSystemConfigVB   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 config As Configuration Dim traceSettings As TraceSection Dim path As String If (Not Page.IsPostBack) Then    path = Request.ApplicationPath    config = WebConfigurationManager.OpenWebConfiguration(path)    traceSettings = CType(config.GetSection("system.web/trace"), _      TraceSection)    initializeForm(traceSettings) End If  End Sub 'Page_Load    '''***********************************************************************  ''' <summary>  ''' This routine provides the event handler for the toggle enable button  ''' click event. It is responsible for toggling the trace enable state  ''' and updating the data in the web.config file.  ''' </summary>  '''  ''' <param name="sender">Set to the sender of the event</param>  ''' <param name="e">Set to the event arguments</param>  Protected Sub btnToggleEnable_ServerClick(ByVal sender As Object, _     ByVal e As System.EventArgs) Dim config As Configuration Dim traceSettings As TraceSection Dim path As String path = Request.ApplicationPath config = WebConfigurationManager.OpenWebConfiguration(path) traceSettings = CType(config.GetSection("system.web/trace"), _   TraceSection) traceSettings.Enabled = Not traceSettings.Enabled traceSettings.PageOutput = Not traceSettings.PageOutput config.Save() initializeForm(traceSettings)  End Sub 'btnToggleEnable_ServerClick    '''***********************************************************************  ''' <summary>  ''' This routine is responsible for displaying the initializing the  ''' controls on the form with the passed trace setting information  ''' </summary>  '''  ''' <param name="traceSettings">Set to the TraceSection information to  ''' be used to initialize the controls on the form  ''' </param>  Private Sub initializeForm(ByVal traceSettings As TraceSection) labEnabled.Text = traceSettings.Enabled.ToString() labRequestLimit.Text = traceSettings.RequestLimit.ToString() labPageOutput.Text = traceSettings.PageOutput.ToString() labTraceMode.Text = traceSettings.TraceMode.ToString() labLocalOnly.Text = traceSettings.LocalOnly.ToString()  End Sub 'initializeForm   End Class 'CH12AccessSystemConfigVB End Namespace 

Example 12-8. Access system configuration information in web.config code-behind (.cs)

 using System; using System.Configuration; using System.Web.Configuration; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH12AccessSystemConfigCS.aspx /// </summary> public partial class CH12AccessSystemConfigCS : 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)   {  Configuration config = null;  TraceSection traceSettings = null;  String path = null;  if (!Page.IsPostBack)  { path = Request.ApplicationPath; config = WebConfigurationManager.OpenWebConfiguration(path); traceSettings = (TraceSection)(config.GetSection("system.web/trace")); initializeForm(traceSettings); }  } // Page_Load  ///***********************************************************************  /// <summary>  /// This routine provides the event handler for the toggle enable button  /// click event. It is responsible for toggling the trace enable state  /// and updating the data in the web.config file.  /// </summary>  ///  /// <param name="sender">Set to the sender of the event</param>  /// <param name="e">Set to the event arguments</param>  protected void btnToggleEnable_ServerClick(Object sender,     EventArgs e)  { Configuration config = null; TraceSection traceSettings = null; String path = null; path = Request.ApplicationPath; config = WebConfigurationManager.OpenWebConfiguration(path); traceSettings = (TraceSection)(config.GetSection("system.web/trace")); traceSettings.Enabled = !traceSettings.Enabled; traceSettings.PageOutput = !traceSettings.PageOutput; config.Save(); initializeForm(traceSettings);  } // btnToggleEnable_ServerClick  ///***********************************************************************  /// <summary>  /// This routine is responsible for displaying the initializing the  /// controls on the form with the passed trace setting information  /// </summary>  ///  /// <param name="traceSettings">Set to the TraceSection information to  /// be used to initialize the controls on the form  /// </param>  private void initializeForm(TraceSection traceSettings)  { labEnabled.Text = traceSettings.Enabled.ToString(); labRequestLimit.Text = traceSettings.RequestLimit.ToString(); labPageOutput.Text = traceSettings.PageOutput.ToString(); labTraceMode.Text = traceSettings.TraceMode.ToString(); labLocalOnly.Text = traceSettings.LocalOnly.ToString();  } // initializeForm   } // CH12AccessSystemConfigCS } 



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

Similar book on Amazon

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