Thursday, June 21, 2007

The last configuration handler I'll ever need...really

Scott Weinstein has a fantastic approach to deserializing configuration sections. I would like to propose an improvement though: make the class generic. Here's a simplified version:

Public Class XmlSerializerSectionHandler(Of T)
Implements IConfigurationSectionHandler

Public Function Create(ByVal parent As Object, ByVal configContext As Object, ByVal section As System.Xml.XmlNode) Implements IConfigurationSectionHandler.Create


Dim nav As XPathNavigator = section.CreateNavigator()

Dim ser As New XmlSerializer(GetType(T))

Return ser.Deserialize(New XmlNodeReader(section))

End Function

End Class

This eliminates the need to embed the type attribute in the data tag and moves it into the type declaration in the section tag. This...

<namessection type="TheMechanicalBride.Web.NamesSection, TheMechanicalBride.Web">
<name>Jafar Husain</name>
<name>Johhny</name>
</namessection>

Becomes...

<namessection>
<name>Jafar Husain</name>
<name>Johhny</name>
</namessection>

snip

<section name="namessection" type="TheMechanicalBride.Web.XmlSerializerSectionHandler `1[[TheMechanicalBride.Web.NamesSection, TheMechanicalBride.Web]]"/>


This is a minor modification but is definitely an improvement as the tag that contains the data no longer needs any awareness of the method by which it is serialized and deserialized.

No comments:

About Me

My photo
I'm a software developer who started programming at age 16 and never saw any reason to stop. I'm working on the Presentation Platform Controls team at Microsoft. My primary interests are functional programming, and Rich Internet Applications.