Microsoft & .NET.NETUsing Message Queues

Using Message Queues

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Welcome to the next installment of the CodeGuru .NET Nuts & Bolts column, and the first column article of the New Year. In this column, we’ll explore the use of message queues and how they can be useful to us in our applications. This will involve using classes in the System.Messaging namespace.

What Is Message Queuing?

Message queuing is a communication tool that allows applications to reliably interconnect in a distributed environment where one of the applications may or may not be available at any given time. The queue acts as a holding container for messages as they are sent between applications. The applications send messages to and read messages from queues to communicate back and forth. An application writes a message to a queue, which will then be received and processed by another application at some point determined by the receiving application. This type of communication is designed for asynchronous use where the applications involved are not waiting for an immediate response from the other end.

Where Can I Get a Message Queue?

Microsoft Message Queue (MSMQ) is a queuing product that was originally introduced along with Microsoft Transaction Server (MTS) as a part of the Option Pack for Windows NT 4.0. It is now known as Windows Message Queuing and is included with the Windows Server products rather than as an add-on. It can be setup through Add/Remove Programs -> Add/Remove Windows Components -> Message Queue.

Queuing Configurations

It can operate in a standalone fashion where only the server on which it is installed may access any of the queues, or it can exist in an Active Directory (AD)-based environment where queues are made available to those with the proper security credentials. When used in an AD environment, a Message Queue network can be established that allows servers to send messages to each other and perform various roles within the queuing network. It does not require any additional licensing for use.

Types of Queues

There are two different types of queues. There are queues that are system generated and those that are user generated. For the sake of this article, I’ll focus solely on the user-generated types. The two main types are as follows:

  • Public—replicated throughout the network and are accessible
  • Private—only available on the computer that contains them

To follow the examples contained in this article, you will need to establish a private queue on your local computer. The Message Queuing can be accessed under Services and Applications in the Computer Management console. The following illustration depicts a queue, called MyPrivateQueue, that will be used for all of the examples below. I assigned Everyone Full Control access to the queue by right-clicking, selecting Properties, and then the Security tab.

Connecting to a Queue

Much like a database connection, the type of queue dictates the connection string used to make a connection to a particular queue. To access a public queue, the connection is made by MachineNameQueueName. To access a private queue, the connection is made by MachineNamePrivate$QueueName. When accessing a queue on a local machine, the MachineName variable may be replaced by the “.” character. A connection can be initiated as follows:

MessageQueue queue = new        MessageQueue(".Private$MyPrivateQueue");

Writing to a Queue

The classes in the System.Messaging namespace make it relatively simple to write messages to a queue. First, you create a connection to the appropriate message queue by using the MessageQueue class, and then specify the message to send by using the Send method. The messages can take the form of something simple such as text or a string containing XML, or something more complex that is created through an instance of the Message class.

Writing to a Queue Sample Code

The following sample demonstrates writing a message to a private queue on the local computer. To execute this code, you must have first created a private queue and granted the appropriate security permissions to write to the queue.

System.Messaging.MessageQueue queue = newSystem.Messaging.MessageQueue(".Private$MyPrivateQueue");queue.Send("Hello world");

If you check the private queue contents through the Computer Management console, you will notice a new message entered into your queue, that looks something similar to the following:

The Send method will write the message in an XML format by default. Other options are available by setting the Formatter on an instance of the Message class.

Reading from a Queue

Just as the classes in the System.Messaging namespace make it simple to write messages to a queue, it is equally as easy to read messages from a queue. First, you create a connection to the appropriate message queue by using the MessageQueue class. Next, you specify a formatter to retrieve the message. Then, create an instance of a Message class and use its Receive method to pull a message from the queue. If you want to check the contents of the queue without removing the message from the queue, use the Peek method instead.

Reading from a Queue Sample Code

The following sample class demonstrates reading a message from a private queue on the local computer. You will notice that the message is not retained in the queue once it is read by using the Receive method.

System.Messaging.MessageQueue queue = new    System.Messaging.MessageQueue(".Private$MyPrivateQueue");queue.Send("Hello world");System.Messaging.Message msg = queue.Receive();msg.Formatter = new System.Messaging.XmlMessageFormatter(    new string[] {"System.String"});Console.WriteLine(msg.Body);

Peeking into a Queue Sample Code

The following sample class demonstrates peeking into a message queue to examine the message without removing it from the queue. If you examine the queue in Computer Manager, you will notice that the message still exists within the queue.

System.Messaging.MessageQueue queue = new    System.Messaging.MessageQueue(".Private$MyPrivateQueue");queue.Send("Hello world");System.Messaging.Message msg = queue.Peek();msg.Formatter = new System.Messaging.XmlMessageFormatter(    new string[] {"System.String"});Console.WriteLine(msg.Body);

Possible Enhancements

Now we have successfully demonstrated writing to and used multiple ways to read from a message queue. There are all sorts of ways that we could use queues to our advantage in our applications. Here are some ideas for you to consider on your own:

  • Application logging—When an error is discovered within your application, or performing application performance tracing, rather than adding additional overhead of writing to an application log, you could write the message to a queue where it can eventually be read and then written to the logging location at some other point in time when the system load is determined to not be as heavy.
  • Launching a remote process asynchronously—When a process needs to be kicked off asynchronously, you could log a message to a message queue indicating the process to start. The receiving application then can read the message and start the appropriate process.
  • Experiment with different formatters—You can write entire objects to the message queue by using serialization to allow an object to be passed to another application for reuse at a future point in time.
  • It is possible to control access to the queue by using various properties—Lock access to the queue while you are reading to prevent other applications from reading from the queue until you complete processing.
  • Use of acknowledgements to request or generate acknowledgement messages—Verifies that a message request was received. You can program your applications to resubmit a particular message if acknowledgement isn’t received within a certain time period.

Future Columns

The topic of the next column is yet to be determined. If you have something in particular that you would like to see explained here, you could reach me at mstrawmyer@crowechizek.com.

About the Author

Mark Strawmyer, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large- and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design, and development of Microsoft-based solutions. You can reach Mark at mstrawmyer@crowechizek.com.

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories