Nota: questa classe è stata introdotta con .NET Framework versione 2.0.
Rappresenta una sezione all'interno di un file di configurazione.
Spazio dei nomi: System.Configuration
Assembly: System.Configuration (in system.configuration.dll)
Visual Basic - (Dichiarazione)
Public MustInherit Class ConfigurationSection
Inherits ConfigurationElement
Dim instance As ConfigurationSection
public abstract class ConfigurationSection : ConfigurationElement
public ref class ConfigurationSection abstract : public ConfigurationElement
public abstract class ConfigurationSection extends ConfigurationElement
public abstract class ConfigurationSection extends ConfigurationElement
La classe ConfigurationSection viene utilizzata per implementare un tipo di sezione personalizzata. Estendere la classe ConfigurationSection per consentire la gestione personalizzata e l'accesso a livello di codice alle sezioni di configurazione personalizzate.
Una sezione registra il tipo di gestione con una voce nelle configSections.
Fare riferimento alla porzione di file di configurazione riportata nell'esempio successivo.
Nota |
|---|
| Nelle versioni precedenti di .NET Framework i gestori delle sezioni di configurazione vengono utilizzati per apportare modifiche alle impostazioni di configurazione a livello di codice. Attualmente, tutte le sezioni di configurazione predefinite sono rappresentate dalle classi che estendono la classe ConfigurationSection. |
Note per gli implementatori:
È possibile utilizzare un modello di codifica a livello di codice o dichiarativo (con attributi) per creare sezioni di configurazione personalizzate.
-
Modello a livello di codice. Questo modello richiede che per ogni attributo di sezione venga creata una proprietà per ottenerne e/o impostarne il valore e aggiungerlo all'elenco proprietà interno della classe base ConfigurationElement sottostante.
-
Modello dichiarativo. Questo modello più semplice, detto anche modello con attributi, consente di definire un attributo di sezione utilizzando una proprietà e di decorarlo con attributi. Questi attributi indicano al sistema di configurazione ASP.NET i tipi di proprietà e i valori predefiniti. Con queste informazioni, ottenute tramite la reflection, il sistema di configurazione ASP.NET crea gli oggetti della proprietà della sezione ed esegue l'inizializzazione necessaria.
Configuration è la classe che consente l'accesso a livello di codice per la modifica dei file di configurazione. È possibile accedere a questi file per la lettura o la scrittura come descritto di seguito.
Se l'applicazione deve poter accedere in sola lettura alla propria configurazione, è consigliabile utilizzare i metodi GetSection in overload nel caso di applicazioni Web. Oppure il metodo GetSection in caso di applicazioni client.
Questi metodi forniscono l'accesso ai valori di configurazione memorizzati nella cache per l'applicazione corrente, garantendo prestazioni migliori rispetto alla classe Configuration.
Nota |
|---|
| Se si utilizza un metodo GetSection statico che accetta un parametro path, il parametro path deve fare riferimento all'applicazione in cui il codice viene eseguito; in caso contrario il parametro viene ignorato e vengono restituite le informazioni di configurazione per l'applicazione in esecuzione. |
Nell'esempio riportato di seguito viene illustrato come implementare una sezione personalizzata a livello di codice.
Vedere ConfigurationElement per un esempio completo di implementazione e utilizzo di una sezione personalizzata implementata mediante il modello con attributi.
' Define a custom section.
' The CustomSection type alows to define a custom section
' programmatically.
NotInheritable Public Class CustomSection
Inherits ConfigurationSection
' The collection (property bag) that conatains
' the section properties.
Private Shared _Properties As ConfigurationPropertyCollection
' Internal flag to disable
' property setting.
Private Shared _ReadOnly As Boolean
' The FileName property.
Private Shared _FileName As New ConfigurationProperty( _
"fileName", GetType(String), _
"default.txt", _
ConfigurationPropertyOptions.IsRequired)
' The MasUsers property.
Private Shared _MaxUsers As New ConfigurationProperty( _
"maxUsers", GetType(Long), _
CType(1000, Long), _
ConfigurationPropertyOptions.None)
' The MaxIdleTime property.
Private Shared _MaxIdleTime As New ConfigurationProperty( _
"maxIdleTime", GetType(TimeSpan), _
TimeSpan.FromMinutes(5), _
ConfigurationPropertyOptions.IsRequired)
' CustomSection constructor.
Public Sub New()
' Property initialization
_Properties = _
New ConfigurationPropertyCollection()
_Properties.Add(_FileName)
_Properties.Add(_MaxUsers)
_Properties.Add(_MaxIdleTime)
End Sub 'New
' This is a key customization.
' It returns the initialized property bag.
Protected Overrides ReadOnly Property Properties() _
As ConfigurationPropertyCollection
Get
Return _Properties
End Get
End Property
Private Shadows ReadOnly Property IsReadOnly() As Boolean
Get
Return _ReadOnly
End Get
End Property
' Use this to disable property setting.
Private Sub ThrowIfReadOnly(propertyName As String)
If IsReadOnly Then
Throw New ConfigurationErrorsException( _
"The property " + propertyName + " is read only.")
End If
End Sub 'ThrowIfReadOnly
' Customizes the use of CustomSection
' by setting _ReadOnly to false.
' Remember you must use it along with ThrowIfReadOnly.
Protected Overrides Function GetRuntimeObject() As Object
' To enable property setting just assign true to
' the following flag.
_ReadOnly = True
Return MyBase.GetRuntimeObject()
End Function 'GetRuntimeObject
<StringValidator( _
InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _
MinLength:=1, MaxLength:=60)> _
Public Property FileName() As String
Get
Return CStr(Me("fileName"))
End Get
Set(ByVal value As String)
' With this you disable the setting.
' Renemmber that the _ReadOnly flag must
' be set to true in the GetRuntimeObject.
ThrowIfReadOnly("FileName")
Me("fileName") = value
End Set
End Property
<LongValidator( _
MinValue:=1, MaxValue:=1000000, _
ExcludeRange:=False)> _
Public Property MaxUsers() As Long
Get
Return Fix(Me("maxUsers"))
End Get
Set(ByVal value As Long)
Me("maxUsers") = Value
End Set
End Property
<TimeSpanValidator( _
MinValueString:="0:0:30", _
MaxValueString:="5:00:0", ExcludeRange:=False)> _
Public Property MaxIdleTime() As TimeSpan
Get
Return CType(Me("maxIdleTime"), TimeSpan)
End Get
Set(ByVal value As TimeSpan)
Me("maxIdleTime") = Value
End Set
End Property
End Class 'CustomSection
// Define a custom section.
// The CustomSection type alows to define a custom section
// programmatically.
public sealed class CustomSection :
ConfigurationSection
{
// The collection (property bag) that conatains
// the section properties.
private static ConfigurationPropertyCollection _Properties;
// Internal flag to disable
// property setting.
private static bool _ReadOnly;
// The FileName property.
private static readonly ConfigurationProperty _FileName =
new ConfigurationProperty("fileName",
typeof(string),"default.txt",
ConfigurationPropertyOptions.IsRequired);
// The MasUsers property.
private static readonly ConfigurationProperty _MaxUsers =
new ConfigurationProperty("maxUsers",
typeof(long), (long)1000,
ConfigurationPropertyOptions.None);
// The MaxIdleTime property.
private static readonly ConfigurationProperty _MaxIdleTime =
new ConfigurationProperty("maxIdleTime",
typeof(TimeSpan), TimeSpan.FromMinutes(5),
ConfigurationPropertyOptions.IsRequired);
// CustomSection constructor.
public CustomSection()
{
// Property initialization
_Properties =
new ConfigurationPropertyCollection();
_Properties.Add(_FileName);
_Properties.Add(_MaxUsers);
_Properties.Add(_MaxIdleTime);
}
// This is a key customization.
// It returns the initialized property bag.
protected override ConfigurationPropertyCollection Properties
{
get
{
return _Properties;
}
}
private new bool IsReadOnly
{
get
{
return _ReadOnly;
}
}
// Use this to disable property setting.
private void ThrowIfReadOnly(string propertyName)
{
if (IsReadOnly)
throw new ConfigurationErrorsException(
"The property " + propertyName + " is read only.");
}
// Customizes the use of CustomSection
// by setting _ReadOnly to false.
// Remember you must use it along with ThrowIfReadOnly.
protected override object GetRuntimeObject()
{
// To enable property setting just assign true to
// the following flag.
_ReadOnly = true;
return base.GetRuntimeObject();
}
[StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
MinLength = 1, MaxLength = 60)]
public string FileName
{
get
{
return (string)this["fileName"];
}
set
{
// With this you disable the setting.
// Renemmber that the _ReadOnly flag must
// be set to true in the GetRuntimeObject.
ThrowIfReadOnly("FileName");
this["fileName"] = value;
}
}
[LongValidator(MinValue = 1, MaxValue = 1000000,
ExcludeRange = false)]
public long MaxUsers
{
get
{
return (long)this["maxUsers"];
}
set
{
this["maxUsers"] = value;
}
}
[TimeSpanValidator(MinValueString = "0:0:30",
MaxValueString = "5:00:0",
ExcludeRange = false)]
public TimeSpan MaxIdleTime
{
get
{
return (TimeSpan)this["maxIdleTime"];
}
set
{
this["maxIdleTime"] = value;
}
}
}
Si tratta di una porzione del file di configurazione applicata all'esempio precedente.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="CustomSection" type="Samples.AspNet, CustomConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />
</configSections>
<CustomSection fileName="default.txt" maxUsers="1000" maxIdleTime="00:15:00" />
</configuration>
Gerarchia di ereditarietà
System.Object
System.Configuration.ConfigurationElement
System.Configuration.ConfigurationSection
Classi derivate
I membri statici pubblici (Shared in Visual Basic) di questo tipo sono validi per le operazioni multithreading. I membri di istanza non sono garantiti come thread safe.
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema.
Informazioni sulla versione
.NET Framework
Supportato in: 2.0