Serialize/Deserialize a Font and Color to/from XML



By ganton ~ June 26th, 2008. Filed under: C#, VB.Net.

Not so long ago I needed to store some of UI appearance values of my project into a custom XML file in order to allow the end-user to configure its UI appearance. As it is expected I had to store also fonts and colors. Both of them can not be directly serialized into XML. For serializing/deserializing colors I used ColorTranslatorclass to convert a color to HTML and vice-versa. After that received HTML can be stored into an XML file.

This post presents the implementation of FontConverter class which is used to convert a Font to Base64String and vice-versa. After converting the Font the result can be stored into XML file.

FontConverter implementation in C#.

   
public static class FontConverter
{
    public static string ToBase64String(Font font)
    {
        try
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, font);
                return Convert.ToBase64String(stream.ToArray());
            }
        }
        catch { }
        return null;
    }
    public static Font FromBase64String(string font)
    {
        try
        {
            using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(font)))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                return (Font)formatter.Deserialize(stream);
            }
        }
        catch { }
        return null;
    }
}

The use of FontConverter in C#.

Font font = new Font("Arial", .5f);
string result = FontConverter.ToBase64String(font);
Font newFont = FontConverter.FromBase64String(result);

FontConverter implementation in VB.Net.

Public Class FontConverter
    Public Shared Function ToBase64String(ByVal font As Drawing.Font) As String
        Try
            Using stream As New MemoryStream()
                Dim formatter As New BinaryFormatter()
                formatter.Serialize(stream, font)
                Return Convert.ToBase64String(stream.ToArray())
            End Using
        Catch
        End Try
        Return Nothing
    End Function
    Public Shared Function FromBase64String(ByVal font As String) As Drawing.Font
        Try
            Using stream As New MemoryStream(Convert.FromBase64String(font))
                Dim formatter As New BinaryFormatter()
                Return formatter.Deserialize(stream)
            End Using
        Catch
        End Try
        Return Nothing
    End Function
End Class

The use of FontConverter in VB.Net.

        Dim font As New Drawing.Font("Arial", 0.5)
        Dim result As String = FontConverter.ToBase64String(font)
        Dim newFont As Drawing.Font = FontConverter.FromBase64String(result)

Now Let’s assume that we have an object named UIAppearance. It consists of _testColor and _testFont fields. The importent moment is that it contains four properties for the two fields. Two of them are used in the application which uses the class and two of them are used only by XML serialization. Note that those used in the program are marked with XmlIgnore attribute which notes XML serialization to not serialize them. Other two properties are decorated with XmlElement attribute in order to control XML element name during serialization.

public class UIAppearance
{
    private Font _testFont;
    private Color _testColor;
    [XmlIgnore()]
    public Font TestFont
    {
        get { return _testFont; }
        set { _testFont = value; }
    }
    [XmlIgnore()]
    public Color TestColor
    {
        get { return _testColor; }
        set { _testColor = value; }
    }
    [XmlElement(ElementName = "TestFont")]
    public string TestFontBase64String
    {
        get {
            return FontConverter.ToBase64String(_testFont);
        }
        set {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("Parameter can not be null or empty string.", "TestFontBase64String");
            _testFont = FontConverter.FromBase64String(value);
        }
    }
    [XmlElement(ElementName = "TestColor")]
    public string TestColorHtml
    {
        get {
            return ColorTranslator.ToHtml(_testColor);
        }
        set {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("Parameter can not be null or empty string.", "TestColorHtml");
            _testColor = ColorTranslator.FromHtml(value);
        }
    }
}

Next code snippet is an example of serializing and deserializing an instance of UIAppearance class. This example uses XmlConverter to serialize the object.

UIAppearance appearance = new UIAppearance()
{
     TestColor = Color.AliceBlue,
     TestFont = new Font("Arial", .5f)
};
string appearanceXml = XmlConverter.XmlConverter.ToXml(appearance);
UIAppearance restoredAppearance =
    XmlConverter.XmlConverter.FromXml<uiappearance>(appearanceXml);

After serialization appearanceXml variable contains the result XML shown below. TestFont element value is cut in order to not make the snippet short.

<?xml version="1.0" encoding="utf-8"?>
<uiappearance xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" xmlns:xsd="<a href="http://www.w3.org/2001/XMLSchema">http://www.w3.org/2001/XMLSchema</a>">
    <testFont>AAEAAAD.......wAAAAs=</testFont>
    <testColor>AliceBlue</testColor>
</uiappearance>

Leave a Reply