Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

with azure brokeredmessage get the body without knowing the type

When you are using the brokered message in the Azure Service Bus, you can retrieve the body of the message with the call .GetBody. The code is simple:

var msg = subscription.Receive(); MyPayload payload = msg.GetBody<MyPayload>(); 

However, is there a way to retrieve the Body without explicitly knowing the class of the body object?

var msg = subscription.Receive(); Type bodyType = Type.GetType( msg.ContentType);  var payload = msg.GetBody<bodyType>(); 
like image 787
yamspog Avatar asked Mar 15 '13 20:03

yamspog


2 Answers

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(); 
like image 142
ckross01 Avatar answered Sep 22 '22 02:09

ckross01


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; } 
like image 28
yamspog Avatar answered Sep 20 '22 02:09

yamspog