ProfileSection Classe

Definição

A ProfileSection classe fornece uma forma de aceder e modificar programaticamente a profile secção de um ficheiro de configuração. Esta classe não pode ser herdada.

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

Exemplos

O excerto seguinte do ficheiro de configuração mostra como especificar declarativamente valores para várias propriedades da ProfileSection classe.

<system.web>
  <profile enabled = "true"
     defaultProvider="AspNetSqlProfileProvider">
    <providers>
      <add  name="AspNetSqlProfileProvider"
        type="System.Web.Profile.SqlProfileProvider"
        connectionStringName="LocalSqlServer"
        applicationName="/"
        description="Stores and retrieves profile data from the
local Microsoft SQL Server database" />
    </providers>
    <properties>
      <add name = "FirstName"/>
      <add name = "LastName"/>
      <add name = "FavoriteURLs" type =
        "System.Collection.Specialized.StringCollection, System"
        serializeAs = "Xml"/>
      <add name = "ShoppingCart" type =
        "MyCommerce.ShoppingCart, MyCommerce"
        serializeAs = "Binary"/>
      <group name = "SiteColors" >
        <add name = "BackGround"/>
        <add name = "SideBar"/>
        <add name = "ForeGroundText"/>
        <add name = "ForeGroundBorders"/>
      </group>
      <group name="Forums">
        <add name = "HasAvatar" type="bool" provider="Forums"/>
        <add name = "LastLogin" type="DateTime" provider="Forums"/>
        <add name = "TotalPosts" type="int" provider="Forums"/>
      </group>
    </properties>
  </profile>
</system.web>

O seguinte exemplo de código mostra como usar o ProfileSection tipo.

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

namespace Samples.Aspnet.SystemWebConfiguration
{
    // Accesses the System.Web.Configuration.ProfileSection members
    // selected by the user.
    class UsingProfileSection
    {
        public static void Main()
        {
            // Process the System.Web.Configuration.ProfileSectionobject.
            try
            {
                // Get the Web application configuration.
                System.Configuration.Configuration configuration = 
                    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/aspnet");
                
                // Get the section.
                System.Web.Configuration.ProfileSection profileSection = 
                    (System.Web.Configuration.ProfileSection) 
                    configuration.GetSection("system.web/profile");

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

// Set the AutomaticSaveEnabled property to false.
profileSection.AutomaticSaveEnabled = false;

                

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

// Set the DefaultProvider property to "AspNetSqlProvider".
profileSection.DefaultProvider = "AspNetSqlProvider";

                

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

// Set the Inherits property to
// "CustomProfiles.MyCustomProfile, CustomProfiles.dll".
profileSection.Inherits = "CustomProfiles.MyCustomProfile, CustomProfiles.dll";

                

// Display all current root ProfilePropertySettings.
Console.WriteLine("Current Root ProfilePropertySettings:");
int rootPPSCtr = 0;
foreach (ProfilePropertySettings rootPPS in profileSection.PropertySettings)
{
    Console.WriteLine("  {0}: ProfilePropertySetting '{1}'", ++rootPPSCtr,
        rootPPS.Name);
}

// Get and modify a root ProfilePropertySettings object.
Console.WriteLine(
    "Display and modify 'LastReadDate' ProfilePropertySettings:");
ProfilePropertySettings profilePropertySettings =
    profileSection.PropertySettings["LastReadDate"];

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

// Set the ReadOnly property to true.
profilePropertySettings.ReadOnly = true;

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

// Set the AllowAnonymous property to true.
profilePropertySettings.AllowAnonymous = true;

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

// Set the SerializeAs property to SerializationMode.Binary.
profilePropertySettings.SerializeAs = SerializationMode.Binary;

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

// Set the Type property to "System.DateTime".
profilePropertySettings.Type = "System.DateTime";

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

// Set the DefaultValue property to "March 16, 2004".
profilePropertySettings.DefaultValue = "March 16, 2004";

// Get the current ProviderName property value.
Console.WriteLine(
    "Current ProviderName value: '{0}'", profilePropertySettings.Provider);

// Set the ProviderName property to "AspNetSqlRoleProvider".
profilePropertySettings.Provider = "AspNetSqlRoleProvider";

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

// Set the Name property to "LastAccessDate".
profilePropertySettings.Name = "LastAccessDate";

// Display all current ProfileGroupSettings.
Console.WriteLine("Current ProfileGroupSettings:");
int PGSCtr = 0;
foreach (ProfileGroupSettings propGroups in profileSection.PropertySettings.GroupSettings)
{
    Console.WriteLine("  {0}: ProfileGroupSetting '{1}'", ++PGSCtr,
        propGroups.Name);
    int PPSCtr = 0;
    foreach (ProfilePropertySettings props in propGroups.PropertySettings)
    {
        Console.WriteLine("    {0}: ProfilePropertySetting '{1}'", ++PPSCtr,
            props.Name);
    }
}

// Add a new group.
ProfileGroupSettings newPropGroup = new ProfileGroupSettings("Forum");
profileSection.PropertySettings.GroupSettings.Add(newPropGroup);

// Add a new PropertySettings to the group.
ProfilePropertySettings newProp = new ProfilePropertySettings("AvatarImage");
newProp.Type = "System.String, System.dll";
newPropGroup.PropertySettings.Add(newProp);

// Remove a PropertySettings from the group.
newPropGroup.PropertySettings.Remove("AvatarImage");
newPropGroup.PropertySettings.RemoveAt(0);

// Clear all PropertySettings from the group.
newPropGroup.PropertySettings.Clear();

                

// Display all current Providers.
Console.WriteLine("Current Providers:");
int providerCtr = 0;
foreach (ProviderSettings provider in profileSection.Providers)
{
    Console.WriteLine("  {0}: Provider '{1}' of type '{2}'", ++providerCtr, 
        provider.Name, provider.Type);
}

// Add a new provider.
profileSection.Providers.Add(new ProviderSettings("AspNetSqlProvider", "...SqlProfileProvider"));

                

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

// Set the Enabled property to false.
profileSection.Enabled = false;

                
                // Update if not locked.
                if (!profileSection.SectionInformation.IsLocked)
                {
                    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 UsingProfileSection Main. Check your");
                Console.WriteLine("command line for errors.");
            }
        }
    } // UsingProfileSection 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.ProfileSection members
    ' selected by the user.
    Class UsingProfileSection
        Public Shared Sub Main()
            ' Process the System.Web.Configuration.ProfileSectionobject.
            Try
                ' Get the Web application configuration.
                Dim configuration As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/aspnet")
                
                ' Get the section.
                Dim profileSection As System.Web.Configuration.ProfileSection = CType(configuration.GetSection("system.web/profile"), System.Web.Configuration.ProfileSection)

' Get the current AutomaticSaveEnabled property value.
Console.WriteLine( _
    "Current AutomaticSaveEnabled value: '{0}'", profileSection.AutomaticSaveEnabled)

' Set the AutomaticSaveEnabled property to false.
profileSection.AutomaticSaveEnabled = false

                

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

' Set the DefaultProvider property to "AspNetSqlProvider".
profileSection.DefaultProvider = "AspNetSqlProvider"

                

' Get the current Inherits property value.
Console.WriteLine( _
    "Current Inherits value: '{0}'", profileSection.Inherits)

' Set the Inherits property to
' "CustomProfiles.MyCustomProfile, CustomProfiles.dll".
profileSection.Inherits = "CustomProfiles.MyCustomProfile, CustomProfiles.dll"

                


' Display all current root ProfilePropertySettings.
Console.WriteLine("Current Root ProfilePropertySettings:")
Dim rootPPSCtr As Integer = 0
For Each rootPPS As ProfilePropertySettings In profileSection.PropertySettings
    Console.WriteLine("  {0}: ProfilePropertySetting '{1}'", ++rootPPSCtr, _
        rootPPS.Name)
Next

' Get and modify a root ProfilePropertySettings object.
Console.WriteLine( _
    "Display and modify 'LastReadDate' ProfilePropertySettings:")
Dim profilePropertySettings As ProfilePropertySettings = _
    profileSection.PropertySettings("LastReadDate")

' Get the current ReadOnly property value.
Console.WriteLine( _
    "Current ReadOnly value: '{0}'", profilePropertySettings.ReadOnly)

' Set the ReadOnly property to true.
profilePropertySettings.ReadOnly = true

' Get the current AllowAnonymous property value.
Console.WriteLine( _
    "Current AllowAnonymous value: '{0}'", profilePropertySettings.AllowAnonymous)

' Set the AllowAnonymous property to true.
profilePropertySettings.AllowAnonymous = true

' Get the current SerializeAs property value.
Console.WriteLine( _
    "Current SerializeAs value: '{0}'", profilePropertySettings.SerializeAs)

' Set the SerializeAs property to SerializationMode.Binary.
profilePropertySettings.SerializeAs = SerializationMode.Binary

' Get the current Type property value.
Console.WriteLine( _
    "Current Type value: '{0}'", profilePropertySettings.Type)

' Set the Type property to "System.DateTime".
profilePropertySettings.Type = "System.DateTime"

' Get the current DefaultValue property value.
Console.WriteLine( _
    "Current DefaultValue value: '{0}'", profilePropertySettings.DefaultValue)

' Set the DefaultValue property to "March 16, 2004".
profilePropertySettings.DefaultValue = "March 16, 2004"

' Get the current ProviderName property value.
            Console.WriteLine( _
                "Current ProviderName value: '{0}'", profilePropertySettings.Provider)

' Set the ProviderName property to "AspNetSqlRoleProvider".
            profilePropertySettings.Provider = "AspNetSqlRoleProvider"

' Get the current Name property value.
Console.WriteLine( _
    "Current Name value: '{0}'", profilePropertySettings.Name)

' Set the Name property to "LastAccessDate".
profilePropertySettings.Name = "LastAccessDate"

' Display all current ProfileGroupSettings.
Console.WriteLine("Current ProfileGroupSettings:")
Dim PGSCtr As Integer = 0
For Each propGroups As ProfileGroupSettings In profileSection.PropertySettings.GroupSettings
                    Console.WriteLine("  {0}: ProfileGroupSettings '{1}'", ++PGSCtr, _
        propGroups.Name)
    Dim PPSCtr As Integer = 0
    For Each props As ProfilePropertySettings In propGroups.PropertySettings
        Console.WriteLine("    {0}: ProfilePropertySetting '{1}'", ++PPSCtr, _
            props.Name)
    Next
Next

' Add a new group.
Dim newPropGroup As ProfileGroupSettings = new ProfileGroupSettings("Forum")
profileSection.PropertySettings.GroupSettings.Add(newPropGroup)

' Add a new PropertySettings to the group.
Dim newProp As ProfilePropertySettings = new ProfilePropertySettings("AvatarImage")
newProp.Type = "System.String, System.dll"
newPropGroup.PropertySettings.Add(newProp)

' Remove a PropertySettings from the group.
newPropGroup.PropertySettings.Remove("AvatarImage")
newPropGroup.PropertySettings.RemoveAt(0)

' Clear all PropertySettings from the group.
newPropGroup.PropertySettings.Clear()

                

Console.WriteLine("Current Providers:")
Dim providerCtr As Integer = 0
For Each provider As ProviderSettings In profileSection.Providers
    Console.WriteLine("  {0}: Provider '{1}' of type '{2}'", ++providerCtr, _
        provider.Name, provider.Type)
Next

' Add a new provider.
profileSection.Providers.Add(new ProviderSettings("AspNetSqlProvider", "...SqlProfileProvider"))

                

' Get the current Enabled property value.
Console.WriteLine( _
    "Current Enabled value: '{0}'", profileSection.Enabled)

' Set the Enabled property to false.
profileSection.Enabled = false

                
                ' Update if not locked.
                If Not profileSection.SectionInformation.IsLocked 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 UsingProfileSection Main. Check your")
                Console.WriteLine("command line for errors.")
            End Try
        End Sub
    End Class
    
End Namespace ' Samples.Aspnet.SystemWebConfiguration

Observações

A ProfileSection classe fornece uma forma de aceder e modificar programaticamente o conteúdo da secção do ficheiro profile de configuração. A profile secção do ficheiro de configuração especifica um esquema para perfis de utilizador. Em tempo de execução, o sistema de compilação ASP.NET utiliza a informação especificada na secção profile para gerar uma classe chamada ProfileCommon, que deriva de ProfileBase. A ProfileCommon definição da classe baseia-se nas propriedades definidas na profile secção do ficheiro de configuração. A classe permite-lhe aceder e modificar os valores para perfis individuais. Uma instância desta classe é criada para cada perfil de utilizador, e pode aceder aos valores individuais do seu código através da HttpContext.Profile propriedade. Para mais informações sobre as funcionalidades do perfil adicionadas à ASP.NET 2.0, consulte ASP.NET Visão Geral das Propriedades do Perfil.

Construtores

Name Description
ProfileSection()

Inicializa uma nova instância da ProfileSection classe usando as definições predefinidas.

Propriedades

Name Description
AutomaticSaveEnabled

Recebe ou define um valor que determina se alterações à informação do perfil do utilizador são automaticamente guardadas ao sair da página.

CurrentConfiguration

Obtém uma referência à instância de topo Configuration que representa a hierarquia de configuração a que pertence a instância atual ConfigurationElement .

(Herdado de ConfigurationElement)
DefaultProvider

Obtém ou define o nome do fornecedor de perfil padrão.

ElementInformation

Obtém um ElementInformation objeto que contém a informação e funcionalidade não personalizáveis do ConfigurationElement objeto.

(Herdado de ConfigurationElement)
ElementProperty

Obtém o ConfigurationElementProperty objeto que representa o ConfigurationElement próprio objeto.

(Herdado de ConfigurationElement)
Enabled

Recebe ou define um valor que indica se a funcionalidade de perfil ASP.NET está ativada.

EvaluationContext

Obtém o ContextInformation objeto para o ConfigurationElement objeto.

(Herdado de ConfigurationElement)
HasContext

Obtém um valor que indica se a CurrentConfiguration propriedade é null.

(Herdado de ConfigurationElement)
Inherits

Obtém ou define uma referência de tipo para um tipo personalizado derivado de ProfileBase.

Item[ConfigurationProperty]

Obtém ou define uma propriedade ou atributo deste elemento de configuração.

(Herdado de ConfigurationElement)
Item[String]

Obtém ou define uma propriedade, atributo ou elemento filho deste elemento de configuração.

(Herdado de ConfigurationElement)
LockAllAttributesExcept

Obtém a coleção de atributos bloqueados.

(Herdado de ConfigurationElement)
LockAllElementsExcept

Obtém a coleção de elementos bloqueados.

(Herdado de ConfigurationElement)
LockAttributes

Obtém a coleção de atributos bloqueados.

(Herdado de ConfigurationElement)
LockElements

Obtém a coleção de elementos bloqueados.

(Herdado de ConfigurationElement)
LockItem

Recebe ou define um valor que indica se o elemento está bloqueado.

(Herdado de ConfigurationElement)
Properties

Recebe a coleção de propriedades.

(Herdado de ConfigurationElement)
PropertySettings

Recebe uma RootProfilePropertySettingsCollection coleção de ProfilePropertySettings objetos.

Providers

Recebe uma coleção de ProviderSettings objetos.

SectionInformation

Obtém um SectionInformation objeto que contém a informação e funcionalidade não personalizáveis do ConfigurationSection objeto.

(Herdado de ConfigurationSection)

Métodos

Name Description
DeserializeElement(XmlReader, Boolean)

Lê XML a partir do ficheiro de configuração.

(Herdado de ConfigurationElement)
DeserializeSection(XmlReader)

Lê XML a partir do ficheiro de configuração.

(Herdado de ConfigurationSection)
Equals(Object)

Compara a instância atual ConfigurationElement com o objeto especificado.

(Herdado de ConfigurationElement)
GetHashCode()

Obtém um valor único que representa a instância atual ConfigurationElement .

(Herdado de ConfigurationElement)
GetRuntimeObject()

Devolve um objeto personalizado quando sobrescrito numa classe derivada.

(Herdado de ConfigurationSection)
GetTransformedAssemblyString(String)

Devolve a versão transformada do nome da assembleia especificado.

(Herdado de ConfigurationElement)
GetTransformedTypeString(String)

Devolve a versão transformada do nome do tipo especificado.

(Herdado de ConfigurationElement)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
Init()

Define o ConfigurationElement objeto para o seu estado inicial.

(Herdado de ConfigurationElement)
InitializeDefault()

Usado para inicializar um conjunto padrão de valores para o ConfigurationElement objeto.

(Herdado de ConfigurationElement)
IsModified()

Indica se este elemento de configuração foi modificado desde a última vez que foi guardado ou carregado quando implementado numa classe derivada.

(Herdado de ConfigurationSection)
IsReadOnly()

Recebe um valor que indica se o ConfigurationElement objeto é apenas de leitura.

(Herdado de ConfigurationElement)
ListErrors(IList)

Adiciona os erros de propriedades inválidas neste ConfigurationElement objeto, e em todos os subelementos, à lista passada.

(Herdado de ConfigurationElement)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
OnDeserializeUnrecognizedAttribute(String, String)

Recebe um valor que indica se um atributo desconhecido é encontrado durante a desserialização.

(Herdado de ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Obtém um valor que indica se um elemento desconhecido é encontrado durante a desserialização.

(Herdado de ConfigurationElement)
OnRequiredPropertyNotFound(String)

Lança uma exceção quando uma propriedade exigida não é encontrada.

(Herdado de ConfigurationElement)
PostDeserialize()

Chamada após desserialização.

(Herdado de ConfigurationElement)
PreSerialize(XmlWriter)

Chamado antes da serialização.

(Herdado de ConfigurationElement)
Reset(ConfigurationElement)

Reinicia o estado interno do ConfigurationElement objeto, incluindo os bloqueios e as coleções de propriedades.

(Herdado de ConfigurationElement)
ResetModified()

Redefine o valor do IsModified() método para false quando implementado numa classe derivada.

(Herdado de ConfigurationSection)
SerializeElement(XmlWriter, Boolean)

Escreve o conteúdo deste elemento de configuração no ficheiro de configuração quando implementado numa classe derivada.

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

Cria uma string XML contendo uma vista não fundida do ConfigurationSection objeto como uma única secção para escrever num ficheiro.

(Herdado de ConfigurationSection)
SerializeToXmlElement(XmlWriter, String)

Escreve as etiquetas exteriores deste elemento de configuração no ficheiro de configuração quando implementado numa classe derivada.

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

Define uma propriedade para o valor especificado.

(Herdado de ConfigurationElement)
SetReadOnly()

Define a IsReadOnly() propriedade para o ConfigurationElement objeto e todos os subelementos.

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

Indica se o elemento especificado deve ser serializado quando a hierarquia de objetos de configuração é serializada para a versão alvo especificada do .NET Framework.

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

Indica se a propriedade especificada deve ser serializada quando a hierarquia de objetos de configuração é serializada para a versão alvo especificada do .NET Framework.

(Herdado de ConfigurationSection)
ShouldSerializeSectionInTargetVersion(FrameworkName)

Indica se a instância atual ConfigurationSection deve ser serializada quando a hierarquia de objetos de configuração é serializada para a versão alvo especificada do .NET Framework.

(Herdado de ConfigurationSection)
ToString()

Devolve uma cadeia que representa o objeto atual.

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

Modifica o ConfigurationElement objeto para remover todos os valores que não deveriam ser guardados.

(Herdado de ConfigurationElement)

Aplica-se a

Ver também