July 29, 2016

Microsoft message queue (MSMQ) in C# and .NET

This article is written based on Microsoft Windows 7 using C# and .NET framework 2.0.


Microsoft message queue (MSMQ) is one of the technique with which you can achieve communication between two application processes running in same machine, under Windows platform.

To use MSMQ, you need to add reference System.Messaging explicitly in to your project and then you can avail its functionalities. Two very basic functions of MessageQueue class are Send() and Receive().

Send() method sends data to the message queue while Receive() method reads data from the message queue.

Microsoft Windows OS have three types of message queuing techniques and those are: -
1. Outgoing queue
2. Private queue
3. System queue

To view a queue, right click on MyCoputer -> Manage, expand Services and Applications and then expand Message QueuingAll queue used to enlist here, under the respective category that you have chosen while creating a message queue.






C# code to send send and receive data:


// Write data:
            string qPath = ".\\Private$\\MyQueue";
            MessageQueue mq;

            if (!MessageQueue.Exists(qPath))
            {
                mq = MessageQueue.Create(qPath);
            }
            else
                mq = new MessageQueue(qPath);

            Message msg = new Message();
            msg.Label = "TestQueue";
            msg.Body = "This is a test method.";
            mq.Send(msg);



// Read data:
try
            {
string qPath = ".\\Private$\\MyQueue";
Message msg = new Message();
                  MessageQueue msQ = new MessageQueue(qPath);
                  msg = msQ.Receive();
msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                  string msgReceived = msg.Body.ToString();
            }
            catch { }



Possible Errors:

1. The queue does not exist or you do not have sufficient permissions to perform the operation.
This is because if you havn’t created any queue or the queue does not exist and you are trying to use a queue. Conditional check  if(!MessageQueue.Exists(qPath)) generally resolve this error.

    2. Cannot find a formatter capable of reading this message.
    This is because you have not defined the respective format of received queue data. Below code can be used to define formatter.

    msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

    Here, I have used XML format and therefore, used XmlMessageFormatter class. Please change in your code for its format accordingly.