Contents Overview 1 Introduction to Queued Components 2 Working with Queued Components 16 Lab 5.1 Creating and Using Queued Components 35 Publisher and Subscriber Architecture 45 L
Trang 1Contents
Overview 1
Introduction to Queued Components 2
Working with Queued Components 16
Lab 5.1 Creating and Using Queued
Components 35
Publisher and Subscriber Architecture 45
Lab 5.2: Creating and Using Event Classes 71
Combining Queued Components and
Events 77
Lab 5.3: (Optional) Combining Queued
Review 93
Module 5: Queued Components and Events
Trang 2to represent any real individual, company, product, or event, unless otherwise noted Complying with all applicable copyright laws is the responsibility of the user No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation If, however, your only means of access is electronic, permission to print one copy is hereby granted
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property
2000 Microsoft Corporation All rights reserved
Microsoft, BackOffice, MS-DOS, Windows, Windows NT, ActiveX, MSDN, PowerPoint, and Visual Basic are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries
The names of companies, products, people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product, or event, unless otherwise noted
Other product and company names mentioned herein may be the trademarks of their respective owners
Trang 3Instructor Notes
In this module, students will learn how to implement asynchronous functionality by using queued components in a COM+ application Students will also learn how to use the COM+ Event service to match and connect applications that publish information with subscribers For advanced students, material is also provided to learn how to combine queued components and events
After completing this module, students will be able to:
! Describe the purpose and benefits of queued components
! Create a queued component
! Instantiate and communicate with a queued component
! Describe the COM+ Events service provided with Microsoft Windows
2000
! Create and use an event class to match publishers with subscribers
! Combine queues with events to make the processing of publisher and subscriber events time independent
In the practice, students will learn to enable an application for queuing and view application queues by using the computer management tool ,Instructor-led demonstrations are provided to illustrate how to create and register an event class, create a subscriber component and add a subscription entry to COM+, publish events, and finally filter events A demonstration is also provided to illustrate how queued components can be combined with events to publish and deliver events asynchronously
In the first lab, students will use COM+ queued components to place orders asynchronously In the second lab, they will use the COM+ events to create and register an event class In the optional lab, students will learn how to combine queued components and events to make publisher and subscriber events time independent
Trang 4Materials and Preparation
This section provides you with the required materials and preparation tasks that are needed to teach this module
Required Materials
To teach this module, you need the following materials:
! Microsoft PowerPoint file 1907A_05.ppt
! Module 5: Queued Components and Events
! Lab 5.1: Creating and Using Queued Components
! Lab 5.2: Creating and Using Event Classes
! Lab 5.3: (Optional) Combining Queued Components and Events
! Animation: "COM+ Queued Components" on the Student CD-ROM, file 1907A_05a005.avi
! Animation: "COM+ Events" on the Student CD-ROM, file 1907A_05a010.avi
Preparation Tasks
To prepare for this module, you should:
! Read all of the materials for this module
! Complete the practice, demonstrations, and labs
! Read the instructor notes and the margin notes for the module
Module Strategy
Use the following strategy to present this module:
! Introduction to Queued Components Discuss the inherent problems associated with synchronous communications
in a distributed environment and highlight how a message-based form of asynchronous communications, such as COM+ queued components, can overcome many of these problems The primary challenge is to provide a reliable way for the various parts of an application to communicate
Other issues that you should consider include unreliable or slow network connections, remote disconnected users, and heterogeneous application architectures Discuss how queued components relate to the underlying Microsoft Message Queue Server (MSMQ) technology Present the architecture of queued components and discuss the three system-provided components: the recorder, the listener, and the player Point out the restrictions on interface design required by queued components
! Working with Queued Components Discuss how to use queued components to manage the communication that occurs between the various parts of an enterprise application Explain how
to view, instantiate, and create queued components Discuss how to communicate with and receive output from queued components Finally, describe how to use the COM+ queued component service to handle transactions and security
Trang 5Use the practice to show how to create a queued component and enable a COM+ application for queuing by using the Component Services tool After the component is created, show how to use the Computer Management tool
to view the application’s queues
! Handling Events Explain that one of the classic challenges in computer programming is determining the best way to notify interested entities that information or data has changed A number of possible solutions exist, each with varying degrees of flexibility and suitability One of the key factors that you need to consider is how tightly the publisher (the notifier) and subscriber (the entity
to be notified) should be coupled when handling events
Discuss the polling approach (ill-suited to a distributed environment) and tightly coupled approaches such as Visual Basic events that are based on the COM connection point mechanism and loosely coupled events such as the COM+ events Discuss the advantages and disadvantages of each
Generally, the looser the coupling, the more adaptable and flexible the solution
! Publisher and Subscriber Architecture Discuss how the publisher and subscriber architecture adopted by the COM+ Event service uses two key components First, an event class is used
to represent the connection between a publisher and subscriber Second, the COM+ Event Store within the COM+ catalog is used as a database for subscriptions
Explain that the COM+ Event service is used to advertise and deliver information to one or more interested parties without a prior knowledge of their identity The COM+ Event service acts as an intermediary between information publishers and subscribers As an intermediary, the COM+ Event service addresses some of the weaknesses associated with other methods for handling COM events, such as the tight coupling approach used
in Visual Basic Explain the critical role of the event class and that subscribers must implement the interfaces exposed by the event class Also explain that the system provides an implementation of the event class, which searches the event store and forwards event notifications to each subscriber in turn
! Working with Events Explain how to create and register event classes, subscribe to events, and publish events Events can also be filtered so that subscribers can be selective about what events they should receive Discuss the two primary methods of filtering: subscriber filtering and publisher filtering Explain the advantages of declarative publisher filtering over run-time publisher filtering (that is, the ability to use the solution with queued components and the fact that the publisher code does not need to be modified)
Trang 6! Combining Queued Components and Events Discuss how the COM+ Event service can be combined with the Queued Component service to make the publisher and subscriber time independent Events can be published asynchronously (by queuing between publisher and event object) or events can be delivered asynchronously (by queuing between event object and subscriber) Developers should choose where to introduce queuing based on the business logic used in their application It is also possible to use a queuing mechanism in both places Discuss how asynchronous communications can affect the order in which events are delivered
! Best Practices Review the key points covered in the module and summarize the best practices as part of your summary In most cases, the module covers a practical way to observe each of the best practices mentioned
Multimedia Presentation
This section provides multimedia presentation procedures that do not fit in the margin notes or are not appropriate for the student notes
COM+ Queued Components
This animation presents the architecture of the queued component service It illustrates the role of the three system-provided components: the recorder, the listener, and the player It also covers how they work together to provide the complete solution
! To prepare for the multimedia presentation
! To show this animation, double-click the file 1907A_05a005.avi
COM+ Events
This animation presents the architecture of the COM+ Event service It shows the event class acting as an intermediary between the publisher and subscriber, and providing the loose coupling It also illustrates how the publisher fires events by calling methods on the event class interface, and how these events are forwarded by the system-provided implementation code within the event class onto each subscriber registered in the COM+ Event Store It also highlights that each subscriber must provide an implementation of the event interface to
“handle” each event
! To prepare for the multimedia presentation
! To show this animation, double-click the file 1907A_05a010.avi
Trang 7The purpose of this demonstration is to show how to enable an application and
a component for queuing and to show how the Queue moniker is used to
instantiate a queued component
! To perform the demonstration
1 Open the project QCServer.vbp located in <install
folder>\Democode\Mod05\Queued Components\Server Describe to the
students how the Server class module contains one method that simply displays the supplied message via a message box
2 Select Make QCServer.dll from the File menu to generate the QCServer
component
3 Using the Component Services tool, create a COM+ application called QC Server Select all the default options
4 Install the QCServer.dll component into the QC Server application
5 Select and then right-click the application and select Properties
6 On the Queuing page, place a check mark in the Queued and Listen check boxes Reiterate the point that the Queued and Listen options cause the
creation of a set of queues for the application that enables the listener to detect inbound messages when the application is running
7 Click OK to dismiss the Properties dialog box
8 Expand the QC Server Components folder and then expand the Interfaces
folder beneath QCServer.Server
9 Select then right-click the _Server interface and select Properties
10 On the Queuing tab of the Properties dialog box, place a check mark in the
Queued check box Explain that this informs COM+ to expect queued
messages to be received for methods on this interface
11 Press OK to dismiss the Properties dialog box
12 Open the project QCTestHarness.vbp in <install
folder>\Democode\Mod05\Queued Components\Client
13 Examine and explain the code behind the Send Message button Explain that this code creates an instance of the QCServer.Server component by using GetObject and the Queue moniker, which results in a reference to a
recorder object Highlight the fact that despite the subtle change in the way that the component is instantiated, object interaction following instantiation
is performed in the standard manner In this case, the SendMessage method
is called with a single string parameter
Note
Trang 814 Run the QC Test Harness application and press the Send Message button
15 Nothing visible will happen at this point because the QCServer application
is not currently running However, point out that a message will have been
delivered to the QCServer application’s queue
16 Press the Send Message button again to generate a second message
17 Using the Computer Management tool, view the contents of the QCServer’s application queue Two messages will currently be in the queue
18 Using the Component Services tool start the QCServer application
19 Two message boxes will be displayed that contain the text parameter passed from the test harness: “Hi There!” Explain that the listener component within the QC Server application detected the messages in the queue, dequeued them, forwarded them to the player (which then instantiated the
QCServer object), and called the method
20 Click OK to dismiss both message boxes
Creating and Registering an Event Class
The purpose of this demonstration is to show how to create an event class by using an ActiveX DLL project and an abstract class module The purpose of the class module is to simply define each function in the event class interface Having created the event class DLL, this demonstration shows how to install the event class component into a COM+ application
This demonstration uses a simplified version of an event class that might be used by an Electronic Point of Sale (EPOS) stock management system As such,
the event interface provides two methods: LastItemSold and
NewOrderPlaced
! To perform the demonstration
1 Open the stock event class project StockEventClass.vbp located in <install
folder>\Democode\Mod05\Events\EventClass
2 Describe to the students that the IStockEvents class module is an abstract
class module in that it contains public functions definitions but no implementation code Point out that the system will provide implementation code when the event class is instantiated by a publisher Also mention that subscribers ultimately must provide concrete implementation code for each function in the interface to “handle” each event
3 Select Make StockEventClass.dll from the File menu to generate the event
class DLL Ensure students are aware that this option simply creates a DLL
containing a type library that contains the IStockEvents interface definition
You have not supplied any code
4 By using the Component Services tool, create a new COM+ application called EPOS Stock Events Take all the default options when creating the application This application will be used to contain the event class
5 Now install the StockEventClass.dll as an event class into the EPOS Stock Events application Demonstrate that installing an event class component in
an application is a similar procedure to adding a normal component, except
that the Install new event class(es) button must be used
Trang 96 Show students that the event class is listed beneath the Components folder and looks like a regular component The only discernable difference is on
the Advanced page of the component’s Properties dialog box Show this page and illustrate the presence of the LCE group box At this point, you can reiterate the purpose of the Fire in parallel option
7 You have now created and registered an event class Now you need some subscribers
8 Return to the Microsoft PowerPoint slides to discuss subscribers
Subscribing To Events
The purpose of this demonstration is to show how to create subscriber components by creating ActiveX DLL projects You will create the DLL
project with class modules that use the Implements keyword to provide a
concrete implementation of the event class interface The demonstration proceeds to show how subscription records are entered into the COM+ Event Store Two subscribers are provided
! To perform the demonstration
1 Open the first event subscriber project EventSubscriber.vbp located in
<install folder>\Democode\Mod05\Events\Subscriber
2 View the StockEventSubscriber class module and illustrate the use of the
Implements keyword Point out that the class module must provide
concrete implementations for all of the methods defined in the interface being implemented Also highlight the fact that a project reference has been set to the StockEventClass type library
3 Select Make EventSubscriber.dll from the File menu to build the subscriber
component
4 Repeat the previous three steps for the EventSubscriber2.vbp project This process will create a second subscriber component (When these subscribers are called, the resulting message boxes displayed by their implementation code will reflect the identity of each subscriber by displaying the
appropriate subscriber number in the message box title bar)
5 By using the Component Services tool, create a new COM+ application called EPOS Subscriber Select the default options when creating this application
6 Add the two subscriber components to the application by using the regular
Install new component(s) button of the Component Install Wizard
7 Expand both components within the Component Services tree view to display the two Subscriptions folders
8 You will now create a new subscription record in the COM+ Event Store Select the Subscriptions folder of the first subscriber, right-click, point to
New, and then point to Subscription
9 Select the _IStockEvents interface from the list displayed by the New
Subscription Wizard Point out that by selecting an individual method at this time, a subscription to a single method may be created
10 Click Next and wait for the StockEventClass.IStockEvents ProgID to be displayed in the Select Event Class dialog box
Trang 1011 Select this ProgID and click Next
12 Enter a suitable description for the subscription such as “First EPOS Event Subscription.”
13 Place a check mark in the Enable this subscription immediately check box and then click Next and Finish to create the subscription Point out that a
persistent subscription has now been registered in the COM+ Event Store This subscription will survive system restarts
14 Repeat the steps 8 to 13 to create a subscription for the second subscriber component
15 Two subscription records now exist in the COM+ Event Store All you need now is a publisher application
16 Return to the PowerPoint slides to discuss publishers and how to publishing events
Publishing Events
The purpose of this demonstration is to show how to create an application that publishes events The stock event publisher application creates an instance of the stock event class and fires the appropriate event method, depending on
which button is pressed One button fires the LastItemSold event while the other fires the NewOrderPlaced event
! To perform the demonstration
1 Open the stock event publisher project StockEventPublisher.vbp located in
<install folder>\Democode\Mod05\Events\Publisher
2 Show the application’s main form and explain that the Item Sold button fires a LastItemSold event while the Product Ordered button fires a
NewOrderPlaced event
3 Explain that the Publish Asynchronously check box is used in a future
demonstration when events are intended for asynchronous publication using queued components (For the current demonstration, you should leave this check box unselected)
4 Examine and explain the code behind each button Explain that to publish an event, you must create an instance of the event class and then call methods
on the event class’s interface to fire events The event class is created in the
CreateEventObject private function because this approach allows control
over whether the object is created in the standard fashion (by using the New keyword) or created via a Queue moniker for asynchronous method publication (This determination is made by setting the Publish
Asynchronously check box)
5 Select an item from the Products list and click the Item Sold button
6 A message box will be displayed with the title box indicating which subscriber has been invoked (Beware that the message box may not come
to the foreground and may appear on the task bar)
7 Click OK to remove the message box
8 A second message box from the other subscriber will appear Click OK to
remove this message box Stress that the order of delivery is determined by the system, and if the order of delivery is important, you will have to write a publisher filter component
Trang 119 Return to the Component Services tool and select the Fire in parallel option on the Advanced page of the event class’s Properties dialog box
Remember that you are setting this property within the EPOS Stock Events application
10 Fire another LastItemSold event by clicking the Item Sold button on the
publisher application This time, both message boxes will appear together because multiple threads are now being used to deliver the events
11 Click OK to dismiss both message boxes
12 Now press the Product Ordered button to fire a NewOrderPlaced event
Once again, two message boxes will be displayed (one from each subscriber)
13 Click OK to dismiss both message boxes
14 You have now successfully published events, which have been delivered synchronously to two subscribers
Filtering Events
The purpose of this demonstration is to show how a subscriber can use subscriber filtering to choose precisely for which events to receive notifications based on the value of one or more of the event method’s parameters
! To perform the demonstration
1 By using the Component Services administration tool, expand the EPOS Subscriber application and then the Components folder
2 Expand the second subscriber component (EventSubscriber2.StockEventSubscriber2) and then expand the Subscriptions folder
3 Select and then right-click the subscription entry and select Properties
4 Select the Options tab and enter lngProductID = 1 in the Filter Criteria
field
5 Click OK to dismiss the dialog box
6 You have now indicated that the second subscriber should only be notified
of events relating to product ID number 1 Point out that the lngProductID
symbol is used in the event class’s type library and that any symbol in this type library, together with relational and logical operators and parentheses, can be used in this expression Explain that the subscriber will only receive
event notifications when the supplied expression evaluates to True
7 Return to the Stock Event publishing application, select the first item in the
list, and press the Item Sold button
8 Two message boxes should appear because the first item in the list has a product ID of 1
9 Press OK to dismiss both message boxes
10 Select the second item in the list and press the Item Sold button
11 A single message box from Subscriber 1 will be displayed Subscriber 2 has not received the notification due to the filter The second item in the list has
a product ID of 2
12 You have now demonstrated subscriber filtering
Trang 12Combining Queued Components with Events
The purpose of this demonstration is to show how queued components can be combined with events to make the publisher and subscriber time independent This demonstration illustrates how queuing can be used between publisher and event classes to enable asynchronous event publication It also shows how it can be used between the event class and subscriber to enable asynchronous event delivery
! To perform the demonstration
1 Using the Component Services tool, select and then right-click the EPOS
Stock Events application and select Properties
2 On the Queuing page of the Properties dialog box, click the Queued and
Listen check boxes
3 Click OK to dismiss the dialog box
4 Expand the Components folder and then the
StockEventClass.IStockEvents class to display the Interfaces folder
5 Expand the Interfaces folder, select and right-click the _IStockEvents interface, and then select Properties
6 On the Queuing page of the Properties dialog box, select the Queued check
box
7 Click OK to dismiss the Properties dialog box
8 Right-click the EPOS Stock Events application and select Shut down
9 By using the stock events publishing application, select the Publish
Asynchronously check box Explain that this selection causes the publisher
code to instantiate the event class by using GetObject and the Queue
12 Press the Item Sold button one more time A second message will be
appended to the EPOS Stock Events application queue
13 Use the Computer Management tool to view the contents of the EPOS Stock Events application queue Two messages will be in the queue
14 By using the Component Services tool, start the EPOS Stock Events application
15 After a delay of approximately one second, four message boxes will be displayed Two events have been delivered to two subscribers
16 Click OK on all the message boxes to dismiss them
17 At this point, you have published events asynchronously To deliver events asynchronously, you will now mark the subscription as queued and queue-enable the subscriber’s application and interfaces
18 By using the Component Services tool, expand the EPOS Subscriber application and then expand the Components folder
Trang 1319 Expand the first subscriber component (EventSubscriber.StockEventSubscriber) and expand its Subscriptions folder to show the First EPOS Event Subscription
20 Select and then right-click the First EPOS Event Subscription, and select
22 Press OK to dismiss the Properties dialog box
23 Repeat steps 19 to 22 to mark the subscription record for the second subscriber as queued
24 You must now mark the _IStockEvents interface on each subscriber
27 On the Queuing tab, place a check mark in the Queued check box
28 Press OK to dismiss the Properties dialog box
29 Repeat steps 25 to 28 to mark the second subscribers _IStockEvents
interface as queued
30 You must now mark the subscriber application as queued In the Component Services tool, select and then right-click the EPOS Subscriber application
and select Properties
31 Select the Queuing tab and place a check mark in both the Queued and
Listen check boxes
32 Press OK to dismiss the Properties dialog box
33 Shut down the EPOS Stock Subscriber application by right-clicking it and
selecting Shut down (Warning: Confirm that the application has been shut
down by selecting the Applications folder and selecting the Status view If the application is still running and refuses to shut down, use Task Manager
to kill the dllhost.exe process.)
34 Ensure that the EPOS Stock Events application is running
35 In the Stock Events publisher application, ensure that a check mark is placed
in the Publish Asynchronously box
36 Select the first item in the list and press Item Sold
37 In the Computer Management tool, view the message queue for the EPOS Subscriber application Two messages will be in the queue (corresponding
to the two subscribers)
38 In the Component Services tool, start the EPOS Subscriber application Two messages will shortly be displayed confirming that the event has been delivered asynchronously to both subscribers
Trang 15# Overview
! Introduction to Queued Components
! Working with Queued Components
! Lab 5.1: Creating and Using Queued Components
! Handling Events
! Publisher and Subscriber Architecture
! Working with Events
! Lab 5.2: Creating and Using Event Classes
! Combining Queued Components and Events
! Lab 5.3: (Optional) Combining Queued Components and Events
! Best Practices and Review
In this module, you will learn how to use COM+ queued components to provide message-based asynchronous communication between the various parts of your application A communication system based on messages will help you
overcome some of the key problems encountered when building enterprise solutions
You will also learn how to use COM+ events The COM+ Event service provides a mechanism to connect applications that publish information with subscribers who want to receive updated information as soon as it becomes available
Objectives
After completing this module, you will be able to:
! Describe the purpose and benefits of queued components
! Create a queued component
! Instantiate and communicate with a queued component
! Describe the COM+ Event service provided with Microsoft Windows 2000
! Create and use an event class to match publishers with subscribers
! Combine queues with events to make the processing of publisher and subscriber events time independent
In this module, you will learn
how to use COM+ queued
components and events to
provide message-based
asynchronous
communication
Trang 16# Introduction to Queued Components
! Asynchronous Communication
! Microsoft Message Queue Server vs Queued Components
! Architecture of Queued Components
! Animation: COM+ Queued Components
In this section, you will learn how you can use COM+ queued components to solve some of the fundamental problems associated with developing enterprise solutions The primary challenge is to provide a reliable way for the various parts of an application to communicate Other issues that you should consider include unreliable or slow network connections, remote disconnected users, and heterogeneous application architectures
This section includes the following topics:
! Asynchronous Communication
! Message Queuing vs Queued Components
! Architecture of Queued Components
! Animation: COM+ Queued Components
Trang 17
Asynchronous Communication
! Issues with WAN-based synchronous communications
Lifetimes of server and client may not overlap Network connection will be less than 100% reliable Network latency cannot be predicted
! Use asynchronous message-based communications
In an enterprise system, communicating between separate computers by using synchronous protocols such as COM is not always the best solution While synchronous protocols are well suited to local area network (LAN) scenarios, a number of factors make them less suited for wide area network (WAN) scenarios
! The lifetimes of client and server may not always overlap
A synchronous protocol relies on the overlap of client and server lifetimes
If the server is not available when the client makes a call, the call will fail
In a distributed system, it is quite possible that a server computer may be unavailable when a client wants to communicate with it For example, the server computer may be offline for planned (or unplanned) maintenance
! The network connection linking client to server may not always be working
If the network connection linking client to server is unavailable, a synchronous call will fail There can be no guarantees that network links will be 100 percent reliable, particularly in a distributed systems
Messaging and Asynchronous Communication
As an alternative to synchronous communication, consider the approach of using asynchronous communications based on messages With a messaging approach, applications on different computers communicate with one another
by passing messages
Trang 18Message-based communication, such as that provided by Microsoft Message Queue Server (MSMQ), eliminates the need for the client to wait for the server’s response The client simply calls the server by sending it a message and then continues with other processing The message is stored in a holding area or queue until the receiver is ready to process it
Asynchronous communication is sometimes described as "loosely coupled" because various pieces of the communication process are independent of one another Also, the client and server may have independent lifetimes The following illustration contrasts the loosely coupled and tightly coupled communication models Each "X" indicates a potential point of failure in the synchronous architecture
Trang 19Asynchronous Communication (continued)
! Advantages of asynchronous communications
$ Facilitates development
$ Improves performance
$ Enhances reliability
$ Allows disconnected clients
$ Facilitates server scheduling
$ Supports heterogeneous environments
Advantages of Asynchronous Communication
Asynchronous communications offer a number of advantages when building distributed applications
Advantage Description
Facilitates development
It is easier to write most distributed applications if you do not need all the participants to be running simultaneously An asynchronous approach based on messages allows one application to send a message to another regardless of whether the destination application is running If the destination application is not available, the message is queued and held in
a storage area It will be processed by the destination application when it subsequently starts
Improves performance
A synchronous communications approach forces a client application to wait for a response from a server, whether or not
a response is actually required On slow networks, this wait can result in significant delays An asynchronous approach allows the client application to communicate with the server and then carry on processing immediately
Enhances reliability A distributed application built by using asynchronous
messaging is more resilient to failure For example, an application using messaging queuing can continue to function despite network failures and offline servers The messages destined for a server application are queued and subsequently forwarded to the application when the network connection resumes or the server comes back online
Trang 20Advantage Description
Allows disconnected clients
Asynchronous messaging allows solutions to be developed that involve disconnected mobile clients For example, consider an insurance salesman carrying a laptop computer While the client’s details and requirements are recorded, there is no need for a direct connection to a server Messages containing the captured data can be stored in local message queues When the salesman returns to his office, he can reconnect and send the messages to the server for permanent recording and processing.Facilitates server
Message bridging products such as those provided by Level 8 systems allow MSMQ solutions to be integrated with systems based on other messaging products such as IBM MQSeries
Asynchronous or Synchronous Communications
There are three possible scenarios when one application needs to communicate with another You can determine the appropriate communication model, asynchronous or synchronous, by the particular scenario used in your application
! Immediate response always required
An application that requires an immediate response for every call is not suited to asynchronous communications In this scenario, do not force an asynchronous solution; instead, use regular COM communications
! Response is never required This application scenario is ideal for one-way asynchronous communications The client’s job is complete when the call has been made and the message sent This model works well for applications whose only task is input For example, a clerk working in a goods inward department and carrying a handheld PC performs input recording only After
notification has been dispatched informing the clerk that the particular goods have arrived, the clerk requires no further confirmation
! Immediate response not required
In this scenario, the application requires responses to a communication at some point in the future This hybrid scenario is also suited to asynchronous communications, specifically to a form referred to as two-way asynchronous communication In this scenario, the application does not require an
immediate response, but expects some form of acknowledgement at some time in the future The application may only require negative
acknowledgements indicating that some error has occurred, or it may require both positive and negative acknowledgements In either case, a separate asynchronous communication can occur from the original server to client
One important point regarding this scenario is that the server must have some way of knowing how to direct a response back to the client In other words, the client’s identification must be made known to the server For more information about receiving asynchronous output, see Receiving Output from Queued Components in this module
Trang 21The primary benefit of using asynchronous communication in this scenario
is that end users do not have to wait for a response if it is not required The response may take a long time because of potential network latency or server unavailability
Trang 22
Message Queuing vs Queued Components
! Message Queuing is integral to Windows 2000
$ Feature-rich messaging solution
! Queued Components builds upon Message Queuing
$ QC provides a higher level of abstraction
In Windows 2000, Message Queuing is an integral part of the operating system While the COM+ Queued Components service builds on the underlying Message Queuing infrastructure, it is important to understand the differences between the two technologies Using queued components offers a number of advantages over directly using Message Queuing
Microsoft Message Queue
Message Queuing is a rich set of run-time services that allows applications on different computers to send and receive asynchronous messages back and forth
An application wanting to receive messages creates a queue, the location and identity of which is known to the operating system The queue is simply a persistent storage area conceptually similar to a mailbox
An application wanting to send a message to another application locates the queue either through system services or by application-based foreknowledge and uses Message Queuing to send the message The message may pass through one or more intermediate nodes before reaching its destination A system administrator configures the network topology
Message Queuing supports the following features
Feature Description
Guaranteed “exactly once” delivery
This feature ensures that only one copy of the message will arrive at the destination Intermediate queues between client and server may be used to ensure that messages do not get lost
if network errors occur It also means that either the client or the server (or possibly both) may be offline while a message is
in transit and it is still guaranteed to arrive
Trang 23Feature Description
Dynamic routing A system administrator can configure the network topology
and associate “costs” between various links The cost can be based on factors such as available bandwidth on the link or the financial cost of the link With dynamic routing, Message Queuing will compute the least cost link between the sender and receiver
Security The Message Queuing security services provide digital
signatures for authenticating messages, access control lists to control access to queues, encryption services for sending private messages, and auditing services Security is discussed further in the “Queued Components and Security” topic Priority-based
messaging
Higher-priority messages are given preference during routing and are inserted toward the front of the queue Messages with equal priority are placed in the queue according to their arrival time
Messages can contain text or binary data
Messages can be up to 4 megabytes (MB) in size and can even contain COM objects assuming that they support the
IPersistStream interface These COM objects include Visual
Basic 6.0 persistable objects and other objects, including side ADO recordsets
client-Transactional Support
All calls to Message Queuing from transaction-enabled COM+ components automatically join whatever transaction is active
As part of a transaction, messages can be committed or rolled back either in the component that sends the message or the component that receives the message For example, if an application updates a database and sends a message to another application within a transaction, any abort condition causes the database updates to roll back Message Queuing also rolls back the send operation For more information about this feature, see Queued Components and Transactions in this module
Programmable Object Model
Message Queuing provides an Automation object model that enables you to program both the sending and receiving application
Two queue types Message Queuing supports recoverable and express queues
Messages sent by using recoverable queues are committed to disk for reliability while in transit Express queues use RAM for speed
Queued Components
The COM+ Queued Components service builds on the Message Queuing infrastructure However, when you work with queued components, the underlying detail of Message Queuing is hidden
A client application creates a queued component in much the same way it would any other component The queued component exposes a COM interface that looks similar to other COM interfaces The client is free to call methods on this interface in the same way that it is for a regular COM interface The main difference arises from the underlying communications mechanism used to deliver the method parameters Traditionally, distributed COM uses synchronous remote procedure calls (RPC) to send the bytes from one computer
to another, as shown in the following illustration
Trang 24With queued components, the communication between the client-side proxy and the server-side stub is handled by Message Queuing The method parameters together with an identification of the target object are placed in a Message Queuing message and are sent to the destination computer
asynchronously, as shown in the following illustration
Notice that the proxy/stub pair has been replaced by the recorder/player The recorder is conceptually equivalent to the proxy, and the player conceptually equivalent to the stub The recorder is responsible for placing the method parameters into the Message Queuing message, and the player is responsible for feeding this data to the actual object at a later time when the message has been delivered For more information about queued component architecture, see Architecture of Queued Components in this module
Trang 25Message Queuing vs Queued Components (continued)
! Queued Components present interface design issues
$ Parameters must be passed by value
$ Calls must be self sufficient
$ Methods must not return application-specific errors
Sub SendOrderAndGetOrderNum( ByVal ProductID As Long,
ByVal Quantity As Integer, OrderNum As Long )
versus Sub SendOrder( ByVal ProductID As Long,
ByVal Quantity As Long )
Interface Design Issues
When you use queued components in your application, the component interface design is subject to a few restrictions
! Parameters must be passed by value, not by reference
Microsoft Visual Basic passes parameters by reference unless explicitly instructed to do otherwise Passing parameters by reference means that any variable passed to a method can be changed by the method, and the calling routine will see the change when the method call returns In a distributed scenario (in which client and server are in separate processes or on separate computers), the value of the parameters must be transmitted from client to server and back again This parameter transmission process is referred to as marshaling
With queued components or with any asynchronous communication scenario, there is no guarantee that the client will still be running when the server processes the method call As a result, it is not possible to send parameter values back from the server to the client All interfaces must be unidirectional
Trang 26To pass parameters by value in Visual Basic, method parameters must be
decorated with the ByVal attribute This attribute informs the marshaling
process that the parameters need only be sent from client to server Any change made by the server to any of the parameters is transparent to the client For example, the following method will work with synchronous COM but not with queued components because the last parameter is passed
by reference and is used for output
Public Sub SendOrderAndGetOrderNumber( _ ByVal ProductID As Long, _ ByVal Quantity As Integer, _ ByRef OrderNum As Long )
To use this method with queued components, you must rewrite this code to use only input parameters:
Public Sub SendOrder ( ByVal ProductID As Long, _ ByVal Quantity As Integer )
If the client ultimately requires an order number as confirmation that the order has been processed, a separate asynchronous communication can occur in the opposite direction from the original server to the client
! Calls must be self sufficient The client must supply every piece of information that the server needs to know by means of the method parameters The server is unable to call back
to the client requesting additional information because there is no guarantee that the lifetimes of the client and server will overlap
! Methods must not return application-specific error codes The return value that a client receives from a call to a queued component indicates only whether the call has been successfully recorded Any application-specific error code generated as a result of some business logic processing will not be seen by the client
Queued Components vs Message Queuing
Using COM+ Queued Components offers a number of advantages over the direct use of Message Queuing
! Higher level of abstraction Queued components represent a higher level of abstraction Abstraction makes queued components easier to use As a result, solutions can be developed more quickly With queued components, you are shielded from the lower-level details of Message Queuing
! Conventional component behavior
By using queued components, you do not have to learn a new object model
As a client application of a queued component, you interact with the component in exactly the same way as you would with a conventional nonqueued component
! Choice of communication method The COM+ components that you develop can be used either asynchronously through the Queued Component service or synchronously through
distributed COM This option provides added flexibility because the same binary component can be accessed by using queues in scenarios in which it makes sense and directly in other scenarios
Trang 27The only minor disadvantage to using queued components occurs with any higher-level abstraction, namely, a loss of detailed control
Although queued components handle the majority of cases the majority of the time, it is not possible to do everything with queued components that you can with Message Queuing However, the advantages of using queued components more than outweigh this minor drawback
Note
Trang 28Architecture of Queued Components
! The Recorder Object
$ Similar to a standard client-side proxy
$ Appears like the real object to the client
$ Records method calls and parameters into a Message Queuing message
! The Listener Object
$ Used by server to dequeue messages
$ Activates player object
! The Player Object
$ Creates actual object and plays recorded calls into it
The COM+ Queued Component architecture is represented by three objects:
! Recorder
! Listener
! Player
The Recorder Object
The Recorder object is provided by the COM+ Queued Component service and
is conceptually similar to a standard COM proxy For this reason, the Recorder object looks like the real object to the client The Recorder object provides an
implementation for all the methods in the object’s interface However, the
actual implementation is quite different The Recorder object’s implementation
for each method accepts the input parameters, and rather than firing them directly at the actual COM object by using a remote procedure call (RPC), it records them into an MSMQ message This process is repeated for each method call made by the client When the client deactivates the object by releasing its reference, the Queued Component service uses MSMQ to send the message containing the recorded calls to the server on which the actual COM object resides
The Listener and Player Objects
When the message arrives at the server, the recipient application uses a
Listener object provided by the system to detect the inbound message MSMQ
services are then used to read the message and a Player object is activated The
Player object creates the actual COM object and plays the recorded calls into it
If the server application is not active when the message arrives, the message will be stored in the application’s queue When the application is subsequently started, it can retrieve and process any awaiting messages
Trang 29Animation: COM+ Queued Components
Delivery Tip
Play COM+ Queued
Components animation that
shows the Recorder,
Listener, and Player objects
working together to deliver a
message
Trang 30# Working with Queued Components
! Developing a Queued Component
! Practice: Creating and Viewing Queued Components
! Instantiating a Queued Component
! Demonstration: Working with Queued Components
! Receiving Output from Queued Components
! Queued Components and Transactions
! Queued Components and Security
In an enterprise solution, you can use queued components to manage the communication that occurs between the various parts of an application In this section, you will learn how to view, instantiate, and create queued components You will also learn how to communicate with and receive output from queued components Finally, you will also learn how the COM+ Queued Component service handles transactions and security
This section includes the following topics:
! Developing a Queued Component
! Practice: Creating and Viewing Queued Components
! Instantiating a Queued Component
! Demonstration: Working with Queued Components
! Receiving Output from Queued Components
! Queued Components and Transactions
! Queued Components and Security
Trang 31
Developing a Queued Component
! Create regular COM+ component
$ Subject to interface restrictions
! Create COM+ application
! Mark application as queued
$ Queued and Listen check boxes
$ COM+ creates application’s queues
! Add component to application
! Marks interface(s) as queued
To develop a queued component, you will not need to write much code to tie into the underlying infrastructure You merely need to use the Component Services administration tool to set one or two configurable attributes
! To develop a queued component
1 Create your queued component as you would any other COM+ component Remember the restrictions that the Queued Component service places on your interface design For more information about these restrictions, see
"Interface Design Issues" in Message Queuing vs Queued Components in this module
2 Create a COM+ application by using the Component Services administration tool
3 Mark the COM+ application as queued
Trang 32From the Application Properties dialog box, select the Queuing tab and check the Queued and Listen boxes as shown in the following illustration
• Checking the Queued box causes COM+ to create message queues used
by any queued components that are subsequently added to the application
• Checking the Listen box tells COM+ to activate the listener service that
it needs to receive inbound calls through Message Queuing Selecting this option also prevents the server from shutting down during idle
processing The Server Process Shutdown option displayed on the
Advanced tab of the Application Properties dialog box is set to Leave running when idle automatically
In certain application scenarios, you may want to uncheck the Listen
box during peak processing hours when the server computer is busy with other activities As a result, incoming messages will be stored in the inbound queue for subsequent retrieval and processing During off-peak hours, perhaps at night, the listener can be reactivated and the application restarted to batch process the queued messages
Note
Trang 334 Confirm the presence of queues by using the Computer Management administration tool
A public queue is a queue registered in the directory service that can
be located by any Message Queuing application A private queue is a queue registered on the local computer (not in the directory service) that typically cannot be located by other applications
5 Add the component into the application and mark its interface or interfaces
as queued
Note
Trang 34In the Interface Properties dialog box, click the Queuing tab and check the
Queued box
Setting the Queued option tells COM+ that it should expect to receive
incoming calls to this interface through MSMQ This setting only affects incoming calls received by the interface and does not affect the outgoing calls made by this component to other components
The Queued check box will not be enabled if the interface has any associated ByRef parameters For more information about interface
restrictions for queued components, see "Interface Design Issues" in Message Queuing vs Queued Components in this module
Note
Trang 35Practice: Creating and Viewing Queued Components
In this practice, you will create a COM+ application and mark it as queued You will then use the Computer Management tool to open and view the application’s queues
! Create a queued COM+ application
1 Start the Component Services administrative tool
On the Start menu, point to Programs, then point to Administrative
Tools, and select Component Services
2 Expand the Component Services, Computers, and My Computer nodes
3 Select, then right-click COM+ Applications, point to New, and select
Application to launch the COM Application Install Wizard
4 Click Next to move past the initial dialog box
5 Click the Create an empty application button
6 Name the application “Test Queue Application,” leave the Activation type
as Server application, and click Next
7 Leave the Application identity as Interactive user and click Next
8 Click Finish to create the application
! Mark the application as queued
1 Expand the COM+ Applications folder
2 Right-click the Test Queue Application and select Properties to launch the
Application Properties dialog box
3 Select the Queuing tab of the Application Properties dialog box
4 Select the Queued and Listen check boxes and click OK
A set of queues will be automatically created for this application
Trang 36
! View the queues by using the Computer Management tool
1 Start the Computer Management tool
On the Start menu, point to Programs, then point to Administrative
Tools, and select Computer Management
2 Expand the Services and Applications and Message Queuing nodes
3 Expand the Public Queues folder
You should see a public queue called "test queue application." COM+ has created this queue for the Test Queue application Inbound messages for the application will arrive in this queue You can view messages by expanding
the test queue application node and selecting Queue messages The queue
will currently be empty
4 Expand the Private Queues folder
You will notice a series of queues with the “test queue application” prefix These queues are used for the queued component automatic retry
mechanism For more information about the retry mechanism, see Queued Components and Transactions in this module
Trang 37Instantiating a Queued Component
! Client uses GetObject with the Queue and New monikers
! Queue moniker new to Windows 2000
! Additional Message Queuing attributes may be specified
Dim objVendor As POVendor.db_Vendor Set objVendor = GetObject(“Queue:/New:POVendor.db_Vendor”) objVendor.Place rsItems, strUserID, lngOrderNum
Set objVendor = GetObject(“Queue:ComputerName=ABC/New:POVendor.db_Vendor”)
To create a queued component, a client does not use the standard CreateObject
or New functions Instead, the client must use the Visual Basic GetObject
function in association with a queue moniker Monikers are COM objects that know how to locate and create other COM objects and are sometimes referred
to as “intelligent activators.” Using a moniker to create an object allows additional intelligence to be built into the activation process Furthermore, monikers allow clients to specify initial state for the newly instantiated object
Instantiating a Queued Component
The following code shows how to create a queued instance of the POVendor.db_Vendor component:
Dim objVendor As POVendor.db_Vendor Set objVendor = GetObject( "Queue:/New:POVendor.db_Vendor" ) objVendor.Place rsItems, strUserID, lngOrderNumber
When you use the Queue moniker, the client is connected to a system-provided
Recorder object instead of the actual POVendor.db_Vendor object The Recorder is nothing more than a proxy generated at run time from the
component’s type library information, supporting the same set of interfaces as
the real object The client is now free to use the Recorder object as if it were
the real object
For example, the component calls the Place method in the preceding code A
recordset containing ordered items, a user ID, and an order number are supplied
as parameters These parameter values are not communicated directly to the real object, but are placed in an Message Queuing message When the client
deactivates the object by setting the object reference to Nothing, or when the
reference goes out of scope, the Message Queuing message is transmitted to the computer hosting the actual POVendor.db_Vendor component
Trang 38The use of the Queue moniker for object activation allows you to use the
same binary component as a queued component and a regular nonqueued
component Instantiating the object without using the Queue moniker will
result in the creation of a nonqueued instance
Working with the Queue Moniker
The Queue moniker is a new type of moniker introduced in Windows 2000
One way to identify a moniker is through its display name For example, the
queue moniker's display name is Queue When a display name such as Queue
is supplied to GetObject, the function looks at the supplied substring up to the
first colon, in this case, “Queue.” This string is treated as a ProgID and searched for in the registry The following illustration shows the ProgID for the
It is the responsibility of the Queue moniker to make sense of the remaining
substring and return a recorder object with the appropriate properties The remaining characters in this example (/New:POVendor.db_Vendor) constitute
the initialization string for another type of moniker called the New moniker The New moniker simulates the semantics of the New operator in Visual Basic
and other languages This type of moniker creates a new COM object based on the ProgID that follows
On the client side, the New moniker tells the Queue moniker the class of object for which to record calls The New moniker is then placed in the Message
Queuing message and is transmitted to the server along with the various method
call parameters With the information contained in the New moniker, the server
subsequently knows which class of objects to create to replay the calls
Note
Trang 39Specifying Additional Message Queuing Attributes
The Queue moniker allows you to supply additional Message Queuing
attributes; for example, the specific computer name on which the server object resides Additional information, such as the computer name, is specified between the colon (:) and backslash (/) characters in the moniker string, as shown in the following example:
Set objVendor = GetObject("Queue:ComputerName=APOLLO/New:POVendor.db_Vendor")
To supply multiple attributes, separate each attribute with a comma For example, to specify a computer name and message priority, the code would resemble the following example:
Set objVendor = GetObject("Queue:ComputerName=APOLLO," & _ "Priority=5/New:POVendor.db_Vendor")
The following table shows the Message Queuing attributes that are available to you when developing queued components
ComputerName Identifies the computer
containing the recipient queue
Derived from server application information installed on client
name
Derived from server application information installed on client
Queuing path name
Derived from server application information installed on client
FormatName Specifies the Message Queuing
format name (GUID)
Message Queuing default
AppSpecific Application-specific data
attached to the message
None
AuthLevel Message authentication level
An authenticated message is digitally signed and requires a certificate for the user sending the message
Derived from server application information installed on client
committed to disk while in transit or kept in RAM for speed (Recoverable versus Express queues)
Recoverable
EncryptAlgorithm Encryption algorithm used for
private messages
Message Queuing default
HashAlgorithm Algorithm used for calculating
checksum for tamper protection
Message Queuing default
Journal Specifies the journaling level of
the queue
Message Queuing default
Trang 40Attribute Meaning Default value
message label attached to the message
Message Queuing default
MaxTimeToReach Specifies a maximum time in
seconds for the message to reach the queue and after which it is deleted
Infinite
MaxTimeToReceive Specifies a maximum time in
seconds for the message to be read by the recipient and after which it is deleted
determining whether the message is encrypted
MSMQ default
response messages that trace a message’s path through the Message Queuing enterprise
Off
For more information about Message Queuing, see "MSMQ Attributes" in the Platform SDK documentation