MSMQ - Overview


1) Overview of MSMQ

MSMQ stands for Microsoft Messaging Queue. MSMQ works on disconnected or connected mode and provides Asynchronous Programming. If client is disconnected from network, in that scenario, MSMQ is the most preferrable method because in this case the Server does not need to wait for client to read the data and send back the acknowledgement to server. (sample code in this article are tested on Visual Studio 2008)

(2) Verifying whether MSMQ is installed on your system


Navigate to "Services" by executing "Services.msc" in Run menu, then Sort on Name and Scroll down to find Message Queuing. If it is not there, that means MSMQ is not installed.

(3) MSMQ Setup

Control Panel -- Add/Remove Windows Components -- Select Message Queuing – Next (and follow in the instructions given on the subsequent windows)

This will install MSMQ in your system and it can be verified by Navigating to Computer Management also as given below…

Control panel -- Administrative Tools -- Computer management.
Explore "Services and Applications", then Explore "Message Queuing.
You will get Outgoing Queues, Private Queues, System Queues, Triggers.

(4) Types of Messages

MSMQ supports 2 kinds of messages: XML and Binary
Sample 3 and 4 illustrate XML and Binary messagings respectively.

(5) MSMQ Architecture (namespace Hierarchy)

System
|
+--- Messaging
.....|
.....+--- Message
.....|
.....+--- MessageQueue
.....|
.....+--- MessageEnumerator
.....|
.....+--- MessageType
.....|
.....+--- MessagePriority
.....|
.....+--- etc.

MSMQ Sample programs

Sample 1 (Creating and using MSMQ queue)

Prerequisites: First Create a MSMQ queue by navigating to Computer management -- Services and Applications -- Message Queuing -- Private Message -- Properties -- New -- Private Queue -- Give name as MyQueues.

Code: Create a C# Console application with following code...

using System;
using System.Text;
using System.Messaging;

namespace MYFirstMSMQ
{
    class Program
    {
        static void Main(string[] args)
        {

            if (MessageQueue.Exists(@".\Private$\MyTestingQueues"))
            {
                MessageQueue messageQueue = new MessageQueue(@".\Private$\MyTestingQueues");
                messageQueue.Label = "Testing Queue";
            }
            else
            {
                // Create the Queue
                messageQueue.Create(@".\Private$\MyTestingQueues");
                messageQueue.Label = "Newly Created Queue";
            }
        }
    }
}
Run the program & verify results by navigating to Queue (MyTestingQueues)

Note: If the queue is already available its name will be changed as "Testing Queue". If the queue is not available, it will be created and the name will be set to "Newly Created Queue"


Sample 2 (Sending Message to MSMQ queue)

Code: Create a C# Console application with following code...



using System;
using System.Text;
using System.Messaging;

namespace MYFirstMSMQ
{
    class Program
    {
        static void Main(string[] args)
        {

            MessageQueue messageQueue = null;
            if (MessageQueue.Exists(@".\Private$\MyTestingQueues"))
            {
                messageQueue = new MessageQueue(@".\Private$\MyTestingQueues");
                messageQueue.Label = "Testing Queue";
            }
            else
            {
                // Create the Queue
                MessageQueue.Create(@".\Private$\MyTestingQueues");
                messageQueue = new MessageQueue(@".\Private$\MyTestingQueues");
                messageQueue.Label = "Newly Created Queue";
            }

            messageQueue.Send("First ever Message is sent to MSMQ", "Title");
        }
    }
} 

Run the program & verify the requly by refreshing "MyTestingQueues" and selecting "Queue Messages"
You will notice that a new message is added in the "Queue Messages". You can open its properties to see various information attached with this message.


Sample 3 (using XmlMessageFormatter)

Code: Create a C# console application with following code...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;

namespace MYFirstMSMQ
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Sending Messages
            MessageQueue messageQueue = null;
            if (MessageQueue.Exists(@".\Private$\MyTestingQueues"))
            {
                messageQueue = new MessageQueue(@".\Private$\MyTestingQueues");
                messageQueue.Label = "Testing Queue";
            }
            else
            {
                // Create the Queue
                MessageQueue.Create(@".\Private$\MyTestingQueues");
                messageQueue = new MessageQueue(@".\Private$\MyTestingQueues");
                messageQueue.Label = "Newly Created Queue";
            }
            System.Messaging.Message message = new System.Messaging.Message("MyTestingQueues");
            message.Priority = MessagePriority.Low;
            messageQueue.Send("First message is sent to MSMQ ", "Message 1");
            messageQueue.Send("Second message is sent to MSMQ ", "Message 2");
            messageQueue.Send("Third message is sent to MSMQ ", "Message 3");
            messageQueue.Send("Forth message is sent to MSMQ ", "Message 4");
            #endregion

            #region Receiving Messages

            messageQueue = new MessageQueue(@".\Private$\MyTestingQueues");
            messageQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
            // iterating the queue contents
            foreach (Message msg in messageQueue)
            {
                string readMessage = msg.Body.ToString();
                Console.WriteLine(readMessage);
                // process Message 
            }
            // after all processing delete the messages
            messageQueue.Purge();

            Console.ReadKey();
            #endregion
        }
    }
} 

Run the application and verify the results

Sample 4 (using BinaryMessageFormatter)

In this sample we will store a JPG image file to MSMQ queue, that can be retrieved and consumed in the later stage.

Prerequisit: Place image file in either debug or release folders of bin folder.

Code: Create a C# console application with following code..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;          // provides Messaging class
using System.Drawing;           // provides Bitmap class

namespace MYFirstMSMQ
{
  class Program
  {
    static void Main(string[] args)
    {

      #region Creating > Storing > Receiving Imabes through MSMQ

      CreateQueue(@".\Private$\ImageQueue");      // Create on local system
      SendMessage();                                                  // Send message 
      ReceiveMessage();                           // Receive message 
      Console.ReadKey();

      #endregion

      return;
    }
// Creates a new queue.
    public static void CreateQueue(string queuePath)
    {
      try
      {
        if (!MessageQueue.Exists(queuePath))
        {
          MessageQueue.Create(queuePath);
        }
        else
        {
          Console.WriteLine(queuePath + " already exists.");
        }
      }
      catch (MessageQueueException e)
      {
        Console.WriteLine(e.Message);
      }
    }

// Sends an image to a queue, using the BinaryMessageFormatter.
    public static void SendMessage()
    {
      try
      {
        // Create new bitmap.
        // File must be in \bin\debug or \bin\release folder
        // Or a full path to its location should be given

        MessageQueue myQueue = new MessageQueue(@".\Private$\ImageQueue");  
        Image myImage = Bitmap.FromFile("MyImage.jpg");
        Message msg = new Message(myImage, new BinaryMessageFormatter());           myQueue.Send(msg);                                                  
      }
      catch (Exception e)
      {
        Console.WriteLine(e.Message);
      }
      return;
    }
/ Receives a message containing an image.
 public static void ReceiveMessage()
{
 try
      {

          MessageQueue myQueue = new MessageQueue(@".\Private$\ImageQueue");  
        myQueue.Formatter = new BinaryMessageFormatter();                   
        System.Messaging.Message myMessage = myQueue.Receive();             
        Bitmap myImage = (Bitmap)myMessage.Body;                            
        myImage.Save("NewImage.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
      }
catch (Exception e)
      {
        Console.WriteLine(e.Message);
      }
 return;
  }
  }
}
ions.Generic;

using System.Text;
using System.Messaging;
sing System.Drawing;    


namespace MYFirstMSMQ
{
  class Program
  {
    static void Main(string[] args)
    {


#region Creating > Storing > Receiving Imabes through MSMQ

      CreateQueue(@".\Private$\ImageQueue");      // Create on local system
      SendMessage();                                                  // Send message
      ReceiveMessage();                           // Receive message
      Console.ReadKey();

      #endregion

      return;
    }
/ Creates a new queue.
    public static void CreateQueue(string queuePath)
    {
      try
      {
        if (!MessageQueue.Exists(queuePath))
        {
          MessageQueue.Create(queuePath);
        }
        else
        {
          Console.WriteLine(queuePath + " already exists.");
        }
      }
      catch (MessageQueueException e)
      {
        Console.WriteLine(e.Message);
      }
    }
// Sends an image to a queue, using the BinaryMessageFormatter.
    public static void SendMessage()
    {
      try
      {
        // Create new bitmap.
        // File must be in \bin\debug or \bin\release folder
        // Or a full path to its location should be given

        MessageQueue myQueue = new MessageQueue(@".\Private$\ImageQueue");
        Image myImage = Bitmap.FromFile("MyImage.jpg");
        Message msg = new Message(myImage, new BinaryMessageFormatter());           myQueue.Send(msg);                                                
      }
      catch (Exception e)
      {
        Console.WriteLine(e.Message);
      }
      return;
    }
// Receives a message containing an image.
    public static void ReceiveMessage()
    {
      try
      {
        MessageQueue myQueue = new MessageQueue(@".\Private$\ImageQueue");
        myQueue.Formatter = new BinaryMessageFormatter();                 
        System.Messaging.Message myMessage = myQueue.Receive();           
        Bitmap myImage = (Bitmap)myMessage.Body;                          
        myImage.Save("NewImage.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
      }
      catch (Exception e)
      {
        Console.WriteLine(e.Message);
      }
 return;
    }
  }
}


Run the application & verify whether the "NewImage.Jpg" is created in the Debug or release folders.

                                             
Author: 

Comments

Popular posts from this blog

C# Constructor

Hiding vs Overriding