Поделиться через


Changing Configuration in External File Example

You can use an external configuration file to extend application configuration settings and to control whether state information is preserved when those settings change, by enabling or disabling the application restart functionality. This is controlled by the restartOnExternalChanges attribute, which is applied to different configuration file sections.

Sample Web Application Files

The following sections include the code to build a sample Web application with a custom section whose configSource attribute points to an external configuration file and whose restartOnExternalChanges attribute is initially set to true.

Running the Web application shows what happens to a global postback counter when changes are made to the external configuration file, and the provided code example demonstrates what happens when restartOnExternalChanges is set to true, set to the default value, and set to false, respectively.

Global.asax

The sample Web application must include this Global.asax page. The following code example defines the page with a global postback counter. The counter keeps track of the postback requests generated by refreshing the application's Default.aspx page (defined later in this topic).

' Code that runs on application startup.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) 
    
    ' This counter is set to 0 the first time 
    ' the application starts and, thereafter, every 
    ' time it restarts.
    Dim postBackCount As Integer = 0
    
    Dim appState As HttpApplicationState = Application.Contents
    appState.Add("postBackKey", postBackCount)

End Sub 'Application_Start
// Code that runs on application startup.
void Application_Start(object sender, EventArgs e) 
{
       
        // This counter is set to 0 the first time 
        // the application starts and, thereafter, every 
        // time it restarts.
        int postBackCount = 0;
        
        HttpApplicationState appState = Application.Contents;
        appState.Add("postBackKey", postBackCount);
        
}

Default.aspx

The Default.aspx page contains code that creates the custom section in the Web.config file, adds an element to the External.config file, and displays the postback counter value. Note that the page must contain a Label control to display the postback counter's current value. The following code example shows one possible way to define this control.

<asp:Label ID="ResultId" runat="server" style="font-weight:bold; color:Red;"/>

The following code example defines the Default.aspx page.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 
        Dim extConfig As ExternalConfiguration = Nothing
        
        If Not IsPostBack Then
            ' Create an instance of the custom section.
            extConfig = New ExternalConfiguration()
        End If
                
        Dim postBackCount As Integer = _
        Fix(HttpContext.Current.Application("postBackKey"))
        'Display current counter value.
        ResultId.Text = postBackCount.ToString()
        
        HttpContext.Current.Application("postBackKey") = _
        Fix(HttpContext.Current.Application("postBackKey")) + 1
        
        extConfig.UpdateAppSettngs()
End Sub 'Page_Load
protected void Page_Load(object sender, EventArgs e)
{
        ExternalConfiguration extConfig = null;
        
        if (!IsPostBack)
        {
            // Create an instance of the cusom section.
            extConfig =
                new ExternalConfiguration();
        }

        int postBackCount =
           (int) HttpContext.Current.Application["postBackKey"];
        ResultId.Text = postBackCount.ToString();

        HttpContext.Current.Application["postBackKey"] =
            (int)HttpContext.Current.Application["postBackKey"] + 1;
 
        extConfig.UpdateAppSettngs();
}

Web.config

The Web.config file defines the MyAppSettings custom section, as shown in the following code example. This example uses the standard type to process this section, but you can create your own type. For details, see ConfigurationElement and ConfigurationSection.

<section 
    name="MyAppSettings" 
    type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
    restartOnExternalChanges="true" 
    requirePermission="false" />

External.config

The External.config file contains the details of the MyAppSettings custom section. Before you run the application for the first time, you must create this file manually in the application root directory. For more information, see the configSource attribute in General Attributes Inherited by Section Elements. For this example, make sure that your code contains the following empty section.

<MyAppSettings></ MyAppSettings>.

ExternalConfiguration.dll

The ExternalConfiguration.dll file contains the code that updates the MyAppSettings custom section. You can place your source code in the App_Code directory of your application. The example will be compiled by ASP.NET when your application is requested. You can also compile the sample provider as a library and place it in the Bin directory of your Web application. The following code example shows how to compile the sample from the command line.

vbc /out: ExternalConfiguration.dll /t:library ExternalConfiguration.vb /r:System.Web.dll /r:System.Configuration.dll
csc /out: ExternalConfiguration.dll /t:library ExternalConfiguration.cs /r:System.Web.dll /r:System.Configuration.dll

The following code example builds the ExternalConfiguration .dll file.

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Web.Configuration

Namespace Samples.AspNet


    Public Class ExternalConfiguration


        ' Instantiate the ExternalConfiguration type.
        Public Sub New()
            ' Access the root Web.config file.
            Dim config As System.Configuration.Configuration = _
            WebConfigurationManager.OpenWebConfiguration("/configTarget")

            ' Get the custom MyAppSettings section.
            Dim appSettings As AppSettingsSection = _
            CType(config.GetSection("MyAppSettings"), AppSettingsSection)

            ' Perform the first update.
            UpdateAppSettings()

        End Sub 'New



        ' Update the custom MyAppSettings section.
        ' Note , if the section restartOnExternalChanges attribute 
        ' is set to true, every update of the external 
        ' configuration file will cause the application 
        ' to restart.
        Public Sub UpdateAppSettings()

            Dim config As System.Configuration.Configuration = _
            WebConfigurationManager.OpenWebConfiguration("/configTarget")

            Dim appSettings As AppSettingsSection = _
            CType(config.GetSection("MyAppSettings"), AppSettingsSection)

            Dim count As Integer = appSettings.Settings.Count

            appSettings.Settings.Add("key_" + count.ToString(), _
            "value_" + count.ToString())

            config.Save()

        End Sub 'UpdateAppSettngs

    End Class 'ExternalConfiguration 

End Namespace
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web.Configuration;

namespace Samples.AspNet
{


    public class ExternalConfiguration
    {

        // Instantiate the ExternalConfiguration type.
        public ExternalConfiguration()
        {
            // Access the root Web.config file.
            System.Configuration.Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                              "/configTarget");

            // Get the custom MyAppSettings section.
            AppSettingsSection appSettings =
                (AppSettingsSection)config.GetSection("MyAppSettings");

            // Perform the first update.
            UpdateAppSettings();
        }


        // Update the custom MyAppSettings section.
        // Note , if the section restartOnExternalChanges attribute 
        // is set to true, every update of the external 
        // configuration file will cause the application 
        // to restart.
        public void UpdateAppSettings()
        {

            System.Configuration.Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                              "/configTarget");

            AppSettingsSection appSettings =
                (AppSettingsSection)config.GetSection("MyAppSettings");

            int count = appSettings.Settings.Count;

            appSettings.Settings.Add(
                "key_" + count.ToString(), 
                "value_" + count.ToString());

            config.Save();
        }

    }
}

Using the Sample Web Application

The first time you run the application, it adds elements to the External.config file.

Every time you refresh the Default.aspx page, the postback counter is reset to zero. This is because the restartOnExternalChanges attribute in the MyAppSettings section is set to true, by default.

If, in the Web.config file, you set the restartOnExternalChanges attribute to false, you will notice that the postback counter keeps incrementing when you refresh the page, despite the changes in the External.config file. This is because you have disabled the application domain restart.

See Also

Tasks

How to: Create Custom Configuration Sections Using ConfigurationSection

Concepts

Managing Changes to Configuration Settings

Securing ASP.NET Configuration

Reference

ConfigurationElement

ConfigurationSection

General Attributes Inherited by Section Elements

location

appSettings Element (General Settings Schema)

trace Element (ASP.NET Settings Schema)

HttpApplicationState