Share via


ProfileSection Clase

Definición

La clase ProfileSection permite obtener acceso y modificar mediante programación la sección profile de un archivo de configuración. Esta clase no puede heredarse.

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
Herencia

Ejemplos

El siguiente extracto del archivo de configuración muestra cómo especificar de forma declarativa valores para varias propiedades de la ProfileSection clase .

<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>  

En el ejemplo de código siguiente se muestra cómo usar el 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

Comentarios

La ProfileSection clase proporciona una manera de acceder y modificar mediante programación el contenido de la sección del archivo profile de configuración. La profile sección del archivo de configuración especifica un esquema para los perfiles de usuario. En tiempo de ejecución, el sistema de compilación de ASP.NET usa la información especificada en la profile sección para generar una clase denominada ProfileCommon, que se deriva de ProfileBase. La ProfileCommon definición de clase se basa en las propiedades definidas en la profile sección del archivo de configuración. La clase permite tener acceso a los perfiles individuales y modificarlos. Se crea una instancia de esta clase para cada perfil de usuario y puede acceder a los valores de perfil individuales del código a través de la HttpContext.Profile propiedad . Para obtener más información sobre las características de perfil agregadas a ASP.NET 2.0, consulte ASP.NET Información general sobre las propiedades del perfil.

Constructores

ProfileSection()

Inicializa una nueva instancia de la clase ProfileSection usando la configuración predeterminada.

Propiedades

AutomaticSaveEnabled

Obtiene o establece un valor que determina si los cambios en la información del perfil de usuario se guardan automáticamente al salir de la página.

CurrentConfiguration

Obtiene una referencia a la instancia de Configuration de nivel superior que representa la jerarquía de configuración a la que pertenece la instancia actual de ConfigurationElement.

(Heredado de ConfigurationElement)
DefaultProvider

Obtiene o establece el nombre del proveedor de perfiles predeterminado.

ElementInformation

Obtiene un objeto ElementInformation que contiene la funcionalidad e información no personalizable del objeto ConfigurationElement.

(Heredado de ConfigurationElement)
ElementProperty

Obtiene el objeto ConfigurationElementProperty que representa al propio objeto ConfigurationElement.

(Heredado de ConfigurationElement)
Enabled

Obtiene o establece un valor que indica si la característica de perfiles de ASP.NET está habilitada.

EvaluationContext

Obtiene el objeto ContextInformation para el objeto ConfigurationElement.

(Heredado de ConfigurationElement)
HasContext

Obtiene un valor que indica si la propiedad CurrentConfiguration es null.

(Heredado de ConfigurationElement)
Inherits

Obtiene o establece una referencia de tipo para un tipo personalizado derivado de ProfileBase.

Item[ConfigurationProperty]

Obtiene o establece una propiedad o atributo de este elemento de configuración.

(Heredado de ConfigurationElement)
Item[String]

Obtiene o establece una propiedad, un atributo o un elemento secundario de este elemento de configuración.

(Heredado de ConfigurationElement)
LockAllAttributesExcept

Obtiene la colección de atributos bloqueados.

(Heredado de ConfigurationElement)
LockAllElementsExcept

Obtiene la colección de elementos bloqueados.

(Heredado de ConfigurationElement)
LockAttributes

Obtiene la colección de atributos bloqueados.

(Heredado de ConfigurationElement)
LockElements

Obtiene la colección de elementos bloqueados.

(Heredado de ConfigurationElement)
LockItem

Obtiene o establece un valor que indica si el elemento está bloqueado.

(Heredado de ConfigurationElement)
Properties

Obtiene la colección de propiedades.

(Heredado de ConfigurationElement)
PropertySettings

Obtiene una colección RootProfilePropertySettingsCollection de objetos ProfilePropertySettings.

Providers

Obtiene una colección de objetos ProviderSettings.

SectionInformation

Obtiene un objeto SectionInformation que contiene la funcionalidad e información no personalizable del objeto ConfigurationSection.

(Heredado de ConfigurationSection)

Métodos

DeserializeElement(XmlReader, Boolean)

Lee XML del archivo de configuración.

(Heredado de ConfigurationElement)
DeserializeSection(XmlReader)

Lee XML del archivo de configuración.

(Heredado de ConfigurationSection)
Equals(Object)

Compara la instancia actual de ConfigurationElement con el objeto especificado.

(Heredado de ConfigurationElement)
GetHashCode()

Obtiene un valor único que representa la instancia actual de ConfigurationElement.

(Heredado de ConfigurationElement)
GetRuntimeObject()

Devuelve un objeto personalizado cuando se reemplaza en una clase derivada.

(Heredado de ConfigurationSection)
GetTransformedAssemblyString(String)

Devuelve la versión transformada del nombre de ensamblado especificado.

(Heredado de ConfigurationElement)
GetTransformedTypeString(String)

Devuelve la versión transformada del nombre de tipo especificado.

(Heredado de ConfigurationElement)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
Init()

Establece el objeto ConfigurationElement en su estado inicial.

(Heredado de ConfigurationElement)
InitializeDefault()

Se utiliza para inicializar un conjunto predeterminado de valores para el objeto ConfigurationElement.

(Heredado de ConfigurationElement)
IsModified()

Indica si se ha modificado este elemento de configuración desde la última vez en que se guardo o cargó al implementarlo en una clase derivada.

(Heredado de ConfigurationSection)
IsReadOnly()

Obtiene un valor que indica si el objeto ConfigurationElement es de solo lectura.

(Heredado de ConfigurationElement)
ListErrors(IList)

Agrega a la lista que se pasa los errores de propiedad no válida que hay en este objeto ConfigurationElement y en todos los subelementos.

(Heredado de ConfigurationElement)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnDeserializeUnrecognizedAttribute(String, String)

Obtiene un valor que indica si se ha encontrado un atributo desconocido durante la deserialización.

(Heredado de ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Obtiene un valor que indica si se ha encontrado un elemento desconocido durante la deserialización.

(Heredado de ConfigurationElement)
OnRequiredPropertyNotFound(String)

Se inicia una excepción cuando no se encuentra una propiedad necesaria.

(Heredado de ConfigurationElement)
PostDeserialize()

Se llama a este método después de la deserialización.

(Heredado de ConfigurationElement)
PreSerialize(XmlWriter)

Se llama a este método antes de la serialización.

(Heredado de ConfigurationElement)
Reset(ConfigurationElement)

Restablece el estado interno del objeto ConfigurationElement, incluyendo los bloqueos y las colecciones de propiedades.

(Heredado de ConfigurationElement)
ResetModified()

Restablece el valor del método IsModified() en false cuando se implementa en una clase derivada.

(Heredado de ConfigurationSection)
SerializeElement(XmlWriter, Boolean)

Escribe el contenido de este elemento de configuración en el archivo de configuración cuando se implementa en una clase derivada.

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

Crea una cadena XML que contiene una vista separada del objeto ConfigurationSection como una sección única para escribir en un archivo.

(Heredado de ConfigurationSection)
SerializeToXmlElement(XmlWriter, String)

Escribe las etiquetas externas de este elemento de configuración en el archivo de configuración cuando se implementa en una clase derivada.

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

Establece una propiedad en el valor especificado.

(Heredado de ConfigurationElement)
SetReadOnly()

Establece la propiedad IsReadOnly() para el objeto ConfigurationElement y todos los subelementos.

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

Indica si el elemento especificado debe serializarse cuando la jerarquía de objetos de configuración se serializa para la versión de destino especificada del .NET Framework.

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

Indica si la propiedad especificada se debe serializar cuando la jerarquía de objetos de configuración se serializa para la versión de destino especificada del .NET Framework.

(Heredado de ConfigurationSection)
ShouldSerializeSectionInTargetVersion(FrameworkName)

Indica si la instancia actual ConfigurationSection se debe serializar cuando la jerarquía de objetos de configuración se serializa para la versión de destino especificada del .NET Framework.

(Heredado de ConfigurationSection)
ToString()

Devuelve una cadena que representa el objeto actual.

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

Modifica el objeto ConfigurationElement para quitar todos los valores que no se deben guardar.

(Heredado de ConfigurationElement)

Se aplica a

Consulte también