ConfigurationPropertyAttribute Classe

Definição

Instrui de modo declarativo o .NET para instanciar uma propriedade de configuração. Essa classe não pode ser herdada.

public ref class ConfigurationPropertyAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Property)]
public sealed class ConfigurationPropertyAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Property)>]
type ConfigurationPropertyAttribute = class
    inherit Attribute
Public NotInheritable Class ConfigurationPropertyAttribute
Inherits Attribute
Herança
ConfigurationPropertyAttribute
Atributos

Exemplos

O exemplo a seguir mostra como definir as propriedades de um objeto personalizado ConfigurationSection usando o ConfigurationPropertyAttribute atributo .

O exemplo contém duas classes. A UrlsSection classe personalizada usa o ConfigurationPropertyAttribute para definir suas próprias propriedades. A UsingConfigurationPropertyAttribute classe usa o UrlsSection para ler e gravar a seção personalizada no arquivo de configuração do aplicativo.

using System;
using System.Configuration;

// Define a custom section.
// This class shows how to use the ConfigurationPropertyAttribute.
public class UrlsSection : ConfigurationSection
{
    [ConfigurationProperty("name", DefaultValue = "Contoso",
        IsRequired = true, IsKey = true)]
    public string Name
    {
        get
        {
            return (string)this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }

    [ConfigurationProperty("url", DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }

    [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
    [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}
Imports System.Configuration


' Define a custom section.
' This class shows how to use the ConfigurationPropertyAttribute.
Public Class UrlsSection
    Inherits ConfigurationSection
    <ConfigurationProperty("name", DefaultValue:="Contoso", IsRequired:=True, IsKey:=True)>
    Public Property Name() As String
        Get
            Return CStr(Me("name"))
        End Get
        Set(ByVal value As String)
            Me("name") = value
        End Set
    End Property

    <ConfigurationProperty("url", DefaultValue:="http://www.contoso.com", IsRequired:=True), RegexStringValidator("\w+:\/\/[\w.]+\S*")>
    Public Property Url() As String
        Get
            Return CStr(Me("url"))
        End Get
        Set(ByVal value As String)
            Me("url") = value
        End Set
    End Property

    <ConfigurationProperty("port", DefaultValue:=0, IsRequired:=False), IntegerValidator(MinValue:=0, MaxValue:=8080, ExcludeRange:=False)>
    Public Property Port() As Integer
        Get
            Return CInt(Fix(Me("port")))
        End Get
        Set(ByVal value As Integer)
            Me("port") = value
        End Set
    End Property
End Class
using System;
using System.Configuration;

public class UsingConfigurationPropertyAttribute
{

    // Create a custom section and save it in the 
    // application configuration file.
    static void CreateCustomSection()
    {
        try
        {

            // Create a custom configuration section.
            UrlsSection customSection = new UrlsSection();

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Add the custom section to the application
            // configuration file.
            if (config.Sections["CustomSection"] == null)
            {
                config.Sections.Add("CustomSection", customSection);
            }

            // Save the application configuration file.
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Modified);

            Console.WriteLine("Created custom section in the application configuration file: {0}",
                config.FilePath);
            Console.WriteLine();
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateCustomSection: {0}", err.ToString());
        }
    }

    static void ReadCustomSection()
    {
        try
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Read and display the custom section.
            UrlsSection customSection =
                config.GetSection("CustomSection") as UrlsSection;
            Console.WriteLine("Reading custom section from the configuration file.");
            Console.WriteLine("Section name: {0}", customSection.Name);
            Console.WriteLine("Url: {0}", customSection.Url);
            Console.WriteLine("Port: {0}", customSection.Port);
            Console.WriteLine();
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }
    }
    
    static void Main(string[] args)
    {
       
        // Get the name of the application.
        string appName =
            Environment.GetCommandLineArgs()[0];

        // Create a custom section and save it in the 
        // application configuration file.
        CreateCustomSection();

        // Read the custom section saved in the
        // application configuration file.
        ReadCustomSection();

        Console.WriteLine("Press enter to exit.");

        Console.ReadLine();
    }
}
Imports System.Configuration

Public Class UsingConfigurationPropertyAttribute

    ' Create a custom section and save it in the 
    ' application configuration file.
    Private Shared Sub CreateCustomSection()
        Try

            ' Create a custom configuration section.
            Dim customSection As New UrlsSection()

            ' Get the current configuration file.
            Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

            ' Add the custom section to the application
            ' configuration file.
            If config.Sections("CustomSection") Is Nothing Then
                config.Sections.Add("CustomSection", customSection)
            End If


            ' Save the application configuration file.
            customSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Modified)

            Console.WriteLine("Created custom section in the application configuration file: {0}", config.FilePath)
            Console.WriteLine()

        Catch err As ConfigurationErrorsException
            Console.WriteLine("CreateCustomSection: {0}", err.ToString())
        End Try

    End Sub

    Private Shared Sub ReadCustomSection()
        Try
            ' Get the application configuration file.
            Dim config As System.Configuration.Configuration = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration)

            ' Read and display the custom section.
            Dim customSection As UrlsSection = TryCast(config.GetSection("CustomSection"), UrlsSection)
            Console.WriteLine("Reading custom section from the configuration file.")
            Console.WriteLine("Section name: {0}", customSection.Name)
            Console.WriteLine("Url: {0}", customSection.Url)
            Console.WriteLine("Port: {0}", customSection.Port)
            Console.WriteLine()
        Catch err As ConfigurationErrorsException
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString())
        End Try

    End Sub

    Shared Sub Main(ByVal args() As String)

        ' Get the name of the application.
        Dim appName As String = Environment.GetCommandLineArgs()(0)

        ' Create a custom section and save it in the 
        ' application configuration file.
        CreateCustomSection()

        ' Read the custom section saved in the
        ' application configuration file.
        ReadCustomSection()

        Console.WriteLine("Press enter to exit.")

        Console.ReadLine()
    End Sub
End Class

Veja a seguir um trecho do arquivo de configuração que contém a seção personalizada, conforme definido no exemplo anterior.

<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
    <configSections>  
        <section name="CustomSection" type="UrlsSection, UsingConfigurationPropertyAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
    </configSections>  
    <CustomSection name="Contoso" url="http://www.contoso.com" />  
</configuration>  

Comentários

Use o ConfigurationPropertyAttribute para decorar uma propriedade de configuração, que instruirá o .NET a instanciar e inicializar a propriedade usando o valor do parâmetro de decoração.

Observação

A maneira mais simples de criar um elemento de configuração personalizado é usar o modelo atribuído (declarativo). Você declara as propriedades públicas personalizadas e as decora com o ConfigurationPropertyAttribute atributo . Para cada propriedade marcada com esse atributo, o .NET usa reflexão para ler os parâmetros de decoração e criar uma instância relacionada ConfigurationProperty . Você também pode usar o modelo programático, nesse caso, é sua responsabilidade declarar as propriedades públicas personalizadas e retornar sua coleção.

O sistema de configuração do .NET fornece tipos de atributo que você pode usar durante a criação de elementos de configuração personalizados. Há dois tipos de atributo:

  1. Os tipos que instruem o .NET como instanciar as propriedades de elemento de configuração personalizadas. Esses tipos incluem:

  2. Os tipos que instruem o .NET como validar as propriedades de elemento de configuração personalizadas. Esses tipos incluem:

Construtores

ConfigurationPropertyAttribute(String)

Inicializa uma nova instância da classe ConfigurationPropertyAttribute.

Propriedades

DefaultValue

Obtém ou define o valor padrão para a propriedade decorada.

IsDefaultCollection

Obtém ou define um valor que indica se esta é a coleção de propriedade padrão para a propriedade de configuração decorada.

IsKey

Obtém ou define um valor que indica se esta é uma propriedade chave para a propriedade de elemento decorado.

IsRequired

Obtém ou define um valor que indica se a propriedade do elemento decorado é necessária.

Name

Obtém o nome da propriedade do elemento de configuração decorado.

Options

Obtém ou define o ConfigurationPropertyOptions da propriedade do elemento de configuração decorado.

TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.

(Herdado de Attribute)

Métodos

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()

Retorna o código hash para a instância.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Confira também