Click here to Skip to main content
13,769,953 members
Click here to Skip to main content
Add your own
alternative version

Stats

5.7K views
166 downloads
37 bookmarked
Posted 14 Sep 2018
Licenced CPOL

Message Queue

, 14 Sep 2018
Rate this:
Please Sign up or sign in to vote.
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.

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

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

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

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.

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

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

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:

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.

Then we will have:

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.

License

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

Share

About the Author

Mahsa Hassankashi
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.

*Article of The Community Spotlight in Microsoft ASP.NET, Wednesday, February 11, 2015, www.asp.net
*Article of The Day in Microsoft ASP.NET Tuesday, February 3, 2015, www.asp.net/community/articles
*1 Jan 2015: CodeProject MVP 2015
*22 Mar 2014: Best Web Dev Article of February 2014 - Second Prize


You may also be interested in...

Comments and Discussions

 
Questionmy vote to 5 Pin
Satyaprakash Samantaray9-Nov-18 8:38
memberSatyaprakash Samantaray9-Nov-18 8:38 
GeneralMy vote of 5 Pin
Wooters30-Sep-18 9:09
memberWooters30-Sep-18 9:09 
GeneralRe: My vote of 5 Pin
Mahsa Hassankashi3-Oct-18 12:19
mvpMahsa Hassankashi3-Oct-18 12:19 
QuestionAndroid Pin
RickZeeland15-Sep-18 7:42
mvpRickZeeland15-Sep-18 7:42 
AnswerRe: Android Pin
Mahsa Hassankashi16-Sep-18 2:19
mvpMahsa Hassankashi16-Sep-18 2:19 
GeneralRe: Android Pin
Ekran Ahmed16-Sep-18 20:20
memberEkran Ahmed16-Sep-18 20:20 
PraiseGreat Pin
Lewis Shelley14-Sep-18 23:01
memberLewis Shelley14-Sep-18 23:01 
GeneralRe: Great Pin
Mahsa Hassankashi16-Sep-18 2:00
mvpMahsa Hassankashi16-Sep-18 2: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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.181119.1 | Last Updated 14 Sep 2018
Article Copyright 2018 by Mahsa Hassankashi
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid