To create the configuration handler, we will need to create a new class and import the System.Configuration namespace. Our new class will also have to inherit the ConfigurationSection class. In version 1.x the handler would implement the IConfigurationSectionHandler interface. However, that interface has now deprecated. Continuing on, we will add an empty construct and a "loaded" construct. I consider a class containing a construct with all attributes a loaded construct. We will also add two properties to the class and two attributes to each property. In Listing 1 an example of this is shown in both Visual Basic and C#.
Listing 1 - An example of a Configuration Handler in Visual Basic .NET and C#
[Visual Basic .NET]
'Class that creates the configuration handler Public Class MyCustomConfigurationHandler Inherits ConfigurationSection 'Empty Construct Public Sub MyCustomConfigurationHandler() End Sub 'Loaded Construct Public Sub MyCustomConfigurationHandler(ByVal firstValue As Integer, _ secondValue As Integer) FirstNumber = firstValue SecondNumber = secondValue End Sub 'First Number Property <ConfigurationProperty("firstNumber", DefaultValue = 1, IsRequired = True)> _ <IntegerValidator(MinValue = -100, MaxValue = 100)> _ Public Property FirstNumber() As Integer Get Return CInt(Me("firstNumber")) End Get Set(ByVal Value As Integer) Me("firstNumber") = Value End Set End Property 'Second Number Property <ConfigurationProperty("secondNumber", DefaultValue = 1, IsRequired = True)> _ <IntegerValidator(MinValue = -100, MaxValue = 100)> _ Public Property SecondNumber() As Integer Get Return CInt(Me("secondNumber")) End Get Set(ByVal Value As Integer) Me("secondNumber") = Value End Set End Property End Class
[Visual C# .NET]
// Class that creates the configuration handler public class MyCustomConfigurationHandler: ConfigurationSection { // Empty Construct public MyCustomConfigurationHandler(){} // Loaded Construct public MyCustomConfigurationHandler(Int32 firstValue, Int32 secondValue) { FirstNumber = firstValue; SecondNumber = secondValue; } // First Number Property [ConfigurationProperty("firstNumber", DefaultValue = 1, IsRequired = true) ][IntegerValidator(MinValue = - 100, MaxValue = 100)] public Int32 FirstNumber { get { return (Int32)this["firstNumber"]; } set { this["firstNumber"] = value; } } // Second Number Property [ConfigurationProperty("secondNumber", DefaultValue = 1, IsRequired = true) ][IntegerValidator(MinValue = - 100, MaxValue = 100)] public Int32 SecondNumber { get { return (Int32)this["secondNumber"]; } set { this["secondNumber"] = value; } } }
The ConfigurationProperty attribute for the property has only one required field and that is the property name as specified in the web.config file. The DefaultValue attribute field is just that. It is the default value for the property. The IsRequired attribute field specifies whether or not the property is required to be contained in the configuration section's attribute list.
User Comments