Home > Articles > Programming > Windows Programming

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020