The Last Configuration Section Handler.. Revisited

If you need to store a little bit of state-- in your configuration file, or on disk-- nothing is faster than some quick and dirty serialization. Or as I like to call it, stringization.

In late 2004, I wrote about The Last Configuration Section Handler, which does exactly this for *.config files. It's based on earlier work by Craig Andera of Pluralsight. Let's bring that code up to date for Visual Studio 2005, and furthermore, we'll do it in C# and The Language of the Gods, VB.NET.

The first thing to do is set up a little class that represents the data you want to serialize. Include whatever types you need, but make everything public so it'll be visible to the serializer.

namespace SomeNamespace
{
    
public class MyStuff
    {
        
public int i;
        
public string s;
    }
}

Now use this routine to serialize it:

static string SerializeObject(object o)
{
    
StringBuilder sb = new StringBuilder();
    
StringWriter sw = new StringWriter(sb);
    
XmlTextWriter xtw = new XmlTextWriter(sw);
    
xtw.Formatting = Formatting.Indented;
    
xtw.WriteRaw(null);

    
XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
    
xsn.Add("", "");

    
XmlSerializer xs = new XmlSerializer(o.GetType());
    
xs.Serialize(xtw, o, xsn);
    
string s = sb.ToString();

    
// <Foo> becomes <Foo type="MyClass.Foo">
    s = Regex.Replace(s, "(<" + o.GetType().Name + ")(>)", "$1 type="" + o.GetType().FullName + ""$2");
    
return s;
}

The output is your class, serialized as a nice human-readable string.

<MyStuff type="SomeNamespace.MyStuff">
  <
i>1234</i>
  <
s>A bunch of information</s>
</
MyStuff>

It's just so darn.. straightforward. As if I needed another reason to love strings. Anyway, take that string and paste it into your web.config file.

To read it in, you'll need a custom config section. Paste this into your config file to define one:

<configSections>
  <
section name="MyStuff" type="XmlSerializerSectionHandler, CSSerializerSection" />
</
configSections>

The actual XmlSerializerSectionHandler is a bit too much code to paste into a blog post, but it's still relatively simple:

  1. Extract the type from the XML Type attribute
  2. Make sure the type is valid
  3. Deserialize the XML into a new object of that type

The XmlSerializerSectionHandler is too verbose to reprint here mainly because I added a bunch of error trapping. If something goes wrong, you get a nice explanatory exception instead of a cryptic error. It's good stuff.

There's almost no difference at all between the two languages, except that VB for some reason requires an additional namespace; instead of "SomeNamespace.MyStuff", it's "VBSerializerSection.SomeNamespace.MyStuff".

Related posts

Monkeypatching For Humans

Although I love strings, sometimes the String class can break your heart. For example, in C#, there is no String.Left() function. Fair enough; we can roll up our sleeves and write our own function lickety-split: public static string Left(string s, int len) { if (len == 0 || s.Length == 0)

By Jeff Atwood ·
Comments

Department of Declaration Redundancy Department

I sometimes (often, actually) regress a few years mentally and forget to take advantage of new features afforded by the tools I'm using. In this case, we're using the latest and greatest version of C#, which offers implicitly typed local variables. While working on Stack Overflow,

By Jeff Atwood ·
Comments

Productivity Tip: Upgrade Your Pentium 4

In C# and the Compilation Tax, several commenters noted that they have "fast dual-core computers", and yet background compilation performance was unsatisfactory for them on large projects. It's entirely possible that this is Visual Studio's fault. However, I'd like to point out

By Jeff Atwood ·
Comments

C# and the Compilation Tax

Over the last four years, I've basically given up on the idea that .NET is a multiple language runtime. * The so-called choice between the two most popular languages, C# and VB.NET, is no more meaningful than the choice between Coke and Pepsi. Yes, IronPython and IronRuby are

By Jeff Atwood ·
Comments

Recent Posts

Let's Talk About The American Dream

Let's Talk About The American Dream

A few months ago I wrote about what it means to stay gold — to hold on to the best parts of ourselves, our communities, and the American Dream itself. But staying gold isn’t passive. It takes work. It takes action. It takes hard conversations that ask us to confront

By Jeff Atwood ·
Comments
Stay Gold, America

Stay Gold, America

We are at an unprecedented point in American history, and I'm concerned we may lose sight of the American Dream.

By Jeff Atwood ·
Comments
The Great Filter Comes For Us All

The Great Filter Comes For Us All

With a 13 billion year head start on evolution, why haven’t any other forms of life in the universe contacted us by now? (Arrival is a fantastic movie. Watch it, but don’t stop there – read the Story of Your Life novella it was based on for so much

By Jeff Atwood ·
Comments
I Fight For The Users

I Fight For The Users

If you haven’t been able to keep up with my blistering pace of one blog post per year, I don’t blame you. There’s a lot going on right now. It’s a busy time. But let’s pause and take a moment to celebrate that Elon Musk

By Jeff Atwood ·
Comments