ASP.NET 2.0 Unleashed

You can add custom configuration sections to a web configuration file. You can use a custom configuration section to store whatever information you want.

For example, if you need to manage a large number of database connection strings, then you might want to create a custom database connection string configuration section. Or, if you want to follow the Provider Model and implement a custom provider, then you need to create a custom configuration section for your provider.

You create a custom configuration section by inheriting a new class from the base ConfigurationSection class. For example, the class in Listing 26.18 represents a simple custom configuration section.

Listing 26.18. App_Code\DesignSection.vb

[View full width]

Imports System Imports System.Configuration Imports System.Drawing Namespace AspNetUnleashed Public Class DesignSection Inherits ConfigurationSection <ConfigurationProperty("backcolor", DefaultValue:="lightblue", IsRequired:=True)> _ Public Property BackColor() As Color Get Return CType(Me("backcolor"), Color) End Get Set(ByVal Value As Color) Me("backcolor") = Value End Set End Property <ConfigurationProperty("styleSheetUrl", DefaultValue:="~/styles/style.css" ,IsRequired:=True)> _ <RegexStringValidator(".css$")> _ Public Property StyleSheetUrl() As String Get Return CType(Me("styleSheetUrl"), String) End Get Set(ByVal Value As String) Me("styleSheetUrl") = Value End Set End Property Public Sub New(ByVal backcolor As Color, ByVal styleSheetUrl As String) Me.BackColor = backcolor Me.StyleSheetUrl = styleSheetUrl End Sub Public Sub New() End Sub End Class End Namespace

The class in Listing 26.18 represents a Design configuration section. This section has two properties: BackColor and StyleSheetUrl.

Notice that both properties are decorated with ConfigurationProperty attributes. The ConfigurationProperty attribute is used to map the property to an element attribute in the configuration file. When you declare the ConfigurationProperty attribute, you can use the following parameters:

  • Name Enables you to specify the name of the attribute in the configuration file that corresponds to the property.

  • DefaultValue Enables you to specify the default value of the property.

  • IsDefaultCollection Enables you to specify whether the property represents the default collection of an element.

  • IsKey Enables you to specify whether the property represents a key for a collection of configuration elements.

  • IsRequired Enables you to specify whether this property must have a value.

  • Options Enables you to use flags to specify the values of the above options.

You also can use validators when defining configuration properties. For example, in Listing 26.18, the RegexStringValidator is used to check whether the value of the StyleSheetUrl property ends with a .css extension.

You can use the following validators with configuration properties:

  • CallbackValidator Enables you to specify a custom method to use to validate a property value.

  • IntegerValidator Enables you to validate whether a property value is an integer value (System.Int32).

  • LongValidator Enables you to validate whether a property value is a long value (System.Int64).

  • PositiveTimeSpanValidator Enables you to validate whether a property value is a valid time span.

  • RegexStringValidator Enables you to validate a property value against a regular expression pattern.

  • StringValidator Enables you to validate a property value that represents a string against a minimum length, maximum length, and list of invalid characters.

  • SubClassTypeValidator Enables you to validate whether the value of a property is inherited from a particular class

  • TimeSpanValidator Enables you to validate a property value that represents a time span against a minimum and maximum value.

Warning

When you use validators such as the RegexStringValidator, make sure that you provide a property with a default value by using the DefaultValue parameter with the ConfigurationProperty attribute.

After you create a custom configuration section, you need to register it in a configuration file before you can use it. The web configuration file in Listing 26.19 adds the DesignSection configuration section to the system.web section.

Listing 26.19. Web.config

<configuration> <configSections> <sectionGroup name="system.web"> <section name="design" type="AspNetUnleashed.DesignSection" allowLocation="true" allowDefinition="Everywhere"/> </sectionGroup> </configSections> <system.web> <design backcolor="red" styleSheetUrl="~/styles/style.css"/> </system.web> </configuration>

You are not required to add a custom configuration section to any particular configuration section group. For that matter, you are not required to add a custom configuration section to any configuration section group at all.

After you register a custom configuration section, you can use it just like any of the standard configuration sections. You can use the methods of the WebConfigurationManager class to retrieve and modify the custom section.

For example, the page in Listing 26.20 uses the custom configuration section just created to retrieve the page background color and style sheet (see Figure 26.12).

Figure 26.12. Using the custom configuration section to modify the page style and background color.

Listing 26.20. ShowDesignSection.aspx

[View full width]

<%@ Page Language="VB" %> <%@ Import Namespace="AspNetUnleashed" %> <%@ Import Namespace="System.Web.Configuration" %> <%@ Import Namespace="System.Drawing" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() ' Get configuration Dim section As DesignSection = CType(WebConfigurationManager .GetWebApplicationSection("system.web/design"), DesignSection) ' Set Background Color htmlBody.Attributes("bgcolor") = ColorTranslator.ToHtml(section.BackColor) ' Set style sheet Dim link As New HtmlLink() link.Href = section.StyleSheetUrl link.Attributes.Add("rel", "stylesheet") link.Attributes.Add("type", "text/css") Page.Header.Controls.Add(link) End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Show Design Section</title> </head> <body runat="server"> <form runat="server"> <div> <h1>Custom Configuration Section Sample</h1> </div> </form> </body> </html>

Creating a Configuration Element Collection

A configuration element can contain a collection of child elements. For example, if you need to create a custom configuration section to configure a provider, then you use child elements to represent the list of providers.

The class in Listing 26.21 represents a configuration section for a ShoppingCart. The configuration section includes three properties: MaximumItems, DefaultProvider, and Providers. The Providers property represents a collection of shopping cart providers.

Listing 26.21. App_Code\ShoppingCartSection.vb

Imports System Imports System.Configuration Namespace AspNetUnleashed Public Class ShoppingCartSection Inherits ConfigurationSection <ConfigurationProperty("maximumItems", DefaultValue:=100, IsRequired:=True)> _ Public Property MaximumItems() As Integer Get Return CType(Me("maximumItems"), Integer) End Get Set(ByVal Value As Integer) Me("maximumItems") = Value End Set End Property <ConfigurationProperty("defaultProvider")> _ Public Property DefaultProvider() As String Get Return CType(Me("defaultProvider"), String) End Get Set(ByVal Value As String) Me("defaultProvider") = value End Set End Property <ConfigurationProperty("providers", IsDefaultCollection:=False)> _ Public ReadOnly Property Providers() As ProviderSettingsCollection Get Return CType(Me("providers"), ProviderSettingsCollection) End Get End Property Public Sub New(ByVal maximumItems As Integer, ByVal defaultProvider As String) Me.MaximumItems = maximumItems Me.DefaultProvider = defaultProvider End Sub Public Sub New() End Sub End Class End Namespace

The Providers property returns an instance of the ProviderSettingsCollection class. This class is contained in the System.Configuration namespace.

The web configuration file in Listing 26.22 illustrates how you can use the ShoppingCartSection.

Listing 26.22. Web.config

<configuration> <configSections> <sectionGroup name="system.web"> <section name="shoppingCart" type="AspNetUnleashed.ShoppingCartSection" allowLocation="true" allowDefinition="Everywhere" /> </sectionGroup> </configSections> <system.web> <shoppingCart maximumItems="50" defaultProvider="SqlShoppingCartProvider"> <providers> <add name="SqlShoppingCartProvider" type="AspNetUnleashed.SqlShoppingCartProvider" /> <add name="XmlShoppingCartProvider" type="AspNetUnleashed.XmlShoppingCartProvider" /> </providers> </shoppingCart> </system.web> </configuration>

The ShoppingCartSection class takes advantage of an existing class in the .NET Framework: the ProviderSettingsCollection class. If you have the need, you can create a custom configuration element collection class.

The AdminUsersSection class in Listing 26.23 enables you to represent a list of users. The class includes a property named Users that exposes an instance of the AdminUsersCollection class. The AdminUsersCollection represents a collection of configuration elements. The AdminUsersCollection class is also defined in Listing 26.23.

Listing 26.23. App_Code\AdminUsersSection.vb

[View full width]

Imports System Imports System.Configuration Namespace AspNetUnleashed Public Class AdminUsersSection Inherits ConfigurationSection <ConfigurationProperty("", IsDefaultCollection:=True)> _ Public ReadOnly Property Users() As AdminUsersCollection Get Return CType(Me(""), AdminUsersCollection) End Get End Property Public Sub New() End Sub End Class Public Class AdminUsersCollection Inherits ConfigurationElementCollection Protected Overrides Function CreateNewElement() As ConfigurationElement Return New AdminUser() End Function Protected Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object Return (CType(element, AdminUser)).Name End Function Public Sub New() Me.AddElementName = "user" End Sub End Class Public Class AdminUser Inherits ConfigurationElement <ConfigurationProperty("name", IsRequired:=True, IsKey:=True)> _ Public Property Name() As String Get Return CType(Me("name"), String) End Get Set(ByVal Value As String) Me("name") = Value End Set End Property <ConfigurationProperty("password", IsRequired:=True)> _ Public Property Password() As String Get Return CType(Me("password"), String) End Get Set(ByVal Value As String) Me("password") = Value End Set End Property End Class End Namespace

Notice that the ConfigurationProperty attribute that decorates the Users property sets the name of the configuration attribute to an empty string. It also marks the property as representing the section's default collection. These options enable you to avoid having to create a subtag for the user collection. The user collection appears immediately below the main <adminUsers> section tag.

The web configuration file in Listing 26.24 illustrates how you can use the AdminUsersSection class.

Listing 26.24. Web.config

<configuration> <configSections> <sectionGroup name="system.web"> <section name="adminUsers" type="AspNetUnleashed.AdminUsersSection" allowLocation="true" allowDefinition="Everywhere" /> </sectionGroup> </configSections> <system.web> <adminUsers> <user name="Bob" password="secret" /> <user name="Fred" password="secret" /> </adminUsers> </system.web> </configuration>

The ASP.NET page in Listing 26.25 displays all the users from the adminUsers section in a BulletedList control (see Figure 26.13).

Figure 26.13. Displaying the contents of the adminUsers section in a BulletedList control.

Listing 26.25. ShowAdminUsersSection.aspx

[View full width]

<%@ Page Language="VB" %> <%@ Import Namespace="AspNetUnleashed" %> <%@ Import Namespace="System.Web.Configuration" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() ' Get configuration Dim section As AdminUsersSection = CType(WebConfigurationManager .GetWebApplicationSection("system.web/adminUsers"), AdminUsersSection) ' Bind section to GridView bltAdminUsers.DataSource = section.Users bltAdminUsers.DataBind() End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Show AdminUsersSection</title> </head> <body> <form runat="server"> <div> <h1>Administrators</h1> <asp:BulletedList DataTextField="Name" Runat="server" /> </div> </form> </body> </html>

Категории