views:

2165

answers:

3

Can I deserialize an object in the Silverlight 3.0 runtime that was serialized using the full .NET 2.0 runtime using the BinaryFormatter? I am using the following code to serialize an object to a ByteArray which we write to a DB table:

        MemoryStream serStream = new MemoryStream();
        BinaryFormatter binFormatter = new BinaryFormatter();
        binFormatter.Serialize(serStream, csMetric);


        serStream.Position = 0;
        return serStream.ToArray();

The Silverlight client then needs to retrieve this binary data from the DB (via a Web service call) and deserizlize the bytes back into an instance of the csMetric class.

Is this possible? If so, how is that done on the client given that the BinaryFormatter is not availble in the SL 3.0 runtime?

Thanks, jon

A: 

Since you have to go through WCF, and thus the full .NET Framework, to get the data into Silverlight anyway I'd recommend deserializing the object on the server before sending it back to Silverlight. The Silverlight 3 WCF stack supports binary WCF encoding which should make the data transfer reasonably efficient.

James Cadd
Thanks James...that's what we are doing at the moment, but it does involve an extra serialziation/deserialization hop on the WCF service. We'd like to avoid that by having the WCF service simply return the bytes out of the DB and send them directly to the SL client...just not sure if that's possible with the SL runtime.
Jon Rauschenberger
A: 

Jon,

Have you tried to deserialize the object using the DataContractSerializer? I have not tested this exact scenario, but this is how I would approach it:

the following is an extension method off of a byte array (byte[]):

pubilc static T Deserialize<T>(this byte[] yourSerializedByteArray)
{
T deserializedObject;

DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using(MemoryStream ms = new MemoryStream(yourSerializedByteArray))
{
  deserializedObject = (T)serializer.ReadObject(ms);
}

return deserializedObject;
}
nice idea, i wonder if it works
Neil
A: 

DataContractSerializer has a whole bunch of problems, I've created a binary serializer that removes some of them (at least for me!) It uses reflection and produces reasonably compact representations that can be sent to WCF services.

More info here http://wp.me/pM95a-m

Mike Talbot