301AA-AdvancedProgramming
Lecturer:AndreaCorradini [email protected]
h;p://pages.di.unipi.it/corradini/
Coursepages:h;p://pages.di.unipi.it/corradini/Dida@ca/AP-18/
AP-2018-10:Components:theMicroso0way
Overview• TheMicrosoFapproachtocomponents• DDE,OLE,COM,AcIveX,…• The.NETframework• CommonLanguageRunIme• .NETcomponents• ComposiIonbyaggregaIonandcontainment• CommunicaIonbyEventsandDelegates• Chapter15,secIons15.1,15.2,15.4,15.11,and15.12ofComponentSo0ware:BeyondObject-OrientedProgramming.C.Szyperski,D.Gruntz,S.Murer,Addison-Wesley,2002.
2
DistributedComponentTechnologiesThegoal:- Integra.onofservicesforapplicaIonsonvariousplaVorms- Interoperability:letdisparatesystemscommunicate
andsharedataseamlesslyApproaches:-MicrosoF:DDE,COM,OLE,OCX,DCOMandAcIveX-Sun:JavaBeans,EnterpriseJavaBeans,J2EE-CORBA(CommonObjectRequestBrokerArchitecture)-Mozilla:XPCOM(GeckofuncIonalityascomponents)-SOAP(usingXML)
3
TheMicrosoFApproach
• ConInuousre-engineeringofexisIngapplicaIons
• Componenttechnologyintroducedgraduallytakingadvantageofprevioussuccess,like– VisualBasiccontrols– Objectlinkingandembedding(OLE)– AcIveX,ASP
• SoluIonsmainlyadoptedonMSplaVorms• Reviewfromolderapproachesto.NET+CLR
4
COM:ComponentObjectModel
• UnderlyingmostMScomponenttechnologies(before.NET)
• MadeavailableonotherplaVorms,butwithli;lesuccess
• Itisabinarystandardforinterfaces
5
The first fundamental wiring model – COM
the calling convention, which is the specification of what exactly is passedwhen calling an operation from an interface.
Methods of an object have one additional parameter – the object theybelong to. This parameter is sometimes called self or this. Its declaration ishidden in most object-oriented languages, but a few, including ComponentPascal, make it explicit. The point is that the interface pointer is passed as aself-parameter to any of the interface’s operations. This allows operations in aCOM interface to exhibit true object characteristics. In particular, the interfacenode can be used to refer internally to instance variables. It is even possible toattach instance variables directly to the interface node, but this is not normallydone. It is, however, quite common to store pointers that simplify the lookupof instance variables and the location of other interfaces.
A COM component is free to contain implementations for any number ofinterfaces. The entire implementation can be a single class, but it does nothave to be. A component can just as well contain many classes that are used toinstantiate objects of just as many different kinds. These objects then collec-tively provide the implementation of the interfaces provided by thecomponent. Figure 15.2 shows a component that provides three differentinterfaces and uses two different objects to implement these.
In Figure 15.2, object 1 implements interfaces A and B, whereas object 2implements interface C. The dashed pointers between the interface nodes areused internally as it must be possible to get from each node to every othernode. The unusual layout of objects and vtables is just what COM prescribes ifsuch an n-to-m relationship between objects and interfaces is desired.However, without proper language support, it is not likely that many compo-nents will take such a complex shape. What is important, though, is that thereis no single object part that ever leaves the component and represents theentire COM object. A COM component is not necessarily a traditional classand a COM object is not necessarily a traditional single-bodied object.However, a COM object can be such a traditional object and all of its inter-faces can be implemented in a single class by using multiple inheritance(Rogerson, 1997).
There are two important questions to be answered at this point. How doesa client learn about other interfaces and how does a client compare the identity
331
Figure 15.1 Binary representation of a COM interface.
Clientvariable
Interfacenode Op 1
Op 2
Op nComponent
8557 Chapter 15 p329-380 8/10/02 12:24 pm Page 331
Theinterfaceisapointertoaninterfacenode,whichisapointertoatableoffuncIonpointers
COMcomponents
• ACOMcomponentmayimplementanynumberofinterfaces.
• TheenIreimplementaIoncanbeasingleclass,butitdoesnothavetobe.
• AcomponentcancontainmanyclassesthatareusedtoinstanIateobjectsofjustasmanydifferentkinds.
• TheseobjectsthencollecIvelyprovidetheimplementaIonoftheinterfacesprovidedbythecomponent.
6
The Microsoft way: COM, OLE/ActiveX, COM+, and .NET CLR
of COM objects? Surprisingly, these two questions are closely related. EveryCOM interface has a common first method named QueryInterface. Thus, thefirst slot of the function table of any COM interface points to a QueryInterfaceoperation. There are two further methods shared by all interfaces. These areexplained below.
QueryInterface takes the name of an interface, checks if the current COMobject supports it, and, if so, returns the corresponding interface reference. Anerror indication is returned if the interface queried for is not supported. Onthe level of QueryInterface, interfaces are named using interface identifiers(IIDs). An IID is a GUID (Chapter 12), which is a 128-bit number guaran-teed to be globally unique. COM uses GUIDs for other purposes also.
As every interface has a QueryInterface operation, a client can get from anyprovided interface to any other. Once a client has a reference to at least oneinterface, it can obtain access to all others provided by the same COM object.Recall that interface nodes are separate and therefore cannot serve to identify aCOM object uniquely. However, COM requires that a given COM objectreturns the same interface node pointer each time it is asked for the IUnknowninterface. As all COM objects must have an IUnknown interface, the identity ofthe IUnknown interface node can serve to identify the entire COM object. Toensure that this identity is logically preserved by interface navigation, theQueryInterface contract requires that any successful query yields an interfacethat is on the same COM object – that is, establishes the same identify viaqueries for IUnknown. To enable sound reasoning, the set of interfacesexplorable by queries must be an equivalence class. This means that the queriesare reflexive in that if they ask for an interface by querying that same interface,they will succeed. They are also symmetrical in that if they ask for an interface,
332
Figure 15.2 A COM object with multiple interfaces.
Clientvariables
Interfacenode A
Interfacenode B
Interfacenode C
Object 1
Object 2
Op A1
Op A2
Op B1Op B2Op B3
Op C1
Op C2
8557 Chapter 15 p329-380 8/10/02 12:24 pm Page 332
COMcomponents• GloballyuniqueidenIfiers(GUID)• EveryCOMinterfacehasthesamefirstfuncIon,toinspectsupportedinterfaces:QueryInterface (GUID->Interfacereference/error)
• GlobalidenItythroughIUnknown !• OtherfuncIonsuniversallyavailable:AddRefandRelease(forGarbageCollecIonviaReferenceCounIng)
8
[uuid(00000000-0000-0000-C000-000000000046)]interfaceIUnknown{HRESULTQueryInterface([in]constIIDiid,[out,iid_is(iid)]IUnknowniid);unsignedlongAddRef();unsignedlongRelease();}
COMcomponentscomposiIon
9
The Microsoft way: COM, OLE/ActiveX, COM+, and .NET CLR
although this particular node may have no remaining references. This is nor-mally acceptable, and sharing of a single reference count is the usual approach.In some cases, interface nodes may be resource intensive, such as when theymaintain a large cache structure. A separate reference count for such an inter-face node can then be used to release that node as early as possible. (Thistechnique of creating and deleting interface nodes as required is sometimesreferred to as “tear-off interfaces.”)
On creation of an object or node, the reference count is initialized to 1before handing out a first reference. Each time a copy of a reference is created,the count must be incremented (AddRef). Each time a reference is given up, thecount must be decremented (Release). As soon as a reference count reacheszero, the COM object has become unreachable and should therefore self-destruct. As part of its destruction, it has to release all references to otherobjects that it might still hold, calling their Release methods. This leads to arecursive destruction of all objects exclusively held by the object under destruc-tion. Finally, the destructed object returns the memory space it occupied.
Reference counting is a form of cooperative garbage collection. As long asall involved components play by the rules and cooperate, memory will be safelydeallocated. At least, objects will never be deallocated while references stillexist. Reference counting has the well-known problem that it cannot deal withcyclic references. Consider the two objects in Figure 15.4.
The two objects are, as a whole, unreachable as no other object still has areference to any of the two. However, the mutual reference keeps bothobjects’ reference counts above zero and thus prevents deallocation.Obviously, this is only a special case. The general case is a cycle of references
334
Figure 15.4 Cyclical references between objects.
Object A Object B
refcnt=1 refcnt=1
Figure 15.3 Depiction of a COM object.
IUnknown
IOleObject
IDataObject
IPersistStorage
IOleDocument
8557 Chapter 15 p329-380 8/10/02 12:24 pm Page 334
COM object reuse
Aggregation can go any number of levels deep. Inner objects, on whateverlevel, always refer to the IUnknown interface of the outermost object. For inter-nal purposes, an outer object retains a direct reference to an inner object’soriginal IUnknown. In this way, an outer object can still query for an innerobject’s interfaces without being referred to its own IUnknown. As is clearlyvisible in Figure 15.6, the inner and outer objects in an aggregation settingmaintain mutual references. As explained above, such cycles would preventdeallocation of aggregates. Thus, COM has special, and again error-prone,rules about how to manipulate the reference counts involved in order for thescheme to work.
Aggregation, as a pure performance tool, if compared to containment, isprobably meaningful only for deeply nested constructions. This is one of thereasons for aggregation in COM practice being less important than contain-ment. Another reason is the increase in complexity. Nevertheless, aggregationcan be put to work where efficient reuse of component functionality is needed.The resulting performance is as good as that of a directly implemented inter-face as aggregated interfaces short-circuit all aggregation levels.
Aggregation can be used to construct efficient generic wrappers (“blind del-egation” of arbitrary interfaces). In particular, aggregation can be used to addsupport for new interfaces on otherwise unchanged objects. However, doingso requires great care as the new interfaces must not interfere with any of the(generally unknown!) interfaces on that object. This works if the potential useof aggregating wrappers and their added interfaces was already known whenconstructing the original objects (then interference is avoided by constructionof these objects) or when the added interfaces are private to some infrastruc-ture. For example, COM remoting builds up proxy objects that implementboth the interfaces of some remote object and private interfaces of the COM
337
Figure 15.6 Aggregation.
Outer object
Inner object
…ReadWrite { … }
{ … }
Inner
IStream
IUnknown
IUnknown
Outer
8557 Chapter 15 p329-380 8/10/02 12:24 pm Page 337
The Microsoft way: COM, OLE/ActiveX, COM+, and .NET CLR
for example, perform some filtering or additional processing. Also, it is impor-tant to retain transparency as a client of the outer object should have no way oftelling that a particular interface has been aggregated from an inner object.
With containment, the inner object is unaware of being contained. This isdifferent for aggregation, which needs the inner object to collaborate. A COMobject has the choice of whether or not to support aggregation. If it does, itcan become an aggregated inner object. Why is this collaborative effortrequired? Recall that all COM interfaces support QueryInterface. If an innerobject’s interface is exposed to clients of the outer object, then theQueryInterface of that inner object’s interface must still cover the interfacessupported by the outer object. The solution is simple. The inner object learnsabout the outer object’s IUnknown interface when it is aggregated. Calls to itsQueryInterface are then forwarded to the outer object’s QueryInterface.
Figure 15.6 shows how the scenario from above changes when using aggre-gation. Recall that the depiction of one object inside another, just as withcontainment, has merely illustrative purposes. The inner object is fully self-standing and most likely implemented by a different component than theouter object. The aggregation relation manifests itself in the mutual object ref-erences established between the inner and the outer object.
336
Figure 15.5 (a) Containment as seen on the level of objects. (b) Alternative depiction emphasiz-ing the containment property.
(a)
…ReadWrite
inner
{ inner.Read }{ inner.Write }
IStream
IUnknown
Outer object
Inner object(b)
…ReadWrite { … }
{ … }
…ReadWrite { … }
{ … }
Inner
{ inner.Read }{ inner.Write }
…ReadWrite
Outer object Inner object
IStream
IUnknown
IStream
IUnknown
IUnknownIStream
8557 Chapter 15 p329-380 8/10/02 12:24 pm Page 336
Containment
Aggrega.on
CreaIngCOMobjects
• ACOMservercanprovideFactoriesforCOMInterfaces
• NotethatversioningisnotsupportedinCOM10
The Microsoft way: COM, OLE/ActiveX, COM+, and .NET CLR
use the CLSID for “rich text.” To support such generic CLSIDs and enableconfiguration, COM allows one class to emulate another. Emulation configu-rations are kept in the system registry. For example, an emulation entry mayspecify that class “Microsoft Word” does the emulation for class “rich text.”
Initializing objects, persistence, structured storage,monikers
COM uses a two-phase approach to object initialization. After creating a COMobject using CoCreateInstance or a factory object, the object still needs to beinitialized. This is like creating a new object in C++ or Java with a constructorthat takes no arguments, the required storage being allocated, but no usefuldata loaded into the new object. Once created, an object must be initialized.There are many ways to do this and the client has control over which methodto use. This two-phase approach is more flexible than the use of constructors.
The most direct way to initialize an object is to ask it to load its data from afile, a stream, or some other data store. For this purpose, COM defines afamily of interfaces that are all derived from IPersist and named IPersistFile,IPersistStream, and so on. This direct approach is useful where a client wantsto take control over the source of data to be used for initialization.
A standard place to store an object’s data is in a COM structured storage. Astructured storage is like a file system within a file. A structured storage simplyis a tree structure. The root of the tree is called a root storage, the tree’s otherinner nodes are called storages, and the tree’s leaf nodes are called streams.Streams are the “files” in a structured storage, while storage nodes are the“directories.” From Windows 2000 on, COM’s structured storages supportsimple transactions that allow an entire structured storage to be updated com-pletely or not at all.
15.5
342
Figure 15.9 COM server with two coclasses, each with a factory.
Class A Class B
IClassFactoryor
IClassFactory2
IClassFactoryor
IClassFactory2
COM server
8557 Chapter 15 p329-380 8/10/02 12:24 pm Page 342
Example from Microsoft environment (80’s)
• Excel-generated pie chart embedded in a Word document displayed in a PowerPoint presentation
• Different applications need to share data or procedures
11
DDE (Dynamic Data Exchange)
• Ali;lehistory:starIngwithevoluIonofMicrosoFapproach:– WindowsgavePCsamoreaccessiblecompuIngenvironment– Problem:lackofconsistencybetweendifferentprograms– Whatifspreadsheetandwordprocessorneedtosharedata?
• EarlysoluIonwasintegraIngsuitesintolargeprograms:– e.g.,MicrosoFWorks–Prosandconsofsuiteapproach?
• MicrosoFcomesoutwithDynamicDataExchange(DDE),circa1989– LetsdifferentWindowsprogramssharedatathroughlinks– Supposesomespreadsheetdatawerelinkedintowordprocessor– Whenyouchangeddatainspreadsheet,thenewdatawouldappearinword
processor– LimitaIon:youcouldn’tupdatethedatainthewordprocessor;youhadtoinvoke
thespreadsheettoupdatethedatethere– Worse,linkswerefragileandwouldbreakifyoumoveddatafilesaroundinfile
system12
OLE (circa 1991)
• Object Linking and Embedding – Linking is essentially DDE, using reference semantics – Embedding lets users copy a snapshot of data into word processor
and save it there – Linking is cheaper when data files are large – Embedding supports compound documents (“document-centric”
computing)
• A way for Windows to create documents containing objects from other programs. – E.g. place a chart from Excel and a slide from PowerPoint into
a Word document – Components containers can be re-used by many applications – But components do not make data independent of application
programs, and OLE is a platform-specific solution. 13
OLE Technology (circa 1993)
• A set of APIs to create and display a (compound) document – Now possible to share code as well as data
• Component Object Model (COM) – COM protocols let components connect to origination program: – E.g. word processor can tell spreadsheet, “the user just clicked on the
spreadsheet, so start yourself up, look for data here, and let me know when you’re done.”
• COM now includes OLE as part of a larger concept – OLE becomes a set of standard COM interfaces
• Embedded documents retain all their original properties – If the user decides to edit the embedded data, Windows activates the
originating application and loads the embedded document
14
OLE Extensions (OCX)
• With Windows 95 came a new standard: – OCX (OLE Custom eXtension component) – A piece of code, smaller than application program, but with its own
user interface – Let users bundle OCX controls to form customized applications – E.g., combine spell checker and synonym provider component to
make a new program – Is this beginning to sound like object-oriented programming?
15
AcIveX(circa1996)
• MicrosoFretoolsOLEandCOMasAcIveX– AcIveXappliestoawholesetofCOM-basedtechnologies
• AcIveXcontrolisMicrosoF'sanswertotheJavatechnologyfromSun– AnAcIveXcontrolisroughlyequivalenttoaJavaapplet,butisknownasanAcIveXcontrol
• WriIngaprogramtorunintheAcIveXenvironmentcreatesaself-sufficientprogramthatcanrunanywhereinAcIveXnetwork
• ThiscomponentisknownasanAcIveXcontrol,andisoFenusedtoa;achaprogramtoawebpage
16
AcIveX-implementaIon
• AnAcIveXcontrolcanbecreatedusingoneofseverallanguagesordevelopmenttools,includingC++andVisualBasic,orwithscripIngtoolssuchasVBScript.
• NetworkOLEforrudimentarysupportofdistributedapplicaIons
• AcIveXcontrolsoriginallywereWindowsonly– OthervendorslaterprovidedMacandUnix/LinuxsupportforAcIveX
• Securityissues:AcIveXcontrolshavefullfileaccess(nosandbox)– CanbesignedforauthenIcaIon
17
THE.NETFRAMEWORK
18
Summary
• The.NETframeworkand.NETcomponents• Typesof.NETcomponents,connecIonsofcomponents,anddeployments
• Localanddistributedcomponents• Aggrega.onandcontainmentcomposiIons• SynchronousandasynchronousmethodinvocaIons
• DelegatesandEvent-basedcommunicaIon
The.NETFramework
• IntroducedbyMicrosoFin2000.• PlaVormforrapidandeasierbuilding,deploying,andrunningsecured.NETsoIwarecomponents
• SupportforrapiddevelopmentofXMLwebservicesandapplica.ons
• HighlyproducIve,component-based,mul.-languageenvironmentforintegraIngexisIngapplicaIonswithinternet
• Emphasisoninteroperability
The.NETFrameworkconsistsof:• TheCommonLanguageSpecifica.on(CLS)Itcontainsguidelines,thatlanguageshouldfollowsothattheycancommunicatewithother.NETlanguages.ItisalsoresponsibleforTypematching.
• TheFrameworkBaseClassLibraries(BCL)Aconsistent,object-orientedlibraryofprepackagedfuncIonalityandApplicaIons.
• TheCommonLanguageRun.me(CLR)Alanguage-neutraldevelopment&execuIonenvironmentthatprovidescommonrunImeforapplicaIonexecuIon.
21
.NETFrameworkstructure(h;p://www.dotnet101.com/arIcles/art014_dotnet.asp)
22
CommonLanguageSpecificaIon
CLSperformsthefollowingfunc.ons:
• Establishesaframeworkthathelpsenablecross-languageintegraIon,typesafety,andhighperformancecodeexecuIon
• Providesanobject-orientedmodelthatsupportsthecompleteimplementaIonofmanyprogramminglanguages
• Definesrulesthatlanguagesmustfollow,whichhelpsensurethatobjectswri;enindifferentlanguagescaninteractwitheachother
23
.NETFrameworkBaseClassLibrary• TheClassLibraryisacomprehensive,object-orientedcollecIon
ofreusabletypes• TheseclasslibrarycanbeusedtodevelopapplicaIonsthat
include:– TradiIonalcommand-lineapplicaIons– Graphicaluserinterface(GUI)applicaIons– ApplicaIonsbasedonthelatestinnovaIonsprovidedbyASP.NET
• WebForms• XMLWebservices
24
CommonLanguageRunIme(CLR)• CLRensures:
– AcommonrunKmeenvironmentforall.NETlanguages– UsesCommonTypeSystem(strict-type&code-verificaKon)– MemoryallocaIonandgarbagecollecIon– IntermediateLanguage(IL)tonaIvecodecompiler.WhichCompilesMSILcodeintonaIveexecutablecode
– Securityandinteroperabilityofthecodewithotherlanguages
• Over36languagessupportedtoday– C#,VB,Jscript,VisualC++fromMicrosoF– Perl,Python,Smalltalk,Cobol,Haskell,Mercury,Eiffel,Oberon,Oz,Pascal,APL,CAML,Scheme,etc.
25
ExecuIoninCLR
CommonLanguageRunIme
VBSource code
Compiler
C++C#
AssemblyILCode
JITCompiler
Managed code
NaIveCode
Compiler Compiler
AssemblyILCode
AssemblyILCode
OperaIngSystemServices26
Overviewof.NETFramework(cont.)
• Supportsdevelopmentanddeploymentofdesktop,window,andweb-basedapplica.onservicesonbothWindowsplaVormonotherplaVormsthroughSOAPandHTTP
• .NETsimplifiesandimprovessupportforcomponentsdevelopmentanddeploymentw.r.t.ComponentObjectModel(COM),andDistributedCOM(DCOM)technology.
• COMcomponentscanbereused.DifferentlyfromCOM,.NETtechnologysupportscomponentversions,anddifferentversionscancoexistwithoutanyconflict.
27
Overviewof.NETFramework(cont.)
• SupportofdistributedcomponentsbyRemo.ngChanneltechnology.
• SupportsofInteroperabilitybetweenCOM,.NETandXMLwebservicecomponents.
• The.NETframeworkisavailablein.NETFrameworkSDKandVisualStudio.NETIDESDKwhichsupportwriIng,building,tesIng,anddeployingof.NETapplicaIons.
• Itsupportsall.NETlanguagessuchasVB.NET,VC.NET,C#,andothers.
28
MicrosoFCLI(CommonLanguageInfrastructure):historicalnotes
• WhenJavabecamepopularMicrosoFjoinedtheiniIaIve• TheideawastoexploitthedynamicloadfeaturesofJVMto
implementacomponentbasedarchitecturelikeCOM• Thereweretwomainproblems:
– InteroperabilitywiththeexisIngcode(COM)– Supportformanyprogramminglanguages
• TheyextendedtheJVMbutSuncomplainedoflicenseinfringement
• MicrosoFstarteddevelopingitsowntechnology• ThiswasbasedontheirexperienceonJava,buttheytriedto
addressthetwoproblemsabove• TheresultwastheCommonLanguageInfrastructure(CLI)• ThecoreofCLIistheCommonLanguageRun.me(CLR)
whichplaysthesameroleastheJMVinJava 29
SomeCLIimplementaIon• CLR–MicrosoF’scommercialoffering• SSCLI(code-named“Rotor”)–MicrosoF’sSharedSourceCLI
• Mono-opensourceprojectiniIaIvesponsoredbyXimian(nowapartofNovell)andnowbyMicrosoF
• Portable.NET–bySouthernStormSoFware,PtyLtd,anAustraliancompany
• OCL–porIonsoftheimplementaIonoftheCLIbyIntel
30
.NET Framework
ASP .Net(WebServices,
Webforms)
Windows Forms (Control, Drawing)
Basic.NET Class library --- mscorlib.dll
CLR (Common Language Runtime) mscoree.dll
CTS (Common Type System)
JIT (just In Time Compiler)
CLR Execution
Windows Platform
.Net Framework SDK
.Net Visual Studio
Class loader
CommonLanguageInfrastructure 31
CommonfeaturesofCLRandJVM
• Secure• Portable• AutomaIcMM(GC)• Typesafety• Dynamicloading• ClassLibrary• OOP
• Mix-ininheritanceNotethattheessenIaltraitsoftheexecuIonenvironmentaresimilar,thoughtherearerelevantdifference
inthedesign
CLIhasbeenstandardized(ECMAandISO)andisasupersetofJava.WewillrefermainlytoCLR.
32
HowCLRworks
C#
C++
ML
VB
…
CIL
x86
Unmanaged
Managed
JIT
Managedx86
GC
CLR
Security
BCL
Loader
FoundaIonof.NETframework–CLR
• CommonLanguageRun.me(CLR)isavirtualmachineenvironmentsi@ngonthetopoftheoperaIngsystem.
• CLRconsistsofCommonTypeSystem(CTS),Just-In-TimeCILCompiler(JIT),VirtualExecu.onSystem,plusothermanagementservices(garbagecollec.on,securitymanagement).
• CLRislikeJVMinJava.ItisassembledinapackageofassemblyconsisIngofMSIntermediateLanguage(MSIL)codeandmanifest(Metadataaboutthispacket).
• TheCILcodeistranslatedintonaIvecodebyJITcompilerinCLR.ILcodeisverifiedbyCTSfirsttocheckthevalidityofdatatypeusedinthecode.
FoundaIonof.NETframework–CLR
• Mul.languagesupport:(VB,managedC++,C#etc)byCommonLanguageCLRimplementaIon.
• AclassinonelanguagecaninheritproperIesandmethodsfromrelatedclassesinotherlanguages.
• TheCTSdefinesastandardsetofdatatypeandrulesforcreaIngnewtypes.– Referencetypes– Valuetypes
• ThecodetargeIngCLRandtobeexecutedbyCLRiscalled.NETmanagedcode.AllMSlanguagecompilersgeneratemanagedcodesthatconformtotheCTS.
FoundaIonof.NETframework–CLR
• TheCILcodeislikeJavabytecode.Regardlessofthesourceprogramminglanguages,ILcodescaninteractbysupportsoftheCLR.
• TheILcodecanbeintheformatofexecutable(.EXE)orDynamicLinkLibrary(.DLL).
• IftheseILcodesaregeneratedby.NETcompiler,theyarecalledmanagedcode.
• Themanagedcodecanbeexecutedonlyon.NETawareplaVorm.SomeDLLorEXEgeneratedbynon.NETcompilers(suchasearlyversionofVC++)arecalledun-managedcode.
FoundaIonof.NETframework–CLR
Assembly in .DLL or .EXE
IL code
VB . Net C# . Net C++ . Net
VB .NetCompiler
C# .NetCompiler
C++Compiler
Class Loader and Type Verifier
JIT
Managed native code
CLR Execution Unit
Class Library
Deployment
CLR
TowardstheCommonTypeSystem• ExecuIonenvironmentssuchasCLRandJVMaredataoriented
• AtypeistheunitofcodemanagedbytherunIme:loading,code,stateandpermissionsaredefinedintermsoftypes
• ApplicaIonsaresetoftypesthatinteracttogether
• OnetypeexposesastaIcmethod(Main)whichistheentrypointoftheapplicaIon:itloadstheneededtypesandcreatestheappropriateinstances
• Therearebasetypes:primi.vetypes,Object,StringandClass(whichistheentry-pointforreflecIon)
• Typeconstructorsare:– Array– Class
• TheprimiIvetypesareunrelatedtoObjectwithrespecttoinheritancerelaIon
• Thisappliestointerfacestoo,butobjectsthatimplementsinterfacesarealwaysinheritedfromobject
• JavatypesystemisfarsimplerthantheoneofCLR
Javatypesystem
Object
interfaceT
intPrimiIvetypes
Class
String
T[]
classT
CommonTypeSystem• Goal:Toestablishaframeworktosupportcross-language
interoperability,typesafety,andhighperformancecodeexecuIon.• Definesarichsetofdatatypes,basedonanobject-orientedmodel.• Definesrulesthatensurethatobjectswri;enindifferentlanguages
caninteractwitheachother.• Specifiestherulesforscopes,typevisibilityandaccesstothe
membersofatype.TheCommonLanguageRunImeenforcesthevisibilityrules.
• Definesrulesoftypeinheritance,virtualmethodsandobjectlifeIme.
• Languagessupportedby.NETcanimplementonlypartofthecommondatatypes.
40
CLRCommonTypeSystem• Commonrooted:alsonumbersinherits
fromObject• Therearemoretypeconstructors:
– Enum:constants– Struct:likeclassbutwithout
inheritanceandstackallocaIon– Delegate:typethatdescribes
asetofmethodswithcommonsignature
• Valuetypes(numbersandstructs)inheritsfromObject.SIllarenotreferencesandaren'tstoredontheheap
• ThetrickisthatwhenavaluetypeshouldbeupcastedtoObjectitisboxedinawrapperontheheap
• TheoppositeoperaIoniscalledunboxing
Object
interfaceT
int Basetypes
Type
String
Array
classT
ValueType
T[]
Delegate DelegateT
Enum EnumT
StructT
The.NETFrameworkClassLibrary
• The.NETframeworkclasslibraryisacollecIonofreusablebasicclasseswhicharewellorganizedbynamespaces.
• CorrespondtoJavaAPIandpackages• Anamespaceconsistsofmanyclassesandsub-namespaces.Itis
deployedasacomponentclasslibraryitselfandisorganizedinacomponent–basedhierarchy.
• The.NETframeworkitselfisbuiltupinacomponentmodel.• Developerscancreatecustomnamespaces• Anamespacecanbedeployedasanassemblyofbinary
components.• using <namespace>! ! inC#or
import <namespace> inVB toaccessclassesinanamespace.
The.NETFrameworkClassLibrary
System
Console Object
Primitive Type Array String
IO
NET
Data
Web
XML
Remoting
Delegate
NameSpace
Class
………
………
TheComponentModelof.NET
• Assemblies(orCILDLLcomponents)replacetheCOMComponents
• The.NETcomponenttechnologyisunified-languageoriented.Any.NETcomponentisintheformatofpre-compiledMSIL,whichcanbebinarypluggedinbyanyotherMSILcomponentsoranyother.NETcompaIbleclients.
• A.NETcomponentisasinglepre-compiledandselfdescribedCILmodulebuiltfromoneormoreclassesormulIplemodulesdeployedinaDLLassemblyfile.
Assemblies • AssembliesarethesmallestunitofcodedistribuIon,deploymentandversioning
• Individualcomponentsarepackagedintoassemblies• CanbedynamicallyloadedintotheexecuIonengineondemandeitherfromlocaldisk,acrossnetwork,orevencreatedon-the-flyunderprogramcontrol
SingleFileAssembly
Resources
MSIL
MetaData
Manifest
ThisAssembly.dll
Resources
MSIL
MetaData
Manifest
ThisAssembly.dll
MSIL
Metadata
A.netmodule
B.netmodule
Manifest(NoAssemblyMetadata)
MSIL
Metadata
Manifest(NoAssemblyMetadata)
MulKFileAssembly
AssemblycharacterisIcs • Self-describing
– Toenabledata-drivenexecuIon• PlaVorm-independent• Boundedbyname
– Locateassembliesbyqueryingitsstrongname– Strongname=(publishertoken,assemblyname,versionvector,
culture)– Versionvector=(major,minor,build,patch)
• AssemblyloadingissensiIvetoversionandpolicy– Assembliesareloadedusingtunablebindingrules,whichallow
programmersandadministratorstocontributepolicytoassembly-loadingbehavior.
• Validated– EachImeanassemblyisloaded,itissubjecttoaseriesofchecksto
ensuretheassembly’sintegrity.
Assemblystructure
• Anassemblyconsistsofuptofourparts:1. Manifest(tableofinforecords):name,version
vector=(major,minor,build,patch),culture,strongname(publickeyfromthepublisher),typereferenceinformaIon(forexportedtypes)listoffilesintheassembly,informaIononreferencedassembliesreference.
2. Metadataofmodules3. CILcodeofmodule4. Resourcessuchasimagefiles.
TheComponentModelof.NET
• AmodulehasCILcodeanditsmetadatabutwithoutmanifest.Notloadabledynamically.BuildingblockatcompileImetobuildupanassemblyModulefile.Extension:.netmodule.
• AnAssemblyismadeupbyoneormanyclassesinamodule.Assemblyhasamanifestfiletoself-describethecomponentitself.
• Anassemblyhasafileextension.dllor.exeandisdynamicallyloadable.
TheComponentModelof.NET
• A.dllfileisnotexecutablejustlikeaclassfileisabytecodefilethatisnotexecutable.
• An.exefile,generatedbya.NETcompiler,hasaPE.NETformat– PE(PortableExecutable)isthestandardMSformatforexecutablefiles
– PE.NETidenIfiestheexecutableasforexecuIonontheCLR:itcausesacalltotheCLRrunImeatthebeginning
TheComponentModelof.NET• A.NETcomponentcanbe
– Local(.dll),canonlybeaccessedlocally(withinsameapplicaIondomain),insamemachine
– Remote(distributed)(.exe),canbeaccessedremotelyinsamemachineordifferentmachines.
• A.NETDLLcomponentcanbedeployed– asaprivatecomponent,knowingthetargetclient– asasharedpubliccomponent
• Inthela;ercaseitmustbepublished(registered)inacentralizedrepositoryGlobalAssemblyCache(GAC),typicallyusingitsstrongname.
• Asharedcomponentsupportsside-by-sidemulIpleversioncomponentexecuIon.
TheConnecIonModelof.NET• .NETcomponentcomposiIonsenablethe
componentreuseineitheraggrega.oncomposi.onsorcontainmentcomposi.ons.
outer
inner
innerM()outerM2()
outer
innerinnerM()
outerM1()
containment
aggrega.on
ContainmentcomposiIons• Ifarequesttotheoutercomponentneeds
helpfromaninnercomponenttherequestisforwardedtothatinnercomponent.
• Theoutercomponentdoesnotexposetheinterfaceoftheinnercomponent.
• Theclientisblindofthehandleroftherequest.TheouterM2()delegatesarequesttotheinnerM()methodofinnercomponent
outer
inner
innerM()outerM2()
containment
AggregaIoncomposiIons• Theserviceofinnercomponenthandsoutitsservicedirectlytotheclientofoutercomponent.– Theoutercomponentexposestheinterfacesofinnercomponent.
– TheinnerM()methodofinnercomponentbecomespartofinterfacetotheoutercomponent
• A.NETcomponentcanalsobecomposedbymixedaggregaIonsandcontainmentsinaflatstructureornestedcomposiIonsinmulIplelevelsindepth.
outer
innerinnerM()
outerM1()aggrega.on
DELEGATESINCLR/C#
54
WhatareDelegates?• ADelegate(inCLR/C#)isatypethatrepresentsreferences
tomethodswithaspecificparameterlistandreturntype.• Eg: delegate int MyFun(int i, int j);
isatypewithinstancesholdingmethodsoftype (int*int à int)
• Similartofunc.onpointersinC++,buttype-safeandsecure.
• AninstanceofaDelegatetypecanhold/referbothtostaIcandtoinstancemethods(oftheprescribedsignature).
• Themethodreferredtobyadelegateinstancecanbeinvokedbypassingthelistofactualparameterstotheinstanceitself.
Possibileusesofdelegates
• Delegatescanusedtopassmethodsasargumentstoothermethods,thussupporIngafuncIonalprogrammingstylewithsomehigher-orderfeatures.
• Delegatescanbeusedtosupporteventbasedprogramming,whereeventhandlersareinvokedthroughdelegates.
• Theabilitytorefertoamethodasaparametermakesdelegatesidealfordefiningcallbackmethods.
Example:useofdelegatetypeinC#class Foo { delegate int MyFun(int i, int j); static int Add(int i, int j) {return i + j;}
int Mult(int x, int y) {return x * y;}
static void Main(string[] args) { MyFun fun = new MyFun(Foo.Add); Console.WriteLine(fun(2, 3)); Foo obj = new Foo(); fun = new MyFun(obj.Mult); Console.WriteLine(fun(2, 3));
} }
• type def MyFun instances: int * int -> int
• Delegate instance:
static method • Prints 5 • Delegate instance:
instance method • Prints 6
Delegateslikeclosures?
• InfuncIonalprogrammingitispossibletodefineafuncIonthatreferstoexternalvariables
• ThebehaviorofthefuncIondependsonthoseexternalvaluesandmaychange
• ClosuresareusedinfuncIonalprogrammingtocloseopentermsinfuncIons
• Delegatesarenotequivalenttoclosuresalthoughtheyareapair(env,func):theenvironmentshouldbeofthesametypetowhichthemethodbelongs
FuncIonalprogramminginC#?• DelegatesallowrepresenIngstaIcandinstance
methodsasvalues,thatcanbepassedasarguments• IntroduceelementsofFPstyleinthemainstream,
cleanereventmodel(call-backscanbenaturallyexpressedasdelegates)
• Example:mappingonanarray:
delegate int MyFun(int); int[] ApplyInt(MyFun f, int[] a) { int[] r = new int[a.Length]; for (int i = 0;i < a.Length;i++) r[i] = f(a[i]); return r; }
Eventsusingdelegates?• EventsystemsarebuiltonthenoIonofnoIficaIon(call-back)
• DescribedwiththeObserverorPublish/Subscribedesignpa;ern,asseenforJavaBeans
• AmethodinvocaIoncanbeseenasanoIficaIon• DelegaIoneventmodelintroducedbyJava1.1:
– Therearesourceofevents– TherearelistenersthatasksourcesfornoIficaIons– Eventfires:amethodisinvokedforeachsubscriber
DelegaIonEventModel
EventSource
SubscriberSubscribe
NoIficaIon
Subscribedlisteners
EventmodelinJava
• WhichmethodshouldcalltheeventsourcetonoIfytheevent?
• InJavatherearenodelegatesandinterfacesareusedinstead(XXXListener)
• Thelistenermustimplementaninterfaceandthesourceprovidesamethodfor(un)subscripIon.
• Avectorofsubscribedlistenersiskeptbytheeventsource
Delegatestohandleevents
• DelegatesallowconnecIngeventsourcestolistenersindependentofthetypesinvolved
• InC#adelegateobjectcanbeusedtospecifywhichmethodmustbeinvokedwhenaneventisfired
• Oneapproachcouldbetostoreanarrayofdelegatesinthesourcetorepresentssubscribers
• Acomponent(notnecessarilythelistener)buildsadelegateonthelistenerandsubscribestoanevent
MulIcastdelegates
• EventnoIficaIonisingeneralone-to-many• CLRprovidesmulIcastdelegatestosupportnoIficaIontomanylisteners
• AmulIcastdelegateisakindofdelegatethatholdsinsidealistof"delegateobjects"
• MulIcastdelegateskeeptrackofsubscripIonstoeventsourcesreducingtheburdenofreplicaIngthecode
MulIcastdelegates:Example
delegate void Event(); class EventSource { public Event evt; … evt(); // fires the event … } class Foo { public void MyMethod() {} } // Elsewhere in the program! EventSource src = new EventSource(); Foo f = new Foo(); src.evt += new Event(f.MyMethod); // subscribe
Unrelatedtypes!
C#anddelegates
• InC#thereisnowaytochoosebetweensingleandmulIcastdelegates
• ThecompileralwaysgeneratesmulIcastdelegates• Ifmorethanonemethodisregistered,theyareinvokedonorderofsubscripIon.ThereturnedvalueistheresultofthelastinvokaIon.
• InprincipleJITcouldgetridofpossibleinefficiencies
Eventkeyword
• C#introducestheeventkeywordtocontrolaccesstoadelegatemember.
• Ifadelegatefieldofaclassislabeledwitheventthenoutsidecodewillbeabletouseonly+=and-=operatorsonit
• Listenerwouldnotbeallowedtoaffectthesubscriberslistinotherways
• Eventinfrastructurescanbeeasilyimplementedbymeansofthiskeywordanddelegates
RemoIngConnectorsfor.NETDistributedComponents
• AcomponentoraclientcannotdirectlyaccessaremotecomponentrunningindifferentapplicaIondomaininsameordifferentprocessesunlessusingRemoIngchannelconnecIon.
• Themarshalingmakesitpossibletoinvokearemotemethodofadistributedcomponent.
• Therearetwowaystomarshalanobject:inMBV(MarshalbyValue)serverpassesacopyofobjecttoclientorinMarshalbyReference(MBR)clientcreatesaproxyofaremoteobject.
• Whenaremotecomponentmustrunataremotesite,MBRistheonlychoice.
• SimilartoRMIinJava
RemoIngAsynchronousCallbackInvocaIonBetweenDistributed.NETComponents
• TheRemoIngasynchronouscallbackisbasedonRemo.ngDelegate.ItwillnotblockouttheclientwhilewaiIngfornoIficaIonfromremotecomponents.
• Forexample,someonewantstobenoIfiedoncethestockpricesreachesaspecifiedlevel.InsteadofpoolingthestockpricealltheIme,whynotlettheservernoIfyyouandyoucandowhateveryouwanttodo.
• Insomeothercases,thejobsonserverwilltakeverylongtocomplete,whynotlettheservernoIfyyouwhenthejobisdone.
• Whenclientmakesasynchronouscalltoremotemethodofremotecomponent,itpassesacallbackmethodtoservertobecalledbacklatethroughRemo.ngDelegate.
Conclusion
• TheMicrosoFapproachtocomponents• SeveraltechnologiesdevelopedaroundCOM• MaininnovaIon:The.NETframeworkin2000• CommonLanguageRunIme• .NETcomponents:Assemblies• ComposiIonbyaggregaIonandcontainment• CommunicaIonbyEventsandDelegates
70