Serialization Examples

Binary Serialization

The following code shows simple serializable classes used in this example:

    [Serializable]
    public class BinaryDataObject
    {
        private readonly List<BinaryChildObject> children = 
            new List<BinaryChildObject>();
        
        public string Value1 { get; set; }

        public int Value2 { get; set; }

        public List<BinaryChildObject> Children { get { return this.children; } }
    }

    [Serializable]
    public class BinaryChildObject
    {
        public string SubValue { get; set; }
    }

Your application will program to your POCO "normally":

    var instance1 = new BinaryDataObject();
    instance1.Value1 = "testme";
    instance1.Value2 = 5;
    instance1.Children.Add(new BinaryChildObject { SubValue = "ChildValue" });

To save the value as a new value, initialize a "ValueHandle" instance with the key, but don't provide a version number:

    // Example only, keys are typically unique business values
    // that can follow any convention:
    var key = "<my Key>#<some sub-topic>";

    // Initial save, don't provide a version number:
    var valueHandle1 = new ValueHandle(key);
    using (var c = new SqlConnection(connectionString))
    using (var s = valueHandle1.GetWriterStream(c))
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(s, instance1);
    }

Note: the Version value is a concurrency mechanism managed by the API that typically you won't have to set.

The value is now stored and can be retrieved using the same key, as follows:

    BinaryDataObject instance2;
    using (var c = new SqlConnection(connectionString))
    using (var r = valueHandle2.GetReaderStream(c))
    {
        var formatter = new BinaryFormatter();
        instance2 = formatter.Deserialize(r) as BinaryDataObject;
    }

As this example shows, reading and writing values from the underlying key value store is "just another stream". Any API that serializes to a stream will work in this same manner. This means you can use just about any serializer to suit your needs, or any custom binary encoding format if your usage requires such low level control.

Stream Composition Examples

Last edited Feb 25, 2015 at 4:13 PM by bkjuice, version 10