25th Nov 2009

LocalMessageSender with strongly typed objects

If you need to have two Silverlight apps talking to each other, you would be using the LocalMessageSender and LocalMessageReceiver classes from the System.Windows.Messaging namespace. The LocalMessageSender class will only allow you to send string messages. So if you are looking to send strongly typed objects using the LocalMessageSender you will have to serialize the object and then deserialize it at the other end. I created a class which will do this work for you. I decided to use JSON as the serialization format because it is much more lightweight than Xml.

using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Common
{
    public class JsonSerializer<T>
    {
        public static string Serialize(T objectToSerialize)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(stream, objectToSerialize);
                stream.Position = 0;

                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        public static T Deserialize(string jsonString)
        {
            using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(stream);
            }
        }
    }
}

You can use this class like this

string serializedMsg = JsonSerializer<SimpleMessage>.Serialize(msg); 
SimpleMessage msg = JsonSerializer<SimpleMessage>.Deserialize(serializedMsg);

To give credit where it is due, I stole most of this code from here – http://www.silverlightshow.net/items/JSON-serialization-and-deserialization-in-Silverlight.aspx

2 Responses to “LocalMessageSender with strongly typed objects”

  1. Binil Thomas Says:

    This repeats the seriazation/deserialization lines all over the codebase. Is is possible to create higher level senders/receivers which natively knows how to do this serialization?

    class TypedMessageSender implements IMessageSender {
    public TypedMessageSender(IMessageSender rawSender) { .. }

    public void sendObject(T obj) {
    rawSender.send(serialize(obj));
    }
    }

  2. Pradeep Says:

    You know what, mashe, I was thinking of doing the exact same thing. I will get to it soon.

Leave a Reply