Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Message Queue

4.94/5 (38 votes)
14 Sep 2018CPOL2 min read 45.5K   1.1K  
This article describes MSMQ technology (publisher and subscriber) in order to communicate among distributed systems in the heterogeneous network and platforms.

Message Queue

Nowadays, we need more to communicate between distributed systems. It is because of a variety in devices and extending communication in order to enhance facilities and convenience. The big question is to select best and appropriate technology to wire each ecosystem and environment.

Message queue is a technology to publish a message throughout platforms and it is reliable, scalable, simple, thread-safe, and convenient to debug. MSMQ allows us to publish message across the heterogeneous networks and platforms.

One of its application is to use in Internet of things where there are highly decoupled devices in the heterogeneous environment.

Image 1

There are sender and receiver in this scenario, as shown in the below picture:

Image 2

Another competitor for message queue is web service. In the web service, most of the handling error if we lose message is on the shoulder of client while persistency in message queue is more.

How to Use MSMQ

MSMQ is based on windows features. It is possible to install Microsoft Message Queue:
Control Panel -> Turn Windows features on or off -> (Select) Microsoft Message Queue (MSMQ) Server

Image 3

Simple MSMQ

Now it is time to code:

Step 1: Create Web Site As Publisher

Selecting type of project is optional, for example, it can be Windows application or WPF as publisher

File -> New -> Web Site

Step 2: Add System.Messaging Reference 

Right click on the References -> Select Add Reference

Image 4

Step 3: Creating Entity For Message

We can pass a message as object to senders with below structure with Serializable attribute for using on the sender side.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MSMQWebApp
{
    [Serializable]
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Step 4: Creating Queue and Publishing Message

In order to access Windows Queue:

Control Panel ->Administrative Tools -> Computer Management -> Services and Applications -> Message Queuing

Image 5

Image 6

The important part is to create a path which is the same as topic for pub and sub systems.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MSMQWebApp
{
    public partial class UsingMSMQ : System.Web.UI.Page
    {        
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            System.Messaging.Message msg = new System.Messaging.Message();
            msg.Label = "Hello From The Web Application";
            msg.Body = "This is body";
            
            MessageQueue mq = new MessageQueue(".\\private$\\WebWinMsg");
            
            mq.Path = @".\private$\WebWinMsg";
            

            if (MessageQueue.Exists(mq.Path) == false)
            {
                MessageQueue.Create(mq.Path);
            }
            else
            {
                mq = new MessageQueue(mq.Path);
            }
            mq.Send(msg, "For Windows Application");
        }

        protected void SendObj_Click(object sender, EventArgs e)
        {
            System.Messaging.Message msg = new System.Messaging.Message();
            msg.Label = "Hello From The Web Application Object";
           
            List<product> product = new List<product>()
            {
                new Product{ Id=1, Name="Product A" },
                new Product{ Id=2, Name="Product B" }
            };
            msg.Body = product;

            MessageQueue mq = new MessageQueue(".\\private$\\WebWinMsgObj");
            
            mq.Path = @".\private$\WebWinMsgObj";


            if (MessageQueue.Exists(mq.Path) == false)
            {
                //Queue does not exist so create it
                MessageQueue.Create(mq.Path);
            }
            else
            {
                mq = new MessageQueue(mq.Path);
            }
            mq.Send(product);
        }
    }
}

Step 5: Using Queue and Receiving Message

We should create another application in order to use message in any platform. I used Windows application as follows:

Image 7

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Messaging;

namespace MSMQWinApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Receive_Click(object sender, EventArgs e)
        {
            MessageQueue mq = new MessageQueue(".\\private$\\WebWinMsg");
            System.Messaging.Message msg = new System.Messaging.Message();

            msg = mq.Receive();
            
            msg.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
            string m = msg.Body.ToString();

            this.listBox1.Items.Add(m.ToString());
        }

        private void Receive_Object_Click(object sender, EventArgs e)
        {
            MessageQueue myQueue = new MessageQueue(".\\myQueue");

            MessageQueue mq = new MessageQueue(".\\private$\\WebWinMsgObj");
            // Set the formatter to indicate body contains an Order.
            mq.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(List<msmqwebapp.product>)});

            try
            {
                // Receive and format the message. 
                System.Messaging.Message msg = mq.Receive();
                //string str= msg.Body.ToString();

                List<msmqwebapp.product> productObj = (List<msmqwebapp.product>)msg.Body;


                this.listBox2.Items.Add(productObj.Where(x => x.Id == 2).FirstOrDefault().Name);
            }

            catch (MessageQueueException)
            {

            }
        }
    }
}

Step 5: How to Run

Because we want to see both of the above application are running, we should configure multiple startup.

Image 8

Then we will have:

Image 9

As you see in the above picture; there are two different kinds of sending, Send and Send Object .

Send button will send simple message with body while the other will send object which can be filtered by linq query;

First click on "Send" on web browser and then on the win app click on "Receive" ; it was for simple msmq.

Second click on "Send Object" on web browser and then on the win app, click on "Receive Object" ; it was for sending object as message in msmq which has a capability for filtering by linq query.

Image 10

Image 11

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)