Using Message Queues

Mark Strawmyer Presents: .NET Nuts & Bolts


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.



Click here for a larger image.

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 MachineName\QueueName. To access a private queue, the connection is made by MachineName\Private$\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 = new
System.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.

# # #



About the Author

Mark Strawmyer

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the fifth year in a row. You can reach Mark at mark.strawmyer@crowehorwath.com.

Comments

  • Brief publishing reveal the incontestable details about gucci and how it can upset your corporation.

    Posted by emeseesip on 05/07/2013 01:26am

    Among The Most Complete adidas E book You Ever Witnessed Or else Your Cash Back [url=http://www.guccija.biz/]グッチ バッグ[/url] Geez, remarkable service. Your corporation gotta consider gucci right now while it's still in stock . . . [url=http://www.guccija.biz/]グッチ 財布 メンズ[/url] nike aids all of us by simply including several exceptional features and options. It's a unvaluable item for all supporter of nike. [url=http://www.guccija.biz/]gucci バッグ[/url] Unprejudiced study unwraps Three completely new stuff surrounding adidas that not a soul is speaking of. [url=http://www.chanelja.biz/]シャネル 財布[/url] The main reason why noone is having a debate about adidas and for these reasons exactly what you ought to execute straight away. [url=http://www.chanelja.biz/]シャネル チェーンウォレット[/url] Recent questions about adidas addressed and consequently reasons why you really should take a look at every phrase within this insider report. [url=http://www.chanelja.biz/]chanel 財布[/url] An overview of adidas that you will reap the benefits of starting today.[url=http://www.nikeja.biz/]ナイキスニーカー[/url] Methods to fully understand every aspect there is to know about adidas in four basic steps.

    Reply
  • burberry femme pas cher

    Posted by Wrinalertiece on 04/30/2013 01:42am

    Burberry Pas Cher Chemise Burberry homme Chemise Burberry Chemise Burberry Pas Cher [url=http://burberryhommepascher97.webnode.fr/]burberryhommepascher97.webnode.fr[/url] , burberry homme [url=http://sacocheburberrypascher5.webnode.fr/]sacocheburberrypascher5.webnode.fr[/url] , Chemise Burberry

    Reply
  • Odd review provides you with the facts over nike which just some people know.

    Posted by icoppyapedcap on 04/25/2013 12:34pm

    PwvMjeHmyKes [url=http://www.nikeyasuijp.com/]ナイキ[/url]XpbZfqLbyVjo [url=http://www.nikeyasuijp.com/nike-air-force1エアフォース1-c-14.html]ナイキ エアフォース[/url]WjzBatCgfQsm [url=http://www.nikeyasuijp.com/nike-air-maxエアマックス-c-12.html]ナイキ エアマックス[/url]KrmDknCehEdb [url=http://www.nikeyasuijp.com/nike-air-jordanエア-ジョーダン-c-13.html]nike free[/url]HwrTrzKzmCvp

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • A help desk is critical to the operations of an IT services business. As a centralized intake location for technical issues, it allows for a responsive and timely solution to get clients and their staff back to business as usual. In addition to handling immediate IT issues, a help desk performs several proactive tasks to ensure clients' IT systems remain operational and downtime is minimized. Thus, utilizing a help desk and following best practices can improve the productivity, efficiency and satisfaction of …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds