Condividi tramite


ProfileSection Classe

Definizione

La ProfileSection classe consente di accedere e modificare a livello di codice la profile sezione di un file di configurazione. Questa classe non può essere ereditata.

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

Esempio

Nell'estratto del file di configurazione seguente viene illustrato come specificare in modo dichiarativo i valori per diverse proprietà della 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>

Nell'esempio di codice seguente viene illustrato come usare il 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

Commenti

La ProfileSection classe consente di accedere e modificare a livello di codice il contenuto della sezione del file profile di configurazione. La profile sezione del file di configurazione specifica uno schema per i profili utente. In fase di esecuzione, il sistema di compilazione ASP.NET usa le informazioni specificate nella profile sezione per generare una classe denominata ProfileCommon, derivata da ProfileBase. La definizione della ProfileCommon classe si basa sulle proprietà definite nella profile sezione del file di configurazione. La classe consente di accedere e modificare i valori per i singoli profili. Viene creata un'istanza di questa classe per ogni profilo utente ed è possibile accedere ai singoli valori del profilo nel codice tramite la HttpContext.Profile proprietà . Per altre informazioni sulle funzionalità del profilo aggiunte a ASP.NET 2.0, vedere Panoramica delle proprietà del profilo ASP.NET.

Costruttori

Nome Descrizione
ProfileSection()

Inizializza una nuova istanza della ProfileSection classe utilizzando le impostazioni predefinite.

Proprietà

Nome Descrizione
AutomaticSaveEnabled

Ottiene o imposta un valore che determina se le modifiche apportate alle informazioni sul profilo utente vengono salvate automaticamente all'uscita della pagina.

CurrentConfiguration

Ottiene un riferimento all'istanza di primo livello Configuration che rappresenta la gerarchia di configurazione a cui appartiene l'istanza corrente ConfigurationElement .

(Ereditato da ConfigurationElement)
DefaultProvider

Ottiene o imposta il nome del provider di profili predefinito.

ElementInformation

Ottiene un ElementInformation oggetto che contiene le informazioni e le funzionalità non personalizzabili dell'oggetto ConfigurationElement .

(Ereditato da ConfigurationElement)
ElementProperty

Ottiene l'oggetto ConfigurationElementProperty che rappresenta l'oggetto ConfigurationElement stesso.

(Ereditato da ConfigurationElement)
Enabled

Ottiene o imposta un valore che indica se la funzionalità del profilo di ASP.NET è abilitata.

EvaluationContext

Ottiene l'oggetto ContextInformation per l'oggetto ConfigurationElement.

(Ereditato da ConfigurationElement)
HasContext

Ottiene un valore che indica se la CurrentConfiguration proprietà è null.

(Ereditato da ConfigurationElement)
Inherits

Ottiene o imposta un riferimento al tipo per un tipo personalizzato derivato da ProfileBase.

Item[ConfigurationProperty]

Ottiene o imposta una proprietà o un attributo di questo elemento di configurazione.

(Ereditato da ConfigurationElement)
Item[String]

Ottiene o imposta una proprietà, un attributo o un elemento figlio di questo elemento di configurazione.

(Ereditato da ConfigurationElement)
LockAllAttributesExcept

Ottiene la raccolta di attributi bloccati.

(Ereditato da ConfigurationElement)
LockAllElementsExcept

Ottiene la raccolta di elementi bloccati.

(Ereditato da ConfigurationElement)
LockAttributes

Ottiene la raccolta di attributi bloccati.

(Ereditato da ConfigurationElement)
LockElements

Ottiene la raccolta di elementi bloccati.

(Ereditato da ConfigurationElement)
LockItem

Ottiene o imposta un valore che indica se l'elemento è bloccato.

(Ereditato da ConfigurationElement)
Properties

Ottiene la raccolta di proprietà.

(Ereditato da ConfigurationElement)
PropertySettings

Ottiene una RootProfilePropertySettingsCollection raccolta di ProfilePropertySettings oggetti .

Providers

Ottiene una raccolta di ProviderSettings oggetti .

SectionInformation

Ottiene un SectionInformation oggetto che contiene le informazioni e le funzionalità non personalizzabili dell'oggetto ConfigurationSection .

(Ereditato da ConfigurationSection)

Metodi

Nome Descrizione
DeserializeElement(XmlReader, Boolean)

Legge il codice XML dal file di configurazione.

(Ereditato da ConfigurationElement)
DeserializeSection(XmlReader)

Legge il codice XML dal file di configurazione.

(Ereditato da ConfigurationSection)
Equals(Object)

Confronta l'istanza corrente ConfigurationElement con l'oggetto specificato.

(Ereditato da ConfigurationElement)
GetHashCode()

Ottiene un valore univoco che rappresenta l'istanza corrente ConfigurationElement .

(Ereditato da ConfigurationElement)
GetRuntimeObject()

Restituisce un oggetto personalizzato quando ne viene eseguito l'override in una classe derivata.

(Ereditato da ConfigurationSection)
GetTransformedAssemblyString(String)

Restituisce la versione trasformata del nome dell'assembly specificato.

(Ereditato da ConfigurationElement)
GetTransformedTypeString(String)

Restituisce la versione trasformata del nome del tipo specificato.

(Ereditato da ConfigurationElement)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
Init()

Imposta l'oggetto ConfigurationElement sullo stato iniziale.

(Ereditato da ConfigurationElement)
InitializeDefault()

Utilizzato per inizializzare un set predefinito di valori per l'oggetto ConfigurationElement .

(Ereditato da ConfigurationElement)
IsModified()

Indica se questo elemento di configurazione è stato modificato dopo l'ultimo salvataggio o caricamento quando implementato in una classe derivata.

(Ereditato da ConfigurationSection)
IsReadOnly()

Ottiene un valore che indica se l'oggetto ConfigurationElement è di sola lettura.

(Ereditato da ConfigurationElement)
ListErrors(IList)

Aggiunge gli errori di proprietà non validi in questo ConfigurationElement oggetto e in tutti i sottoelementi all'elenco passato.

(Ereditato da ConfigurationElement)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
OnDeserializeUnrecognizedAttribute(String, String)

Ottiene un valore che indica se viene rilevato un attributo sconosciuto durante la deserializzazione.

(Ereditato da ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Ottiene un valore che indica se durante la deserializzazione viene rilevato un elemento sconosciuto.

(Ereditato da ConfigurationElement)
OnRequiredPropertyNotFound(String)

Genera un'eccezione quando non viene trovata una proprietà obbligatoria.

(Ereditato da ConfigurationElement)
PostDeserialize()

Chiamato dopo la deserializzazione.

(Ereditato da ConfigurationElement)
PreSerialize(XmlWriter)

Chiamato prima della serializzazione.

(Ereditato da ConfigurationElement)
Reset(ConfigurationElement)

Reimposta lo stato interno dell'oggetto ConfigurationElement , inclusi i blocchi e gli insiemi di proprietà.

(Ereditato da ConfigurationElement)
ResetModified()

Reimposta il valore del IsModified() metodo su false quando implementato in una classe derivata.

(Ereditato da ConfigurationSection)
SerializeElement(XmlWriter, Boolean)

Scrive il contenuto di questo elemento di configurazione nel file di configurazione quando implementato in una classe derivata.

(Ereditato da ConfigurationElement)
SerializeSection(ConfigurationElement, String, ConfigurationSaveMode)

Crea una stringa XML contenente una visualizzazione non archiviata dell'oggetto ConfigurationSection come singola sezione da scrivere in un file.

(Ereditato da ConfigurationSection)
SerializeToXmlElement(XmlWriter, String)

Scrive i tag esterni di questo elemento di configurazione nel file di configurazione quando implementato in una classe derivata.

(Ereditato da ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Imposta una proprietà sul valore specificato.

(Ereditato da ConfigurationElement)
SetReadOnly()

Imposta la IsReadOnly() proprietà per l'oggetto ConfigurationElement e tutti i sottoelementi.

(Ereditato da ConfigurationElement)
ShouldSerializeElementInTargetVersion(ConfigurationElement, String, FrameworkName)

Indica se l'elemento specificato deve essere serializzato quando la gerarchia degli oggetti di configurazione viene serializzata per la versione di destinazione specificata di .NET Framework.

(Ereditato da ConfigurationSection)
ShouldSerializePropertyInTargetVersion(ConfigurationProperty, String, FrameworkName, ConfigurationElement)

Indica se la proprietà specificata deve essere serializzata quando la gerarchia di oggetti di configurazione viene serializzata per la versione di destinazione specificata di .NET Framework.

(Ereditato da ConfigurationSection)
ShouldSerializeSectionInTargetVersion(FrameworkName)

Indica se l'istanza corrente ConfigurationSection deve essere serializzata quando la gerarchia degli oggetti di configurazione viene serializzata per la versione di destinazione specificata di .NET Framework.

(Ereditato da ConfigurationSection)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Modifica l'oggetto ConfigurationElement per rimuovere tutti i valori che non devono essere salvati.

(Ereditato da ConfigurationElement)

Si applica a

Vedi anche