Microsoft Computing: The Microsoft COM Architecture, Part 1

Microsoft
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Although in principle a legacy technology, Microsoft's Component Object Model for application development, or COM, is the most widely used specification in the computer world today. Every Windows system relies heavily on the COM architecture as the basis of reusable code. This month's article is the first of two parts that will explore this important technology.

What Is COM?

COM is a specification for creating programs that will run in a language-independent manner under the Microsoft Windows platform. The term COM is also used to refer to the underlying architecture within Windows that makes the technology work. The whole point of the COM strategy is to build and exploit reusable binary code. Such a piece of code, once created, is called a binary COM server and takes the form (usually) of a DLL file.

COM architecture allows a program to work with Windows to find and use routines that are external to the program without regard for programming languages used. For example, a desktop application written in Visual Basic (VB) can run routines written in Visual C++ (VC++) and vice versa. Windows will accommodate the request for external access to a COM server through a mechanism called "cross-process marshalling." This is the internal systems management works within Windows that links and services the requests.

Using a COM Interface

A good way to become familiar with how COM programming works is to see how an external program uses COM technology to accomplish a particular task. A couple of code examples follow to present the case.

Again, the idea is to be able to reuse program code. So if a particular chunk of code, or even a full-blown application, is created to the COM specification, it will be accessible externally from a user-written program. Take, for example, Microsoft Word or Excel. These are well-known standalone applications. But additionally, programs like Word and Excel are created to comply with the COM programming model. This means that these powerful applications can be used as tools to be exploited by my humble homegrown program. Does that mean I can cause my little VB or VC++ program to include the services offered by Word or Excel? It must be a miracle.

The COM Public Interface

So here's how a code library that adheres to the COM architecture is accessed. The code library or application must have a public interface. That is, there must be methods and properties visible to the outside world. The public properties of a COM library can be accessed (set and get) from an external program, and the public methods can be executed from an external program. Although the way that the public interface of a COM server is used is well-specified, the server's actual interface depends on the application.

So how do you know what the public interface is for a COM server? There is published documentation available for most Windows and other commercial applications of the COM specification. Additionally, a code editor like Visual Studio includes tools to help sort out the methods and properties of a COM server.

Figure 1 shows the Object Browser within Visual Studio. Displayed in the browser is the public interface for Microsoft Word.

http://www.mcpressonline.com/articles/images/2002/Microsoft-WindowsCOM%20V4%2005170400.jpg

Figure 1: The public interface for MS Word is displayed in Visual Studio Object Browser. (Click images to enlarge.)

In Figure 1, the Object Browser is displaying only a small portion of the Word public interface. Class names are shown in the left panel, and the corresponding members of the class are on the right. In the example, the method SendMail is highlighted and is a member of the class Document. We know SendMail is a method because of the little green "building block in action" icon next to it. The members with the little hand delivering what looks like a telegram are properties.

Each of the member items listed in the Object Browser for MS Word are part of Word's public interface and are thus available for manipulation from without. COM is a powerful architecture, indeed.

But wait a minute. How does my little VB program know I want to use MS Word as a tool? If you go to your PC and bring up VB6 and start the Object Browser, you will not have access to the Word COM object. Another step must be completed first.

Before you can access the members of a COM server, you must establish a reference to the server's library. In VB6, you do this from the Project menu and then select the References item. The dialog box shown in Figure 2 will be displayed, showing the libraries referenced by your project.

http://www.mcpressonline.com/articles/images/2002/Microsoft-WindowsCOM%20V4%2005170401.jpg

Figure 2: The VB6 project references dialog shows the libraries referenced by your project.

The references dialog shows the usual inclusions for VB plus one other: the Microsoft Word 9.0 Object Library. This is what allows the VB program to be aware of the public members within MS Word. After setting this reference, you should be able to see MS Word members in your Object Browser. It's also interesting to scroll through the list of available references. Each item is a registered COM server on your PC with some sort of public interface, and each can be used as a tool, just like we're doing with Word.

In VB code, Word's functionality is represented as an object. The properties and methods of Word may then be accessed as WordObject.Property or WordObject.Method. The following code sample shows how the Word object comes into existence and how a simple property--the printer that Word is using as the default--is made available to the VB program.

Private Sub Form_Load()

Dim objWord As Word.Application
Dim sWork As String

    Set objWord = New Word.Application
    sWork = objWord.ActivePrinter
    
    Set objWord = Nothing

End Sub

When this code is executed, a new instance of Word is created and assigned to the program object variable objWord. The methods and properties of the Word object are then available as members. In the example, the ActivePrinter property is accessed and put in the string variable sWork.

Pay special note to the line Set objWord = Nothing. This essential cleanup step releases the Word application from its tie to the VB program and allows it to die a natural death. Without it, orphaned objects will persist and can cause process locks, memory leaks, and other complications.

In the following slightly-more-involved example, Word is being instructed to make itself visible and then open a document. Once the doc is opened, the PrintOut method is invoked, which will print the document on the default printer just as if the user had clicked his way to the same result. Note that making Word visible is optional. If you prefer, you can keep Word tucked under the covers and take all the credit yourself.

Private Sub Form_Load()

Dim objWord As Word.Application
    
    Set objWord = New Word.Application
    objWord.Visible = True
    
    objWord.Documents.Open ("C:docmyDoc.doc")
    objWord.ActiveDocument.PrintOut
    objWord.ActiveDocument.Close
    
    objWord.Visible = False
    Set objWord = Nothing

End Sub

If the instance of Word is invisible when the Word object is released, the instance will terminate. If it's visible, the instance of Word will persist until it's closed manually. This is handy when you want to start Word, open a document, and then turn it over to the user for editing.

An Example of Using Word as a COM Object

As an illustration of when to use Word within another application, suppose you want to create a letter for each of your customers, announcing your company's new product. Normally, this could be handled with a Word mailmerge application. But suppose the requirement is a little too tricky for a simple Word mailmerge application, and additional intelligence is required. Let's say the application will have to create slightly different text within each letter for each of several types of customers. Also, for one type of customer, the letter should be emailed, not printed. For all others, the letter should be printed but not emailed. COM technology to the rescue.

OK, that's pretty simple--for a program, that is. A program can get customer data, determine the customer type, and take appropriate action. A program can instruct the Word COM object to create each document correctly and either print or email the result.

Using a Starter Document

It's a common practice in an application like this example to create a Word document to serve as the template or starter doc. This starter doc will contain all the text that will go in the letters, thus sparing the programmer the tedium of inserting and formatting the text programmatically. Also within the starter doc are named tags called "bookmarks." These bookmarks may be cleverly arranged within the document to allow exact spots to be addressed by name from within the program (Figure 3).

http://www.mcpressonline.com/articles/images/2002/Microsoft-WindowsCOM%20V4%2005170402.jpg

Figure 3: Bookmarks are named tags within a Word document.

In Figure 3, note the I-bar symbols. These are the spots within the document where bookmarks have been defined. The figure also shows a new bookmark, GolfCart, being created and placed at the cursor's current position.

When the VB application is run, it will determine the type of text that should be in the letter (baby stroller or golf cart) and delete the other type of text. The program will position the cursor at the named bookmark and remove the incorrect text. (Note that it's easier to remove extra text than to insert new text.) The code below presents a simple illustration.

Private Sub Form_Load()

Dim objWord As Word.Application
    
    Set objWord = New Word.Application
    
    With objWord
        .Visible = True
        .Documents.Open ("C:docmyDoc.doc")
    
        ' Insert the address information...
        .Selection.GoTo What:=-1, Name:="Address"
        .Selection.Text = myFile!Address1
        
        ' Insert the name...
        .Selection.GoTo What:=-1, Name:="Name"
        .Selection.Text = myFile!firstName
        
        ' Remove the text that does not apply...
        If myFile!customerType = "Golf" Then
            .Selection.GoTo What:=-1, Name:="Stroller"
            .Selection.HomeKey Unit:=5
            .Selection.MoveDown Unit:=4, Count:=1, Extend:=1
            .Selection.Cut
            ' Send golfers their letter by email...
            .ActiveDocument.SendMail
        Else
            ' Similar to above (omitted)...
            ' Send new parents their letter by regular mail...
            .ActiveDocument.PrintOut
        End If
        
        .ActiveDocument.SaveAs FileName:="tempdoc.doc", _
AddToRecentFiles:= False  
        .ActiveDocument.Close
    
    End With
    
    objWord.Visible = False
    Set objWord = Nothing

End Sub 

This modest chunk of code opens the starter document and then goes to the bookmarked locations within the document and inserts text (the .Selection.GoTo and .Selection.Text statements). Then, the code finds and deletes the extraneous paragraphs within the documents with the .Selection.HomeKey, .Selection.MoveDown, and .Selection.Cut statements. If the customer is a golfer, the document is then emailed (.ActiveDocument.SendMail). Otherwise, the document is sent to the printer (.ActiveDocument.PrintOut).

It doesn't require an overly vivid imagination to see the value in the COM technology specification. With a COM-capable programming language acting as the "pivot man," substantial processing power and flexibility is at hand. But accessing another object's public interface is only part of the picture. Another powerful aspect of the COM architecture allows you to create your own binary COM servers. Next month, we'll continue the discussion of the COM architecture and look into the future of COM in the emerging .NET world.

Chris Peters has 26 years of experience in the IBM midrange and PC platforms. Chris is president of Evergreen Interactive Systems, a software development firm and creators of the iSeries Report Downloader. Chris is the author of The OS/400 and Microsoft Office 2000 Integration Handbook, The AS/400 TCP/IP Handbook, AS/400 Client/Server Programming with Visual Basic, and Peer Networking on the AS/400 (MC Press). He is also a nationally recognized seminar instructor. Chris can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..

Chris Peters has 32 years of experience with IBM midrange and PC platforms. Chris is president of Evergreen Interactive Systems, a software development firm and creators of the iSeries Report Downloader. Chris is the author of i5/OS and Microsoft Office Integration Handbook, AS/400 TCP/IP Handbook, AS/400 Client/Server Programming with Visual Basic, and Peer Networking on the AS/400. He is also a nationally recognized seminar instructor and a lecturer in the Computer Science department at Eastern Washington University. Chris can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Chris Peters available now on the MC Press Bookstore.

i5/OS and Microsoft Office Integration Handbook i5/OS and Microsoft Office Integration Handbook
Harness the power of Office while exploiting the i5/iSeries database.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  •  

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: