WebPartsSection Classe

Definição

Fornece acesso programático à seção do arquivo de configuração webParts.Provides programmatic access to the webParts configuration file section. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class WebPartsSection sealed : System::Configuration::ConfigurationSection
public sealed class WebPartsSection : System.Configuration.ConfigurationSection
type WebPartsSection = class
    inherit ConfigurationSection
Public NotInheritable Class WebPartsSection
Inherits ConfigurationSection
Herança

Exemplos

Este exemplo demonstra como especificar valores de forma declarativa para vários atributos da webParts seção, que também podem ser acessados como membros da WebPartsSection classe.This example demonstrates how to specify values declaratively for several attributes of the webParts section, which can also be accessed as members of the WebPartsSection class.

O exemplo de arquivo de configuração a seguir mostra como especificar valores declarativamente para a webParts seção.The following configuration file example shows how to specify values declaratively for the webParts section.

<system.web>  
  <webParts>  
    <personalization  
      defaultProvider=" AspNetSqlPersonalizationProvider ">  
        <!-- Providers may only be defined at the   
            application level -->  
      <providers>  
        <add name="AspNetSqlPersonalizationProvider"  
type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider"  
        connectionStringName="LocalSqlServer"  
        applicationName="/" />        
      </providers>  
      <authorization>  
        <deny users="*" verbs="enterSharedScope" />  
        <allow users="Admin" verbs="modifyState" />  
      </authorization>  
    </personalization>  
    <transformers>  
      <add name="RowToFieldTransformer"  
        type="System.Web.UI.WebControls.WebParts.RowToFieldTransformer" />  
      <add name="RowToFilterTransformer"  
        type="System.Web.UI.WebControls.WebParts.RowToFilterTransformer" />  
      <add name="RowToParametersTransformer"  
type="System.Web.UI.WebControls.WebParts.RowToParametersTransformer" />  
    </transformers>  
  </webParts>  
</system.web>  

O exemplo de código a seguir demonstra como usar a WebPartsSection classe.The following code example demonstrates how to use the WebPartsSection class.

using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Configuration.Provider;
using System.Web.Configuration;

namespace Samples.Aspnet.SystemWebConfiguration
{
    // Accesses the System.Web.Configuration.WebPartsSection
    // members selected by the user.
    class UsingWebPartsSection
    {
        public static void Main()
        {
            // Process the System.Web.Configuration.WebPartsSectionobject.
            try
            {
                // Get the Web application configuration.
                Configuration configuration = 
                    WebConfigurationManager.OpenWebConfiguration("/aspnet");

                // Get the section.
                WebPartsSection webPartsSection = (WebPartsSection) 
                    configuration.Sections["system.web/webParts"];
// Add a Transfomer Info Object to the collection using a constructor.
webPartsSection.Transformers.Add(new TransformerInfo(
    "RowToFilterTransformer",
    "MyCustomTransformers.RowToFilterTransformer"));

// Show all TransformerInfo objects in the collection.
for (int ti = 0;
    ti < webPartsSection.Personalization.Providers.Count; ti++)
{
    Console.WriteLine("  #{0} Name={1} Type={2}", ti,
        webPartsSection.Transformers[ti].Name,
        webPartsSection.Transformers[ti].Type);
}

// Remove a TransformerInfo object by name.
webPartsSection.Transformers.Remove("RowToFilterTransformer");

// Remove a TransformerInfo object by index.
webPartsSection.Transformers.RemoveAt(0);

// Clear all TransformerInfo objects from the collection.
webPartsSection.Transformers.Clear();

// Get the current DefaultProvider property value.
Console.WriteLine(
    "Current DefaultProvider value: '{0}'",
    webPartsSection.Personalization.DefaultProvider);

// Set the DefaultProvider property.
webPartsSection.Personalization.DefaultProvider = 
    "ASPNetSQLPersonalizationProvider";
// Add a provider.
webPartsSection.Personalization.Providers.Add(
    new ProviderSettings("CustomProvider", 
    "MyCustomProviders.Provider"));

// List current providers.
for (int pi = 0; 
    pi < webPartsSection.Personalization.Providers.Count; pi++)
{
    Console.WriteLine("  #{0} Name={1} Type={2}", pi,
        webPartsSection.Personalization.Providers[pi].Name,
        webPartsSection.Personalization.Providers[pi].Type);
}

// Add an authorization.
AuthorizationRule ar = 
    new AuthorizationRule(AuthorizationRuleAction.Allow);
ar.Verbs.Add("ModifyState");
ar.Users.Add("Admin");
webPartsSection.Personalization.Authorization.Rules.Add(ar);

// List current authorizations.
for (int ai = 0;
    ai < webPartsSection.Personalization.Authorization.Rules.Count; 
    ai++)
{
    Console.WriteLine("  #{0}:", ai);
    AuthorizationRule aRule = 
        webPartsSection.Personalization.Authorization.Rules[ai];
    Console.WriteLine("  Verbs=");
    foreach (string verb in aRule.Verbs)
        Console.WriteLine("    * {0}", verb);
    Console.WriteLine("  Roles=");
    foreach (string role in aRule.Roles)
        Console.WriteLine("    * {0}", role);
    Console.WriteLine("  Users=");
    foreach (string user in aRule.Users)
        Console.WriteLine("    * {0}", user);
}


                // Update if not locked.
                if (! webPartsSection.IsReadOnly())
                {
                    configuration.Save();
                    Console.WriteLine("** Configuration updated.");
                }
                else
                {
                    Console.WriteLine("** Could not update, section is locked.");
                }
            }
            catch (System.ArgumentException e)
            {
                // Unknown error.
                Console.WriteLine(
                    "A invalid argument exception detected in UsingWebPartsSection Main. Check your");
                Console.WriteLine("command line for errors.");
            }
        }
    } // UsingWebPartsSection class end.
} // Samples.Aspnet.SystemWebConfiguration namespace end.

Imports System.Collections
Imports System.Collections.Specialized
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Configuration
Imports System.Web.Configuration

Namespace Samples.Aspnet.SystemWebConfiguration
  ' Accesses the System.Web.Configuration.WebPartsSection
  ' members selected by the user.
  Class UsingWebPartsSection
    Public Shared Sub Main()
      ' Process the System.Web.Configuration.WebPartsSectionobject.
      Try
        ' Get the Web application configuration.
                Dim configuration As System.Configuration.Configuration = _
        WebConfigurationManager.OpenWebConfiguration("/aspnet")

        ' Get the section.
        Dim webPartsSection As WebPartsSection = _
         CType(configuration.Sections("system.web/webParts"), _
         WebPartsSection)

' Add a Transfomer Info Object to the collection using a constructor.
webPartsSection.Transformers.Add(New TransformerInfo( _
  "RowToFilterTransformer", _
  "MyCustomTransformers.RowToFilterTransformer"))

' Show all TransformerInfo objects in the collection.
Dim ti As Integer
For ti = 0 To webPartsSection.Personalization.Providers.Count - 1
  Console.WriteLine("  #{0} Name={1} Type={2}", ti, _
    webPartsSection.Transformers(ti).Name, _
    webPartsSection.Transformers(ti).Type)
Next

' Remove a TransformerInfo object by name.
webPartsSection.Transformers.Remove("RowToFilterTransformer")

' Remove a TransformerInfo object by index.
webPartsSection.Transformers.RemoveAt(0)

' Clear all TransformerInfo objects from the collection.
webPartsSection.Transformers.Clear()

' Get the current DefaultProvider property value.
Console.WriteLine( _
  "Current DefaultProvider value: '{0}'", _
  webPartsSection.Personalization.DefaultProvider)

' Set the DefaultProvider property.
webPartsSection.Personalization.DefaultProvider = _
  "ASPNetSQLPersonalizationProvider"
' Add a provider.
webPartsSection.Personalization.Providers.Add( _
  New ProviderSettings("CustomProvider", _
  "MyCustomProviders.Provider"))

' List current providers.
Dim pi As Integer
For pi = 0 To webPartsSection.Personalization.Providers.Count - 1
  Console.WriteLine("  #{0} Name={1} Type={2}", pi, _
    webPartsSection.Personalization.Providers(pi).Name, _
    webPartsSection.Personalization.Providers(pi).Type)
Next

' Add an authorization.
Dim ar As AuthorizationRule = _
  New AuthorizationRule(AuthorizationRuleAction.Allow)
ar.Verbs.Add("ModifyState")
ar.Users.Add("Admin")
webPartsSection.Personalization.Authorization.Rules.Add(ar)

' List current authorizations.
Dim ai As Integer
For ai = 0 To _
  webPartsSection.Personalization.Authorization.Rules.Count
    Console.WriteLine("  #{0}:", ai)
    Dim aRule As AuthorizationRule = _
      webPartsSection.Personalization.Authorization.Rules(ai)
    Console.WriteLine("  Verbs=")
    Dim verb As String
    For Each verb In aRule.Verbs
      Console.WriteLine("    * {0}", verb)
      Console.WriteLine("  Roles=")
    Next
    Dim role As String
    For Each role In aRule.Roles
      Console.WriteLine("    * {0}", role)
      Console.WriteLine("  Users=")
    Next
    Dim user As String
    For Each user In aRule.Users
      Console.WriteLine("    * {0}", user)
    Next
Next

                ' Update if not locked.
                If Not webPartsSection.IsReadOnly() Then
                    configuration.Save()
                    Console.WriteLine("** Configuration updated.")
                Else
                    Console.WriteLine("** Could not update, section is locked.")
                End If
            Catch e As System.ArgumentException
        ' Unknown error.
        Console.WriteLine( _
          "A invalid argument exception detected in UsingWebPartsSection Main. Check your")
        Console.WriteLine("command line for errors.")
      End Try
    End Sub
  End Class
End Namespace ' Samples.Aspnet.SystemWebConfiguration

Comentários

A webParts seção arquivo de configuração permite especificar um Web Parts provedor de personalização, definir autorizações de personalização e adicionar classes personalizadas que estendem a WebPartTransformer classe para uso por Web Parts conexões.The webParts configuration file section allows you to specify a Web Parts personalization provider, set personalization authorizations, and add custom classes that extend the WebPartTransformer class for use by Web Parts connections.

Construtores

WebPartsSection()

Inicializa uma nova instância da classe WebPartsSection usando as configurações padrão.Initializes a new instance of the WebPartsSection class using default settings.

Propriedades

CurrentConfiguration

Obtém uma referência para a instância Configuration de nível superior que representa a hierarquia de configuração à qual a instância atual ConfigurationElement pertence.Gets a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to.

(Herdado de ConfigurationElement)
ElementInformation

Obtém um objeto ElementInformation que contém as informações não personalizáveis e a funcionalidade do objeto ConfigurationElement.Gets an ElementInformation object that contains the non-customizable information and functionality of the ConfigurationElement object.

(Herdado de ConfigurationElement)
ElementProperty

Obtém o objeto ConfigurationElementProperty que representa o próprio objeto ConfigurationElement.Gets the ConfigurationElementProperty object that represents the ConfigurationElement object itself.

(Herdado de ConfigurationElement)
EnableExport

Obtém ou define um valor que indica se você deseja habilitar a exportação de dados de controle para um arquivo de descrição XML.Gets or sets a value indicating whether to enable the export of control data to an XML description file.

EvaluationContext

Obtém o objeto ContextInformation para o objeto ConfigurationElement.Gets the ContextInformation object for the ConfigurationElement object.

(Herdado de ConfigurationElement)
HasContext

Obtém um valor que indica se a propriedade CurrentConfiguration é null.Gets a value that indicates whether the CurrentConfiguration property is null.

(Herdado de ConfigurationElement)
Item[ConfigurationProperty]

Obtém ou define uma propriedade ou um atributo desse elemento de configuração.Gets or sets a property or attribute of this configuration element.

(Herdado de ConfigurationElement)
Item[String]

Obtém ou define uma propriedade, atributo ou elemento filho desse elemento de configuração.Gets or sets a property, attribute, or child element of this configuration element.

(Herdado de ConfigurationElement)
LockAllAttributesExcept

Obtém a coleção de atributos bloqueados.Gets the collection of locked attributes.

(Herdado de ConfigurationElement)
LockAllElementsExcept

Obtém a coleção de elementos bloqueados.Gets the collection of locked elements.

(Herdado de ConfigurationElement)
LockAttributes

Obtém a coleção de atributos bloqueados.Gets the collection of locked attributes.

(Herdado de ConfigurationElement)
LockElements

Obtém a coleção de elementos bloqueados.Gets the collection of locked elements.

(Herdado de ConfigurationElement)
LockItem

Obtém ou define um valor que indica se o elemento está bloqueado.Gets or sets a value indicating whether the element is locked.

(Herdado de ConfigurationElement)
Personalization

Obtém um objeto WebPartsPersonalization que permite especificar o provedor de personalização de Web Parts e definir autorizações de personalização de Web Parts.Gets a WebPartsPersonalization object that allows you to specify the Web Parts personalization provider and set Web Parts personalization authorizations.

Properties

Obtém a coleção de propriedades.Gets the collection of properties.

(Herdado de ConfigurationElement)
SectionInformation

Obtém um objeto SectionInformation que contém as informações não personalizáveis e a funcionalidade do objeto ConfigurationSection.Gets a SectionInformation object that contains the non-customizable information and functionality of the ConfigurationSection object.

(Herdado de ConfigurationSection)
Transformers

Obtém uma coleção de objetos TransformerInfo .Gets a collection of TransformerInfo objects.

Métodos

DeserializeElement(XmlReader, Boolean)

Lê o XML do arquivo de configuração.Reads XML from the configuration file.

(Herdado de ConfigurationElement)
DeserializeSection(XmlReader)

Lê o XML do arquivo de configuração.Reads XML from the configuration file.

(Herdado de ConfigurationSection)
Equals(Object)

Compara a instância ConfigurationElement atual com o objeto especificado.Compares the current ConfigurationElement instance to the specified object.

(Herdado de ConfigurationElement)
GetHashCode()

Obtém um valor exclusivo que representa a instância ConfigurationElement atual.Gets a unique value representing the current ConfigurationElement instance.

(Herdado de ConfigurationElement)
GetRuntimeObject()

Retorna um objeto personalizado quando substituído em uma classe derivada.Returns a custom object when overridden in a derived class.

(Herdado de ConfigurationSection)
GetTransformedAssemblyString(String)

Retorna a versão transformada do nome do assembly especificado.Returns the transformed version of the specified assembly name.

(Herdado de ConfigurationElement)
GetTransformedTypeString(String)

Retorna a versão transformada do nome do tipo especificado.Returns the transformed version of the specified type name.

(Herdado de ConfigurationElement)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
Init()

Define o objeto ConfigurationElement para seu estado inicial.Sets the ConfigurationElement object to its initial state.

(Herdado de ConfigurationElement)
InitializeDefault()

Usado para inicializar um conjunto padrão de valores para o objeto ConfigurationElement.Used to initialize a default set of values for the ConfigurationElement object.

(Herdado de ConfigurationElement)
IsModified()

Indica se este elemento de configuração foi modificado desde a última vez em que foi salvo ou carregado quando implementado em uma classe derivada.Indicates whether this configuration element has been modified since it was last saved or loaded when implemented in a derived class.

(Herdado de ConfigurationSection)
IsReadOnly()

Obtém um valor que indica se o objeto ConfigurationElement é somente leitura.Gets a value indicating whether the ConfigurationElement object is read-only.

(Herdado de ConfigurationElement)
ListErrors(IList)

Adiciona os erros de propriedade inválida deste objeto ConfigurationElement e de todos os subelementos à lista passada.Adds the invalid-property errors in this ConfigurationElement object, and in all subelements, to the passed list.

(Herdado de ConfigurationElement)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
OnDeserializeUnrecognizedAttribute(String, String)

Obtém um valor que indica se um atributo desconhecido é encontrado durante a desserialização.Gets a value indicating whether an unknown attribute is encountered during deserialization.

(Herdado de ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Obtém um valor que indica se um elemento desconhecido é encontrado durante a desserialização.Gets a value indicating whether an unknown element is encountered during deserialization.

(Herdado de ConfigurationElement)
OnRequiredPropertyNotFound(String)

Gera uma exceção quando uma propriedade necessária não é encontrada.Throws an exception when a required property is not found.

(Herdado de ConfigurationElement)
PostDeserialize()

Chamado depois da desserialização.Called after deserialization.

(Herdado de ConfigurationElement)
PreSerialize(XmlWriter)

Chamado antes da serialização.Called before serialization.

(Herdado de ConfigurationElement)
Reset(ConfigurationElement)

Redefine o estado interno do objeto ConfigurationElement, incluindo os bloqueios e as coleções de propriedades.Resets the internal state of the ConfigurationElement object, including the locks and the properties collections.

(Herdado de ConfigurationElement)
ResetModified()

Redefine o valor do método IsModified() para false quando implementado em uma classe derivada.Resets the value of the IsModified() method to false when implemented in a derived class.

(Herdado de ConfigurationSection)
SerializeElement(XmlWriter, Boolean)

Grava o conteúdo desse elemento de configuração no arquivo de configuração quando implementado em uma classe derivada.Writes the contents of this configuration element to the configuration file when implemented in a derived class.

(Herdado de ConfigurationElement)
SerializeSection(ConfigurationElement, String, ConfigurationSaveMode)

Cria uma cadeia de caracteres XML que contém uma exibição não mesclada do objeto ConfigurationSection como uma única seção a ser gravada em um arquivo.Creates an XML string containing an unmerged view of the ConfigurationSection object as a single section to write to a file.

(Herdado de ConfigurationSection)
SerializeToXmlElement(XmlWriter, String)

Grava as marcas externas desse elemento de configuração no arquivo de configuração quando implementado em uma classe derivada.Writes the outer tags of this configuration element to the configuration file when implemented in a derived class.

(Herdado de ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Define uma propriedade para o valor especificado.Sets a property to the specified value.

(Herdado de ConfigurationElement)
SetReadOnly()

Define a propriedade IsReadOnly() para o objeto ConfigurationElement e para todos os subelementos.Sets the IsReadOnly() property for the ConfigurationElement object and all subelements.

(Herdado de ConfigurationElement)
ShouldSerializeElementInTargetVersion(ConfigurationElement, String, FrameworkName)

Indica se o elemento especificado deve ser serializado quando a hierarquia do objeto de configuração é serializada para a versão de destino especificada do .NET Framework.Indicates whether the specified element should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.

(Herdado de ConfigurationSection)
ShouldSerializePropertyInTargetVersion(ConfigurationProperty, String, FrameworkName, ConfigurationElement)

Indica se a propriedade especificada deve ser serializada quando a hierarquia do objeto de configuração é serializada para a versão de destino especificada do .NET Framework.Indicates whether the specified property should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.

(Herdado de ConfigurationSection)
ShouldSerializeSectionInTargetVersion(FrameworkName)

Indica se a ConfigurationSection instância atual deve ser serializada quando a hierarquia do objeto de configuração é serializada para a versão de destino especificada do .NET Framework.Indicates whether the current ConfigurationSection instance should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.

(Herdado de ConfigurationSection)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Modifica o objeto ConfigurationElement para remover todos os valores que não devem ser salvos.Modifies the ConfigurationElement object to remove all values that should not be saved.

(Herdado de ConfigurationElement)

Aplica-se a

Confira também