Distributed Object Systems
– 8 –
DCOM 2
Piet van OostrumOct 7, 2008
GDOS-8
COM (and some Corba)
I Dynamic Invocation
I Containment/Aggregation/Delegation I Automation
I Monikers
Piet van Oostrum GDOS-8 1
GDOS-8
Dynamic Invocation in COM
I Can Dynamic invocation in COM be done as in Corba?
I Use Request object instead of stub I marshalling/protocol remains the same
I NO!In case of inproc object there is no stub/skeleton involved
i.e. call is direct
I Dynamic invocation through the IDispatch interface I Servermust implementthe IDispatch interface
I Is used for dynamic programming languages (Visual Basic, scripting languages, . . . )
I Wizards can help you implement IDispatch
I IDispatch interface often uses special parameter types: VARIANT,BSTRING,SAFEARRAY
I These are just complicated struct/unions to represent Visual Basic datatypes.
Piet van Oostrum GDOS-8 2
GDOS-8
Dynamic Invocation
I The server object must implement this special IDispatch interface (compare Corba’s DSI)
I Every method that the server offers through IDispatch gets a number (index) called DISPID
I In Corba you use methodname, in COMnumber
I The server will usually switch on the DISPID
I GetTypeInfocan be called to get info about the types of the methods (if available – usually from a type library)
I Type Library= file containing compiled IDL (AST)
Piet van Oostrum GDOS-8 3
GDOS-8
Client side
I The client can then use this IDispatch interface
I So the client must be able to call at least one static interface I The client must doQueryInterfaceto get the IDispatch
interface
I methodGetIDsofNamesis used to couple names of methods
and DISPIDs
I It has an array of names as in parameter and an array of
DISPIDs as out parameter
I TheInvokemethod is used to make the call I The client calls theInvokemethod
I A specialVARIANTtype is used for the parameters I VARIANTcontains type info for the marshaller
I Visual Basic types can be used and some special structs
(BSTRING,SAFEARRAY,DATE,DECIMAL)
Piet van Oostrum GDOS-8 4
GDOS-8
Interfaces
I Multiple Interfaces
I If multiple dispinterfaces are defined by the object, one has to
be designated asdefault.
I This is what Visual Basic uses.
I TheQueryInterfaceforIDispatchwill give the default
interface
I The others can be obtained by explicitQueryInterface
I Dual Interface
I A dual interface is an interface that can be called both
statically and dynamically
I It inherits from IDispatch and adds also the static methods I This may be important for high performance applications
GDOS-8
IDL notation dispinterface
[uuid(3CFDB282-CCC5-11D0-BA0B-00A0C90DF8BC)] dispinterface IStat {
properties: methods:
[id(1)] void init();
[id(2)] void addItem(double item); [id(3)] double getAvg();
[id(4)] long getNum(); };
Piet van Oostrum GDOS-8 6
GDOS-8
IDL notation dual interface
[object,
uuid(3CFDB282-CCC5-11D0-BA0B-00A0C90DF8BC), dual
]
interface IStat: IDispatch [id(1)] HRESULT init();
[id(2)] HRESULT addItem([in] double item); [id(3)] HRESULT getAvg([out] double avg); [id(4)] HRESULT getNum([out] long num); };
Piet van Oostrum GDOS-8 7
GDOS-8
Contents
I Dynamic Invocation I Containment/Aggregation/Delegation I Automation I MonikersPiet van Oostrum GDOS-8 8
GDOS-8
Implementation inheritance in COM
I Microsoft literature about COM discourages inheritance I Fragile Base Class problem:
I Mostly for compiled languages
I Subclass is dependent of base class (superclass) I Later changes to base class may damage subclass if not
recompiled
I The size of objects (i.e. structs or classes) I The offsets to "visible" (public or protected) data I The offsets to the virtual functions in the vtable
I Instead of inheritance use Containment/Delegation or Aggregation
I Please note: In .NET one of the strong points is the possibility to inherit even across programming languages. But there are strong checks at load time.
Piet van Oostrum GDOS-8 9
GDOS-8
Containment or Delegation
Interface A IUnknown Interface B IUnknownOuter Object Inner Object
I Outer Object implements A methods and B methods (because interface A extends B)
I Outer object’s implementation of B methods just calls Inner object’s B methods
void m(int x) { b.m(x); }
I Inner Object is not aware of the special relationship I Inner Object can be considered as a helper object
Piet van Oostrum GDOS-8 10
GDOS-8
Aggregation
Interface A IUnknown Interface B IUnknown Inner Object Outer ObjectI Outer object puts inner object’s method pointer in its own method table
I Problem: normally Inner object would return its own IUnknown pointer if QueryInterface is done on interface B I Solution: When Outer object creates Inner object, it passes its
own IUnknown pointer as ‘Controlling Unknown’ CoCreateInstance(CLSID_CStat, pOuter, ...
GDOS-8
Inheritance and Delegation in Corba
I Delegation can be used when a programming language does not support multiple inheritance
n() A B m() n() C m() p()
Piet van Oostrum GDOS-8 12
GDOS-8
Delegation
class A { void m(); } class B { void n(); } class C { private A a; private B b; C(A a, B b) { this.a = a; this.b = b; } m() { a.m(); } n() { b.n(); } p() { ... } }Piet van Oostrum GDOS-8 13
GDOS-8
Inheritance problem
I The problem with this solution is that C cannot be used where an A or B is required.
I A solution is to use interfaces and implementation classes
interface A { ... } interface B { ... }
class A_impl implements A { ... } class B_impl implements B { ... } class C implements A, B
{
private A_impl a; // or private A a; private B_impl b; // or private B b; ... etc ...
}
or even interfaceCand classC_impl
Piet van Oostrum GDOS-8 14
GDOS-8
Corba Servant (Inheritance Model)
I InterfaceMyInterface
I Abstract InterfaceMyInterfaceOperations (generated by IDL compiler)
I SkeletonMyInterfacePOA
implementsMyInterfaceOperations I Servant extends Skeleton class
Skeleton Operations
implement.Servant
I Problem if you want Servant to extend other class
Piet van Oostrum GDOS-8 15
GDOS-8
Corba Delegation Model (Tie)
I Servant class doesn’t have to extend skeleton I Only implementMyInterfaceOperations I Servant can inherit from another class
I IDL compiler generates Tie class that inherits from skeleton I Tie class delegates to implementation class
I Tie+implementation = “actual servant”
Skeleton Operations
Servant
implement. Tie
Delegation
Piet van Oostrum GDOS-8 16
GDOS-8
Tie class
(generated by IDL compiler)
public class HelloPOATie extends HelloPOA {
public HelloPOATie(HelloOperations delegate) { this._impl = delegate;
} ...
public String sayHello () {
return _impl.sayHello(); // delegation } // sayHello
GDOS-8
Corba Delegation Model (Tie)
class HelloImpl extends SomeOtherClass implements HelloOperations ... method implementations as usual // Server class: create a servant.
HelloImpl helloImpl = new HelloImpl(); // create a tie, with servant being the delegate.
HelloPOATie tie = new HelloPOATie(helloImpl); // obtain the objectRef for the tie
// this step also implicitly activates the object Hello href = tie._this(orb);
Piet van Oostrum GDOS-8 18
GDOS-8
COM
I Dynamic Invocation I Containment/Aggregation/Delegation I Automation I MonikersPiet van Oostrum GDOS-8 19
GDOS-8
(OLE) Automation
I Automation (formerly known as OLE Automation) is a way to
scripta program from another program
I E.g. Microsoft Word: Open a document, insert some text and save it.
I Usually done from scripting languages, e.g. Visual Basic, Python, Ruby.
I Application must make its operations available as (Automation) COM interfaces (IDispatch). I Collection of interfaces known as OLE.
I For use in web browsers a stripped down collection is ActiveX.
Piet van Oostrum GDOS-8 20
GDOS-8
Visual Basic and COM
I Visual Basic (up to version 6)
I Developed as COM programming language I Seamless integration with COM
Dim statvar as Stat.Stat Dim statvar as Object
Set statvar = CreateObject("Stat") Set statvar = New Stat.Stat Dim statvar as New Stat.Stat statvar.init
statvar.AddItem 3.14 Set result = statvar.GetAvg
I When declared as Object uses runtime resolution
I When declared as specific class uses compile time resolution I Type info comes from Type Library (loaded at compile time or
runtime).
Piet van Oostrum GDOS-8 21
GDOS-8
Automation with Visual Basic
Dim Word As Object Dim Doc As Object Dim Spot As Object
Set Word = CreateObject("Word.Application") Word.Visible = True
Set Doc = Word.Documents.Add() Set Spot = Doc.Range(0, 0)
Spot.InsertBefore "Hello From Visual Basic" Doc.SaveAs "test.doc"
Doc.Close Word.Quit
Piet van Oostrum GDOS-8 22
GDOS-8
Early/Late Binding
I VB looks up the type info from the type library
I The Windows registry contains mapping from Program Id ("Word.Application") to Class Id
I The registry contains the location of the type library I Variables declared asObject(Dim Word As Object) must
be resolved at runtime I This is calledLate Binding.
I VB can also do the lookup at compile time: Early Binding:
I Register the type library at compile time I Use:Dim Word As New Word.Application
GDOS-8
Automation with Python
Can be used with ActiveState Python, or Standard Python + win32allextensions
from win32com.client import Dispatch word = Dispatch("Word.Application") word.Visible = True
doc = word.Documents.Add() spot = doc.Range(0, 0)
spot.InsertBefore("Hello from Python") doc.SaveAs("test.doc")
doc.Close() word.Quit()
Piet van Oostrum GDOS-8 24
GDOS-8
Python/COM observations
I Python is very simple to use for Automation
I Python looks up the type library and makes all decisions at runtime
I You can even do it interactively
I This makes development and try-out very easy I You can also run themakepyscript
I This generates additional Python files containing the methods of the interface (like stubs)
I At runtime these are used if available I This is comparable to Early Binding (faster)
Piet van Oostrum GDOS-8 25
GDOS-8
Java and (D)COM
I Originally with Microsoft Java Virtual Machine (now defunct) I Visual J++ 6.0 or MS Java SDK
I Almost transparent
I Java virtual machine does all the administration I Build Interface pointers, refcounts etc.
I Special language extension is used (in specially formatted comments)
I Jactivexprogram generates interface and class files from TLB (Type Library)
I Wrapper classes: CCW (Com callable wrapper) to call Java from COM, JCW (Java callable wrapper) to call COM from Java
I J-Integra and EZ JCom are commercial implementations of
the COM protocol in Java (any Java).
Piet van Oostrum GDOS-8 26
GDOS-8
J-Integra example
import excel.*; ...
Application app = new Application(); app.setVisible(true);
Workbooks workbooks = app.getWorkbooks(); Workbook workbook = workbooks.add(null); Sheets worksheets = workbook.getWorksheets();
Worksheet sheet = new Worksheet(worksheets.add(null, null, null, null)); Range range = sheet.getRange("A1:C3", null); Object[][] newValue = {
{"abcd", new Boolean(false), new Double(98.0/12)}, {new Date(), new Integer(5454), new Float(22.0/7)}, {new Boolean(true), "xyzt", new Date() } };
range.setValue(newValue); // Update the spreadsheet
Piet van Oostrum GDOS-8 27
GDOS-8
Python – OpenOffice.org automation
Python as a separate process: Script programmer explicitely
writes application startup code. Startup code must connect to Ooo. Code executes slow, as every call to OOo is going through the inter process bridge.
Python process must be started separately.
OOo listens on an inter process resource (socket or named pipe). This must be switched on seperately either on command line or with the OOo configuration. OOo Process Python Process PyUNO Runtime Python Code
Piet van Oostrum GDOS-8 28
GDOS-8
Python – OpenOffice.org automation
Python embedded in OpenOffice.org process:
OOo Process
PyUNO Runtime
Python UNO
component
Script must be written as a PyUNO component (adding a coding overhead)
GDOS-8
Py-UNO example
import uno
# get the uno component context from the PyUNO runtime localContext = uno.getComponentContext()
# create the UnoUrlResolver
resolver = localContext.ServiceManager \ .createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext )
# connect to the running office
ctx = resolver.resolve( "uno:socket,host=localhost,\ port=2002;urp;StarOffice.\ ComponentContext" ) smgr = ctx.ServiceManager
Piet van Oostrum GDOS-8 30
GDOS-8
Py-UNO example
# get the central desktop object
desktop = smgr.createInstanceWithContext(
"com.sun.star.frame.Desktop",ctx) # access the current writer document
model = desktop.getCurrentComponent() # access the document’s text property text = model.Text
# create a cursor
cursor = text.createTextCursor() # insert the text into the document
text.insertString( cursor, "Hello World", 0 )
Piet van Oostrum GDOS-8 31
GDOS-8
Mac OS X Applescript
tell application "Microsoft Word" set newDoc to make new document
insert text "Hello from Applescript" at end of text object of active document save as newDoc file name "test.doc"
end tell
Piet van Oostrum GDOS-8 32
GDOS-8
COM
I Dynamic Invocation I Containment/Aggregation/Delegation I Automation I MonikersPiet van Oostrum GDOS-8 33
GDOS-8
COM Monikers
I Monikersare (persistent) ‘names’ for persistent objects I If you want to revive a persistent object (e.g. Excel
worksheet):
I Create an object of that class (CoCreateInstance) I Force the object to load its persistent data (IPersist...) I There can be many parameters to specify where the data
comes from, e.g file name, which part of an object
I E.g. linked worksheet in Word document: filename and range
of the worksheet
I How does Word know what parameters to give and what they mean (especially if it is an unknown class)?
I The object needs to have this information itself I Monikers are used to encapsulate this data
I Word doesn’t have to know all the interfaces of all possible
linked objects
Piet van Oostrum GDOS-8 34
GDOS-8
Moniker Implementation
I Client only deals with theIMonikerinterface
I E.g. in Object linking the moniker is stored in the structured document
I InterfaceIMoniker:
I BindToObjectbinds the moniker to an object
I BindToStoragebinds the Moniker to the Storage of the object I 13 more methods
I Also inherits fromIPersistsStream(4 methods) I which inherits fromIPersist(1 method)
GDOS-8
Moniker use
1 pointer method call/return 1. client calls IMoniker:: BindToObject(IID_A) A 4. Client invokes methods2. Moniker instantiates Object Client
Server
Moniker
the object and tells it to load its persistent data interface A is
returned via 3. Pointer to
moniker
Piet van Oostrum GDOS-8 36
GDOS-8
Moniker Examples
I File Moniker: contents is a file, persistent data is file name I Item Moniker: describes an item in a composite object, e.g.
worksheet in an Excel workbook, persistent data is the item’s name and the moniker of the object in which it is contained I Composite Moniker: groups together other monikers, e.g. File Moniker, worksheet item and range item. Persistent date: the component monikers
I Java Moniker: describes a Java class (now defunct):
Dim dat As Object
Set dat = CreateObject("java:java.util.Date") Dim s As String
s = dat.toString
Piet van Oostrum GDOS-8 37
GDOS-8
Composite Moniker
IMoniker moniker
File moniker Item moniker Item moniker IMoniker IMoniker IMoniker Client Word R1C1:R5C4 Grades.xls Sheet1 Composite
Piet van Oostrum GDOS-8 38
GDOS-8
COM Structured Storage
I Structured Storageis used forcompound documents I These documents can contain other (sub)documents I E.g. a Word document containing an Excel sheet
I Each subdocument can be accessed more or less independently I COM structured documents work like a filesystem within a file I It hasstreams(file-like) andcontainers(directory-like) I InterfaceIStreamfor file-like objects
I Read,Write,Seek. . . methods
I InterfaceIstoragefor thecontainers
I CreateStream,OpenStreamfor Streams in the Storage I CreateStorage,OpenStoragefor sub-storages I methods for renaming, destroying, copying and moving I Transaction support (Commit,Revert)
I Setting the class of an object, getting information . . .
I Other interfaces to deal with persistence
Piet van Oostrum GDOS-8 39
GDOS-8
Structured Storage in general
I Apple and IBM worked together on OpenDoc I compound document architecture
I document consists of parts
I different parts can have different part editors I part editors work in a part of the visible window I parts can have different presentations
I parts can have different versions I Now abandoned (sources are available)
Piet van Oostrum GDOS-8 40
GDOS-8
Example
OpenDoc document
•
Consists of document parts
- Each having its own part editor - Which editor is user configurable
GDOS-8
Different representations
Distributed Object Systems 31/03/98 © Atze Dijkstra
OpenDoc 14 Dept. of Comp.Science, UU
Presentations
•
Part can have different presentations
•
Part info
-
Presentation data
-
Can be stored with the frame
•
View type
-
Determines the basic kind of presentation
Piet van Oostrum GDOS-8 42
GDOS-8
What is the problem?
I Putting parts together in a single document
I Reinventing the filesystem within a file I Better use the real filesystem I Or make mountable filesystems I No need to rewrite applications I Ship a document in a zip file
I Versioning
I Use existing tools, like CVS, subversion
I Contra: not integrated with compound documents
I Simultaneous access
I Is usually done with database systems
I Maybe file access should be upgraded to include transactions I Can be done with an additional Transactions layer