COM Begins with COM

team lib

COM+ Begins with COM

From a client-side component-creation perspective, COM and COM+ are about the same. Despite all the hype to the contrary, you can create a component using either form of the technology. In fact, COM+ is merely an augmentation of existing COM technology when it comes to working with components. The important thing to remember is that COM+ is a true superset of COM, so you lose nothing by using COM+ in place of COM in your applications. Consequently, the information you learned about using COM in .NET in Chapters 3 and 4 also applies to working with COM+. Of course, COM+ deals exclusively with components and not controls, so you need to consider only component interoperability issues.

Youll find that the .NET environment reacts somewhat differently from a COM+ application because this application type installs differently. For this reason you should develop your application with a two-machine setupone machine is the server, and the other is the client. When you install the proxy application on the client machine, youll find it doesnt include some features of a standard COM setup because it doesnt need them. The action takes place on the server, not on the client, so the client needs only a pointer to the server. The next section describes some interoperability issues of using COM+ applications with .NET.

In addition to .NET differences, COM and COM+ have some differences that you need to consider when developing your application. For example, the design goals for COM+ are different than those for COM, so naturally, the two technologies work somewhat differently. Its important to know about these differences as you attempt to move a component from COM to COM+ otherwise , youll run into problems before you even begin to work with .NET. The following sections describe these differences.

A Look at COM+ Interoperability

Unlike COM, COM+ interoperability begins at the server. You create the COM+ application using the component as we did in the Creating COM+ Applications and Installing Components section of Chapter 2. Once you export the proxy, you install it on the client machine. For a developer, this means installing the proxy on your workstation. Once you have the proxy installed, youll be able to view the COM+ application using the Component Services console.

At this point, you use the component just as you would any other component within the .NET IDE. In general, the material in the Generating Runtime Callable Wrappers section of Chapter 3 applies to obtaining a reference to the component. However, you need to consider several special issues when working with COM+ applications. The most important issue is that youre working with a proxy generated on another machine.

Chapter 3 discussed three methods for gaining access to a COM component. The easiest method to use when working with a COM+ application is the integrated development environment (IDE)otherwise, youll need to locate the local copy of the type library to use with TlbImp.exe or the TypeLibConverter class. If you choose one of these other methods, youll need the application ID. Right-click the application entry in the COM+ Applications folder of the Component Services console, and choose Properties from the context menu. Select the General tab, and youll see a dialog box similar to the one shown in Figure 5-1.

click to expand
Figure 5-1: Youll need the Application ID to locate the components for the COM+ application on your local drive.

The Application ID field is the one that youre interested in because COM+ uses this GUID to keep the components from each application separate. Append this information to the Program Files\ComPlus Applications\ path, and youll have the path to your components. In this case, the complete path would be Program Files\ComPlus Applications\{EE249684-FD8F-45A2-ADFE- F682E7620587}. This folder holds a copy of your component and the type library. Make sure you dont move or otherwise change the component or type library when you use it.

Well also see in Chapter 9 that interoperability requires some interesting component planning. The problem is one of getting COM+ to recognize the component. The base class for your component makes a difference. Consequently, well discuss components created with the following base classes:

  • Object

  • Component

  • ServicedComponent

Of the three, the ServicedComponent class provides the greatest flexibility. A component based on the Object or Component class will have limited flexibility and present problems for Windows 2000 developers. However, a component based on the ServicedComponent class can present problems of its own. For example, youll find it difficult to create an application proxy if you install the component using the RegSvcs.exe utility.

As we saw in Chapter 2, creating a simple component results in a COM+ component addition that includes only the methods found in the Component class and those found in the Object class. This includes the Equals() , GetHashCode() , GetType() , and ToString() methods. All this type of component requires is that you add the [ClassInterface(ClassInterfaceType.AutoDual)] attribute.

Tip 

Whenever you create a component for COM+, you should include the [Guid] attribute. Whenever COM+ registers your component as part of the installation process, it makes a registry entry. The common language runtime creates a GUID at random unless you define the [Guid] attribute. Cleaning up the registry after a development session can become quite time consuming. Using the same GUID all the time means youll spend less time cleaning and more time developing.

When you design a component based on the Component class, you need to add a few more bits of code. Listing 5-1 shows a component that youll find in the Chapter05\MyMath (Component) folder in the companion content. You can get the companion content at the books Web site: http:// www.microsoft.com/mspress/books/6426.asp .

Listing 5-1: MyMath.cs (Component)
start example
 usingSystem; usingSystem.Runtime.InteropServices; usingSystem.ComponentModel; namespaceMyMath { ///<summary> ///Asimpleclassthatshowsthefourbasicmathfunctions. ///</summary> [Guid("0C4340A2-C362-4287-9A03-8CDD3D1F80F6"), ClassInterface(ClassInterfaceType.AutoDual)] publicclassMathFunctions:Component { ///<summary> ///AddtwoInt32valuestogether. ///</summary> ///<paramname="Value1">Thefirstnumber.</param> ///<paramname="Value2">Thesecondnumber.</param> ///<returns>Thetwonumbersadded.</returns> publicInt32DoAdd(Int32Value1,Int32Value2) { returnValue1+Value2; } ///<summary> ///SubtractoneInt32valuefromanother. ///</summary> ///<paramname="Value1">Initialvalue</param> ///<paramname="Value2">Valuetosubtract</param> ///<returns>Value2subtractedfromValue1</returns> publicInt32DoSubtract(Int32Value1,Int32Value2) { returnValue1-Value2; } ///<summary> ///MultiplytwoInt32values. ///</summary> ///<paramname="Value1">Thefirstnumber.</param> ///<paramname="Value">Thesecondnumber.</param> ///<returns>Thetwovaluesmultiplied.</returns> publicInt32DoMultiply(Int32Value1,Int32Value2) { returnValue1*Value2; } ///<summary> ///DivideoneInt32valuebyanother. ///</summary> ///<paramname="Value1">Initialvalue.</param> ///<paramname="Value2">Divisor</param> ///<returns>Value1dividedbyValue2</returns> publicInt32DoDivide(Int32Value1,Int32Value2) { returnValue1/Value2; } } } 
end example
 

As you can see, this component requires that you subclass the Component class found in the System.ComponentModel namespace. Fortunately, this namespace appears in the System.dll file, so you dont need to reference any additional DLLs in your component. Figure 5-2 shows that creating a component using this technique adds the IComponent and IDisposable interfaces, which include the add_Disposed() , remove_Disposed() , Site() , and Disposed() methods. Youll use the add_Disposed() and remove_Disposed() methods to add and remove event handlers for the Disposed event. Notice that there are also two copies of the Site() methodone to get the Site property value and one to set it.

click to expand
Figure 5-2: Creating a component based on the Component class adds the IComponent and IDisposable interfaces.

Creating a component that subclasses the ServicedComponent class gets a little more complex. You need to add a reference to the System.EnterpriseServices.dll. In addition, you need to add the appropriate reference to your code and add some code for the ServicedComponent class. Listing 5-2 shows a typical example of the code you need. (Youll find the complete component in the Chapter05\MyMath (ServicedComponent) folder of the companion content.)

Listing 5-2: MyMath.cs (ServicedComponent)
start example
 usingSystem; usingSystem.Runtime.InteropServices; usingSystem.EnterpriseServices; namespaceMyMath { ///<summary> ///Asimpleclassthatshowsthefourbasicmathfunctions. ///</summary> [Guid("0C4340A2-C362-4287-9A03-8CDD3D1F80F6"), ClassInterface(ClassInterfaceType.AutoDual)] publicclassMathFunctions:ServicedComponent { ///<summary> ///AddtwoInt32valuestogether. ///</summary> ///<paramname="Value1">Thefirstnumber.</param> ///<paramname="Value2">Thesecondnumber.</param> ///<returns>Thetwonumbersadded.</returns> publicInt32DoAdd(Int32Value1,Int32Value2) { returnValue1+Value2; } ///<summary> ///SubtractoneInt32valuefromanother. ///</summary> ///<paramname="Value1">Initialvalue</param> ///<paramname="Value2">Valuetosubtract</param> ///<returns>Value2subtractedfromValue1</returns> publicInt32DoSubtract(Int32Value1,Int32Value2) { returnValue1-Value2; } ///<summary> ///MultiplytwoInt32values. ///</summary> ///<paramname="Value1">Thefirstnumber.</param> ///<paramname="Value">Thesecondnumber.</param> ///<returns>Thetwovaluesmultiplied.</returns> publicInt32DoMultiply(Int32Value1,Int32Value2) { returnValue1*Value2; } ///<summary> ///DivideoneInt32valuebyanother. ///</summary> ///<paramname="Value1">Initialvalue.</param> ///<paramname="Value2">Divisor</param> ///<returns>Value1dividedbyValue2</returns> publicInt32DoDivide(Int32Value1,Int32Value2) { returnValue1/Value2; } } } 
end example
 

The System.EnterpriseServices namespace is especially important to COM+ developers because it provides access to a number of COM+ resources, including the component constructor string. Well discuss the intricacies of this class later in the book. For now, you need to know that its also the source of the ServicedComponent class. Figure 5-3 shows that this component includes a number of new interfaces, including IDisposable , IManagedObject , IRemoteDispatch , and System_EnterpriseServices_IServicedComponentInfo . Your application should never use the methods found in the IRemoteDispatch and System_EnterpriseServices_IServicedComponentInfo interfacestheyre reserved for .NET Framework use. COM uses the IManagedObject interface during component activation and marshaling. Again, you wont normally interact with this interface from an application.

click to expand
Figure 5-3: Creating a component based on the ServicedComponent class adds a number of additional interfaces.

COM+ Design Goals

In Chapter 2, we discussed the reasons you might want to use COM+ for development purposes, even with the features that .NET provides. However, we really havent discussed the COM+ part of the picture. To understand what you gain by using COM+, you need to understand some of the goals that the design team had in mind when putting COM+ together:

  • Make developing server components as easy as developing client components. Before COM+, there were a lot of server- specific issues to take care of, such as multiple users hitting a component at the same time. COM+ removes many problems that come with a multiuser environment like the one you find on servers. Of course, the solution is to promote distributed application development.

  • Make it just as easy to develop enterprise applications as it is to develop workgroup applications. COM+ allows you to create components that will scale to any size . Load balancing is a term that youll hear more and more as companies try to create an environment in which a single programming effort will result in components that continue to work as the company grows.

These two goals define the essential reasons to use COM+. Unlike COM, Microsoft designed COM+ to allow you to create distributed applications that rely on component technology that scales to any size. This COM+ difference will greatly affect how you create applications in the future. In many cases, youll now create components that applications on the client will use to access data on yet another server.

Lets talk about the client and server situation a little further. COM+ is also part of the Microsoft distributed architecture strategy. Essentially , COM+ is an n - tier architecture, where various servers perform specific tasks. Those tasks are just part of a whole application. In other words, a single application on the user s machine might require the services provided by more than one server. One server might have the components that include the basic business logic for the request, another server might access in-memory databases containing things like a list of the states in the United States, and a third server might provide access to the companys main data store. In short, COM+ is the predecessor to the current Web services technology that many companies are considering adopting.

Transactions and COM+

One of the more important reasons to use COM+ is ensuring the integrity of the data you transfer from one machine to another. Anytime two machines talk to each other using any media (cable, wireless, or anything else you can think of), you have to create some type of data exchange protocol. Even if the machines are sitting side-by-side in the same room, theres a chance of losing data because of a bad connection or interference. Given todays distributed environment, theres a much greater chance for lost data, which means that you need some type of transaction technology in place.

Microsoft Transaction Server (MTS) is part of the COM+ universe. MTS is the mechanism by which COM+ guarantees delivery of data from one machine to another. These services not only ensure the data delivery, they also ensure that both the sender and receiver are satisfied with the integrity of the data. The following list provides an overview of the services MTS can provide to COM+:

  • Transactions A transaction is a single group of instructions the sender or receiver carry out to complete a task. Either a transaction is completed or MTS rolls it back so that the application environment is the same as it was before the transaction started. MTS frees the programmer from managing transactions. All the programmer needs to do is specify that a given set of instructions constitutes a transaction.

  • Resource pooling Most servers have huge quantities of memory and hard-disk space that components can use to complete tasks. However, given the complex environment in which the developer places components, trying to manage resources is a difficult task to say the least. MTS also features automated resource management. Not only does resource pooling free the programmer from micromanaging system resources, it also ensures each component gets the resources it needs.

  • Security Getting data from one point to another and ensuring the database records it properly wont do much for you if someone breaks into the connection between the client and server and corrupts the data. As a result, security is one of the more important features that MTS provides.

  • Administration Managing your MTS setup so that you can get optimum performance from your server is an important task. Microsoft provides a Microsoft Management Console (MMC) snap-in that makes MTS management easier.

As you can see, MTS provides a lot more than just transaction management, although thats its main function. The other services MTS provides merely augment the main function of making sure data gets from one point to another without interruption and that all parties performing operations on that data complete their tasks successfully, or not at all. Without these services, COM+ as a whole would fail because data security is a primary requirement to creating distributed applications.

You wont work directly with MTS in most cases. The Distributed Transaction Coordinator (DTC) enables MTS to start transactions on behalf of a component. The DTC also manages transactions that occur on multiple servers. For example, if a component on one server wants to participate in a transaction on another server, the DTC will manage the communication. MTS performs the actual transactional tasks, but the DTC is central to allowing the transaction to occur in the first place. Youll manage the DTC using the Distributed Transaction Coordinator folder elements of the Component Services console shown in Figure 5-4. (In this case, youre seeing the statistics for the server in question.) Well use this management tool more as the book progresses.

click to expand
Figure 5-4: Use the Distributed Transaction Coordinator folder elements to manage transactions on a server.

One service that doesnt appear in our list is serialization. This particular feature of MTS ensures that both data and commands arrive at the database in the same order the client created them, even if the network protocol used to transfer the packets of information doesnt guarantee any order of delivery. This means you wont need to worry quite as much about the features provided by the underlying network protocolat least not when it concerns the order your data will arrive in.

Messages and COM+

COM+ also includes the concept of disconnected applications. A disconnected application is a form of asynchronous processing in which the client and server dont need to exist at the same time. Messaging, a type of e-mail communication, provides the glue required to keep client and server communicating. (The use of message queues isnt precisely the same as e-mail, but the analogy is a good one for understanding how the process works.)

At the heart of this technology is Queued Components , which in turn uses Microsoft Message Queuing (MSMQ) services. MSMQ is the base stand-alone technology originally introduced for use within Microsoft Windows NT for message-based application development. Queued Components are the new COM+ version of MSMQ that offers a true superset of the older technology. All older MSMQ interfaces are still in place, but now you also have more automation and integration with COM available in Queued Components. Queued Components provides both an application programming interface (API) and a component- based interface for developers. The following list describes some of the benefits of using Queued Components.

Note 

Youll see MSMQ and Queued Components used throughout the book in an almost interchangeable way. Ill use the term Queued Components whenever Im talking about a Queued Component specific feature such as a wizard, while MSMQ will always refer to the underlying technology or an existing feature like a programming API. Its important to see Queued Components as a slightly augmented version of MSMQ that was designed specifically for use with COM+ and not as a new product.

  • Better road- warrior support In the past, an application that required services from the server or wanted to provide input to the server had to maintain a live connection. Obviously, this is impossible for employees on the road, so companies often had to rely on cumbersome technologies of dubious value that forced the employee to use different methods in different situations. In addition to the problem of getting an employee trained to use more than one data entry and management method, there was a problem with getting the employee to use the right method at the right time.

  • Lower development costs Older technologies forced the programmer to do more work. Even if the programmer needed to worry only about two data-entry scenarios, that still required twice the amount of code and debugging. In essence, the programmer was writing the same application twice because of a lack of disconnected application tools. Of course, the doubling of data-entry features also resulted in larger applications that required more memory to load. A disconnected application takes only slightly more disk space and memory than a single interface application designed for desktop- only use.

  • No live connection needed Applications that rely on Queued Components dont care about the current connected state of the application. Data that an application wants to send to the server gets stored in a local message queue if the application cant establish a connection with the server. When the user makes a connection, Queued Components automatically uploads the data in the message queue for the user. In this respect, a Queued Component application acts as an answering machine. A recorder on the client creates the message, a listener on the server alerts the server-side component to the presence of the message, and a player retrieves the message from the queue.

  • Preemptive resource management The application can also download resources such as database updates or new application functionality from the server before the user attempts to break the connection with the server. This resource management technique helps the user request at least a subset of the data from the server, even though the user might not realize there isnt a connection in place for getting the requested information. The only time the user will notice any difference is if the application needs the data requested immediately and the preemptive resource management module didnt anticipate the need to download it from the server. For example, the application could automatically request the client records needed for the clients appointments the following day based on appointment-book entries. Even if the task didnt get done, as soon as the user establishes a connection, the resource management module can download the requested data in the background. The resource management module can make the request by using messages stored in the users local queue.

Unlike many other COM+- related services discussed in this chapter, youll use the Computer Management console to manage the queues on a system, unless you choose to create a custom console for the purpose. Figure 5-5 shows an example of the Computer Management console with the Message Queuing folder displayed. Notice that this folder appears in the Services And Applications folder.

click to expand
Figure 5-5: Manage the queues for an application using the Message Queuing folder features.

As you can see, MSMQ provides four levels of message queues: Outgoing Queues, Public Queues, Private Queues, and System Queues. Well use all these queues to create various applications in the book. The System Queues folder is the only folder that actually contains queues when you first install Message Queuing (the name of the option found in the Windows Components Wizard For Windows XP). This queue generally contains messages of a system nature, including messages that MSMQ couldnt deliver. The Outgoing Queues folder contains all messages the local computer will send to the server once a connection is established. The Public Queues folder contains permanent queues that are visible to the public, while the Private Queues folder contains queues that only local applications should see.

Visual Studio .NET makes it almost too easy to use a queue. You can access both local and remote queues using Server Explorer, as shown in Figure 5-6. Notice that you can access all but the Outgoing Queues folder, which makes sense because this folder contains only temporary queues (and only while the client lacks a connection to the server).

click to expand
Figure 5-6: Use Server Explorer to access local and remote queues.

To add a queue to your application, drag and drop it onto the form. Visual Studio .NET will create a MessageQueue object for you. The properties will contain all the correct pointers for the queue. Well discuss message queues at length in Chapter 10.

COM+ Services

So far, weve seen that COM+ is an amalgam of various existing technologies. In short, nothing Ive said so far is very new. However, the way that COM+ provides a wrapper for making all these technologies work together is a relatively new idea.

Many COM+ concepts well discuss are similar to those found in .NET. COM+ is the predecessor to the .NET technologies. Although I havent mentioned it yet, you should use the remoting features of .NET before you rely on COM+ for managed application requirements. Web services also provide a good alternative to COM+ for Internet applications. In fact, as shown in Figure 5-7, the IDE generates an error if you attempt to directly use a managed component thats part of a COM+ application. Theres no reason to pay a double performance penalty for using the componentuse it directly as a managed component whenever possible. Of course, disconnected applications are one scenario in which you might want to use managed components in a COM+ application from your managed clientits a viable application strategy. In addition, you can still use COM+ to make your managed components available to unmanaged clients .

click to expand
Figure 5-7: Attempting to directly import a managed component thats part of a COM+ application into your application will generate an error message.

COM+ isnt merely a wrapper for existing services, however. It also provides unique services that you wont find in any older Microsoft offerings. The following list provides you with an overview of what these services are. Well study these features in detail as the book progresses.

  • Events Applications can receive events generated on the server as if they occurred on the local machine. This means the server-side components you create will have a direct connection to the client. COM+ allows you to use unicast (in which an event is sent to one event sink), multicast (in which an event is sent to multiple event sinks), and unbound (in which an event occurs when client makes contact) events. The unbound event is particularly useful because it can inform a client about conditions on the server after the client performs an initial logon. In other words, every client who logs on to the system will receive the current (dynamic) server status.

  • Security COM+ relies on MTS for the security of its data in many cases. However, COM+ still has security concerns when instantiated objects on the server need to communicate with a client and there isnt any transaction. In addition, COM+ enables the developer to create queued componentsessentially a component in a message. We discussed security issues as part of the Adding Security to a COM+ Application section of Chapter 2.

  • Component Load Balancing (CLB) Large companies normally use more than one server for their data storage needs. Of course, this means the company normally needs to provide access to specific servers to a given user in order to manually balance the server load. Load balancing lets everyone access all the available servers through a router. The router keeps track of how much of a load each server has and balances new requests accordingly . In addition, the router can move current requests from a failed server to the good ones in the cluster without the user even realizing a server failure has occurred.

  • Queued Components Clients require updates to the components they hold from time to time and, in some cases, will require a new component before they can perform a specific task. In the past, the administrator had to install new components individually on each machine or create cumbersome batch files to do the job. The use of Queued Components helps each client to receive automatic component updates. The administrator doesnt need to do much more than install the component on the server. Because all users have access to the same component, they all receive the update at the same time.

  • Compensating resource manager Legacy applications require this particular service. It builds a framework around the old server application so that clients can access the application using all the new features COM+ provides. The main goal of this service is to help you maintain your investment in established applications, yet allow the old application to interact with other resources on the server. Of course, this feature comes at the cost of performance, so upgrading your components to .NET is one option you should consider.

  • Administration COM+ uses an MMC snap-in to provide administrative services for your server-side components. This snap-in lets you manage all COM components and helps you administer all new services COM+ provides. This snap-in also provides a programming interface that allows you to install, configure, and automatically deploy your COM+ components. It relies on the Active Directory catalog to store the attributes for each of the components installed on the server. The COM+ component attributes include transactions, security roles, and activation properties.

  • Publish/subscribe event model COM+ provides a new event model that helps the developer create applications that dont need to know quite as much about each other. The component publishes events and doesnt care where those events go. An application can subscribe to events without really knowing their source. In between these two applications are component services, which manage the connection between publisher and subscriber.

 
team lib


COM Programming with Microsoft .NET
COM Programming with Microsoft .NET
ISBN: 0735618755
EAN: 2147483647
Year: 2006
Pages: 140

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net