Microsoft.NET

……………………………………………….Expertise in .NET Technologies

MSMQ in .NET Framework

Posted by Ravi Varma Thumati on April 1, 2011

Introduction

Before diving in to programming Message Queuing, this section discusses the basic concepts of messaging and compares it to synchronous and asynchronous programming. With synchronous programming, when a method is invoked, the caller has to wait until the method is completed. With asynchronous programming, the calling thread starts the method that runs concurrently. Asynchronous programming can be done with delegates, class libraries that support asynchronous methods (e.g Web service proxies) or by using custom threads.With both synchronous and asynchronous programming, the client and the server must be running at the same time.

Message Queuing or what you can call, as MSMQ itself is an asynchronous programming. This is because the client does not wait for the server to read the data sent to it. But there is a difference between the MSMQ itself and the asynchronous programming. In MSMQ world, all the sender and recipient transaction can be occur in disconnected and connected method, while the asynchronous  programming, the transaction can only occur in connected mode.

Message Queuing is kind of email for application to application communication. But MSMQ has lots more features to offer, such as guaranteed delivery, transactions, confirmations, express mode using memory and so on. With MSMQ you can send, receive, and route messages in a connected or disconnected environment

When to use MSMQ (Message Queuing)

One case where MSMQ is useful is when the client application is often disconnected from the network or it can also be use in a scenario where you have lots of process need to be done on certain time. Rather than pushing all the process to be executed at one go, you can actually distribute it into a MSMQ and process it one by one. This will prevent your CPU to be exhausted and running 100% during the peak time and 0% during the non peak time.

MSMQ Features

  1. Messages can be sent in a disconnected environment. It is not necessary for the sending and the receiving application to run at the same time.
  2. With express mode, messages can be sent very fast.
  3. For recoverable mechanism, messages can be sent using the guaranteed delivery.
  4. Message Queues can be secured with access control lists to define which users can send and receive the data from the queue.
  5. MSMQ version 3.0 supports sending multicast messages.
    (Only Windows Server 2003 and Windows XP support MSMQ version 3.0. Windows 2000 still use MSMQL version 2.0)

To start using MSMQ on  your machine, you need to install the MSMQ from your Add/Remove programs in Windows and remember to start the service after you have installed it. You can send a message to a MSMQ server across the network.

Message Queuing Architecture

With Message Queuing, messages are written and read from a Message Queue. Messages and message queues have several attributes that must be further elaborated. The message includes a body containing the data that is sent and a label that is the title of the message.

Message Queues have several types of messages:

  1. Normal message is sent by an application.
  2. An acknowledgement message reports the status of normal message. Acknowledgement messages are sent to administration queues to report success or failures of sending normal messages.

Creating Message Queues

Before you start coding MSMQ, you need to make sure that you have created the Queue itself.  To create MSMQ, Go to Start -> Control Panel -> Administrative Tools -> Computer Management Menu.

In the treeview pane, the Message Queuing is located below the Services and Applications.
Right Click the Private Queues and create new Queue named it MyQueues. Please note, public queues are available only if you installed the MSMQ in Active Directory Mode.

Programming Message Queuing

Basic MSMQ Code

if(MessageQueue.Exists("@.\Private$\MyQueues")) {
    MessageQueue oMq = new MessageQueue(@".\Private$\MyQueues");
    oMq.Label = "Testing Queue";
}
else {
    //Create the Queue
    MessageQueue.Create(@".\Private$\MyQueues");
}

The code above basically will check if the Queue called MyQueues exists or not on your local machine queue. And if not exists, it will create that. You will also notice that you can create the queues programmatically using the code without have to use Computer Management to create that.

Depending on the queue type, different identifiers are required when queues are opened. The following table shows the syntax of the queue for specific types

Queues Type Syntax
Public Queue MachineName\QueueName
Private Queue MachineName\Private$\QueueName
Journal Queue MachineName\QueueName\Journal$

If you like to open Queue from Remote Machine,  you need to pass either the IPAddress or the hostname. For localmachine queue, you can just use “.”
Sending a Message to MSMQ


To send a message , you can use the Send Method of the MessageQueue class .

if (MessageQueue.Exists(@".\Private$\MyQueues"))
{
    MessageQueue oMq = new MessageQueue(@".\Private$\MyQueues");
    oMq.Send("Testing Message", "Title");
}
else
{
    //Create the Queue
    MessageQueue oMq = MessageQueue.Create(@".\Private$\MyQueues");
    oMq.Send("Testing Message", "Title");
}

After you execute the code above, try to expand your private queue and you should see there is a new message inside the queue.

 

 

Sending Priority Messages to MSMQ

MessageQueue oMq = new MessageQueue(@".\Private$\MyQueues");
System.Messaging.Message oMsg = new System.Messaging.Message("Testing");
oMsg.Priority = MessagePriority.Highest;
oMq.Send(oMsg);

As you can see, we can set the Priority properties from the Message object and when you retrieve it back, the message with the highest priorities will be read first.

Receiving Messages from MSMQ

To read messages, you can use Receive() method. With the Receive()method a single message is read and removed from the queue. If messages are sent with different priorities, the message with the highest is read first.

MessageQueue oMq = new MessageQueue(@".\Private$\MyQueues");
oMq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
System.Messaging.Message oMsg = oMq.Receive();
MessageBox.Show(oMsg.Body.ToString());

The Receive() method basically will delete the message from the queue. This is infact quite dangerous if there is an error happen when reading the queue. This will cause your messages to be deleted forever and no way you can get it back. Rather than calling the Receive() method, it might be better if you use enumerator to loop through all the messages and manually delete the message once you have done reading and processing the message.

Enumerating Messages from MSMQ

MessageQueue oMq = new MessageQueue(@".\Private$\MyQueues");
queue.Formatter = new XmlMessageFormater(new string [] {"System.String"});
foreach(Message message in queue) {
    MessageBox.Show(message.Body);
}

MSMQ interaction

Developing messaging-based applications begins with a queue. MSMQ includes four queue types:

  • Outgoing: Used to temporarily store messages before they are sent to its destination.
  • Public: Published in the Active Directory. Applications on different servers throughout the network can find and use public queues via Active Directory.
  • Private: These queues are local to a server and are not available to other machines (thus, these queues are not published in Active Directory).
  • System: Contains journal messages (sent from the system), dead messages, and transactional dead-letter messages. Dead messages are undeliverable.

Programmatic manipulation of MSMQ is available via the Systems.Messaging namespace. There are two main objects in this namespace:

  • Message: The actual message or data sent to or read from a queue.
  • MessageQueue: The MSMQ message queue that will receive/send messages.

Conclusion

In the article, you can see how Message Queuing can be used. Message Queuing is an important technology to offer not only asynchronous but also disconnected communication. The sender and receiver can be running at different times which makes Message Queuing an option for smart clients and also useful to distribute the load on the server over time.

 

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

 
%d bloggers like this: