Background

I’m currently doing some work in the area of cross-AppDomain development, where all objects are either marshalled (transparently) using .NET Remoting or serialised. It turns out that, when DataSet objects are serialised, their extended properties are serialised as strings. This means that, when operating on a DataSet which has come from another AppDomain, the complex data type you added as an extended property has unexpectedly become a string representation of it.

There’s a quick and easy solution to this problem; manually serialising extended properties using the built-in .NET XML serialisation mechanism. However, not all .NET types are fully supported by the XML serialiser, as I discovered while trying to serialise an object with a property of type System.Drawing.Color. Here’s a quick and easy way to work around this issue:

Solution

The solution is two-fold; firstly, we should exclude the Color property from XML serialisation (using the XmlIgnore attribute), because we know it’s not supported:

[XmlIgnore]
public Color TextColor {
    get;
    set;
}

Next, we need to provide an additional public read/write property that is XML-serialisable:

public string TextColorHtml {
    get { return ColorTranslator.ToHtml(TextColor); }
    set { TextColor = ColorTranslator.FromHtml(value); }
}

The property needs to be public and provide a getter and setter, because the XML serialiser will invoke it, and does not execute with high enough privileges to be able to read into private/protected/internal properties or set the values of backing variables. I’ve chosen to serialise the HTML representation of the colour, because it is already XML-friendly and translates back and forth easily.

The advantage to using this approach is that you do not have to change the representation used by your class; the Color structure is very useful and very pervasive in .NET. Also, since the additional property has no backing variable (it is entirely procedural), no additional memory is needed to store each instance of the type.

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required