Settings add remove programs add remove windows components message queuing

Table of Contents

  • 1 How do I install MSMQ message queuing on Windows 10?
  • 2 How do I enable MSMQ on Windows 10?
  • 3 What is the replacement for MSMQ?
  • 4 How do I connect to MSMQ?
  • 5 How to install Microsoft Message Queue ( MSMQ ) Server Core?
  • 6 How can I add MSMQ to my server?
  • 7 What is message queuing?
  • 8 What is simple queue service?

How do I install MSMQ message queuing on Windows 10?

To do this:

  1. Select Windows Start->Control Panel.
  2. Click on Add/Remove Programs.
  3. Click on the Add/Remove Windows Components icon on the left.
  4. Select Message Queuing. Select the check box.
  5. Click on the Details button.
  6. Select Common.
  7. Keep clicking OK to continue the install.

How do you check MSMQ is installed or not?

  1. Open Control Panel.
  2. Click Programs and then, under Programs and Features, click Turn Windows Features on and off.
  3. Expand Microsoft Message Queue (MSMQ) Server, expand Microsoft Message Queue (MSMQ) Server Core, and then select the check boxes for the following Message Queuing features to install:
  4. Click OK.

How do I enable MSMQ on Windows 10?

How to Enable MSMQ Server on Windows 10- Quick Steps:

  1. Open Control Panel.
  2. Switch the view to Category.
  3. Click on the Programs.
  4. Then proceed with Programs and Features.
  5. On the left pane, you will find the option Turn Windows features on or off.
  6. Windows features dialog box will pop-up now.

How do I enable local MSMQ?

To install Message Queuing 3.0 on Windows XP and Windows Server 2003

  1. Open Control Panel.
  2. Click Add Remove Programs and then click Add Windows Components.
  3. Select Message Queuing and click Details.
  4. Ensure that the option MSMQ HTTP Support is selected on the details page.

What is the replacement for MSMQ?

Kafka, RabbitMQ, IBM MQ, Azure Service Bus, and ActiveMQ are the most popular alternatives and competitors to MSMQ.

How do I enable MSMQ on Windows?

In the Windows Features dialog box, look for Microsoft Message Queue (MSMQ) Server. Click on the checkbox to enable it. Then, you have to click OK.

How do I connect to MSMQ?

To configure a Microsoft Message Queuing (MSMQ) connection, follow the steps below:

  1. Add a new connection and go to the Edit section of the API Connection Manager.
  2. Specify a Name for your connection.
  3. Select MSMQ from the Type dropdown menu.
  4. Enter the Path of the queue you want to connect to:

What port does MSMQ use?

TCP port 1801
MSMQ protocol operates over TCP port 1801.

How to install Microsoft Message Queue ( MSMQ ) Server Core?

Click Next ,then click Install. Open Control Panel. Click Programs and then, under Programs and Features, click Turn Windows Features on and off. Expand Microsoft Message Queue (MSMQ) Server, expand Microsoft Message Queue (MSMQ) Server Core, and then select the check boxes for the following Message Queuing features to install:

How to check if Microsoft Message Queuing is installed?

Ensure that MSMQ is installed and running. Microsoft Message Queuing must be installed and ready for use before you deploy Monitoring/Archiving server. To verify that MSMQ has been installed, do the following: a. Click Start and the click Run .

How can I add MSMQ to my server?

Expand Microsoft Message Queue (MSMQ) Server, expand Microsoft Message Queue (MSMQ) Server Core, and then select the check boxes for the following Message Queuing features to install: MSMQ Active Directory Domain Services Integration (for computers joined to a Domain). MSMQ HTTP Support. Click OK.

How to fix MSMQ internal message queuing certificate does not exist?

‘User’s internal Message Queuing certificate does not exist.’ Interactively log on to each server that will be sending messages. Use the user account that the sending apps are running under. This will create the certificate, one per machine, for that account.

What is message queuing?

Message Queuing is a message infrastructure and a development platform for creating distributed messaging applications for the Microsoft Windows Operating System.

How does message queue system work?

Message queues implement an asynchronous communication pattern between two or more processes/threads whereas the sending and receiving party do not need to interact with the message queue at the same time. Messages placed onto the queue are stored until the recipient retrieves them.

What is simple queue service?

Simple Queue Service (SQS) AWS SQS is a web service that provides us with a message queue on the cloud to which a sender process (not humans) can send a message and a reader process (not humans) can retrieve/process/delete the message. So message queue is basically a temporary repository of messages on the AWS cloud.

What is message queue in Windows?

Message Queuing (also known as MSMQ ) is a messaging infrastructure and a development tool for creating distributed messaging applications for Microsoft Windows operating systems . Applications developed for Message Queuing send messages to queues, which are temporary storage locations, from which messages can proceed…

MSMQ stands for Microsoft Message Queuing is one of the most reliable way to sending and receiving messages from one system to another system; both system can be located at different geographical locations. The benefit of MSMQ is that the receiving application doesn’t have to run at the time of sending the message. Messages are stored in the queue of the system (Microsoft Operating System) and once the receiving application runs, it starts peeking the messages one by one.

To perform a task asynchronously is to execute it without waiting for a result. This type of processing allows we to start a time-consuming process and continue working without having to wait for that process to finish executing.
Asynchronous processing is ideal to use in many situations—especially on the Web, where a user’s request could take a long time to process, but we want to provide a response back to the user immediately. By handling the user’s request asynchronously, our system can respond regardless of how long that request may actually take to execute.

To install Message Queuing 4.0 on Windows Server 2008 or Windows Server 2008 R2

In Server Manager, click Features.
In the right-hand pane under Features Summary, click Add Features.
In the resulting window, expand Message Queuing.
Expand Message Queuing Services.
Click Directory Services Integration (for computers joined to a Domain), then click HTTP Support.
Click Next, then click Install.

To install Message Queuing 4.0 on Windows 7 or Windows Vista

Open Control Panel.
Click Programs and then, under Programs and Features, click Turn Windows Features on and off.
Expand Microsoft Message Queue (MSMQ) Server, expand Microsoft Message Queue (MSMQ) Server Core, and then select the check boxes for the following Message Queuing features to install:
MSMQ Active Directory Domain Services Integration (for computers joined to a Domain).
MSMQ HTTP Support.
Click OK.
If we are prompted to restart the computer, click OK to complete the installation.

To install Message Queuing 3.0 on Windows XP and Windows Server 2003

Open Control Panel.
Click Add Remove Programs and then click Add Windows Components.
Select Message Queuing and click Details.
System_CAPS_noteNote
If we are running Windows Server 2003, select Application Server to access Message Queuing.
Ensure that the option MSMQ HTTP Support is selected on the details page.
Click OK to exit the details page, and then click Next. Complete the installation.
If we are prompted to restart the computer, click OK to complete the installation.

To Check MSMQ interface:
My Computer -> Manage -> Services and Applications -> Message Queueing.

There are two types of Messaging Queue:
1. Public Queue:
Provide Message routing.
Public queues are accessed through “Machine nameQueue name”
2. Private Queue:
Do not Provide any routing.
Private queues are accessed through “Machine namePrivate$Queue name”.
If MSMQ is installed on the same machine as our application then we can replace the machine name with a dot, for example “.Private$testQue”

Creating a Queue in the system
Creating a queue in the system is an easy task. Go to My Computer and right click, select Manage and explore the nodes as displayed in the picture below.
IC163748
Right click the Private Queues and select New > Priovate Queue and create a queue. Alternatively, this can be done using C# code as well. My code snippet below does that automatically (ie. if queue doesn’t exists, it creates otherwise use the existing one).

Creating Queues Programmatically
Although the MSMQ interface is available for creating, deleting, and exploring message queues, we can also work with queues through the System.Messaging namespace. Several static methods (meaning we can call them without creating an actual instance of the class) have been provided on the MessageQueue class that give we the ability to check if a queue exists (Exists), create a queue (Create), and delete a queue (Delete). Using these methods, our application can check for the existence of a queue, and create it automatically if it does not exist. The function, GetQ, listed next provides the exact functionality just described:

 if (MessageQueue.Exists(@".\Private$\MyQueue"))
 {
     myQueue = new MessageQueue(@".\Private$\MyQueue");
 }
 else
 {
     myQueue = MessageQueue.Create(@".\Private$\MyQueue");
 }
Delete
 MessageQueue.Delete(@".\Private$\MyQueue")

Now, let’s send a message to the MSMQ
The following code example shows how to  send a message, setting a few options including formatting and encryption before using the MessageQueue object’s Send method with the preconfigured Message object:

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

namespace MessageSender
{
    class Program
    {
        static void Main(string[] args)
        {
            do
            {
                Console.WriteLine("Enter Message to be send");
                Console.WriteLine("High Priority Message should be start with HP:");
                string text = Console.ReadLine();

                MessageQueue myQueue;

                if (MessageQueue.Exists(@".\Private$\MyQueue"))
                {
                    myQueue = new MessageQueue(@".\Private$\MyQueue");
                }
                else
                {
                    myQueue = MessageQueue.Create(@".\Private$\MyQueue");
                }
                Message message = new System.Messaging.Message();
                message.Formatter = new BinaryMessageFormatter();
                message.Body = text;
                message.Label = "myTestMessage";

                if (text.Contains("HP:")) { message.Priority = MessagePriority.High; }
                else { message.Priority = MessagePriority.Normal; }
                myQueue.Send(message);
                Console.WriteLine("Message has sent");
            } while (Console.ReadKey().Key != ConsoleKey.Q);
        }
    }
}

One of the key message options we may wish to specify controls how the message is serialized for sending. By default, this is set to use XMLMessageFormatter, which serializes objects into an XML representation and is suitable for most purposes. Two other formatters are available, however: the BinaryMessageFormatter and ActiveXMessageFormatter, both of which serialize objects into a binary (not human-readable like XML) format.

Receiving messages from MSMQ
To receive a message from queue, we need to first instantiate the queue using MessageQueue. we will need to make sure that the queue exists, otherwise we shall get an error.
Once we have placed messages onto our queue, someone will likely wish to retrieve those messages, taking the data off the queue in the order in which it was added. To obtain a message from the queue, and then retrieve the data it contains, requires a few important steps:

* First, as with sending a message, obtain a MessageQueue object pointing at the       appropriate queue:
var myQueue = new MessageQueue(@”.\Private$\MyQueue”);
* Next, use the Receive method of the queue to obtain the first message from the queue:
Message message = myQueue.Receive();
* Then, if we are using the XML formatter (the default), set up the formatter of the Message object with a list of possible data types that might be contained in the message. In this case, we are expecting only one possible data type, String:
Message message = myQueue.Receive();
message.Formatter = new BinaryMessageFormatter();
* Finally, use the Body property to retrieve our data, casting it into the appropriate type:
Console.WriteLine(message.Body.ToString())

With large messages and slow network links in mind, the MessageQueue object provides an asynchronous way to receive messages in addition to the Receive method. To receive a message asynchronously, we proceed as before and obtain a reference to the appropriate queue, and then, instead of calling Receive, we will call BeginReceive (specifying a time-out if desired). This starts the receive process, and execution will continue immediately with the next line of code.
When a message has been successfully retrieved,and the MessageQueue object’s ReceiveCompleted event will fire and our event handler will be called. The retrieved message is sent to our event handler as part of one of its parameters, and we can use that object to retrieve the actual data as usual.

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

namespace MessageReceiver
{
    class Program
    {
        private static MessageQueue myQueue = null;
        private static object lockObject = new object();

        static void Main(string[] args)
        {
            Console.WriteLine("Received Messages");

            myQueue = new MessageQueue(@".\Private$\MyQueue");
            // Setup an event to listen for new messages.
            myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);

            // Start listening.
            myQueue.BeginReceive();
            /*Message message = myQueue.Receive();
            message.Formatter = new BinaryMessageFormatter();
            Console.WriteLine(message.Body.ToString());*/
            while (Console.ReadKey().Key != ConsoleKey.Q)
            {
                // Press q to exit.
            }
        }


        static void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            lock (lockObject)
            {
                // The message is plain text.
                e.Message.Formatter = new BinaryMessageFormatter();
                string text = (string)e.Message.Body;
                Console.WriteLine("Message received: " + text);
            }

            // Listen for the next message.
            myQueue.BeginReceive();
        }
    }
}

tutorial: https://www.youtube.com/watch?v=ZHiu81Gqb_o

Службы очереди сообщений

Службы очереди сообщений (Microsoft Message Queuing Services, MSMQ) — сервис, входящий в стандартную поставку Microsoft Windows 2000 Server. С помощью MSMQ приложения, работающие в разное время, могут связываться через разнородные сети и системы, способные временно работать автономно. Приложения посылают сообщения MSMQ и используют очереди MSMQ — это позволяет быть уверенным, что сообщение рано или поздно достигнет адресата. MSMQ обеспечивает гарантированную доставку сообщений, интеллектуальную маршрутизацию, защиту и передачу сообщений, основанную на приоритетах.

При помощи MSMQ конечные пользователи могут связываться через автономные сети и системы, вне зависимости от текущего состояния поддерживающих связь приложений и систем. При помощи MSMQ разработчики могут сосредоточиться на программировании бизнес-логики, а не решать проблемы работы с сетями, поскольку MSMQ обеспечивает гарантированную доставку. Администраторы систем при помощи MSMQ могут эффективно управлять большими, сложными сетями очередей сообщений.

Программные продукты с такими возможностями часто называют программным обеспечением поддержки очередей сообщений, программным обеспечением с промежуточным накоплением или средствами среднего уровня, ориентированными на сообщения (MOM, Message-Oriented Middleware).

Особенности и возможности службы MSMQ: .

Интеграция с Windows 2000 Server. Поддерживается служба Active Directory, в которой хранятся отдельные объекты MSMQ.
Работа в смешанном режиме. MSMQ может функционировать в смешанных сетевых средах, состоящих из серверов и клиентов на базе как Windows NT 4.0, так и Windows 2000.
Совместимость сверху вниз. Служба MSMQ полностью совместима с MSMQ версии 1.0.
Передача сообщений без установления логического соединения. Поскольку MSMQ использует бессеансовую модель на прикладном уровне, отправитель и получатель не обязаны применять один и тот же протокол. MSMQ поддерживает протоколы IP и IPX.
Поддержка приоритетов трафика. Приоритеты сообщений позволяют срочному или важному трафику вытеснять менее важный, что гарантирует адекватное время ответа критическим приложениям за счет менее важных приложений.
Гарантированная доставка. Сообщения помещаются в хранящуюся на диске очередь, что обеспечивает гарантированную доставку сообщений.
Транзакции. Имеется возможность использования транзакций MSMQ, т. е. можно объединить несколько действий MSMQ в транзакцию и обеспечить гарантированную доставку сообщений, а также то, что они будут доставлены не более одного раза или что доставленные сообщения будут успешно извлечены из очереди адресатом.
Динамические очереди. Администраторы могут изменять свойства очередей без воздействия на приложения передачи сообщений.
Маршрутизация. MSMQ поддерживает интеллектуальную маршрутизацию, которая основана на физической топологии сети, группировке сеансов и на обеспечении транспортной связности. Группировка сеансов облегчает эффективное использование медленных линий.
Безопасность. MSMQ поддерживает механизмы безопасности: управление доступом, аудит, шифрование и аутентификацию. Управление доступом реализовано с применением системы безопасности Windows 2000 и цифровых подписей. Аудит реализован при помощи службы регистрации событий Windows 2000. Шифрование и аутентификация (использование цифровых подписей) обеспечиваются при помощи механизмов открытых и закрытых ключей.
Широкая интеграция систем. Приложения MSMQ могут выполняться на целом ряде аппаратных платформ, использующих продукты для обеспечения связи со службой MSMQ, поставляемые фирмой Level 8 Systems, партнером Microsoft, Исходно MSMQ поддерживает Windows NT, Windows 95 и Windows 98. Поддержка остальных систем поставляется фирмой Level 8 Systems.
Среда программирования MSMQ.. Прикладной интерфейс MSMQ позволяет разрабатывать приложения MSMQ на языке С или C++. MSMQ также включает элементы управления СОМ, которые можно применять для создания приложений MSMQ в Microsoft Visual Java (VJ), Visual Basic (VB) или любых других приложений-контейнеров СОМ (например, Microsoft Access или Borland/Inprise Delphi). При помощи Microsoft ASP и Microsoft US можно интегрировать MSMQ-приложение с веб-страницами и формами, использующими элементы управления СОМ. При помощи MAPI Transport Provider и Exchange Connector можно интегрировать приложение MSMQ с формами Exchange и клиентами MAPI. Транспорт MSMQ

RPC можно использовать для создания надежных приложений, использующих вызовы RPC.

Установка MSMQ. Чтобы добавить или удалить службу:

1. В меню Пуск (Start) выберите команду Настройка (Settings) | Панель управления (Control panel) | Установка/удаление программ (Add/Remove Programs).
2. В левой панели диалогового окна Установка/удаление программ выберите вкладку Добавление/удаление компонентов Windows.
3. Откроется окно Мастер компонентов Windows (Windows Components Wizard). В списке Компоненты Windows (Windows Components) выберите опцию Службы очереди сообщений (Message Queuing Services) (рис. 22.18).
4. Нажмите кнопку Далее (Next) и следуйте командам мастера.

Рис 22.18. Установка служб очереди сообщений

Примечание

Сначала нужно установить сервер MSMQ на контроллере домена Windows 2000 (в группе серверов, объединенных территориально), а затем можно устанавливать программное обеспечение MSMQ на других компьютерах. Сервер MSMQ не может быть установлен на компьютерах, работающих под управлением Windows 2000 Professional.

Служба MSMQ в Windows NT 4.0 и Windows 2000. Перечислим общие задачи управления службой MSMQ. Интерфейс пользователя для выполнения этих задач отличается в Windows 2000 от интерфейса в Windows NT 4.0.

В табл. 22.6 перечислены отличия в терминологии и в архитектуре предыдущих версий от текущей версии MSMQ.

Таблица 22.6. Управление службой MSMQ в Windows 2000 и в Windows NT 4.0

Необходимое действие Windows NT 4.0 Windows 2000
Управление доступом, установка аудита или изменение владельца для Message Queuing MSMQ Explorer Оснастка Active Directory- пользователи и компьютеры (Active Directory Users and Computers)
Изменение учетной записи для службы MSMQ Значок Services на панели управления Оснастка Управление компьютером (Computer Management)
Настройка параметров маршрутизации MSMQ Explorer Оснастка Active Directory — пользователи и компьютеры
Создание внешних (foreign) узлов или добавление внешних компьютеров MSMQ Explorer Оснастка Active Directory-пользователи и компьютеры
Добавление, удаление и настройка компьютеров MSMQ; установка квот для компьютеров или изменение свойств MSMQ Explorer Оснастка Active Directory — пользователи и компьютеры
Установка параметров IPX/SPX для компьютеров MSMQ Значок Network на панели управления Значок Сеть и удаленный доступ к сети (Network arid Dialup Connections) на панели управления
Создание, удаление и настройка очередей; установка квот очереди или изменение свойств MSMQ Explorer Оснастка Active Directory — пользователи и компьютеры
Просмотр и удаление сообщений; просмотр свойств сообщений MSMQ Explorer Оснастка Active Directory — пользователи и компьютеры

Управление службой MSMQ. Управление MSMQ на локальном компьютере осуществляется при помощи оснастки Управление компьютером — узел Службы и приложения | Очередь сообщений. Основное управление объектами MSMQ в организации осуществляется с применением оснастки Active Directory — пользователи и компьютеры. Для управления MSMQ в организации:

1. Запустите оснастку Active Directory — пользователи и компьютеры.
2. В дереве консоли разверните узел Active Directory — пользователи и компьютеры.
3. В меню Вид (View) выберите пункт Пользователи, группы и компьютеры как контейнеры (Users, Groups and Computers as Containers), а затем в том же меню выберите пункт Дополнительные функции (Advanced Features).
4. В дереве консоли найдите нужный домен, затем подразделение, наконец нужный компьютер, на котором установлена MSMQ, щелкните правой кнопкой мыши на узле msmq и в контекстном меню выберите пункт Свойства (Properties).

Microsoft Message Queue (MSMQ):
MSMQ is a messaging protocol that allows applications running on separate servers/processes to communicate in a failsafe manner. A queue is a temporary storage location from which messages can be sent and received reliably, as and when conditions permit. Queues are used to receive and send the Messages.

To Install MSMQ, Go to Control Panel -> Add Remove Program -> Add Windows Component and select “Message Queuing”

Install MSMQ - Microsoft Messaging Queue

Install MSMQ – Microsoft Messaging Queue

There are two types of Messaging Queue:

1. Public Queue:

  • Provide Message routing.
  • Public queues are accessed through “Machine nameQueue name”

2. Private Queue:

  • Do not Provide any routing.
  • Private queues are accessed through “Machine namePrivate$Queue name”.
  • If MSMQ is installed on the same machine as your application then you can replace the machine name with a dot, for example “.Private$Sales”

MSMQ is deployed in two mode:
1. Workgroup mode

  • only private Queue therefore no messaging routing
  • only “Common” and “Trigger” components needed.

2. Domain mode

  • private and public queue.
  • Machine that installed MSMQ must be the part of domain and uses Active Directory.
  • “Common”, “Trigger”, “Active Directory Integration”, “Routing Suport” components are needed.

MSMQ Installs two window services also:

  1. Message Queueing
  2. Message Queueing Triggers

Administrative interface:
To Open admin Panel , My Computer -> Manage -> Services and Applications -> Message Queueing.

MSMQ Admin panel

MSMQ Admin panel

Under each queue you will find following three items:

1. Queue Messages

  • All the messages currently seating in Queue.
  • You can view the properties of all messages but cannot change it.
  • Cannot create new messages or cannot delete an individual existing messages.
  • You can delete all the messages by right click on “Queue messages” and select “All Tasks | Purge”

2. Journal Messages

  • During Queue creation journal can be “enabled” means a copy of message from queue is placed into journal.
  • Means you have the copy of all messages of queue which is read or processed.
  • Purge (Delete) messages regulary from journal otherwise its size will be increased.

3. Triggers

  • Allows to register the Trigger when message is placed in Queue.
  • During Trigger setting you can specify COM component or external executable.

Other than Public and Private Queue, one more Queue is present which is “System Queue”. Which cannot be modified or removed.

Under System Queue you will find following three items:
1. Journal Messages:

  • During Queue creation journal can be “enabled” means a copy of message from queue is placed into journal. And if the journal is not enabled then copy of message is placed in “System queue’s journal” (condition it should be enabled at code).  Means its your choice that you want to maintain journal at system queue level or message queue level.

2. Dead – Letter Messages :

  • copy of all the Messages which are not delivered or expired before deliver or expired before its read / received (condition it should be enabled at code).

3. Transactional Dead – Letter Messages:

  • Same as “Dead – Letter Messages” but its for Transactional Messages.

Introduction

There are several different kinds of queues available in the C# ASP .NET framework with the most popular one being the standard Queue collection object. While these collections are easy to work with and fairly robust they are still stored in memory and therefore temporary. Often, in enterprise application design, more stringent means of managing and storing temporary data are required.

In the case of receiving timely data to be processed, using a queue in your software design makes sense. When the data needs to be guaranteed for delivery and protected from loss, the Microsoft Message Queue MSMQ provides a scalable easy solution.

At its core, Microsoft Message Queue MSMQ is a queue collection with a persistent storage backing. This means that data sent to the queue is automatically persisted within an internal Windows database. The MSMQ is also thread-safe, which means a multi-threaded C# ASP .NET application may safely send and receive messages with the queue and be gauranteed a thread-safe enviornment, and that messages will not be lost. As powerful and complex as the Microsoft Message Queue MSMQ sounds, it’s actually quite easy and convenient to use.

Overall Look at the Microsoft Message Queue MSMQ

Before jumping into the detailed code, using the Microsoft Message Queue with C# ASP .NET is very similar to working with a queue collection with the exception that you have even more properties and tools available for working with the data. Messages can be stored as plain text, XML, binary, or even a custom selected format, dictated by the Message Formatter property of the queue. Below is a psuedo-code summary of how to use a Microsoft Message Queue MSMQ.

// Initialize the queue

// Begin listening for new events on the queue

// Send a message to the queue

// Close the queue

You Do Have a Queue, Don’t You?

Since Microsoft Message Queue MSMQ is part of the Windows operating system, you need to first verify that the component is installed on your PC and that you have a queue available to work with. To check if MSMQ is installed, open the Computer Management window by clicking Start->Settings->Control Panel->Administrative Tools->Computer Management. Click the plus sign next to Services and Applications. You should see an item called Message Queuing. If you need to install MSMQ, you can do so by entering the Add Remove Programs window, click Add Remove Windows Components, and checkmark the option for Message Queuing.

Once Microsoft Message Queue MSMQ is available on your PC, you need to create a queue. Two basic types of queues exist: public and private. While there are slight security differences between using public and private queues, they are for the most part, the same in usage. In code, they only differ by the path you use to connect to the queue. Specifically, two paths are shown below to connect to a public and private queue. The text “Private$” precedes the path for private message queues.

Public Message Queue Path
.\MyQueue”

Private Message Queue Path

“.\Private$\MyQueue

To create a new queue, right-click on the “Public Queues” folder and select New->Public Queue. It is generally a good choice to checkmark the Transactional option so that you queue will support transactions. Enter a name for the queue to create a new MSMQ queue. With the queue created, you can view the messages in the queue by clicking the plus sign next to your queue name, select Queue messages, and hit F5 to refresh the pane. Initially, the queue is empty until we send a few messages its way. To manually empty the queue, right-click on “Queue messages”, select All Tasks, and select Purge.

Getting a Message into the Queue

Using a Microsoft Message Queue MSMQ is very straight-forward and involves opening your message queue, sending a message, and closing the queue. Since the message queue object implements the IDisposable interface, we can utilize the “using” statement to automatically close and dispose of the queue for us. Below is an example of opening the queue, sending a basic message, and closing. Note, this article demonstrates sending two types of messages to the queue, therefore an enum type is defined to dictate which type of message we’re sending.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public enum MessageType
{
    MESSAGE_TYPE_PLAIN_TEXT = 0,
    MESSAGE_TYPE_HELLO_WORLD = 1
};

static void Main(string[] args)
{
  
   using (queue = new MessageQueue(".\\MyQueue"))
   {
       
        queue.MessageReadPropertyFilter.AppSpecific = true;

       
        queue.Formatter = new BinaryMessageFormatter();

       
        using (MessageQueueTransaction mqt = new MessageQueueTransaction())
        {
            mqt.Begin();

           
            Message myMessage = new Message("Hello World", new BinaryMessageFormatter());
            myMessage.Label = "First Message";
            myMessage.AppSpecific = (int)MessageType.MESSAGE_TYPE_PLAIN_TEXT;

           
            queue.Send(myMessage, mqt);
        }
   }
}

After running the above code, if you view your message queue in the Computer Management window and refresh the messages, you will see a new message available in the queue. If you view the contents of the message, you’ll notice it’s encoded in XML and formatted in binary. This is because we chose to use the BinaryMessageFormatter(), which allows us to serialize any type of object in the queue’s message body and deserialize it back to its original object type.

Receiving Messages from the Queue

Receiving messages generally happens asynchronously in Microsoft Message Queue MSMQ. You add a ReceiveCompleted event to the queue and begin listening for new messages to arrive. When a message arrives, your event is triggered, passed a message object, and you can then deserialize the body and process the contents. Your final call in the ReceiveCompleted function would be to start listening again for new messages.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);


queue.BeginReceive();

static void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
   lock (lockObject)
   {
     
      string text = (string)e.Message.Body;
      Console.WriteLine("Message received: " + text);
   }

  
   queue.BeginReceive();
}

All Messages are Objects

Before showing the complete example code to work with Microsoft Message Queue MSMQ, it’s important to understand that the message bodies stored in the queue are actually objects. This is a powerful choice by Microsoft because it allows you to store any type of message, class, structure, and even algorithms, within a message body for transmission. With this information, we begin by creating an example class to hold our message content.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[Serializable]
class HelloWorld
{
    private string text = "";

    public HelloWorld()
    {
    }

    public HelloWorld(string _text)
    {
        text = _text;
    }

    public string GetText()
    {
        return text;
    }
}

Notice that the class is serializable. This is required in order to serialize the class into a message’s body. In the example above of sending a message to the queue, we used a simple text message (a string). In the example below, we’ll send a HelloWorld object and a string. This example shows how to send two different types of messages and process them accordingly. Note, MSMQ is generally used in a service form of application, rather than a console application. However, in this article, a console-style application is used for simplicity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public enum MessageType
{
    MESSAGE_TYPE_PLAIN_TEXT = 0,
    MESSAGE_TYPE_HELLO_WORLD = 1
};

class Program
{
    private static MessageQueue queue = null;
    private static object lockObject = new object();

    static void Main(string[] args)
    {
        
        using (queue = new MessageQueue(".\\MyQueue"))
        {
            
            queue.MessageReadPropertyFilter.AppSpecific = true;

            
            queue.Formatter = new BinaryMessageFormatter();

            
            queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);

            
            queue.BeginReceive();

            using (MessageQueueTransaction mqt = new MessageQueueTransaction())
            {
                mqt.Begin();

                
                Message myMessage = new Message("Hello World", new BinaryMessageFormatter());
                myMessage.Label = "First Message";
                myMessage.AppSpecific = (int)MessageType.MESSAGE_TYPE_PLAIN_TEXT;

                
                queue.Send(myMessage, mqt);

                
                HelloWorld helloWorld = new HelloWorld("Hello World from an object.");
                myMessage = new Message(helloWorld, new BinaryMessageFormatter());
                myMessage.Label = "Second Message";
                myMessage.AppSpecific = (int)MessageType.MESSAGE_TYPE_HELLO_WORLD;
                myMessage.Priority = MessagePriority.Normal;

                
                queue.Send(myMessage, mqt);

                mqt.Commit();
            }

            while (Console.ReadKey().Key != ConsoleKey.Q)
            {
                
            }
        }
    }

    static void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
    {
        lock (lockObject)
        {
            if ((MessageType)e.Message.AppSpecific == MessageType.MESSAGE_TYPE_HELLO_WORLD)
            {
                
                HelloWorld helloWorld = new HelloWorld();
                helloWorld = (HelloWorld)e.Message.Body;
                Console.WriteLine("Message received: " + helloWorld.GetText());
            }
            else
            {
                
                string text = (string)e.Message.Body;
                Console.WriteLine("Message received: " + text);
            }

            
            queue.BeginReceive();
        }
    }
}

Notice how in the code that sends the messages, we utilize the AppSpecific property of the message to indicate the type of message body being stored. The AppSpecific property is an integer unused by Windows and is available to the developer. This property is often used by developers in the case of messages possibly failing and being re-tried, in which case it is used to count how many times the message has been sent. After the value reaches a certain threshold, the message may be posted to the Dead-letter messages queue located under the “System Queues” folder in Computer Management. Dead-letter messages are also termed “poisoned messages”. However, in the example above, the AppSpecific property is being used to identify the type of message body (since we are sending two different messages to the same queue). If the AppSpecific property identifies our HelloWorld type, we deserialize the message’s body as a HelloWorld object. Otherwise, we know it will be a simple string.

When the above example is ran, you will see two lines printed to the console almost instantly, as Microsoft Message Queue MSMQ operates quite fast. If you refresh your queue in the Computer Management window, you should continue seeing an empty list of messages, as the messages were immediately processed and removed from the queue by your code.

The Message Loop

The final line in the example above was “queue.BeginReceive()”. This is a critical line to a successful implementation of Microsoft Message Queue in that it provides the means for continuous listening on the message queue. Each time a message is received, the listening process stops. This helps provide a thread-safe environment. However, it also means it’s the developer’s responsibility to resume listening to the queue.

Poisoned Messages and Retry Attempts

As mentioned above, while Microsoft Message Queue MSMQ provides a persistent backing store and thread-safe system for managing queued messages, it’s still possible for processing of the message to fail. For example, consider the case where each time a message is received you transfer a file over the Internet. File transfers are bound to fail at some point, such as a server temporarily going down. In which case, your message will be considered to have failed. Since this is a temporary failure, you would want to re-queue the message and try again. There are different ways of dealing with failed messages, with the most obvious being to simply put the message back on the top of the queue to immediately try again. However, if the failure of the message was due to some invalid data within the body, which would cause to fail every single time (such as a bad FTP address or other data), then the message is a poisoned message — meaning that it can never be successfully processed. If the message is put back on the top of the queue every time, you end up wasting valuable processing time since each receive call on the queue obtains the same message, which is bound to fail. After so many retry attempts (counted by incrementing a property such as the AppSpecific field), you can cease re-queing the message and instead move it to a failed queue. However, there are better ways to handle a failed, and possibly poisoned, message.

The first suggestion for dealing with a failed message was to increment its AppSpecific count (or other field), and re-queue the message at the top. Alternately, you could re-queue the message at the bottom of the queue by setting its MessagePriority to “Lowest”. This gives all newer messages a chance to be processed first before getting back to the failed message.

Depending on your situation, there are even more ways, with increasing complexity, of handling failed and poisoned messages. The method you choose depends on your particular software design.

Conclusion

Microsoft Message Queue MSMQ provides a robust and scalable system for handling timely data in a queue. MSMQ provides a reliable persistent backing store via an internal Windows database, which persists data on the queue between C# ASP .NET web application sessions and system restarts. Message queues can be public or private and support transactional commands in a thread-safe environment. Message bodies can contain a variety of formatted data and is easily created using message formatters such as the XMLMessageFormatter and the BinaryMessageFormatter. Receiving messages from is handled by listening for the Receive event, deserializing the message body, and processing the contents. Messages may fail when processing and can be retried in a number of ways. When a message is doomed to fail every time, it is considered a poisoned message and should be handled in a speedy and reliable manner.

Using Microsoft Message Queue MSMQ in C# ASP .NET web applications allows us to easily process queued data and provide scalable enterprise architecture solutions.

About the Author

This article was written by Kory Becker, software developer and architect, skilled in a range of technologies, including web application development, machine learning, artificial intelligence, and data science.

  • Setfsb скачать на русском для windows 10 на русском
  • Setting windows 10 environment variables
  • Setting utility series sony vaio windows 10
  • Setpoint logitech windows 10 64 bit
  • Setpoint lets you customize your mouse keyboard touchpad and number pad settings in windows