17
Sun, Nov
2 New Articles

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

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • 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.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • 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

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • 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: