Theme: default | dark | nature

XMLSerializerSectionHandler

Download Download

This class is very useful for adding custom configuration settings in web.config for your HttpModules. This is all you will ever need to quickly parse through web.config for any module you write! All you need to do is write your serializer class. (See one of my custom modules for a full sample.)

Imports System
Imports System.Configuration
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Xml.XPath

Namespace GLC.Tools.Configuration
    Public Class XmlSerializerSectionHandler : Implements IConfigurationSectionHandler
        Public Function Create(ByVal parent As Object, ByVal configContext As Object, ByVal section As System.Xml.XmlNode) As Object Implements IConfigurationSectionHandler.Create
            Dim navigator As XPathNavigator = section.CreateNavigator()

            Dim typeName As String = navigator.Evaluate("string(@type)").ToString

            Dim serializer As New XmlSerializer(Type.GetType(typeName, True, True))

            Return serializer.Deserialize(New XmlNodeReader(section))
        End Function
    End Class
End Namespace

In your web.config file, you must add a section like this:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="redirects" type="GLC.Tools.Configuration.XmlSerializerSectionHandler, GLC.Tools" />
  </configSections>
  <redirects type="GLC.Tools.Modules.RedirectConfig, GLC.Tools">
    <add targetUrl="^~/SomePlace/" destinationUrl="~/SomeOtherPlace/" mode="remote" />
  </redirects>
</configuration>
...
</configuration>
<system.web>
    <httpModules>
      <add name="RedirectModule" type="GLC.Tools.Modules.RedirectModule, GLC.Tools" />
    </httpModules>
...
</system.web>

Your serializer class would look something like this:

    <XmlRoot("redirects")> Public Class RedirectConfig
        <XmlElement("add")> Public Items As Redirect()

        Public Class Redirect
            <XmlAttribute("targetUrl")> Public TargetUrl As String
            <XmlAttribute("destinationUrl")> Public DestinationUrl As String = "~/"
            <XmlAttribute("permanent")> Public IsPermanent As Boolean = False
            <XmlAttribute("ignoreCase")> Public IgnoreCase As Boolean = True
            <XmlAttribute("mode")> Public Mode As RedirectModule.RedirectMode = RedirectModule.RedirectMode.On
            <XmlIgnore()> Public Regex As Regex
        End Class
    End Class

Contact us today! Free consulting with no obligation.