Ejemplo de cómo cambiar la configuración en un archivo externo

Actualización: noviembre 2007

Se puede usar un archivo de configuración externo para extender la configuración de la aplicación y controlar si la información de estado se conserva cuando dicha configuración cambia mediante la funcionalidad de reinicio de la aplicación. Esto está controlado por el atributo restartOnExternalChanges, que se aplica a diferentes secciones del archivo de configuración.

Ejemplo de archivos de aplicación Web

Las siguientes secciones incluyen el código para generar una aplicación Web de ejemplo con una sección personalizada cuyo atributo configSource señala un archivo de configuración externo y cuyo atributo restartOnExternalChanges se establece inicialmente en true.

Al ejecutar la aplicación Web, se ve lo que sucede con el contador global de devolución de datos cuando se realizan cambios en el archivo de configuración externo, y en el ejemplo de código proporcionado se muestra lo que ocurre cuando se establece el valor de restartOnExternalChanges en true, en el valor predeterminado y en false, respectivamente.

Global.asax

La aplicación Web de ejemplo debe incluir esta página Global.asax. En el ejemplo de código siguiente se define la página con un contador global de devolución de datos. El contador realiza un seguimiento de las solicitudes de devolución de datos generadas mediante la actualización de la página Default.aspx de la aplicación (la cual se define más adelante en este tema).

' 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

La página Default.aspx contiene código que crea la sección personalizada en el archivo Web.config, agrega un elemento al archivo External.config y muestra el valor del contador de devolución de datos. Observe que la página debe contener un control Label para mostrar el valor actual del contador de devolución de datos. En el ejemplo de código siguiente se muestra una posible manera de definir este control.

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

En el ejemplo de código siguiente se define la página Default.aspx.

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

El archivo Web.config define la sección personalizada MyAppSettings, tal como se muestra en el ejemplo de código siguiente. En este ejemplo se utiliza el tipo estándar para procesar esta sección, pero se puede crear un tipo propio. Para obtener información detallada, vea ConfigurationElement y 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

El archivo External.config contiene los detalles de la sección personalizada MyAppSettings. Antes de ejecutar por primera vez la aplicación, debe crear manualmente este archivo en el directorio raíz de la aplicación. Para obtener más información, vea el atributo configSource en Atributos generales heredados por elementos de una sección. Para este ejemplo, asegúrese de que el código contenga la siguiente sección vacía.

<MyAppSettings></ MyAppSettings>.

ExternalConfiguration.dll

El archivo ExternalConfiguration.dll contiene el código que actualiza la sección personalizada MyAppSettings. Puede colocar el código fuente en el directorio App_Code de la aplicación. ASP.NET compilará el ejemplo cuando se solicite la aplicación. El proveedor del ejemplo también se puede compilar como una biblioteca y colocarlo en el directorio Bin de la aplicación Web. En el ejemplo de código siguiente se muestra cómo se compila el ejemplo desde la línea de comandos.

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

En el ejemplo de código siguiente se genera el archivo ExternalConfiguration.dll.

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();
        }

    }
}

Utilizar la aplicación Web de ejemplo

La primera vez que se ejecuta la aplicación, se agregan elementos al archivo External.config.

Cada vez que se actualiza la página Default.aspx, el contador de devolución de datos se restablece en cero. Esto es porque el atributo restartOnExternalChanges en la sección MyAppSettings tiene el valor true de forma predeterminada.

Si en el archivo Web.config establece el valor del atributo restartOnExternalChanges en false, observará que el contador de devolución de datos seguirá incrementándose cuando actualice la página, a pesar de los cambios en External.config. Esto es porque ha deshabilitado el reinicio del dominio de aplicación.

Vea también

Tareas

Cómo: Crear secciones de configuración personalizadas mediante ConfigurationSection

Conceptos

Administrar los cambios en los valores de configuración

Proteger la configuración de ASP.NET

Referencia

ConfigurationElement

ConfigurationSection

Atributos generales heredados por elementos de una sección

ubicación

Elemento appSettings (Esquema de configuración general)

Elemento trace (Esquema de configuración de ASP.NET)

HttpApplicationState