Monday, August 29, 2011

Silverlight local messaging issues with ‘\0’

When we want to communicate between 2 Silverlight applications locally, we have a framework way to accomplish the same.Its nothing but 2 classes LocalMessageSender and LocalMessageReceiver.Recently we had faced an issue with local messaging system of Silverlight.The problem was LocalMessageSender sends a message without any exception but when LocalMessageReceiver receives the message, it is not the same message. Its not incorrect data, but the length itself reduced.
We first checked the size of the message which we are sending.It not exceeding 40KB limit as per Microsoft.Then we started digging into the project specifics and could see that the data passed is binary data.ie it’s the data got from a BinarySerializer which is just using the BinaryWriter Class to make the data as binary.The investigation continued to find the character which says the end of the message at the receiver side. After couple of hours I got the character which is nothing but our famous ‘\0’ which was used in C & C++ to denote as end of string.
Our binary serializer was adding this character while serializing the objects. Since the serializer internally uses BinaryWriter, this happens by the BinaryWriter when serializing numbers. I have checked .Net string specification and it says the string is represented using its length rather than the old ‘\0’ style. But don’t know why in local message sending, this is happening.
You can reproduce it simply.Try to send the message "Joy\0George" it will transmit or receives only ‘Joy’.I am not sure which communication end is cutting the message.

private void btnJSON_Click(object sender, RoutedEventArgs e)
{
SendMessage("joy\0George");
}
private void SendMessage(string serialized)
{
MessageBox.Show("Length:"+serialized.Length.ToString());
LocalMessageSender sender = new LocalMessageSender("TestPoint");
sender.SendCompleted += new EventHandler<SendCompletedEventArgs>(sender_SendCompleted);
sender.SendAsync(serialized);
}
void sender_SendCompleted(object sender, SendCompletedEventArgs e)
{
if (e.Error != null) MessageBox.Show(e.Error.ToString());
}





Here is the receiving end.




Private Sub ListenForMessage()
Dim receiver As New LocalMessageReceiver("TestPoint")
AddHandler receiver.MessageReceived, AddressOf Received
receiver.Listen()
End Sub
Private Sub Received(ByVal sender As Object, ByVal e As MessageReceivedEventArgs)
MessageBox.Show("Length " + e.Message.Length.ToString())
DirectCast(sender, IDisposable).Dispose()
End Sub




Don’t confuse with the C# and VB.Net code.All will compile into same ILCode Smile.At the sending side the length will be 10 and receiving end the length will be 3 if we send the above mentioned string which has ‘\0’. 

I can guess that Microsoft uses unmanaged modules to accomplish the communication which takes ‘\0’ as end of string. Anyway I have posted in Silverlight forums.

No comments: