Microsoft Message Queueing – A Practical Intro

NB – This is a very much in draft. Hopefully I’ll get sometime to come back and re-word sections.

Setting Up / Checking Queue Exists in Code

1. Make sure Message Queueing is installed. Windows XP – Right Click ‘My Computer’ and select Manage. Under ‘Services and Applications’ there should be a Message Queue entry.

If MSMQ is not installed, going to Control Panel – Add Remove Programs – Add Windows Features and select Message Queuing. Note I didn’t require my Windows Disc to add this component.

2. Create a new queue – due to me not being a networked machine I’m only able to create a private queue. Its quite probable you’ll need a public queue for you applications. Hopefully there won’t be any differences between public and private. Within Computer Manager, right click on the ‘Private Queue’ (or publi queue), select create queue – I’ve called mine ‘test’.

3. Now fire up Visual Studio (again, I’m using 2008, shouldn’t be any differences from 2005). I’ve created a console application to do the testing in – which results in all my methods being statics through laziness!

4. In the Solution Explorer, right click on the ‘References’ and select ‘Add Reference…’. Locate the System.Messaging library from Microsoft and add it to the project. Then add the ‘using System.Messaging’ line to the top of the file.

5. Then enter the following lines. They check that the queue exists. (Note: If using a public queue, you should be able to specify the machine name\queue name):


if (MessageQueue.Exists("mainpc\\private$\\test"))
 {
 Console.WriteLine("Exists! Result!");
 }
 else
 {
 Console.WriteLine("Queue doesn't exist. D'oh");
 }

 Console.ReadLine();

Sending A Message To The Queue

1. Within the queue exists code, enter the following code – this code will simply send the xml to the message queue. The label assigned ‘Test Message’ is strictly optional.


MessageQueue myQueue = new MessageQueue("mainpc\\private$\\test");

 try
 {
 myQueue.Send("<pc>MyPc</pc>", "Test message");
 Console.WriteLine("Appears to have sent message");
 }
 catch (Exception exc)
 {
 Console.WriteLine("Not good, exception raised. Exc: " + exc.Message);
 }

To confirm it has sent, return to Computer Manager and look at the Queued Messages for the test queue – you should see the entry in there.

However it would be far nicer if we were able to post objects to the queue – all the data that we’re interested in – and we can! See the following code:

a. Create the class to represent the object. I’ve create a very simple Employee example. Note the need for a parameter-less constructor in order to be able to serialise the object:


public class Employee
 {
 public string Name {get; set;}
 public int Age { get; set; }
 public string Role { get; set; }

 public Employee()
 {
 }

 public Employee(string theName, int theAge, string theRole)
 {
 Name = theName;
 Age = theAge;
 Role = theRole;
 }
 }

b. Alter the original send message line to now be:


Employee manager = new Employee("Joe Bloggs", 21, "Manager");
 myQueue.Send(manager, "Employee Msg");

If you now execute the program, it should send the message. Return to computer manager and you should see two message in the queue. Select the one with the label ‘Employee Msg’ and right click-Properties. Select the ‘Body’ tab, and the message details should appear – the message content is just about short enough to fit it all in.

Reading From The Queue

The reading is a little more involved, but not much so bear with me.

1. Make the Message Queue object a member variable of the class so its got scope across the many functions.

2. Begin by performing the same ‘Exists’ check from before. Then create the message queue object again. We then need to tell the code what function to call when it receives a message, and this done by assigining the ReceivedCompleted event to a function. We then tell the queue to BeginReceiving messages.

We also need to implement the function specified in the event for ReceivedCompleted. Here we do nothing exciting in this example but complete the read.


static void Main(string[] args)

{

if (MessageQueue.Exists("mainpc\\private$\\test"))
 {
 Console.WriteLine("Exists! Result!");

 myQueue = new MessageQueue("mainpc\\private$\\test");
 myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(ReceivedMessage);
 myQueue.BeginReceive();
 }
 else
 {
 Console.WriteLine("Queue doesn't exist. D'oh");
 }

 Console.ReadLine();

}

static void ReceivedMessage(object sender, ReceiveCompletedEventArgs e)
 {
 Console.WriteLine("Received a message");
 myQueue.EndReceive(e.AsyncResult);
 Console.WriteLine("Finished reading the message.");

 }

Again run the app, and then check that the number of messages in the queue has gone down.

The only message remaing in the queue should now be our ‘Joe Bloggs’ Employee object. How about we do the code to deserialize that back into the original object so we can play with it?

To do so, we need to introduce a few methods to handle deserialization of the message. First we need to tell the queue what format the message is going to be in. This is done by altering the 3 initialisation lines from:


myQueue = new MessageQueue("mainpc\\private$\\test");
 myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(ReceivedMessage);
 myQueue.BeginReceive();

to:


myQueue = new MessageQueue("mainpc\\private$\\test");
 myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(ReceivedMessage);
 myQueue.Formatter = new XmlMessageFormatter(GetMessageFormatter());
 myQueue.BeginReceive();

The GetMessageFormatter() method is simply:


private static Type[] GetMessageFormatter()
 {
 Type[] types = new Type[2];
 types[0] = typeof(Employee);
 types[1] = typeof(Object);
 return types;
 }

The MessageReceived() method changes to:


static void ReceivedMessage(object sender, ReceiveCompletedEventArgs e)
 {
 Console.WriteLine("Received a message");
 Message msg = myQueue.EndReceive(e.AsyncResult);
 Employee receivedEmpl = GetMessageContents(msg);
 Console.WriteLine("Name = " + receivedEmpl.Name);
 Console.WriteLine("Finished reading the message.");
}

The GetMessageContents() method simply deserializes the xml to the object – a nifty little offering from .NET that I’m yet to find in Java (anybody?!):


private static Employee GetMessageContents(Message msg)
 {
 XmlSerializer serIn = new XmlSerializer(typeof(Employee));
 XmlTextReader textRdr = new XmlTextReader(msg.BodyStream);
 return ((Employee)serIn.Deserialize(textRdr));
 }

Run this example, and you should see Joe Bloggs (or whatever name you originally specified get printed out).

Apologises this isn’t a well thought through post. I simply don’t have the time at the moment. Hopefully this will serve as a quick and nasty introduction, enough to get people started. The Internet is a vast resource, but this kind of stuff was missing when I first started out with MSMQ – perhaps its now out there.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s