Перспективные материалы и технологии (22.03.01 Материаловедение и технологии материалов)
1 ООПРС Лекция 1 COM Технологии. 2 COM технологии COM е...
-
date post
04-Jan-2016 -
Category
Documents
-
view
219 -
download
0
Transcript of 1 ООПРС Лекция 1 COM Технологии. 2 COM технологии COM е...
1
ООПРС
Лекция 1
COM Технологии
2
COM технологии
COM е патентована технология наMicrosoft Corporationвъведена през 1993 г. иизградена около платформата Windows.
3
4
5
Генезис на COM ипромени в технологиите
• Обекти за вграждане и свързване (OLE)• Конвенционални GUI базирани ОС, Windows• Динамичен обмен на данни (DDE)• Обектно-ориентирано програмиране (ООП)• Component Object Model(COM)• Разпределени COM (DCOM)• COM +
6
clipboard
DDE
OLE
COM
1/2
• Интегритет м/у приложенията.• Комуникация м/у тях
7
2/2
DLL :
• зависимост от разположението
. Зависимост от езика
с COM технологията се решават тези проблеми
• повишена защита• поддържа възможност за множество потребители• поддържат DB connection pool
DLL и COM
8
COM Терминология
• Class
• Object
• Component
• Interface
Object – combination of code and data that canbe treated as a unit• Component – reusable piece of executable codethat can be used with other applications withminimum efforts; could be .EXE, .DLL or .OCX• Interface – set of functions grouped togetherunder one name; COM can support more thanone interface• DLL – dynamic link library is a highly reusablecomponent that can communicate with objects inclient/server application
GUID – globally unique identifiers are128 bit integers used to identify everyinterface and component object class
9
Interface Definition Language
[ object, uuid( E7CD0D00-1827-11CF- 9946444553540000) ]interface ISpellChecker : IUnknown{
import “unknown.idl”;HRESULT LookUpWord(
[in] OLECHAR word[31],[out] boolean *found );
HRESULT AddToDictionary([in] OLECHAR word[31]);
HRESULT RemoveFromDictionary([in] OLECHAR word[31]);
}
10
Обекти и интерфейси
Интерфейсът е набор от семантично свързани функции, реализирани в определен обект. Това включва прототип или сигнатура.Използването (instantiation) става, когато интефейсът е реализиран и е изработен указател към масив от указатели към функциите му:
обект на потребителя
указател към fn1()
обект
pInterface
указател към fn2()
реализация на
интерфейса
11
обекти и интерфейси
интерфейс А
Потребителски
Обект(компонент)
pInterfaceA
Реализация на Интерфейса А
потребителски достъп до функции обект с обект на интерфейс Аинтерфейси
Реализация на интерфейса Б
ВътрешниДанни На обета
A
Б
Обект, поддържащ 2 интерфейса
A::QueryInterface()
COM обект
12
таблица от таблица отуказатели указателикъм IUnknown към друг интерфейс
QueryInterface() QueryInterface() Release() Release() AddRef() AddRef()
*fn1() *fn2()
Базов интерфйс Произволен интерфейс с 2 собствени метода
Намираме се в 1 компонент
13
Interface IUnknownВсеки COM интерфейс и COM компонент трябва да реализирастандартния интерфейс IUnknown:
14
На Windows ниво COM обект се създава обикновено чрез извикванена API функцията CoCreateInstanse, която създава обект и връща указателкъм него от тип IUnknown, чийто вътрешен брояч е със стойност 1. Акоподадем този указател на друг клиент, той трябва да увеличи брояча му,извиквайки метода AddRef. Когато обектът повече не е необходим, сеизвиква неговия метод Release, който намалява брояча с единица иавтоматично проверява дали е станал нула (т.е. дали това е бил последниятактивен интерфейс към обекта). Ако това е така, то самият обект сесамоунищожава. Когато клиентът иска да работи с друг интерфейс наобекта, той извиква метода му QueryInterface с аргумент идентификаторана искания интерфейс. Ако обектът може да му го предостави му връщауказател и увеличава брояча си с единица. Трябва да подчертаем, че COMклиентът никога не получава указател към истинския обект, а винагиуказател към интерфейс, който е наследник на IUnknown.
15
Software Tools
• Basic and Visual Basic• Visual FoxPro• C, C++ and Visual C++• Small Talk• Ada• Visual J++
16
Component Object Library
RegistrationDB
Application
CLSID
CLSIDDLL
.EXE
Creating a component object
CLSID
17
Cient Application
In-ProcessObject
Local Object Proxy
Client Process
In-Process Server
RemoteObject Proxy
Stub
Local Object
Local Server Process
COMLocal
ServerRPC
Remote Machine
Stub
COM
RemoteObject
Remote Server
Remote Server Process
RPC
COM
18
Client Applicatio
n
COM
Object
Server
1) Create Object
2) Locate Implementation
4) Call interface members3) Get object interface pointer return to client
What happens when a client wishes to create and use a COM object?
19
When an application uses a COM object:
2) calls CoCreateInstance (exported by COMPOBJ.DLL) passing the CLSID of the used object; CoCreateInstance : uses the registry to discover which server implements the desidered class
asks the server to create an instance
receives from the server a pointer to the IUnknown interface
1) initializes the system : CoInitialize
3) uses IUnknown.QueryInterface to access the wanted interface4) uses Addref and Release to manage the object lifecycle5) in the end calls CoUninitialize
20
Introducing DCOM
DCOM (1995) is a seamless evolution of COM
you can take advantage of your existing investment in COM-based applications, components, tools and knowledge
An extension to COM that allows network-based component interaction
COM : processes can run on the same machine but in different address spaces
DCOM extension : allows processes to be spread across a network
21
DCOM Architecture
DCOM sits right in the middle of the components fo your application; it provides the invisible glue that ties things together.
COMObject
Component
SecurityProvider
DCE RPC
Protocol Stack
SecurityProvider
DCE RPC
Protocol Stack
DCOM network-protocol
COMObject
Component
22
Security by Configuration
1) DCOM obtains user name
2) Authenticate user
3) Is user in the list?
4) Fail or allow call
23
DCOM, CORBA, RMI
Java RMI - JavaSoft
CORBA -OMG
DCOM - Microsoft
24
Java RMI
• Very easy to use• Remoteable interfaces have a special exception• Supports object-by-value• Versioning is built into serialization
• Callbacks are blocked in synchronized methods
• Not always intuitive
• Not available to other languages
• There are limited development tools
• Performance can be slow as you scale
25
CORBA 1/2
• Architecture for system composition• Has a standard terminology for concepts• Declarative interfaces separate the interface
from the implementation• Provides mappings from IDL to C, C++,
SmallTalk and Java• Supports :
• evolvable and marshallable data• design portability• standard interoperability protocols
• Scalable for large systems
26
CORBA 2/2
• No inheritance for Exceptions• Objects cannot support two versions of the
same interface• IDL is not internationalized• Divergent security mechanisms (Kerberos, SSL)• Few advanced services• C++ mapping has complicated memory
management rules• Limited developer tools (usually just an IDL
compiler)• Limited concurrency model
27
DCOM• Lots of tools, books and developers• Separates interface from implementation• Good integration of automation objects with
VisualBasic and Java• Good set of compound document interfaces• Microsoft depends on it working
• Minimal support on non-Microsoft platforms
• Hard to keep registry consistent
• Reference counting is a problem
• Client has to choose the interaction model
28
I1 : C1
Pointer to VMT
Attribute 1
Attribute 2
Attribute 3
……………………
I2 : C1
Pointer to VMT
Attribute 1
Attribute 2
Attribute 3
……………………
Pointer to function 1 Pointer to function 2 Pointer to function 3 Pointer to function 4
VMT of class C1
implementations
back
VMT : Virtual Method Table 2/2
29
MTS : Microsoft transaction Server 1/2
A container for in-process server side components.
A component-based programming model. An MTS component is a type of COM component that executes in the MTS run-time environment.
• Allows you to define and use transactions within COM objects
What does it do?
• Enforces modelling based on components – just as COM
30
• Uses roles and packages
• Uses Just In TIME (JIT) Activation
• Run-time divided into three parts :
• Surrogate Process (MTS.EXE)
• Microsoft Distributed Transaction Coordinator (MS DCT)
• MTS Explorerback
• Handles communication between components through DCOM and HTTP protocols
MTS : Microsoft transaction Server 2/2
31
Пример
32
33
Методи на COM
…
public bool delete (int accountKey) { bool result = false; MessageBox.Show ("Bank::delete() invoked...", "Key Value = "+accountKey); ……
34
Използване на компонента
using Bank;try { // Create the COM+ componentBank.AccountManager manager = new Bank.AccountManager ();
35
36
Пример 2 – Ole automation (com)
Sub SpellCheck( )Dim Obj As ObjectSet Obj = CreateObject(“Excel.Application”)Word = InputBox(“Enter word”)If Obj.CheckSpelling(Word) Then
MsgBox( “Valid word” )Else
MsgBox( “Word not found” )End If
End Sub