Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BinaryFormatter does not exist in CF. Solutions?

I need to serialize/deserialize obj in/from byte[] on compact framework but there is no BinaryFormatter, what should i do? Thanks. This is the class i am using on the server side and i want it also on the client(a device with windows mobile 6)

public class Serializer
{
    public byte[] SerializeObject(object obj)
    {
        if (obj == null)
            return null;
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, obj);
            return stream.ToArray();
        }
    }

    public object DeserializeObject(byte[] bytes)
    {
        if (bytes == null)
            return null;
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream(bytes);
        return formatter.Deserialize(stream);
    }
}
like image 223
gigi Avatar asked Feb 23 '11 13:02

gigi


3 Answers

For your scenario, you might consider switching protobuf-net; this is not the same format as BinaryFormatter, so both client and server would need tweaks, but is a binary serialization API that works on both platforms, and is typically much smaller as an added extra. The format is actually google's "protocol buffers" encoding; very fast, platform-independent, and designed to be flexible as you add properties etc. And it is free. Some fool just gives it away.

like image 113
Marc Gravell Avatar answered Nov 15 '22 05:11

Marc Gravell


We originally used the As Good As It Gets Compact Framework Serialization which is completely binary compatible with the full framework BinaryFormatter but the per-device licensing was a deal breaker. Depending on how many devices you need to support, it may work for you. We also found that BinaryFormatter did have memory and time overhead -- not anywhere near the cost of SoapFormatter but still significant for a CE device.

In the end, we created a serialization framework using BinaryWriter and BinaryReader directly along with System.Activator to create the classes. This allowed us to remove a great deal of the memory and time overhead associated with the built in serialization at the cost of careful versioning of the objects and ordering of the fields. It should be noted that our custom serialization work pre-dated the release of protbuf.net.

like image 35
Jack Bolding Avatar answered Nov 15 '22 05:11

Jack Bolding


you can find an implementation of what you need for the CF here: http://www.codeproject.com/KB/cs/CF_serializer.aspx

also interesting: how to serialize objects in compact framework

I did not try it myself because I have never needed it. sorry if I only post few links.

like image 2
Davide Piras Avatar answered Nov 15 '22 07:11

Davide Piras