How to work with MSMQ in C#

MSMQ is a simple, convenient, reliable and persistent backing store for storing your messages

MSMQ

MSMQ

MSMQ (Microsoft Message Queuing) is a message queue that is available by default as part of Windows. A reliable way of sending and receiving messages across computer systems, MSMQ provides a queue that's scalable, thread-safe, simple, and convenient to use while at the same time providing you the opportunity to persist the messages inside the Windows database. The MSDN states: "Message Queuing (MSMQ) technology enables applications running at different times to communicate across heterogeneous networks and systems that may be temporarily offline. Applications send messages to queues and read messages from queues."

Typically, you have two distinct applications when working with MSMQ -- the sender and the receiver. When the messages are sent by the sender, i.e., the sending application, the receiving application need not be in execution state -- the messages are actually stored in a queue maintained by the host operating system and these are de-queued as and when they are needed by the receiving application.

Creating a Queue

You can turn on MSMQ in your system through the "Turn Windows features on or off" option from the control panel. Once MSMQ has been installed in your system, creating a queue is simple. Just go to "My Computer", right click and select Manage. In the "Computer Management" window you can create a new queue from the "Message Queuing" node. You can also create a queue programmatically.

Programming MSMQ in C#

To work with MSMQ, you would need to include the System.Messaging namespace. To create a queue programmatically, you need to leverage the Create method of the MessageQueue class. The following code snippet illustrates this.

MessageQueue.Create(@".\Private$\IDG");

To create a queue and send a message to it, you can use the following code snippet.

MessageQueue.Create(@".\Private$\IDG");              

messageQueue = new MessageQueue(@".\Private$\IDG");

messageQueue.Label = "This is a test queue.";

messageQueue.Send("This is a test message.", "IDG");

Now, suppose you would like to check if the queue exists and if it does, send a message to it. If the queue doesn't exist, you may want to create a new one and then send it a message. This is exactly what the following code listing does for you.

static void Main(string[] args)

        {

            MessageQueue messageQueue = null;

            string description = "This is a test queue.";

            string message = "This is a test message.";

            string path = @".\Private$\IDG";

            try

            {

                if (MessageQueue.Exists(path))

                {

                    messageQueue = new MessageQueue(path);

                    messageQueue.Label = description;

                }

                else

                {

                    MessageQueue.Create(path);

                    messageQueue = new MessageQueue(path);

                    messageQueue.Label = description;

                }

                messageQueue.Send(message);

            }

            catch

            {

                throw;

            }

finally

{

           messageQueue.Dispose();

}

      }

The following code listing illustrates how you can process the messages stored in a message queue using C#.

private static List<string> ReadQueue(string path)

        {

            List<string> lstMessages = new List<string>();

            using (MessageQueue messageQueue = new MessageQueue(path))

            {

                System.Messaging.Message[] messages = messageQueue.GetAllMessages();

                foreach (System.Messaging.Message message in messages)

                {

                    message.Formatter = new XmlMessageFormatter(

                    new String[] { "System.String, mscorlib" });

                    string msg = message.Body.ToString();

                    lstMessages.Add(msg);

                }

            }

            return lstMessages;

        }

Next, you can invoke the ReadQueue method to retrieve the messages stored in the message queue as shown in the code snippet below.

string path = @".\Private$\IDG";

List<string> lstMessages = ReadQueue(path);

You can also store objects in the message queue. As an example, suppose you need to store a log message to the queue. The log message is stored in an instance of the LogMessage class that contains the necessary properties that pertain to the details of the log message. Here's how the LogMessage class would look like -- I've made it simple with just two properties only.

public class LogMessage

    {

        public string MessageText { get; set; }

        public DateTime MessageTime { get; set; }

    }

You should modify the LogMessage class to incorporate other necessary properties, i.e., message severity, etc. The following method illustrates how you can store an instance of the LogMessage class to the message queue.

private static void SendMessage(string queueName, LogMessage msg)

        {

            MessageQueue messageQueue = null;

            if (!MessageQueue.Exists(queueName))

                messageQueue = MessageQueue.Create(queueName);

            else

                messageQueue = new MessageQueue(queueName);          

            try

            {

                messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(LogMessage) });

                messageQueue.Send(msg);

            }

            catch

            {

                //Write code here to do the necessary error handling.

            }

            finally

            {

                messageQueue.Close();

            }          

        }

The following code snippet illustrates how you can create an instance of the LogMessage class, populate it with data and then invoke the SendMessage method to store the instance created in the message queue.

LogMessage msg = new LogMessage()

            {

                MessageText = "This is a test message.",

                MessageTime = DateTime.Now

            };

SendMessage(@".\Private$\IDGLog", msg);

The following code listing illustrates how you can read the LogMessage instance stored in the message queue.

private static LogMessage ReceiveMessage(string queueName)

        {

            if (!MessageQueue.Exists(queueName))

                return null;

            MessageQueue messageQueue = new MessageQueue(queueName);

            LogMessage logMessage = null;

            try

            {

                messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(LogMessage) });

                logMessage = (LogMessage)messageQueue.Receive().Body;

            }

            catch { }

            finally

            {

                messageQueue.Close();

            }

            return logMessage;

        }

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.