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

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