Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

Message Queue

Rate me:
Please Sign up or sign in to vote.
4.94/5 (38 votes)
14 Sep 2018CPOL2 min read 42.5K   1K   47   11
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)


Written By
Doctorandin Technische Universität Berlin
Iran (Islamic Republic of) Iran (Islamic Republic of)
I have been working with different technologies and data more than 10 years.
I`d like to challenge with complex problem, then make it easy for using everyone. This is the best joy.

ICT Master in Norway 2013
Doctorandin at Technische Universität Berlin in Data Scientist ( currently )
-------------------------------------------------------------
Diamond is nothing except the pieces of the coal which have continued their activities finally they have become Diamond.

http://www.repocomp.com/

Comments and Discussions

 
Questiondoes this work only same server Pin
Amit Patel198519-Feb-20 23:25
Amit Patel198519-Feb-20 23:25 
GeneralGood article and well described Pin
rammanusani26-Mar-19 7:44
rammanusani26-Mar-19 7:44 
PraiseExcellent Explanation Pin
Maddy.777418-Dec-18 23:43
professionalMaddy.777418-Dec-18 23:43 
Questionmy vote to 5 Pin
Satyaprakash Samantaray9-Nov-18 7:38
Satyaprakash Samantaray9-Nov-18 7:38 
GeneralMy vote of 5 Pin
Wooters30-Sep-18 8:09
Wooters30-Sep-18 8:09 
GeneralRe: My vote of 5 Pin
Mahsa Hassankashi3-Oct-18 11:19
Mahsa Hassankashi3-Oct-18 11:19 
QuestionAndroid Pin
RickZeeland15-Sep-18 6:42
mveRickZeeland15-Sep-18 6:42 
AnswerRe: Android Pin
Mahsa Hassankashi16-Sep-18 1:19
Mahsa Hassankashi16-Sep-18 1:19 
That is a good question Thumbs Up | :thumbsup: . Actually I used Web Site Application as a Server Side and Windows Application as a Client Side due to satisfy my purpose to illustrate how to connect two distributed system together.

But in the case of your question, I can mention these below links:

Indeed there are two ways.

(1): I am new born in mobile app.
setting-msmq-your-mobile
Android MessageQueue


(2): Using Retrofit, firstly writing two API Services which you can use one as publisher and another is for subscribing. Secondly use retrofit in order to get result
retrofit-a-simple-android-tutorial

In the case of any question please let me know.



GeneralRe: Android Pin
Ekran Ahmed16-Sep-18 19:20
Ekran Ahmed16-Sep-18 19:20 
PraiseGreat Pin
Lewis Shelley14-Sep-18 22:01
Lewis Shelley14-Sep-18 22:01 
GeneralRe: Great Pin
Mahsa Hassankashi16-Sep-18 1:00
Mahsa Hassankashi16-Sep-18 1:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.