Serialization

Let’s take a look at how easy it is to (de)serialize your objects no matter what assembly version you use. First of all, instead of deriving from ModelBase, it is very important to derive from SavableModelBase.

Serialization modes

Depending on the target framework, several options are available as serialization modes:

Serialization modeWPFSilverlightWindows PhoneWinRT
Binary
XML

Serializing a model

The code below shows how to save an object (which can, of course, be a complex graph of nested objects):

var myObject = new MyObject();
myObject.Save(@"C:\myobject.dob");

Looks too easy, but this really is the only thing you need to do. You can specify the serialization mode in the several available overloads of the Save method.

Loading is as easy as saving, as you can see in the following code:

var myObject = MyObject.Load(@"C:\myobject.dob");

Backwards compatibility for binary serialization

This example shows how an “old” (standard .NET) data class that uses custom binary serialization can easily be converted to a ModelBase to use the ModelBase even for all your existing classes.

Declare a new ModelBase class (remember the ‘dataobject’ code snippet). If the new class is in a new assembly, or has a new name or namespace, use the RedirectType attribute to let the ModelBase know that when it finds the old type, it should deserialize that type into the new type.

Then, by default, the ModelBase class will try to deserialize the old object. If it fails to do so, it will fall back on the default values provided by the property declarations. However, it is also possible to override the GetDataFromSerializationInfo method:

/// <summary>
/// Retrieves the actual data from the serialization info.
/// </summary>
/// <remarks>
/// This method should only be implemented if backwards compatibility should be implemented for
/// a class that did not previously implement the ModelBase class.
/// </remarks>
protected override void GetDataFromSerializationInfo(SerializationInfo info)
{
    // Check if deserialization succeeded
    if (DeserializationSucceeded)
    {
        return;
    }

    // Deserialization did not succeed for any reason, so retrieve the values manually
    // Luckily there is a helper class (SerializationHelper) 
    // that eases the deserialization of "old" style objects
    FirstName = SerializationHelper.GetString(info, "FirstName", FirstNameProperty.GetDefaultValue());
    LastName = SerializationHelper.GetString(info, "LastName", LastNameProperty.GetDefaultValue());
}