OLE Automation
Encyclopedia
In Microsoft Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

 applications programming, OLE Automation (later renamed by Microsoft
Microsoft
Microsoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions...

 to just Automation, although the old term remained in widespread use), is an inter-process communication
Inter-process communication
In computing, Inter-process communication is a set of methods for the exchange of data among multiple threads in one or more processes. Processes may be running on one or more computers connected by a network. IPC methods are divided into methods for message passing, synchronization, shared...

 mechanism based on Component Object Model
Component Object Model
Component Object Model is a binary-interface standard for software componentry introduced by Microsoft in 1993. It is used to enable interprocess communication and dynamic object creation in a large range of programming languages...

 (COM) that was intended for use by scripting languages – originally Visual Basic – but now are used by languages run on Windows. It provides an infrastructure whereby applications called automation controllers can access and manipulate (i.e. set properties of or call methods on) shared automation objects that are exported by other applications. It supersedes Dynamic Data Exchange
Dynamic Data Exchange
Dynamic Data Exchange is a technology for interprocess communication under Microsoft Windows or OS/2.- Overview :Dynamic Data Exchange was first introduced in 1987 with the release of Windows 2.0 as a method of interprocess communication so that one program can communicate with or control another...

 (DDE), an older mechanism for applications to control one another. As with DDE, in OLE Automation the automation controller is the "client" and the application exporting the automation objects is the "server".

Usage

Automation was designed with the ease of scripting in mind, so controllers often provide languages such as Visual Basic for Applications
Visual Basic for Applications
Visual Basic for Applications is an implementation of Microsoft's event-driven programming language Visual Basic 6 and its associated integrated development environment , which are built into most Microsoft Office applications...

 to end users, allowing them to control automation objects via scripts. Automation objects can be written in conventional languages such as C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, but the C++ syntax for COM (and therefore Automation) is complex and not very programmer-friendly. In contrast, languages such as Visual Basic
Visual Basic
Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...

 and Borland Delphi
Borland Delphi
Embarcadero Delphi is an integrated development environment for console, desktop graphical, web, and mobile applications.Delphi's compilers use its own Object Pascal dialect of Pascal and generate native code for 32- and 64-bit Windows operating systems, as well as 32-bit Mac OS X and iOS...

 provide a convenient syntax for Automation which hides the complexity of the underlying implementation.

Interfaces

An Automation object is a COM object implementing the IDispatch
IDispatch
IDispatch is the interface that exposes the OLE Automation protocol. It is one of the standard interfaces that can be exposed by COM objects. The I in IDispatch refers to interface...

 interface (for details on interfaces and calling conventions, see Component Object Model
Component Object Model
Component Object Model is a binary-interface standard for software componentry introduced by Microsoft in 1993. It is used to enable interprocess communication and dynamic object creation in a large range of programming languages...

). Automation objects are referred to as ActiveX objects, while an application that manipulates an ActiveX object is referred to as an ActiveX Client. This interface exposes four methods, the most important of which is Invoke. This method allows calling methods of a class by name, with an arbitrary number of parameters. Neither the name of the method nor the number (and exact types) of parameters need to be known at compile time, as it is the case for COM objects not supporting Automation; moreover, in scripting languages there is no "compile time" at all. This technique is called late binding
Late binding
Late binding is a computer programming mechanism in which the method being called upon an object is looked up by name at runtime. This is informally known as duck typing or name binding....

.

Most existing COM components are Automation-compliant and furthermore allow both late binding and traditional, compile-time early binding. This is achieved by implementing so-called dual interfaces, which are interfaces derived from IDispatch. Generally, both late and early binding expose the same functionality for Automation clients; languages such as Visual Basic and Delphi, as well as some C++ libraries, which provide a higher level of abstraction for COM, make sure that all Automation components created in these languages correctly duplicate their interfaces with late and early binding.

Generally, implementing early binding is more troublesome. Late binding is slower, but more reliable, as it does not require binary compatibility between versions of the same component. For late binding, a client only needs to know the name (or CLSID) of the desired object and the names and parameters of methods it actually uses, while for early binding, the client needs to know the complete definition and identifier (IID) for every interface requested, as well as the exact position of each method in the interface vtable. This is, however, more a problem of COM in general rather than Automation, as early binding relies on traditional COM calling conventions.

Automation servers may be implemented as single-use or multi-use. For the former, each client connects to an individual instance of the server, with an individual instance of its class factory. For the latter, many clients connect to a single server, sharing that server's class factory across all clients.

The servers for the automation objects may be either out-of-process executables or in-process DLL
Dynamic-link library
Dynamic-link library , or DLL, is Microsoft's implementation of the shared library concept in the Microsoft Windows and OS/2 operating systems...

s.

Type libraries

In order to automate an application, the developer of an automation controller must know the object model that is employed by the target application exporting activation objects. This requires that the developer of the target application publicly document its object model. Development of automation controllers without knowledge of the target application's object model is "difficult to impossible".
Because of these complications, Automation components are usually provided with type libraries, which contain metadata
Metadata
The term metadata is an ambiguous term which is used for two fundamentally different concepts . Although the expression "data about data" is often used, it does not apply to both in the same way. Structural metadata, the design and specification of data structures, cannot be about data, because at...

 about classes, interfaces and other features exposed by an object library. Interfaces are described in Microsoft Interface Definition Language. Type libraries can be viewed using various tools, such as the Microsoft OLE/COM Object Viewer (oleview.exe, part of the Microsoft Platform SDK
Microsoft Platform SDK
Microsoft Windows SDK, Platform SDK, and .NET Framework SDK are software development kits from Microsoft that contain header files, libraries, samples, documentation and tools required to develop applications for Microsoft Windows and .NET Framework....

) or the Object Browser in Visual Basic (up to version 6) and Visual Studio .NET. Type libraries are used to generate Proxy pattern
Proxy pattern
In computer programming, the proxy pattern is a software design pattern.A proxy, in its most general form, is a class functioning as an interface to something else...

/stub
Method stub
A method stub or simply stub in software development is a piece of code used to stand in for some other programming functionality. A stub may simulate the behavior of existing code or be a temporary substitute for yet-to-be-developed code...

 code for interoperating between COM and other platforms, such as Microsoft .NET and Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

. For instance, the .NET Framework SDK
Software development kit
A software development kit is typically a set of software development tools that allows for the creation of applications for a certain software package, software framework, hardware platform, computer system, video game console, operating system, or similar platform.It may be something as simple...

 includes tools that can generate a proxy .NET DLL to access Automation objects using both early binding (with information about interfaces extracted from a type library) and late binding (via IDispatch, mapped to the .NET Reflection API), with the built-in .NET-to-COM bridge called COM Interop
COM Interop
COM Interop is a technology included in the .NET CLR that enables COM objects to interact with .NET objects, and vice versa.COM Interop aims to provide access to the existing COM components without requiring that the original component be modified. It tries to make the .NET types equivalent to the...

. While Java lacks built-in COM support, toolsets like JACOB
Jacob
Jacob "heel" or "leg-puller"), also later known as Israel , as described in the Hebrew Bible, the Talmud, the New Testament and the Qur'an was the third patriarch of the Hebrew people with whom God made a covenant, and ancestor of the tribes of Israel, which were named after his descendants.In the...

 and jSegue can generate proxy source code (consisting of two parts, a set of Java classes and a C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 source for a Java Native Interface
Java Native Interface
The Java Native Interface is a programming framework that enables Java code running in a Java Virtual Machine to call and to be called by native applications and libraries written in other languages such as C, C++ and assembly.-Purpose and features:JNI enables one to write native methods to...

 DLL) from type libraries. These solutions only work on Windows.

Microsoft has publicly documented the object model of all of the applications in Microsoft Office
Microsoft Office
Microsoft Office is a non-free commercial office suite of inter-related desktop applications, servers and services for the Microsoft Windows and Mac OS X operating systems, introduced by Microsoft in August 1, 1989. Initially a marketing term for a bundled set of applications, the first version of...

, and some other software developers have also documented the object models of their applications. Object models are presented to automation controllers as type libraries, with their interfaces described in ODL
Object Description Language
Object Description Language was the original interface definition language created by Microsoft for specifying interfaces to be used in OLE Automation. It was a superset of the OMG IDL.Microsoft provided a utility mktyplib to compile ODL files....

.

Language support

Automation is available for a variety of languages, including, but not limited to:
  • ABAP
    ABAP
    ABAP , is a high-level programming language created by the German software company SAP...

  • C
    C (programming language)
    C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

  • C++
    C++
    C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

     (directly or via a library like MFC
    Microsoft Foundation Class Library
    The Microsoft Foundation Class Library is a library that wraps portions of the Windows API in C++ classes, including functionality that enables them to use a default application framework...

     or ATL
    Active Template Library
    The Active Template Library is a set of template-based C++ classes developed by Microsoft, intended to simplify the programming of Component Object Model objects. The COM support in Microsoft Visual C++ allows developers to create a variety of COM objects, OLE Automation servers, and ActiveX...

    )
  • Visual Basic
    Visual Basic
    Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...

     and Visual Basic for Applications
    Visual Basic for Applications
    Visual Basic for Applications is an implementation of Microsoft's event-driven programming language Visual Basic 6 and its associated integrated development environment , which are built into most Microsoft Office applications...

  • Delphi
  • Microsoft .NET languages
  • APL (most Windows versions)
  • Java
    Java (programming language)
    Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

     (only with third-party tools)
  • JScript
    JScript
    JScript is a scripting language based on the ECMAScript standard that is used in Microsoft's Internet Explorer.JScript is implemented as a Windows Script engine. This means that it can be "plugged in" to any application that supports Windows Script, such as Internet Explorer, Active Server Pages,...

     and VBScript
    VBScript
    VBScript is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. It is designed as a “lightweight” language with a fast interpreter for use in a wide variety of Microsoft environments...

  • Open Object Rexx
  • Perl
    Perl
    Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

  • PHP
    PHP
    PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

  • PowerBuilder
    PowerBuilder
    PowerBuilder is an integrated development environment owned by Sybase, a division of SAP. It has been in use since 1991, peaking around 1998 with around 100,000 users....

  • Python
    Python (programming language)
    Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

  • Ruby (via the 'win32ole' library included in the standard Ruby 1.8.x or later distribution)
  • Tcl
    Tcl
    Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...

  • Visual DataFlex
    Visual DataFlex
    Visual DataFlex is a 4GL windows programming language by Data Access, targeted at creating database and client-server type programs.- Architecture :Visual DataFlex has a 3-layer architecture:Bottom layer: At this level you have the database tables....

  • WinBatch
    Winbatch
    Winbatch is a Microsoft Windows scripting language developed by Wilson WindowWare. Its environment includes an interpreter and a code editor along with a dialog designer and optional compiler to create self-contained executables....


Examples

The following Perl code launches Microsoft Excel
Microsoft Excel
Microsoft Excel is a proprietary commercial spreadsheet application written and distributed by Microsoft for Microsoft Windows and Mac OS X. It features calculation, graphing tools, pivot tables, and a macro programming language called Visual Basic for Applications...

, loads an existing document, gets the values of four cells, exits the application, and then displays (from within Perl) the four values retrieved.

  1. This program illustrates controlling Excel from within Perl
  2. adapted from: http://blazonry.com/perl/xl_oleauto.php


use strict;
use warnings;

use OLE; # OLE.pm module

my $xlfile = "c:\\workingdir\\Perl\\test.xls"; # supply a test xls or csv
  1. Make OLE connection: this creates an instance of an Excel server

my $xl = CreateObject OLE 'Excel.Application' || die $!;
  1. Set application visibility: 1 = visible; 0 = not visible

$xl->{'Visible'} = 1;
  1. Open Excel file

my $book = $xl->Workbooks->Open($xlfile);
  1. Setup active worksheet

my $sheet = $book->Worksheets(1);
  1. Retrieve values from worksheet

my $a1 = $sheet->Range("A1")->{'Value'};
my $b1 = $sheet->Range("B1")->{'Value'};
my $a2 = $sheet->Range("A2")->{'Value'};
my $b2 = $sheet->Range("B2")->{'Value'};
  1. Close it up

$xl->ActiveWorkbook->Close(0);
$xl->Quit;

print $a1, " ", $b1, "\n"; #1st row
print $a2, " ", $b2, "\n"; #2nd row


The following Visual Basic 6 (or VBA) code launches Microsoft Excel
Microsoft Excel
Microsoft Excel is a proprietary commercial spreadsheet application written and distributed by Microsoft for Microsoft Windows and Mac OS X. It features calculation, graphing tools, pivot tables, and a macro programming language called Visual Basic for Applications...

, creates a new document, selects some cells, types "Hello World!" into cells A1:C6, and then shows the application window. It operates using late binding, but early binding can be enabled simply by changing the object type from Object (an alias for IDispatch) to Excel.Application, provided that the Excel type library is referenced in the project.


Dim excelApp as Object
Set excelApp = CreateObject("Excel.Application")
excelApp.Workbooks.Add
excelApp.Range("A1:C6").Select
excelApp.ActiveCell.Formula = "Hello World!"
excelApp.Visible = True


Here is sample code in C++, which just makes the window visible, using the pure COM API for late binding without other libraries or wrappers:


HRESULT hres;
CLSID clsid;
CLSIDFromProgID(L"Excel.Application", &clsid);
IDispatch *excelApp;

// Start Excel as a COM server in a separate process
hres = CoCreateInstance(clsid, 0, CLSCTX_LOCAL_SERVER, IID_IDispatch, reinterpret_cast(&excelApp));

if(FAILED(hres))
{
// error handling
}

DISPID dispidVisible;
OLECHAR *propertyName = "Visible";
hres = excelApp->GetIDsOfNames(IID_NULL, &propertyName, 1, LOCALE_SYSTEM_DEFAULT, &dispidVisible);

if(FAILED(hres))
{
// error handling
}

unsigned returnArg;
VARIANT varTrue;
DISPID rgDispidNamedArgs[1] = DISPID_PROPERTYPUT;
DISPPARAMS params = { &varTrue, rgDispidNamedArgs, 1, 1 };

// set the variant to a boolean true
varTrue.vt = VT_BOOL;
varTrue.boolVal = 0xFFFF;

// make the window visible: excelApp.Visible = True
hres = excelApp->Invoke(dispidVisible, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYPUT, params, 0, 0, &returnArg);

if(FAILED(hres))
{
// error handling
}

// ... use the object

// free the object
excelApp->Release;


Here is an example Ruby code using WIN32OLE library.


require 'win32ole'

excel = WIN32OLE.new('Excel.Application')
excel.visible = true
workbook = excel.Workbooks.Add;
worksheet = workbook.Worksheets(1);
worksheet.Range("A1:D1").value = ["North","South","East","West"];
worksheet.Range("A2:B2").value = [5.2, 10];
worksheet.Range("C2").value = 8;
worksheet.Range("D2").value = 20;

range = worksheet.Range("A1:D2");
range.select
chart = workbook.Charts.Add;

workbook.saved = true;

excel.ActiveWorkbook.Close(0);
excel.Quit;


Here is an example C++ code (doing the same as the Visual Basic code) using VOLE, a compiler-independent COM/Automation driver library:


using vole::object;
using vole::collection;

object excelApp = object::create("Excel.Application", CLSCTX_LOCAL_SERVER);
object workBooks = excelApp.get_property(L"Workbooks");

workBooks.invoke_method(L"Add");

object range = excelApp.get_property(L"Range", "A1:C6");

range.invoke_method(L"Select");

object activeCell = excelApp.get_property(L"ActiveCell");

activeCell.put_property(L"Formula", "Hello World!");

excelApp.put_property(L"Visible", true);


Here is an example C++ code (doing the same as the Visual Basic code) using MFC
Microsoft Foundation Class Library
The Microsoft Foundation Class Library is a library that wraps portions of the Windows API in C++ classes, including functionality that enables them to use a default application framework...

-provided wrappers for Excel 97:

  1. include "excel8.h"


// ...

OleVariant covTrue((short)TRUE), covFalse((short)FALSE), covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

_Application excelApp;

if(!excelApp.CreateDispatch("Excel.Application"))
{
// error handling
}

excelApp.GetWorkbooks.Add(covOptional);
excelApp.GetRange(COleVariant("A1"),COleVariant("C6")).Select;
excelApp.GetActiveCell.SetFormula("Hello World!");
excelApp.SetVisible(TRUE);


Finally, here is an example for PHP5:



$excelApp = new COM("Excel.Application") or die("Cannot create an Excel object");
$excelApp->Workbooks->Add;
$excelApp->Range("A1:C6")->Select;
$excelApp->ActiveCell->Formula = "Hello World!";
$excelApp->Visible = 1;

?>


In C# (and VB.NET with strict type checking) late binding is always explicit, producing code almost as complex as the pure C++ example. In contrast, early binding in .NET offers cleaner-looking code, like the other three examples (although the given examples implicitly involve late binding while .NET does not).

Name confusion

Automation objects do not necessarily use Microsoft OLE, which stands for Object Linking and Embedding
Object Linking and Embedding
Object Linking and Embedding is a technology developed by Microsoft that allows embedding and linking to documents and other objects. For developers, it brought OLE Control eXtension , a way to develop and use custom user interface elements...

 — currently only a subset of COM — although some of Automation objects (which are a special type of COM objects) can be used in OLE and/or ActiveX
ActiveX
ActiveX is a framework for defining reusable software components in a programming language-independent way. Software applications can then be composed from one or more of these components in order to provide their functionality....

 environments. The confusion has its roots in Microsoft's earlier (rather vague) definition of OLE, which was previously more or less a synonym of COM — to the point that the acronym "OLE" frequently appears in legacy COM code, like parts of the MFC
Microsoft Foundation Class Library
The Microsoft Foundation Class Library is a library that wraps portions of the Windows API in C++ classes, including functionality that enables them to use a default application framework...

library.

Object models for specific applications

— full printed documentation of the object model of Microsoft Office

External links

  • OLE Automation General paper on the introduction and problems implementing OLE.
  • "VOLE - A Neat C++ COM/Automation Driver" — an open-source, compiler-independent C++ COM Automation driver library, for use when having to drive IDispatch directly. VOLE is highly robust, fully encapsulates all "low-level" aspects of IDispatch, and is very flexible, taking and returning normal C++ types.
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK