Mudando a Configuração em Exemplo de Arquivo Externo

Você pode usar um arquivo de configuração externo para estender as definições de configuração do aplicativo e controlar se a informação de estado é preservada quando essas definições mudam pela ativação ou desativação da funcionalidade de reinício do aplicativo.Isto é controlado pelo atributo restartOnExternalChanges , que é aplicado a diferentes seções do arquivo de configuração.

Arquivos de Aplicativo Web de Teste

As seções a seguir incluem o código para construir um aplicativo Web teste com uma seção habitual cujo atributo configSource aponta para um arquivo de configuração externo e cujo atributo restartOnExternalChanges é inicialmente definido para true.

Rodar o aplicativo Web mostra o que acontece a um contador global postback quando mudanças são feitas no arquivo de configuração externa, e o exemplo de código fornecido demonstra o que acontece quando restartOnExternalChanges é definido para true, definido para o valor padrão e definido para false, respectivamente.

O arquivo Global.asax

O aplicativo Web teste deve incluir essa página Global.asax.O exemplo de código a seguir define a página com um contador global postback.O contador mantém o caminho das solicitações postback geradas pela atualização da página Default.aspx do aplicativo (definida mais tarde neste tópico).

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

Padrão.aspx

A página Default.aspx contém código que cria a seção habitual no arquivo Web.config, adiciona um elemento ao arquivo External.config e mostra o valor do contador postback.Note que a página deve conter um controle Label para exibir o valor atual do contador de postback.O exemplo a seguir mostra um possível meio de definir este controle.

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

O exemplo a seguir define a 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

O arquivo Web.config define a seção habitual MyAppSettings, como mostrado no exemplo de código a seguir.Este exemplo usa o tipo padrão para processar esta seção, mas você pode criar seu próprio tipo.Para obter detalhes, consulte ConfigurationElement e 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

O arquivo External.config contém os detalhes da seção habitual MyAppSettings.Antes de você rodar o aplicativo pela primeira vez, você deve criar este arquivo manualmente no diretório raiz do aplicativo.Para obter mais informação, veja o atributo configSource aem Atributos de Geral herdados por elementos de seção.Para este exemplo, esteja certo de que seu código contém a seção vazia a seguir.

<MyAppSettings></ MyAppSettings>.

ExternalConfiguration.dll

O arquivo ExternalConfiguration.dll contém o código que atualiza a seção habitual MyAppSettings.Você pode localizar seu código-fonte no diretório App_Code de seu aplicativo.O exemplo vai ser compilado pelo ASP.NET quando seu aplicativo for solicitado.Você pode ainda compilar o fornecedor de teste como uma biblioteca e localizá-lo no diretório Bin de seu aplicativo Web.O exemplo de código a seguir mostra como compilar o teste através da linha de comando

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

O exemplo de código a seguir contrói o arquivo 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();
        }

    }
}

Usando o Aplicativo Web Teste

A primeira vez que você rodar o aplicativo, ele adiciona elementos para o arquivo External.config.

Toda vez que você atualizar a página Default.aspx, o contador postback é reinicializado para zero.Isto é porque o atributo restartOnExternalChanges na seção MyAppSettings é definido para true, por padrão.

Se, no arquivo Web.config, você definir o atributo restartOnExternalChanges para false, você irá observar que o contador postback permanece incrementando quando você atualiza a página, apesar das mudanças no arquivo External.config.Isto é porque você desativou o reinício do domínio do aplicativo.

Consulte também

Tarefas

Como: Criar usando ConfigurationSection Custom configuração Sections

Conceitos

Managing Changes to Configuration Settings

Protegendo configuração ASP.NET

Referência

ConfigurationElement

ConfigurationSection

Atributos de Geral herdados por elementos de seção

location

appSettings elemento (Geral Settings Esquema)

Rastrear elemento (esquema configurações ASP.NET)

HttpApplicationState