Post on 30-Dec-2015
1Chapter :CCCCCCCC CCCCCCC CCCCCCC
By Noppadon Kamolvilassatian Dept. of Computer Engineering, Prin
ce of Songkla University Source: Mastering Visual Basic 5, Mi
crosoft Corporation
CCCCCCCCCC
• Animation• Explain the major constructs of COM.• Explain the major constructs of Automation.• Create a client application that can man
ipulate other applications through Auto mation, use multiple interfaces on an ob
ject, and receive notifications from a server.
Outline
• The Component Object Model (COM)• Implementing Automation• Characteristics of Server Components• Creating a Client in Visual Basic• Creating a Client that Uses Microsoft Excel
CCCCCC CCCCC CCCCC()
• Overview of COM• Advantages of Using COM• The COM Specification• Using Interfaces• The IUnknown Interface• Client and Server Communication
Overview of COM
• Component: A unit of executable code that provides functionality.
COM specifies how components are created and how client applications connect to com
ponents.• Object: A combination of code and data tha
t can be treated as a unit.• Automation: Part of the COM specification
that defines a standard method for creating components and using objects.
Advantages of Using COM• - Binary Compatibility and Cross Platform DevelopmentCOM is independent of the development language and operating system.
• Code ReusabilityComponent technology enables reuse of objects in a variety of applications without knowledge about the implementations of objects.
• Version ControlNew functionality can be added to a component (by adding or changing the implementation of an interface) without affecting clients that already use the component.
The COM Specification
The COM specification defines:– How an object is created from a component.– How a client accesses features of the object.– The object's responsibility for destroying itself whe
n it is no longer in use.
All of these activities are handled by interf aces, which make using a server much e asier than before.
CCCCC CCCCCCCCCC
Interfaces are groups of functions that pro vide connection points.
• Interfaces provide standardized access t o the methods and properties (functiona
lity).• They are a contract that ensures consist
ent access to functionality.• They structure that access so that serve
rs are easier to use.
CCCCC CCCCCCCCCC
CCCCC CCCCCCCCCC A credit card object with two interfaces, IRetail and IManager , that provide functionality to
a retail store client and a credit manager client.
The IUnknown Interface
• The COM specification requires the follo wing functionality of all objects.
– The object must be able to keep track of the number of connections made to it. When no l
onger in use, it must be able to destroy itself.– The object must be capable of being queried
by a client for additional interfaces that it m ay support.
• In order to provide this functionality, all - objects have a built in interface named I
Unknown .
Funct i ons of t he I Unknown Int er f ace• The IUnknown interface has three func
tions.• The functions AddRef and Release kee
p track of the creation and destruction o f the object
• QueryInterface lets clients query for ot her interfaces provided by the object.
Client and Server Communication• COM supports three types of objects: -inprocess (DLL), - -out of process (EXE in se
parate process), and remote (DLL or EX E on a different machine via Distributed
COM or DCOM)• You use the exact same code to hook up
- - - to an in process, out of process, or remo te object.
Client and Server Communication• A client and an -in process server share t
he same address space.• A client and an - -out of process server has
to communicate across the process boundary.• The communication between a client an
d a remote server is even more complex.
COM and the Registry
• For a component to become available fo r clients, it must register itself with the
operating system. It updates a section in the system registry.
• At run time, the client (in conjunction wi th COM) uses the information in the regi
stry to call the server component.• Animation
Implementing Automation
• Automation is a technology for manipulating objects that are defined by an application or library from outside the application.
• Automation is the part of COM that enables objects to be created and programmed by cli
ents in a standard way.• Automation works through a standard interf
ace known as IDispatch . This interface expor ts any number of properties and methods su
pported by an object.
Type Libraries• Clients get information about Automation objects fro
m a server by inspecting the server component's type library. Also known as an object library.
– Interfaces supported by the object.
– The properties, methods, and events provided by the object.
– The return types and parameters types of the object's methods and events.
– The Dispatch IDs these methods and properties use.
– The name of the Help file and Help topics.
The Object Browser
• An Object Browser is a tool that lets you view the methods and properties of an A
utomation object.
• Demonstration
Object Models
• When a server is designed, the objects t hat it offers can be structured into an ob ject model.
• An object model organizes the objects in the server into a hierarchy that represe nts which objects contain other objects.
• This structure makes the server easier t o use.
CC CCCCC CCCCCC CCCCC
The IDispatch Interface
• The dispatch interface, IDispatch , is a st andard Automation interface designed f
or exposing component methods and pr operties to a client.
• This interface contains four functions.• The functions GetTypeInfoCount and GetTypeInfo obtain information about the i
nterfaces, methods, and properties that a component supports.
The IDispatch Interface
• GetIDsOfNames takes one or more prop erties and/or methods, and returns their
dispatch ID (dispID ) values as defined in the type library.
• Invoke takes a dispID and a pointer to a n array of parameters, and causes the o
bject to execute the associated property or method
Binding
• Animation on how late binding works
Characteristics of Server Component• Determining Where Server ComponentsRun• Notifying Clients
C CCCCC CCCCC C CCCC CCCCCC CC mponents Run
• -In process– - Implemented as a dynamic link library (DLL
).– Run in the same process space as its client application.– Most efficient communication
C CCCCC CCCCC C CCCC CCCCCC CC mponents Run
• - -Out of process– Implemented as an executable file.– Run in its own process space.– --Communication across process boundaries
- slower than an in process server.– - - A single instance of an out of process compo
nent can service many clients, share global dta, and insulate other client applications fr
om a client’s problem.
C CCCCC CCCCC C CCCC CCCCCC CC mponents Run
• Remote– - - Out of process components, located on a sep
arate machine.– --Communication overhead is very high slowest.– Allow processing on a more powerful computer.– The component can also be located closer to
the work it is doing (such as located closer t o a remote database).
CCCCCCCCC CCCCCCC• I f you wanted the component to perform a task tha
t you knew will need several minutes to complete, you would notify the client asynchronously when t
he server completed some task. Use events or callb acks to notify.
Creating a Client in Visual Basic
1. Set a reference to the type library of a component.
2 . Declare an object variable. 3. Create an object. 4. Use the object’s methods and properties.
Setting References
1. On the Project menu, click References.
2. In the References dialog box, select the
type library you want to connect to, and then click OK.
Declaring Object Variables
• Generic Object VariablesDim x As Object
• Specific Object VariablesDim ex as Excel.Application
• Specific variable declarations give bette r performance, and enable Visual Basic t o display data about the available metho
ds and properties.
Creating Objects
• Using the CreateObject FunctionDim objMyObject as Project1.Class1Set objMyObject = CreateObject("Project1.Class1")
• Using the New Keyword with a Set statementDim objMyObject as Project1.Class1Set objMyObject = New Project1.Class1
• The second method is more efficient in so me cases.
Using Automation Objects
• To invoke the methods and properties of the object you have created, use the dot
(.) operator.
object.[method]
Receiving Notification from S erver: Events
• When building a client, you need the kn ow which events are generated by the c
omponent, and implement each event wi th an event handler
Receiving Notification from Ser ver: Events
• First, declaring the event interfacePublic WithEvents obj as Server.Object
• Second, implement the event handlersPrivate Sub obj_Event1()' Take some action based on Event1.
End Sub
Private Sub obj_Event2(vNewValue As Variant)' Take some action based on Event2.
End Sub
Creating a Client that Uses Micro soft Excel
How to:• Use workbooks and charts.• Use Automation to create an instance of
Microsoft Excel, and then manipulate so me of its object’s methods and properties.
• Get and set property values to create and manipulate a chart object.
Demonstration
The Microsoft Excel Object MoCCC
The Microsoft Excel Object MoCCC• Use the dot (.) operator to reference objects
xl.Workbooks("BOOK1.XLS").Worksheets("SHEET1").Range("A1").Value = 5
• Use the Parent property to reference an object that is one level higher.
xlwb.Parent 'refers to the Application object
The Microsoft Excel Object MoCCC• Create object variables to reference to objects t
hat you use repeatedly.Dim xl as Excel.ApplicationDim xlSheet as Excel.WorksheetSet xl = CreateObject("Excel.Application")Set xlSheet = xl.Workbooks("BOOK1.XLS").Worksheets("SHEET1")
xlSheet.Range("A1").Value = 5
• Set a reference to an object by name of by index.set xlwb = xl.Workbooks("MYBOOK.XLS")set xlwb = xl.Workbooks(1)
• Creating an Instance of Microsof t Excel• Set a reference to the MS Excel type library:
-- -- 50Project >References >Microsoft Excel . Object Li.
• Using the New KeywordDim xl as Excel.ApplicationDim xlchart as Excel.ChartDim xlsheet as Excedl.Worksheet
set xl = New Excel.Applicationset xlchart = New Excel.Chartset xlsheet = New Excel.Worksheet
• Close Microsoft Excelxl.Quit
Using Methods in MS Excel
• Add a new workbook to the Workbooks collection
xl.Workbooks.Add ()
• Open a specific workbookxl.Workbooks.Open "c:\book1.xls "
Using Methods in MS Excel
• Error handling when opening a workbookDim xl as Excel.ApplicationDim xlwb as Excel.WorkBookOn Error Resume Nextset xl = CreateObject("Excel.Application")set xlwb = xl.Workbooks.Open ("c:\book1.xls")If Err <> 0 ThenMsgbox "Unable to open workbook."Unload Me
End If
Using Methods in MS Excel
• Close the active workbookxl.ActiveWorkbook.Close SaveChanges := False
• Close the workbook Book1.xlsxl.Workbooks("BOOK1.XLS").Close SaveChanges :=False
Getting and Setting Values
set xlsheet = _ xlapp.Workbooks("Book1").Worksheets("Sheet1")xlsheet.Range("A1").Value = 5xlsheet.Range("myrange").Value = 10
Getting and Setting Values
set xl = CreateObject("Excel.Application")' Explicitly state the exact hierarchy.xl.Workbooks("x.xls").Worksheets("s").Range("A1")
.Value = 5
' Assume the current active workbook and worksheet.
xl.Range("A2").Value = 5
' Establish object variable to reference objects.Set wb = xl.Workbooks("source.xls")Set ws = wb.Worksheets("sheet1")Set rg = ws.Range("A1")rg.Value = 5
Using the Charts Collection
• Select a series of cells on a worksheet and crea te a chart
xlsheet.Range("A1:D4").Selectset xlc = xl.Charts.Add()xlc.Type = xl3DColumn
• Set a reference to an existing chart, then chan ge the type of chart
set xlc = xl.workbooks("bk1.xls").Charts("mycht")
xlc.Type = xl3DColumn
Using the Charts Collection
Sub cmdCreateChart_Click()Dim xl as Excel.Application
Dim xlc as Excel.Chart
Set xl = CreateObject("Excel.Application")
xl.Visible = True
xl.Workbooks.Add
xl.Range("A1").Value = 3
xl.Range("A2").Value = 2
xl.Range("A1:A2").Select
Set xlc = xl.Charts.Add()
xlc.Type = xl3DColumn
End Sub
Lab (Demonstration)
Exercise 1: Controlling Microsoft Excel
In this exercise, you will control Microso CCCCC CCCCC CCCCC CCCCCC.
2 2 22222222 2 222222 222222222222
In this exercise, you will create a client application that uses the functionality of
a version of the Credit Card component, which is created in later chapters.
Exercise 1: Controlling Micros oft Excel
• 3 4The cells C and C have been named “Grow” 222 “Inflation” , .
• 2222 2222 22222 , 16:16 “Net_Profit.”
Exercise 2: Creating a ClientApplication
The Credit Card component exposes two interfaces.
1. The default interface validates the purchase of an item with these properties and methods.Name TypeCardNumber PropertyExpireDate PropertyPurchaseAmount PropertyApprove Method
2. The IManage interface is used to change the credit limit of a client.
Name Type
CreditLimit Property
CCC CCCCCC
Handed in by 17 August, 3:30 pm.
• A 3-page summary of “ActiveX Demystified”.
• Answers to self-check questions with explanations of your answers.
• Complete code of lab exercise 1 and 2 with explanations of statements in the code.