Ole Albers
Ole Albers

Reputation: 9295

InvalidOperationException when trying to access Body from Message

I try to access the messages of the windows message queue:

var activeQueue = new MessageQueue("\\myhost\\private$\\just.a.queue", QueueAccessMode.Receive);
foreach(message in _activeQueue.GetAllMessages().ToList()) {
   Console.WriteLine(message.Body);
}

I receive an InvalidOperationException when trying to access message.Body (And on nearly every other property other than Id - fields).

Upvotes: 2

Views: 1394

Answers (2)

Alexander
Alexander

Reputation: 20224

On a side note, there are two possibilities how to use a formatter to decode a message:

Queue.Formatter = new MessageFormatter(); // Set formatter on queue
Msg = Queue.Receive();
Body = Msg.Body;

or

Msg = Queue.Receive();
Msg.Formatter = new MessageFormatter(); // Set formatter on msg
Body = Msg.Body;

which can also be combined:

Queue.Formatter = new MessageFormatter();
Msg = Queue.Receive();
if(Msg.Label.Contains('Other')) Msg.Formatter = new OtherMessageFormatter();
Body = Msg.Body;

but the following will fail:

Msg = Queue.Receive();
Queue.Formatter = new MessageFormatter();

because when the queue receives a message, the message's formatter is initialized as the queue's current formatter, so it won't work if the queue's formatter is only set after the first message has already been received.

Upvotes: 1

Ole Albers
Ole Albers

Reputation: 9295

Thanks to @Soner Gönül I was able to solve my problem. This is the solution:

message.Formatter = new ActiveXMessageFormatter();
var reader = new StreamReader(message.BodyStream);
var msgBody = reader.ReadToEnd();
Console.WriteLine(msgBody)

Upvotes: 5

Related Questions