Home > Articles > Programming > Windows Programming

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

RequestQueMonitor Project

The RequestQueMonitor application is a standalone Windows Form application that monitors the Requests queue to which the Controller class sends an asynchronous message. We want the asynchronous processing for the EAIFramework to happen in a Windows service so that it takes advantage of the benefits of service features such as restarts after a crash, and so on. For now, though, the RequestQueMonitor will serve that purpose. The nice thing about running it as a Windows application is that you can watch the processing flow happen. With the RequestQueMonitor running, you can submit an asynchronous EAIRequest XML message to the web service and see a message in the text box of the application as the message is picked up from the queue and processed. Later, you will convert this monitor to a Windows service.

A main text box in the application shows status information. Figure 7-9 shows the application as it exists just after launch.

Figure 7.9Figure 7-9 RequestQueMonitor screen.

When the application starts, no monitoring is occurring. To start watching the Request message queue, click the Start Listener button. You will see a few things happen on the screen. First, a message is printed on the top-left side of the screen telling what time the monitor started watching the queue. Below that, a line is printed showing how many messages have been read off the queue. At the top center of the screen, you should see the white box turn green, with the message "Listener Status" printed in the center. Green signifies that the monitor has successfully connected to the message queue and has entered into the while loop, waiting patiently for messages to appear. Finally, you will see a couple of messages in the status text box. The first tells you that the monitor has connected to the message queue. It prints the name of the message queue, which was pulled from a ConfigData instance, just like in the Controller instance earlier.

The code enters a while loop and makes a call to the Receive() method. It gives a new TimeSpan object of 5 seconds, which means that the code will block for 5 seconds, waiting for a message to become available. If a message arrives within the time specified, it is read in, and you can process it in whatever way you need to. On the other hand, if the time period expires, the message queue object throws a MessageQueueException. In the catch block, a message is printed telling you that the timeout for the requested operation has expired.

Figure 7-10 shows the RequestQueMonitor screen after having read a message from the queue, processed three Request blocks within that message, and then listened for a couple of timeout cycles without having another message to read and process.

Figure 7.10Figure 7-10 RequestQueMonitor processing a transaction.

That's really good information, for a while. A button on the bottom-right side of the screen enables you to toggle this timeout message on and off. When the application starts, a Boolean flag is set to print the timeout message. As soon as you click the toggle button, the Boolean flag is set to false and the messages are no longer printed.

The only component on the screen that I haven't talked about yet is the Shut Down Listener button. As you might have surmised, clicking this stops the message queue monitoring. It works by setting a class-level Boolean member that is used in the main receive while loop. As you will see in a moment, if the flag is set appropriately, the while loop exits and the connection to the message queue is closed. When you click the Shut Down Listener button, you might notice a several-second lag. This is because the shutdown doesn't take effect until the current time TimeSpan expires.

RequestQueMonitor startListening() Method

Now let's take a look at the startListening() method (see Listing 7-6). The loop for reading messages from the queue lives here.

Listing 7-6: The startListening() Method

  /// <summary>
  /// Helper method, called when the Start Listening 
  /// button is clicked. It gets the name of the
  /// Requests message queue, opens a connection, and

  /// then starts a while loop to wait for messages.
  /// Currently, the timeout for any specific waiting
  /// period is 5 seconds, set in a TimeSpan instance.
  /// To break out of the while loop and stop Listening,
  /// a class member, named bShutdown, is set in a button
  /// click event handler elsewhere. When the user 
  /// presses the Shut Down Listener button, the flag
  /// is set to true. The next time the while loop
  /// fires, it sees that the Boolean is true and exits

  /// the read (while) loop.
  /// </summary>
  private void startListening()
  {
   ConfigData cdata = new ConfigData();

   string strQueName = cdata.getConfigSetting(
    "RequestsQueueName");

   MessageQueue mq;
   RequestsProcessor rProc;
   
   // See if we need to create the queue
   try
   {
    textBox1.Text =
     "Monitor: Going to check que: " + 
     strQueName;
    if( !MessageQueue.Exists(strQueName)){
     MessageQueue.Create(strQueName);
    }//end if
   }
   catch(Exception exc)
   {
        textBox1.Text =
      "Monitor: ERROR calling MessageQueue." +
     "Exists(): " + exc.Message;
   }//end catch

   // Create a MessageQueue instance, set it as
   // Recoverable - to make the messages stored to
   // disk during their trip, and set the Formatter
   // to XmlMessageFormatter that understands the
   // EAIRequest object.
   mq = new System.Messaging.MessageQueue(strQueName);
   mq.DefaultPropertiesToSend.Recoverable = true;
   XmlMessageFormatter xmf = 
    (XmlMessageFormatter)mq.Formatter;
   xmf.TargetTypes = new Type[]{typeof(EAIRequest)};
   mq.Formatter = xmf;

   // Now that we're listening, change the background
   // color of the Listener Status box to Green, to
   // graphically indicate such.
   lblStatus.BackColor = Color.LightGreen;

   System.Messaging.Message msg;

   while( !RequestQueMonitor.bShutDown )
   {
    try{
     msg=mq.Receive(new System.TimeSpan(0,0,5));
     
     textBox1.AppendText(
      ">>>>> Read a new message\r\n");
     this.updateCount(++nCount);

          EAIFramework.Messages.EAIRequest req =
      (EAIFramework.Messages.EAIRequest)
      msg.Body;

     rProc = new RequestsProcessor(req);
     ArrayList al = rProc.process();

     textBox1.AppendText( "TrnxID " +
      req.TransactionID + ": " +
      " we got " + al.Count + 
      " Components back\r\n");
    } catch (MessageQueueException mqe) {
     // Only print out this message to the text
     // box if the user wants to see it
     // - This Boolean is controlled by the

     // event handler method for the 
     // Turn on/off Timeout msg button.
     if( bShowTimeout)textBox1.AppendText
       ("..." + mqe.Message + "\r\n");
    } catch (Exception exc) {
     textBox1.AppendText(
      "..." + exc.Message + "\r\n");
    }//end catch()
   }//end while()

   mq.Close();
   // Now that we're not listening anymore, change
   // the background of the Listener Status box
   // to pink.
   lblStatus.BackColor = Color.Pink;
  }//end startListening()

The method starts by getting the name of the RequestsQueueName from the EAIConfig file, just like in the engine, and stores the value in the member strQueName. This keeps the submitter code and the listener code in synch. If you want to change the name of the queue, you simply make the change in one place and (in this case) restart the RequestQueMonitor application.

The method next checks to see if the message queue exists. If so, it just drops through and continues processing. If it doesn't exist, it creates a new message queue, named after the value of strQueName. This is accomplished by a single statement:

MessageQueue.Create(strQueName);

Next, the MessageQueue instance is created. As discussed earlier, you set the Recoverable property of the message queue to true to force MSMQ to write each request to disk as it flows through the system. In this way, it is much less likely that messages will be lost if a power failure or other catastrophic problem occurs.

Finally, the Formatter for the message queue is set. You'll notice that we set the TargetTypes of the Formatter to type typeof(EAIRequest). This tells the message queue that any messages read back in from the queue should contain EAIRequest objects within the Body member of the messages. Again, it is a way of setting default processing behavior on the message queue, and it eliminates the need for explicitly setting the Formatter type for every Message object created for this message queue.

With the connection to the message queue started, change the background property of the status box, in the top middle of the screen, to LightGreen. I personally like being able to glance at the screen and see the status of the listener. green means go; red (well, okay, Pink) means stop.

You now enter the main while() loop for reading messages from the queue. The class-level Boolean member is named bShutDown. When the program starts, this member is given the value of false. When the processing hits this while loop each time, it checks the value of bShutDown. In the event handler method for the Shut Down Listener button, the value of bShutDown is set to true. When this happens, the while loop exits.

The first statement in the while() loop is a call to the Receive() method on the MessageQueue instance. This returns a Message object if a message is available. Notice that you send in a new TimeSpan object with a value of 5 seconds. If a message is read, you print a message to the text box, update a counter, and pull in the EAIRequest object that should be contained in the Body member of the Message instance. This EAIRequest object gets sent to a RequestsProcessor instance, just the same as when the Controller calls RequestsProcessor for synchronous request processing. In this case, you're not really doing anything with the response yet. That will come later. For now, you just want to make sure that you're reading in the messages, converting the contents to an EAIRequest object, and sending it on for processing.

If there is no message to be returned within the specified 5 seconds, a MessageQueueException is thrown. In a way similar to bShutDown, the bShowTimeout member indicates whether to display the timeout messages. This Boolean member is maintained in the event handler for the Turn on(off) Timeout msg button.

When the bShutDown member is set to true, it tells you that the user wants to quit listening. All you need to do here is close the MessageQueue to free up the resources held by it, and change the background of the status box to Pink. The application is then ready for the user to either exit or press the Start Listening button again.

  • + Share This
  • 🔖 Save To Your Account