# Automation in Delphi COM Programming

## In-Process Automation Servers

The first automation server we're going to develop is a simple in-process automation server. You should remember from Chapter 2 that in-process servers execute in the same address space as the client application.

### Example: Unit Conversion Server

This automation server will be able to convert between different area measurements. It can convert between square meters, square centimeters, square yards, square feet, square inches, square kilometers, square miles, and acres. You've already seen the method that will be responsible for the conversion, which appears as follows:

`function Convert(Quantity: Double; InUnit: Integer; OutUnit: Integer): Double; safecall;`

In a nutshell, Convert converts a given quantity from the unit of measure designated by InUnit to the unit of measure designated by OutUnit. The actual code that performs the conversion is quite simple, and is shown in the following example:

```const
auSquareMeters = \$00000000;
auSquareCentimeters = \$00000001;
auSquareYards = \$00000002;
auSquareFeet = \$00000003;
auSquareInches = \$00000004;
auSquareKilometers = \$00000005;
auSquareMiles = \$00000006;
auAcres = \$00000007;
function TUnitAuto.Convert(Quantity: Double; InUnit,
OutUnit: Integer): Double;
const
AreaFactor: Array[auSquareMeters .. auAcres] of Double =
(10000.0, 1.0, 8361.2736, 929.0304, 6.4516, 10000000000.0,
25899881103.4, 40468726.0987);
begin
Result := Quantity * AreaFactor[InUnit] / AreaFactor[OutUnit];
end;```

The AreaFactor array contains the factors necessary to convert between a given unit of measure and square centimeters. For example, one square meter is 10,000 square centimeters, and one acre is 40,468,726.0987 square centimeters. The Convert function simply converts from InUnit to square centimeters, and then from square centimeters to the OutUnit.

Now that you know how the process works, let's create an automation server to expose this functionality.

1. Select File, New from Delphi's main menu. In the ActiveX tab of the Object Repository, select the ActiveX Library icon. So far, the steps are identical to those we took when we created an in-process COM server.

2. Select File, New from the main menu again, and in the ActiveX tab of the Object Repository, select Automation Object. Delphi displays the Automation Object Wizard, shown in Figure 4.2.

Figure 4.2
The Automation Object Wizard.

1. Enter a Class Name of AreaUnitConverter, and click OK. Delphi creates a unit for the class, and also creates a type library. The type library editor will automatically be displayed.

2. Click IAreaUnitConverter in the Object List. Notice in the Information Pane that the IAreaUnitConverter interface descends from IDispatch (Figure 4.3).

We already know what the Convert method needs to do, so let's add it to the interface.

Figure 4.3
The Type Library Editor.

1. Click the New Method icon on the toolbar, and name the method Convert. Notice that in the Information Pane, Delphi has assigned a dispid of 1 to this method.

2. Click the Parameters tab, and set the Return Type to Double. Now add a parameter named Quantity, of type Double. Add an Integer parameter named InUnit and another Integer parameter named OutUnit.

When you're finished, your screen should look like Figure 4.4.

Now, rather than forcing users of this automation server to remember that 0 means square meters and so on, let's add an enumeration to the type library.

Figure 4.4
The Type Library Editor after adding a method.

1. Click the New Enumeration button on the toolbar. Name the enumeration AreaUnit. Now click the NewConst button and add a constant named auSquareMeters. Do the same for auSquareCentimeters, auSquareYards, auSquareFeet, auSquareInches, auSquareKilometers, auSquareMiles, and auAcres. Delphi will automatically assign the values zero through seven to the enumeration constants.

2. Click the Refresh Implementation button on the type library toolbar to ensure that the Delphi code reflects the additions made to the type library. You can now close the Type Library Editor.

3. Save the Delphi unit as AreaUnit.pas, and the project as UnitSrv.dpr. Now flesh out the Convert method so it appears as follows:

```function TUnitAuto.Convert(Quantity: Double; InUnit,
OutUnit: Integer): Double;
const
AreaFactor: Array[auSquareMeters .. auAcres] of Double =
(10000.0, 1.0, 8361.2736, 929.0304, 6.4516, 10000000000.0,
25899881103.4, 40468726.0987);
begin
Result := Quantity * AreaFactor[InUnit] / AreaFactor[OutUnit];
end;```

That's all we need to do for this server. Compile it to make sure you didn't make any typos, and then select Run, Register ActiveX Server to register the server with the Windows registry.

I'm not going to bother listing the source code for the server, because you've already seen most of it, and what you have not seen, Delphi automatically created for you. Now we can concentrate on writing a client application to access the server.

Note - You might be thinking that this process seemed entirely too easy. We didn't even press Ctrl+Shift+G to generate a GUID for the IAreaUnitConverter interface. The fact is that we've done all the work required to write a dual-interface automation server. Delphi's wizard automatically generated the necessary GUIDs for us.

You might have noticed that it was even easier to create this COM automation server than it was to create the plain COM servers in Chapter 2. When I write COM code, I almost always create automation servers. They're a snap to create, and they're much more flexible than standard COM objects.

### CreateOleObject and GetActiveOleObject

Earlier, I showed you how CreateOleObject is used to start a new instance of an automation server. CreateOleObject is declared in the file comobj.pas as follows:

```function CreateOleObject(const ClassName: string): IDispatch;
var
ClassID: TCLSID;
begin
ClassID := ProgIDToClassID(ClassName);
OleCheck(CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
CLSCTX_LOCAL_SERVER, IDispatch, Result));
end;```

As you can see, this function first obtains the GUID of the class that we're creating. Then, it passes that GUID to CoCreateInstance. I discussed CoCreateInstance in Chapter 2. ProgIDToClassID is basically a wrapper around the Windows API called CLSIDFromProgID. So, in a nutshell, CreateOleObject works similarly to CreateComObject, except CreateOleObject takes a class name as a parameter instead of a GUID.

However, CreateOleObject always creates a new instance of a given server. What if you want to connect to an already running instance of a server? Or maybe you do not know whether the server is running or not. You'd like to start it if it is not running, and connect to it if it is.

GetActiveOleObject can be used to obtain a reference to a server that is running in memory. In Chapter 2, I discussed the Running Object Table in Windows, which tracks all active COM objects. GetActiveOleObject looks in the Running Object Table to see if the given server is running. If it is, it returns a reference to the IDispatch interface on that server. If the server is not running, GetActiveOleObject raises an exception.

With that information in mind, the following procedure will start a new copy of Word if it isn't running, and will connect to an already-running copy if it is:

```procedure StartOrLinkToWord;
var
V: Variant;
begin
try
V := GetActiveOleObject('Word.Basic');
except
V := CreateOleObject(Word'.Basic');
end;

// Do something with V here...
end;```

### Example: Unit Conversion Client

Now we can concentrate on writing a client program to access the automation server we just created. Figure 4.5 shows the main form of the UnitCli application at runtime.

As you can see, this program's interface is composed of six buttons. The left column of buttons creates and accesses the automation server in each of the three possible ways: by interface, by variant, and by dispinterface. The right column of buttons operates the same as the left column, except it makes 100,000 calls in a row for timing purposes.

Figure 4.5
UnitCli performs time tests on interfaces, dispinterfaces, and variants.

The code required to access the server is small, in all three cases. Let's view an example of the code for accessing the server through an interface first.

```procedure TForm1.btnInterfaceClick(Sender: TObject);
var
I: IUnitAuto;
begin
I := CoUnitAuto.Create;
ShowMessage(FloatToStr(I.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;```

You've seen similar code in Chapter 2. The call to CoUnitAuto creates an instance of the automation server, and I.Convert converts 1.0 square meters to square centimeters. Do not forget that due to reference counting, the server is automatically destroyed at the end of the procedure.

Now let's look at accessing the same server through a variant.

```procedure TForm1.btnVariantClick(Sender: TObject);
var
V: Variant;
begin
V := CreateOleObject('UnitSrv.UnitAuto');
ShowMessage(FloatToStr(V.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;```

This code is very similar to the code required to access the server through an interface. The first line of code makes a call to CreateOleObject to create an instance of the server. You're probably wondering how I knew to use UnitSrv.UnitAuto as the class name to pass to CreateOleObject. Delphi creates this string for you by concatenating the name of the server, a dot, and the name of the CoClass. For reference, the type library for the UnitSrv server is shown in Figure 4.6.

As you can see, the name of the library is UnitSrv. The CoClass is highlighted in the Object List, and is named UnitAuto. Therefore, the classname for the object is UnitSrv.UnitAuto.

A second method you can use to determine the class name of the server is to look up the GUID in the Windows Registry. The GUID for UnitAuto is {A1E420C3-F75F-11D2-B3B9-0040F67455FE}. In the Registry, you'll see an entry like that shown in Figure 4.7.

Figure 4.6
UnitSrv type library.

Figure 4.7
UnitAuto entry in RegEdit.

You cannot use these methods if you are using somebody else's automation server that might not have been created in Delphi, or if you do not know the GUID of the object in question. In those cases, the documentation for that server should give you the class name(s) available for you to use.

After CreateOleObject works its magic and stores a reference to the automation server in the variant V, we can make calls to that server just as if we were using an interface. As I explained before, the internal mechanism for making variant calls is considerably different (and slower) than that used for interfaces.

The final method for accessing the automation server is through a dispinterface.

```procedure TForm1.btnDispInterfaceClick(Sender: TObject);
var
DI: IUnitAutoDisp;
begin
DI := CoUnitAuto.Create as IUnitAutoDisp;
ShowMessage(FloatToStr(DI.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;```

As you can see, this code is almost identical to the code used for interfaces. The only difference is that the interface obtained through CoUnitAuto.Create is converted to a dispinterface.

Listing 4.1 shows the code for the main form of the client application.

#### Listing 4.1  UnitCli Application—MainForm.pas

```unit MainForm;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

type
TForm1 = class(TForm)
btnVariant: TButton;
btnInterface: TButton;
btnDispInterface: TButton;
btnTimeInterface: TButton;
btnTimeVariant: TButton;
btnTimeDispInterface: TButton;
lblInterface: TLabel;
lblVariant: TLabel;
lblDispInterface: TLabel;
procedure btnVariantClick(Sender: TObject);
procedure btnInterfaceClick(Sender: TObject);
procedure btnDispInterfaceClick(Sender: TObject);
procedure btnTimeInterfaceClick(Sender: TObject);
procedure btnTimeVariantClick(Sender: TObject);
procedure btnTimeDispInterfaceClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

uses
ComObj, UnitSrv_TLB;

{\$R *.DFM}

procedure TForm1.btnV
ariantClick(Sender: TObject);
var
V: Variant;
begin
V := CreateOleObject('UnitSrv.UnitAuto');
ShowMessage(FloatToStr(V.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;

procedure TForm1.btnInterfaceClick(Sender: TObject);
var
I: IUnitAuto;
begin
I := CoUnitAuto.Create;
ShowMessage(FloatToStr(I.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;

procedure TForm1.btnDispInterfaceClick(Sender: TObject);
var
DI: IUnitAutoDisp;
begin
DI := CoUnitAuto.Create as IUnitAutoDisp;
ShowMessage(FloatToStr(DI.Convert(1.0, auSquareMeters, auSquareCentimeters)));
end;

procedure TForm1.btnTimeInterfaceClick(Sender: TObject);
var
I: IUnitAuto;
Count: Integer;
Dbl: Double;
T1, T2: DWord;
begin
I := CoUnitAuto.Create;
T1 := GetTickCount;
for Count := 1 to 100000 do
Dbl := I.Convert(1.0, 0, 1);
T2 := GetTickCount;
lblInterface.Caption := IntToStr(T2 - T1) + ' ms';
end;

procedure TForm1.btnTimeVariantClick(Sender: TObject);
var
V: Variant;
Count: Integer;
Dbl: Double;
T1, T2: DWord;
begin
V := CreateOleObject('UnitSrv.UnitAuto');
T1 := GetTickCount;
for Count := 1 to 100000 do
Dbl := V.Convert(1.0, auSquareMeters, auSquareCentimeters);
T2 := GetTickCount;
lblVariant.Caption := IntToStr(T2 - T1) + ' ms';
end;

procedure TForm1.btnTimeDispInterfaceClick(Sender: TObject);
var
DI: IUnitAutoDisp;
Count: Integer;
Dbl: Double;
T1, T2: DWord;
begin
DI := CoUnitAuto.Create as IUnitAutoDisp;
T1 := GetTickCount;
for Count := 1 to 100000 do
Dbl := DI.Convert(1.0, auSquareMeters, auSquareCentimeters);
T2 := GetTickCount;
lblDispInterface.Caption := IntToStr(T2 - T1) + ' ms';
end;

end.```

This application can access our server either through an interface, a dispinterface, or IDispatch. A real application would simply choose one of the three methods. My purpose in showing all three methods is two-fold:

1. I want you to see how to use each method in your own applications.

2. This program performs some timing tests to show you the relative times for each method.

If you'll refer back to Figure 4.5, you'll see the timing results on my own computer. These values represent the time required to call the Convert method 100,000 times.

As you can see, interfaces are by far the fastest way to call a method on an automation server. Variants are more than an order of magnitude slower, and dispinterfaces lie somewhere in between.

By now, you should be familiar with in-process Automation servers. However, in-process Automation servers are not always appropriate. If you want to create COM servers that run in a separate address space from the client application, you'll need to create an out-of-process Automation server. The next section will guide you through the creation and uses of out-of-process Automation servers.

### InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

## Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

## Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

### Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

### Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

### Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

### Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

### Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

### Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

## Other Collection and Use of Information

### Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

### Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

### Do Not Track

This site currently does not respond to Do Not Track signals.

## Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

## Children

This site is not directed to children under the age of 13.

## Marketing

Pearson may send or direct marketing communications to users, provided that

• Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
• Such marketing is consistent with applicable law and Pearson's legal obligations.
• Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
• Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

## Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

## Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

## Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

## Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

## Sharing and Disclosure

Pearson may disclose personal information, as follows:

• As required by law.
• With the consent of the individual (or their parent, if the individual is a minor)
• In response to a subpoena, court order or legal process, to the extent permitted or required by law
• To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
• In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
• To investigate or address actual or suspected fraud or other illegal activities
• To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
• To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
• To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.