Extension - How to Create a New Serializer

This sample demonstrates how to manage your own data type where they are outside of your business layer.

Note: this code can be found as part of the source code in the E01_NewSerializer.cs file.

Business Data

/// <summary>
/// Player class - basic version.
/// </summary>
public class Player
{
    /// <summary>
    /// Gets or sets the identifier of the player.
    /// </summary>
    public int Identifier { get; set; }

    /// <summary>
    /// Gets or sets the name of the player.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets the city of the player.
    /// </summary>
    public City City { get; set; }
}

/// <summary>
/// Represents cities.
/// </summary>
public enum City
{
    /// <summary>
    /// First city.
    /// </summary>
    Metropolis,

    /// <summary>
    /// Second city.
    /// </summary>
    GothamCity,
}

Extension

We implements a new serializer that will work on City values.

/// <summary>
/// Implements the serialization process for <see cref="City"/> values.
/// </summary>
public class CitySerializer : AbstractMonoTypeSerializer
{
    /// <summary>
    /// Gets the <see cref="City"/> type.
    /// </summary>
    protected override Type AssociatedType
    {
        get { return typeof(City); }
    }

    /// <summary>
    /// Serializes a <see cref="City"/> value.
    /// </summary>
    /// <param name="writer">The target writer.</param>
    /// <param name="value">The serialized value.</param>
    protected override void InternalSerialize(BinaryWriter writer, object value)
    {
        writer.Write(Enum.GetName(typeof(City), value));
    }

    /// <summary>
    /// Reads a <see cref="City"/> value.
    /// </summary>
    /// <param name="reader">The source reader.</param>
    /// <returns>The deserialized value.</returns>
    protected override object InternalDeserialize(BinaryReader reader)
    {
        string name = reader.ReadString();
        return Enum.Parse(typeof(City), name, false);
    }
}

Integration

The code to integrate the new serializer is quite simple but should be called before the data source initialization.

// The initializer is overriden by one with the CitySerializer
Engine.Instance.Initializer = new Api.DefaultInitializer()
    .AddSerializer(new CitySerializer());

This extension doesn't change how to use the library!

// Initialize the data source
IDataSource ds = Engine.Instance.RegisterDataSource(new DefaultDataSourceDefinition("TeamDS")
    .AddClass<Player, int>(p => p.Identifier));

// Create business objects
Player player = new Player() { Identifier = 1, Name = "Batman", City = City.GothamCity };
ds.Save(player);
Player loaded = ds.Load<Player>(1);

Last edited Mar 29, 2011 at 5:21 AM by Faz, version 1

Comments

No comments yet.