Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

System.Messaging Namespace

This seems like a good spot to take a brief detour to discuss the System.Messaging namespace. All of the classes needed to interact with the Microsoft Message Queuing (MSMQ) system are found here. The MSMQ is message-oriented middleware (MOM) that allows for the robust, asynchronous communication between programs. Classes in this namespace give the functionality to connect to, monitor, administer, send messages to, receive messages from, and peek into messages in a message queue. Clients of message queues need not be on the same physical box as the message queue. When a MessageQueue object is instantiated, an IP can be supplied to indicate where to find the queue. Indeed, the destination machine that is the intended recipient of the message needn't even be running when the message is sent.

A message queue is a construct running on a machine that listens for and accepts messages. Each individual message queue has a specific name and is addressed by that name. That's why in the code shown in Listing 7.5, we created the MessageQueue object by passing in the strQueueName value to the constructor.

Basically, the message queue is a hopper into which messages are thrown. These messages accumulate, regardless of whether any code is in place to handle the messages. If and when code is ready to handle messages for a particular message queue, the code takes one message at a time and processes the message. In this case, code is in place to process the EAIRequest object sent to the queue through a RequestsProcessor instance. Messages are taken from the queue in a first in, first out (FIFO) manner, by default. This is accomplished by using one of the Receive() methods. Receive() is an overloaded method; we examine its use when we look at the code later in this chapter, in the Reading Messages section, to monitor the queue and process the requests.

It is also possible to set a priority on messages as they are sent into the message queue. If a message is sent in with a higher priority, it takes precedence over other messages and is retrieved before those messages that have been in the queue longer but that have a lower priority. Priorities are set on the Priority member of a Message object. The acceptable values for priorities are enumerated in the static member System.Messaging.MessagePriority and have the following names:

  • Highest

  • Very High

  • High

  • Above Normal

  • Normal

  • Low

  • Very Low

  • Lowest

For example, if you wanted a particular message to have the highest priority possible, you would issue the following command on the Message instance before it was sent into the message queue:

msg.Priority = System.Messaging.MessagePriority.Highest

To take this a bit further, let's say that you support a set of requests that allow an administrator to suspend a certain request type (we'll cover this later). Maybe a particular subsystem is down and you want to hold all transactions until you know that it's back up. In this case, you would want these types of requests to be processed as soon as possible to reduce the number of requests already queued up that will fire (and fail). This is a perfect example of a request type that should get bumped up to a much higher priority.

Message Queue Types

Two main types of message queues exist: system and user-defined. System message queues are used, as you might guess, by the operating system. Various events can be sent to one of the system message queues. User-defined message queues can be of two types: public and private.

Public message queues are available to all systems connected to the network. These queues are published and can be replicated across the network.

Private message queues, on the other hand, are not published across the network, so access from another machine must be made explicitly with the full pathname of the queue. They mainly are intended for use locally on the machine where the queue is running.

For our purposes here, we use private message queues. Because the web service will be running on the same machine as the message queue, by default, it is a simple matter for the EAIFramework engine to send a message to a private queue. The code could be easily changed, however, to use a public queue.

Message queues also can be created to be either transactional or nontransactional. By default, they are created as nontransactional. The code shown in Listing 7-5 creates a nontransactional message queue. A transactional message queue expects every interaction with it to be encapsulated in a transaction. The start of a transaction is signaled by a Begin message to the message queue. It then expects some messages and, finally, either a commit or rollback message.

If a message queue is created as transactional, all messages sent into it must be a part of a transaction. If a message arrives that is not in a transaction, an exception is thrown. Likewise, if a message queue is created as nontransactional and a message arrives as a part of a transaction, an exception is thrown.

Transactions ensure that all the messages sent in as a part of a transaction are processed successfully. If they are not, a rollback occurs that basically undoes all of the work that was previously done as a part of the transaction in question.

For example, if you wanted to send in two messages and ensure that both were successfully processed, you could build the following structure to send the appropriate messages:

 MessageQueueTransaction trnx = new MessageQueueTransaction();
 MessageQueue myQ = new MessageQueue(@".\private$\secrets");
 trnx.Begin();
 try 
 {
  myQ.Send("Message Number 1", trnx);
  myQ.Send("Message Number 2", trnx);
  trnx.Commit();
 } 
 catch 
 {
  trnx.Abort();
 } 
 finally 
 {
  myQ.Close();

}

By using the try/catch/finally structure, you can, with minimal code, send messages and then either commit the operations or roll them back via the Abort() method. When either the work is done or it has been aborted because of some error, the Close() method closes the MessageQueue instance.

For the main Requests MessageQueue, we are not using a transactional message queue, because each request being sent in is contained in a single message. It would be perfectly reasonable, however, to create and use a transactional message queue for subsequent Request processing, in some cases. If you know that a particular set of Request types will be coming in and can be processed asynchronously, and if they all need to be cranked through successfully en mass, you could have the main Requests message queue processing send individual Request blocks to another transactional message queue.

Until now, the transactions described have been internal (to the message queue) transactions, meaning that they are limited only to MSMQ activities. External transactions also exist that can interact with other systems that can also take part in the transaction. These other systems include databases, such as SQL Server and Oracle. External message queue transactions are part of a specific technology called Microsoft Distributed Transaction Coordinator (MS DTC). This technology enables you to treat database calls as integral parts of a transaction. If a database call fails, the DTC transaction can roll back all previous databases, as well as MSMQ steps. Although a discussion of external transactions is beyond the scope of this book, they are a very powerful feature and are worthy of further study as your needs arise.

Recoverable Messages

One final word on types of messages is in order here before we get to sending and receiving. By default, the entire MSMQ message flow is an in-memory operation. This means that a message is created on a client, sent to the destination message queue, and stored until code is ready to accept and process the message, all in memory. Although it is very fast, this method of message delivery holds certain risks. If the sender machine is taken down for some reason before the message is sent to the destination machine, or if the destination machine accepts the message into its message queue and then fails before it can process the message, the message is lost entirely.

This is not normally a good thing. We would like a way to ensure that a message that we send will be delivered even if one of the machines goes down. This could easily be remedied by saving the message to disk while it is in transit and sitting in the queue waiting for processing. And that's just what the smart people at Microsoft did.

For any particular message, you can set the Recoverable member of the message to true, indicating that you would like this message to be recovered if a catastrophic event befalls one of the machines during the message's merry trip down the pipe. The following line of code sets the Recoverable member on a previously instantiated Message object named msg:

msg.Recoverable = true;

This approach requires that each individual Message object set the Recoverable member. You can also set a member on a MessageQueue indicating that all messages should be recoverable. This is the approach we take here. This is accomplished by issuing the following command on a message queue object named msgQue:

msgQue.DefaultPropertiesToSend.Recoverable = true;

Sending a Message

To send a message to a message queue, you create a System.Messaging.Message object. This message object contains the contents that you want sent to the queue. When a message is sent to a queue, a subclass of the System.Messaging.IMessageFormatter class is specified. The formatter streams the incoming object (EAIRequest, in this case) into the Message object. Then on the other side, the code that retrieves the message from the message queue also uses a formatter object to stream the contents of the Message object, housed in the Body member, into an instance of whatever object was originally streamed into the message.

As you can see in Figure 7-5, a client creates and sends a Message object to the message queue. These messages are accepted and stored in the MessageQueue. When a process is available, the messages are sent to the registered monitor code for processing.

Figure 7.5Figure 7-5 Overall message queue flow.

We make use of this service here to handle asynchronous request processing. Certain requests sent into the EAIFramework either will not need to be handled on the spot or might take far too long to process for a web service to wait for (keeping the HTTP connection open to the caller so that it can send an HTTP response). These are ideal candidates for asynchronous processing. Because a unique identifier is generated when the initial request is sent in, you can send that ID back to the caller and then not worry about when the actual processing is done. The monitor code attached to the message queue takes care of updating the transaction log when a transaction is processed.

Examining Message Queues

You can see what message queues are running and see what messages are waiting in the queue, as well as manage queues, by using the Computer Management tool. To access it, right-click My Computer on the Windows 2000 desktop, and click Manage. You'll see the Computer Management dialog box pop up. From this screen, you can manage most of the software component configurations on the machine.

On the left side of the screen, expand the Services and Applications item, if it isn't already expanded. You should see several entries under it, including Microsoft SQL Servers and Services. Expand the item named Message Queuing. This is your interface to access the MSMQ service. Figure 7-6 shows the Computer Management dialog box with an arrow pointing to the Message Queuing item.

Figure 7.6Figure 7-6 Computer Management screen.

Now expand the Private Queues item. An example of this screen is shown in Figure 7-7. This shows you all private queues running on the machine.

Figure 7.7Figure 7-7 MSMQ private queue.

If you select one of these queues, you'll see two entries appear on the right side of the screen. Queue Messages is the item in which any currently queued messages are stored. You can double-click any queued message and examine the body, as well as its other properties. Figure 7-8 shows the message dialog box, with the Body tab active.

Figure 7.8Figure 7-8 Examining the body of a message.

One good way to test that your code is actually submitting messages to the queue is to not have any queue-monitoring code running so that nothing is performing a Retrieve() on the queue. When your client-side code submits messages to the queue, they stay in the queue. You can then use this tool to ensure that the messages are indeed being queued up in the correct message queue. You can also open the messages and examine their contents.

Formatters

For messages to flow smoothly in and out of message queues, meaning that both the sender and receiver understand what the other is trying to say, you use a subclass of the IMessageFormatter class. This class is used to serialize the object in the Body member of the Message object.

Three formatters are supplied with the .NET Framework:

  • ActiveXMessageFormatter

  • BinaryMessageFormatter

  • XmlMessageFormatter

The default formatter is the XmlMessageFormatter, which suits our needs. For information on the ActiveXMessageFormatter or the BinaryMessageFormatter, you can explore MSDN.

The XmlMessageFormatter serializes and deserializes messages. It streams in and out of the Body member of a message. Therefore, you can insert any object into the Body of a message with the XmlMessageFormatter. You cannot, however, also use a default XmlMessageFormatter to Retrieve() a message. To accomplish this, you must either set the Formatter on the message that you want to get back and explicitly tell the message what object to expect back, or set the Formatter on the MessageQueue. This is a cleaner way of handling retrieving so that you have to specify only what kind of object(s) will be returned once on the queue. After that, the appropriate conversion takes place and the returned message contains the correct type of object.

If you want to set the formatter on a Message object to specify that you expect back an EAIRequest object at retrieval time, you would execute the following statement:

   msg.Formatter = new XmlMessageFormatter(
    new Type[]{typeof(EAIRequest)});

If instead you want to set the default Formatter for the MessageQueue to be an XmlMessageFormatter that uses the EAIRequest object, you would execute the following statements:

   mq = new System.Messaging.MessageQueue(strQueName);
   XmlMessageFormatter xmf = (XmlMessageFormatter)mq.Formatter;
   xmf.TargetTypes = new Type[]{typeof(EAIRequest)};
   mq.Formatter = xmf;

When the message queue has been set up in this way, it renders the previous formatter setting unnecessary. Now, when a message is retrieved from the queue, it uses an XmlMessageFormatter object that speaks EAIRequest.

Reading Messages

Now that you have created a MessageQueue appropriately, sent a message to it, and verified that the message arrived and is being held in the correct queue, it's time to read it in. This is accomplished by connecting to the message queue in exactly the same manner as explained earlier, and then calling the Receive() method of the MessageQueue instance. This overloaded method pulls in the first message, based upon arrival time in the queue and its priority, and returns it to the caller. It also removes the message from the queue. It is then up to the calling code to process the message and take all necessary actions.

NOTE

A second way to read a message is nondestructive. As with the Receive() method, the Peek() method returns a Message object for a message but does not remove the message from the message queue. Because we want to process the incoming requests once, we call the Receive() method so that it removes the request from the message queue.

The simplest version of the Receive() method takes no arguments. When the call is issued, it blocks until a message is available to be returned from the message queue. This means that if a message never appears, the call to Receive()never returns. In most cases, this is not the behavior you want. Fortunately, another version enables you to supply a TimeSpan object that indicates how long the Receive() method should wait for a message. This call can throw one of two exceptions. It can throw ArgumentException if the TimeSpan argument sent in is invalid. In this case, the TimeSpan must be greater than zero.

It also can throw a MessageQueueException. This occurs when either there was a problem accessing the message queue, or the specified amount of time passed without seeing a message to return. Therefore, you can create a processing loop that can do some kind of work or check to see if it should exit in a while loop. For example, a processing Receive() loop could look something like the following:

while( bKeepTrying )
{
 try
 {
  msg=mq.Receive(new System.TimeSpan(0,0,5));
  EAIFramework.Messages.EAIRequest req =
   (EAIFramework.Messages.EAIRequest)msg.Body;
  // do some processing here...
 }
 catch(MessageQueueException mqe)
 {
  // This is the message that the Receive() timeout
  // throws. In this case, no message is ready
  // to be read within 5 seconds of issuing the
  // Receive() call.
  Console.WriteLine("Just caught a MsgQueExc: " +
   mqe.Message);
 }//end catch
}//end while()

In fact, this is exactly the way we will watch the Requests message queue in the RequestQueMonitor project, which we will discuss in the next section. This project contains a Windows Form application with a few controls to make it easy to watch for messages and to process them. We shall discuss the most interesting aspects of the code here, and I encourage you to take a look at the application.

  • + Share This
  • 🔖 Save To Your Account