Owen
Owen

Reputation: 7098

MSMQ empty object on message body

Ok, so I'm very VERY new to MSMQ and I'm already confused.

I have created a private queue and added a few messages to it, all good so far. BUT when I retrieve the messages back from the queue the message body contains a empty object of the type I added. By this I don't mean that the body is null, it does have a reference to a type of the object that I added, but it's not instantiated so all the properties are in their null or default state.

This is the code I use to add to the queue:

using (var mQueue = new MessageQueue(QueueName))
{
    var msg = new Message(observation)
    {
            Priority = MessagePriority.Normal,
             UseJournalQueue = true,
            AcknowledgeType = AcknowledgeTypes.FullReceive,
    };
    mQueue.Send(msg);
}

And this is the code that dequeues the messages:

using (var mQueue = new MessageQueue(QueueName))
{
    mQueue.MessageReadPropertyFilter.SetAll();
    ((XmlMessageFormatter)mQueue.Formatter).TargetTypes =
                                                  new[] { typeof(Observation) };
    var msg = mQueue.Receive(new TimeSpan(0, 0, 5));
    var observation = (Observation)msg.Body;

    return observation;
}

Upvotes: 0

Views: 2264

Answers (2)

Glen Little
Glen Little

Reputation: 7128

Also, make sure that your custom Message object has public setters on each property!

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941227

The Message constructor uses XML serialization to serialize your "observation" object. You'll need to make sure that this works properly. XML serialization will only deal with public members of the class, it is not going to serialize private members. Your object may well look "empty" after it is deserialized again.

Here's some test code to verify that it works properly:

using System;
using System.IO;
using System.Xml.Serialization;

class Program {
  static void Main(string[] args) {
    var ser = new XmlSerializer(typeof(Observation));
    var sw = new StringWriter();
    var obj = new Observation();
    ser.Serialize(sw, obj);
    Console.WriteLine(sw.ToString());
    var sr = new StringReader(sw.ToString());
    var obj2 = (Observation)ser.Deserialize(sr);
    // Compare obj to obj2 here
    //...
    Console.ReadLine();
  }
}
public class Observation {
  // etc...
}

Upvotes: 3

Related Questions