views:

1767

answers:

4

I'm writing messages to a Message Queue in C# as follows:

queue.Send(new Message("message"));

I'm trying to read the messages as follows:

Messages messages = queue.GetAllMessages();
foreach(Message m in messages)
{
  String message = m.Body;
  //do something with string
}

However I'm getting an error message which says: "Cannot find a formatter capable of reading this message."

What am I doing wrong?

+6  A: 

I solved the problem by adding a formatter to each message. Adding a formatter to the queue didn't work.

Messages messages = queue.GetAllMessages();
foreach(Message m in messages)
{
  String message = m.Body;
  message.Formatter = new System.Messaging.XmlMessageFormatter(new String[] 
    { "System.String,mscorlib" });
  //do something with string
}
macleojw
Perfect! Just what i wanted.
NLV
+2  A: 

Or you can use

 message.Formatter =
     new System.Messaging.XmlMessageFormatter(new Type[1] { typeof(string) });
static
A: 

Thanks, I had the same problem. This was very helpful

Faisal
A: 

It seems that the serialization is only done when accessing the Body property of the Message class. As long as you access the Body property after you set on the message the right Formatter it works fine.

If you prefer not to create a Formatter for each message you can set the Formatter on the queue and for each message (before accessing the Body property) set the Formatter property from the Formatter of the queue.

_queue.Send(new Message() { Formatter = _queue.Formatter, Body = myData } );

var msg = _qeueu.Receive();
msg.Formatter = _queue.Formatter;
var myObject = (MyClass) msg.Body;
selalerer