Microsoft Message Queue Example and Overview with C#

Many enterprise applications today require reliable message delivery mechanism. This is absolutely essential in financial transactions. There are a number of techniques available to achieve this including a Custom made Queuing server, the underlying protocol in that case would be Transfer Control Protocol TCP and it has to be made reliable by wrapping it in a layer of requests and acknowledgements, persisting all the requests and acknowledgements of a transaction in a database and applying rules for “Transaction Processing” as in a database. So the transaction is literally atomic and has many phases.This is sometimes difficult to achieve since implementing Sockets is itself a difficult proposition, it comes with the issues of Server client synchronization , memory management with multiple threads and usually the proprietary protocol that’s used for message passing or a custom developed API which needs to be configured for server and clients.
I have recently used MSMQ and was able to achieve all this without the need to develop long API or a lot of development. Integrating it with C# was very easy and the message passing has been very reliable. All the threads, queue management and connection are in built into MSMQ .In this article I would describe the basic things that you need to do to integrate MSMQ into your projects. Before using any of the sample code makes sure that MSMQ is installed on your system. If not it can be installed from the Add/Remove Windows component option. Once it is installed it is displayed in the administrative applications list and then you can use the code similar to one described in various sections. Make sure you add following references in your application:
System.Messaging
System.Messaging.Formatters
Writing Strings or Formatted Objects to MSMQ:
The sample code below would create a Message Queue in the private queues list with the name TestMSMQ. All messages that you post would be posted in this queue. // Name of the Private Queu you want to post data to
String queueName = “.\private$\TestMSMQ”; // The string message tou want to send// The  objects of user defined classes can also be sent
// MSMQ holds the serizlized version when received the body // should be converted to the same class object again
String messageToSend = “This is a test message”; // the message object that would be send
System.Object obj = messageToSend; // Create a MSMQ message queuing transaction.
MessageQueueTransaction msgTran = new MessageQueueTransaction(); // Begin a MSMQ transaction.// If the Queue doesn’t exist create it Using API
msgTran.Begin(); if (MessageQueue.Exists(queueName))   
    msgQueue = new MessageQueue(queueName);
else   
    msgQueue = MessageQueue.Create(queueName);  

msgQueue = new MessageQueue(queueName); 
Message msg = new Message(); 
// Assign the message to the BODY Property
msg.Body = obj; // Associate a binary or an XML formatter
msg.Formatter = new System.Messaging.BinaryMessageFormatter();
 // Send the Message
msgQueue.Send(msg, msgTr);  // Commit the transaction.
msgTran.Commit(); 
Reading from MSMQ: 

Receiving a Message from the Message Queue is Simple. If a user defined datatype resides in the body of the message and the Message queue is accessed from different applciations, services the same type should exist in both the services , applications. This can be done by placing them in a project and adding a reference to the project in both the applications , then converting the object returned by the Body of the message to an instance of the required Type. Note:Receiving a message would dequeue the Message from MessageQueue. If you want to make sure that whenever a message is removed from the message queue a copy of it is saved  you can use the Journal queue by setting the use journal queue flag while posting to the message queue. However if you don’t want to dequeue the message an Enumerator can be obtained and be processed with a loop that peeks the Message Queue messages. Use Peek instead of Receive and Receive only when absolutely certain about removing the message from the queue. // process the online messages here
string onlineQueueName = .\private$\TestMSMQ”;              // initialize the Message Queue instance
MessageQueue msgQueue;msgQueue = new MessageQueue(onlineQueueName); System.Messaging.Message Msg = nullMsg = olMq.Receive();Note : If you might be interested in  working code for MSMQ or have some design and architecture ideas feel free to discuss or email me at hiasad@hotmail.com

Advertisements

11 Comments

Filed under C#

11 responses to “Microsoft Message Queue Example and Overview with C#

  1. Jasvinder

    Nice Article

  2. Bashe

    awesome. i wanted to use named pipes to solve some problem but your atricle showed me a better solution to solve my problem (Message Queue)

  3. bobwah

    Could someone please sort out the foramatting of the text in this article.
    Also there is no declaration of the variable:

    MessageQueue msgQueue;

    at the start of the artcile and

    MessageQueueTransaction msgTran = new MessageQueueTransaction();

    is later referred to as

    msgQueue.Send(msg, msgTr);

  4. Hi! I was surfing and found your blog post… nice! I love your blog. 🙂 Cheers! Sandra. R.

  5. Raj

    After Selecting MSMQ in Windows Component Wizard asking for

    SetUp did not locate a suitable domain Controller or Controller server

    Specify a Windows AP domaincontroller a Windows 2000 domain Controller or an MSMQ 1.0 PEC or PSC .

    I am not what that means ANy help is Appretiated.

    Thanks in advance

    RAj

  6. kiranmai

    I have implemented message queuing and implemented background
    worker for fast processing of messages currently 500 messages are
    sending in 5 seconds but i need 10 times faster
    can any one help me for providing solution

    • asadsiddiqi

      Hi there,
      This is where your application design comes into play. A Message queue is a simple SAF which gives you an API to read messages. Is your application reading a message from Queue, processing the whole message and then reading the next ? If your processing code is slow or long then the processing time is more. You can spend some time optimizing the processing code. Also keep in mind that you can use threads in your design for concurrent processing (for things that could be separated out). I am not sure if you can optimize a 5 second piece of code to a 0.5 second piece of code or if it is even realistic or not 🙂

    • kiranmai

      i got solution for the above issues please refer below link if any body needs solution
      http://www.codeproject.com/Articles/167917/Microsoft-Message-Queuing-A-Simple-Multithreaded-C

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