with azure brokeredmessage get the body without knowing the type with azure brokeredmessage get the body without knowing the type azure azure

with azure brokeredmessage get the body without knowing the type


If the intent is to only grab the message body regardless of the content you can get it as a stream.

Stream stream = message.GetBody<Stream>();StreamReader reader = new StreamReader(stream);string s = reader.ReadToEnd();


Here is the complete code to deserialize from the brokeredmessage:

public T GetBody<T>(BrokeredMessage brokeredMessage){  var ct = brokeredMessage.ContentType;  Type bodyType = Type.GetType(ct, true);  var stream = brokeredMessage.GetBody<Stream>();  DataContractSerializer serializer = new DataContractSerializer(bodyType);  XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max);  object deserializedBody = serializer.ReadObject(reader);  T msgBase = (T)deserializedBody;  return msgBase;}


In sample before ContentType utilized to detect body type. I believe ContentType should be set by sender.I do similar logic, I set one of message properties to type of object on sender side and call GetBody<>() on receiver with type retrived from message property.like this:

public void SendData(object payloadData)    {        if (payloadData == null) return;        var queueClient = QueueClient.CreateFromConnectionString(ConnectionString, _queueName);        var brokeredMessage = new BrokeredMessage(payloadData);        brokeredMessage.Properties["messageType"] = payloadData.GetType().AssemblyQualifiedName;        queueClient.Send(brokeredMessage);    }

Message property "messageType" has full name of type.

On receiving side I do like this:

 var messageBodyType = Type.GetType(receivedMessage.Properties["messageType"].ToString());                if (messageBodyType == null)                {                    //Should never get here as a messagebodytype should                    //always be set BEFORE putting the message on the queue                    Trace.TraceError("Message does not have a messagebodytype" +                                     " specified, message {0}", receivedMessage.MessageId);                    receivedMessage.DeadLetter();                }                //read body only if event handler hooked                    var method = typeof(BrokeredMessage).GetMethod("GetBody", new Type[] { });                    var generic = method.MakeGenericMethod(messageBodyType);                    try                    {                        var messageBody = generic.Invoke(receivedMessage, null);                         DoSomethingWithYourData();                        receivedMessage.Complete();                    }                    catch (Exception e)                    {                        Debug.Write("Can not handle message. Abandoning.");                        receivedMessage.Abandon();                    }                }