301aa - advanced programming [ap-2017] -...
Post on 17-Jul-2019
225 Views
Preview:
TRANSCRIPT
301AA-AdvancedProgramming[AP-2017]
Lecturer:AndreaCorradiniandrea@di.unipi.itTutor:LilloGalleBagalleBa@di.unipi.it
DepartmentofComputerScience,PisaAcademicYear2017/18
AP-2017-08: Components:theMicroso0way
Overview
• TheMicrosoOapproachtocomponents• DDE,OLE,COM,AcQveX,…• The.NETframework• CommonLanguageRunQme• .NETcomponents• ComposiQonbyaggregaQonandcontainment• CommunicaQonbyEventsandDelegates
2
DistributedComponentTechnologiesThegoal:- Integra(onofservicesforapplicaQonsonvariousplaYorms- Interoperability:letdisparatesystemscommunicate
andsharedataseamlesslyApproaches:-MicrosoO:DDE,COM,OLE,OCX,DCOMandAcQveX-Sun:JavaBeans,EnterpriseJavaBeans,J2EE-CORBA(CommonObjectRequestBrokerArchitecture)-Mozilla:XPCOM(GeckofuncQonalityascomponents)-SOAP(usingXML)
3
TheMicrosoOApproach
• ConQnuousre-engineeringofexisQngapplicaQons
• Componenttechnologyintroducedgraduallytakingadvantageofprevioussuccess,like– VisualBasiccontrols– Objectlinkingandembedding(OLE)– AcQveX,ASP
• SoluQonsmainlyadoptedonMSplaYorms• Reviewfromolderapproachesto.NET+CLR
4
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
5
DDE (Dynamic Data Exchange)
• AliBlehistory:starQngwithevoluQonofMicrosoOapproach:– WindowsgavePCsamoreaccessiblecompuQngenvironment– Problem:lackofconsistencybetweendifferentprograms– Whatifspreadsheetandwordprocessorneedtosharedata?
• EarlysoluQonwasintegraQngsuitesintolargeprograms:– e.g.,MicrosoOWorks–Prosandconsofsuiteapproach?
• MicrosoOcomesoutwithDynamicDataExchange(DDE),circa1989– LetsdifferentWindowsprogramssharedatathroughlinks– Supposesomespreadsheetdatawerelinkedintowordprocessor– Whenyouchangeddatainspreadsheet,thenewdatawouldappearinword
processor– LimitaQon:youcouldn’tupdatethedatainthewordprocessor;youhadtoinvoke
thespreadsheettoupdatethedatethere– Worse,linkswerefragileandwouldbreakifyoumoveddatafilesaroundinfile
system6
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. 7
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
8
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?
9
AcQveX(circa1996)
• MicrosoOretoolsOLEandCOMasAcQveX– AcQveXappliestoawholesetofCOM-basedtechnologies
• AcQveXcontrolisMicrosoO'sanswertotheJavatechnologyfromSun– AnAcQveXcontrolisroughlyequivalenttoaJavaapplet,butisknownasanAcQveXcontrol
• WriQngaprogramtorunintheAcQveXenvironmentcreatesaself-sufficientprogramthatcanrunanywhereinAcQveXnetwork
• ThiscomponentisknownasanAcQveXcontrol,andisoOenusedtoaBachaprogramtoawebpage
10
AcQveX-implementaQon
• AnAcQveXcontrolcanbecreatedusingoneofseverallanguagesordevelopmenttools,includingC++andVisualBasic,orwithscripQngtoolssuchasVBScript.
• NetworkOLEforrudimentarysupportofdistributedapplicaQons
• AcQveXcontrolsoriginallywereWindowsonly– OthervendorslaterprovidedMacandUnix/LinuxsupportforAcQveX
• Securityissues:AcQveXcontrolshavefullfileaccess(nosandbox)– CanbesignedforauthenQcaQon
11
CommunicaQonProtocolModels
– RemoteProcedureCall(RPC)Ø Since1980s,pioneeredbySunØ TesQngwithvariouscommunicaQonmodels
– DistributedextensionofMSCOM(DCOM)Ø LetsCOMtalktootherplaYormsØ ComplexconfiguraQonandcomplicatedsecuritymodel
– RemoteMethodInvocaQon(RMI)Ø CommunicaQonbetweenmethodsofJavaclasses
– DrawbacksofRPC/RMIapproach?Ø PlaYorm-specific,proceduralandlow-level
12
.NETComponents
• The.NETframeworkand.NETcomponents• Typesof.NETcomponents,connecQonsofcomponents,anddeployments
• Localanddistributedcomponents• Aggrega(onandcontainmentcomposiQons• SynchronousandasynchronousmethodinvocaQons
The.NETFramework• IntroducedbyMicrosoOin2000.• PlaYormforrapidandeasierbuilding,deploying,andrunningsecured.NETsoOwarecomponents
• SupportforrapiddevelopmentofXMLwebservicesandapplicaQons
• HighlyproducQve,component-based,mul(-languageenvironmentforintegraQngexisQngapplicaQonswithinternet
• IncludesavirtualmachinethatprovidesanewplaYormforsoOwaredevelopment
Overviewof.NETFramework(cont.)
• IncludessupportforXMLandSimpleObjectAccessProtocol(SOAP)todeploywebservices
• Goal:supportdesktop,window,andweb-basedapplicaQonservicesonbothWindowsplaYormonotherplaYormsthroughSOAPandHTTP
• .NETsimplifiesandimprovessupportforcomponentsdevelopmentanddeploymentw.r.t.ComponentObjectModel(COM),andDistributedCOM(DCOM)technology.
• COMcomponentscanbereused.COMdoesnotsupportversioning(sidebysideexecuQon),whichmaycauseversionconflict(DLLHellproblem)..NETtechnologysupportscomponentversions,anddifferentversionscancoexistwithoutanyconflict.
Overviewof.NETFramework(cont.)
• SupportofdistributedcomponentsbyRemo(ngChanneltechnology.• InteroperabilitybetweenCOM,.NETandXMLwebservicecomponents.• .NETwebserviceisareplacementofMSDCOMtechnologyforInternet
applicaQonssupportedbyXML,SOAPandHTTPprotocols.ItovercomesDCOM’slackofsupportforfirewall.
• The.NETframeworkisavailablein.NETFrameworkSDKandVisualStudio.NETIDESDKwhichsupportwriQng,building,tesQng,anddeployingof.NETapplicaQons.Itsupportsall.NETlanguagessuchasVB.NET,VC.NET,C#,andothers.
• The.NETframeworkconsistsoftwomainparts:CommonLanguageRun(me(CLR)andasetofunifiedframeworkbasicclasslibrariesincludingASP.NETwebformsforbuildingwebapplicaQons,WindowsFormsforbuildingdesktopapplicaQons,andADO.NETfordataaccess.
MicrosoOCLI(CommonLanguageInfrastructure):historicalnotes
• WhenJavabecamepopularMicrosoOjoinedtheiniQaQve• TheideawastoexploitthedynamicloadfeaturesofJVMto
implementacomponentbasedarchitecturelikeCOM• Thereweretwomainproblems:
– InteroperabilitywiththeexisQngcode(COM)– Supportformanyprogramminglanguages
• TheyextendedtheJVMbutSuncomplainedoflicenseinfringement
• MicrosoOstarteddevelopingitsowntechnology• ThiswasbasedontheirexperienceonJava,buttheytriedto
addressthetwoproblemsabove• TheresultwastheCommonLanguageInfrastructure(CLI)• ThecoreofCLIistheCommonLanguageRun(me(CLR)
whichplaysthesameroleastheJMVinJava
.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
CLRandJVM
• Secure• Portable• AutomaQcMM(GC)• Typesafety• Dynamicloading• ClassLibrary• OOP
• Mix-ininheritanceNotethattheessenQaltraitsoftheexecuQonenvironmentaresimilar,thoughtherearerelevantdifference
inthedesign
CLIhasbeenstandardized(ECMAandISO)andisasupersetofJava.WewillrefermainlytoCLR.
Anewlayertotheonion
ApplicaQonsMLRT
CRTApp1
AppnRT
OS Hw
App2
RunQmemediatesaccessbetweentheapplicaQonandOS
DifferentrunQmesimplementsinadifferentwayLPabstracQonssuchtypes:interoperabilityiscomplex
ApplicaQons
T1
T2
Tn
T3TlTm
CLR OS Hw
RunQmeexposesasupersetofOSServicesthroughtheBCL
ApplicaQonsaregroupoftypesinteracQngtogether
Typesystem
• ExecuQonenvironmentssuchasCLRandJVMaredataoriented
• AtypeistheunitofcodemanagedbytherunQme:loading,code,stateandpermissionsaredefinedintermsoftypes
• ApplicaQonsaresetoftypesthatinteracttogether
• OnetypeexposesastaQcmethod(Main)whichistheentrypointoftheapplicaQon:itloadstheneededtypesandcreatestheappropriateinstances
Javatypesystem• Therearebasetypes:numbers,Object,StringandClass
(whichistheentry-pointforreflecQon)• Typeconstructorsare:
– Array– Class
• ThenumbertypesareunrelatedtoObjectwithrespecttoinheritancerelaQon
• Thisappliestointerfacestoo,butobjectsthatimplementsinterfacesarealwaysinheritedfromobject
• JavatypesystemisfarsimplerthantheoneofCLR
CLRtypesystem
Object
interfaceT
int Basetypes
Type
String
Array
classT
ValueType
T[]
Delegate DelegateT
Enum EnumT
StructT
CLRTypeSystem
• Commonrooted:evennumbersinheritsfromObject• Therearemoretypeconstructors:
– Enum:constants– Struct:likeclassbutwithoutinheritanceandstackallocaQon– Delegate:typethatdescribesasetofmethodswithcommon
signature• Valuetypes(numbersandstructs)inheritsfromobject.SQll
arenotreferencesandaren’tstoredontheheap• Thetrickisthatwhenavaluetypeshouldbeupcastedto
Objectitisboxedinawrapperontheheap• TheoppositeoperaQoniscalledunboxing
FoundaQonof.NETframework–CLR
• CommonLanguageRun(me(CLR)isavirtualmachineenvironmentsivngonthetopofWindowsoperaQngsystem.
• CLRconsistsofCommonTypeSystem(CTS),Just-In-TimeCILCompiler(JIT),VirtualExecu(onSystem,plusothermanagementservices(garbagecollec(on,securitymanagement).
• CLRislikeJVMinJava.ItisassembledinapackageofassemblyconsisQngofMSIntermediateLanguage(MSIL)codeandmanifest(Metadataaboutthispacket).
• TheCILcodeistranslatedintonaQvecodebyJITcompilerinCLR.ILcodeisverifiedbyCTSfirsttocheckthevalidityofdatatypeusedinthecode.
FoundaQonof.NETframework–CLR
• Mul(languagesupport:(VB,managedC++,C#etc)byCommonLanguageCLRimplementaQon.
• AclassinonelanguagecaninheritproperQesandmethodsfromrelatedclassesinotherLanguages.
• TheCTSdefinesastandardsetofdatatypeandrulesforcreaQngnewtypes.– Referencetypes– Valuetypes
• ThecodetargeQngCLRandtobeexecutedbyCLRiscalled.NETmanagedcode.AllMSlanguagecompilersgeneratemanagedcodesthatconformtotheCTS.
FoundaQonof.NETframework–CLR
• TheCILcodeislikeJavabytecode.Regardlessofthesourceprogramminglanguages,ILcodescaninteractbysupportsoftheCLR.
• TheILcodecanbeintheformatofexecutable(.EXE)orDynamicLinkLibrary(.DLL).
• IftheseILcodesaregeneratedby.NETcompiler,theyarecalledmanagedcode.
• Themanagedcodecanbeexecutedonlyon.NETawareplaRorm.SomeDLLorEXEgeneratedbynon.NETcompilers(suchasearlyversionofVC++)arecalledun-managedcode.
FoundaQonof.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
CLR
• TheCLRisahighperformanceexecuQonengine.Itprovidesacode-execuQonenvironmentwhichmanagesthecodetargeQngthe.NETframework.
• Thecodemanagementincludesmanagementofmemory,thread,security,codeverificaQonandILcompilaQon.
The.NETFrameworkClassLibrary
• The.NETframeworkclasslibraryisacollecQonofreusablebasicclasseswhicharewellorganizedbynamespaces.TheframeworkclasslibrarycollectsallclassesincludingWindowsFoundaQonClasses(WFC)intoasingleunifiedsetofclass
• CorrespondtoJavaAPIandpackages• Anamespaceconsistsofmanyclassesandsub-namespaces.It
isdeployedasacomponentclasslibraryitselfandisorganizedinacomponent–basedhierarchy.
• The.NETframeworkitselfisbuiltupinacomponentmodel.
The.NETFrameworkClassLibrary
System
Console Object
Primitive Type Array String
IO
NET
Data
Web
XML
Remoting
Delegate
NameSpace
Class
………
………
The.NETFrameworkClassLibrary
• Developerscancreatecustomnamespaces• Anamespacecanbedeployedasanassemblyofbinarycomponents.
• using <namespace>inC#orimport <namespace>inVBtoaccessclassesinanamespace.
TheComponentModelof.NET
• CILDLLcomponentsarereplacingCOMComponents• MSILRemoIngChannelsEXEcomponentsarereplacingDCOMComponent
• WebServicecomponentsarenewSOAPcomponentsintendedtobecross-plaOorm,andcross-languagewebbasedcomponents.
• The.NETcomponenttechnologyisunified-languageoriented.Any.NETcomponentisintheformatofpre-compiledMSIL,whichcanbebinarypluggedinbyanyotherMSILcomponentsoranyother.NETcompaQbleclients.
TheComponentModelof.NET
• A.NETcomponentisasinglepre-compiledandselfdescribedCILmodulebuiltfromoneormoreclassesormulQplemodulesdeployedinaDLLassemblyfile.
• Anassemblyconsistsofuptofourparts:1)Manifest(tableofinforecords):nameofassembly,keyinfoversion,strongname,cultureinfo,filesthatmakeupassembly,referencedependedassembliesexportedinfo.
2)Metadataofmodules3)CILcodeofmodule4)Resourcessuchasimagefiles.
TheComponentModelof.NET
• AmodulehasCILcodeanditsmetadatabutwithoutmanifest.Notloadabledynamically.BuildingblockatcompileQmetobuildupanassemblyModulefile.Extension:.netmodule.
• AnAssemblyismadeupbyoneormanyclassesinamodule.Assemblyhasamanifestfiletoself-describethecomponentitself.
• Anassemblyhasafileextension.dllor.exeandisdynamicallyloadable.A.dllfileisnotexecutablejustlikeaclassfileisabytecodefilethatisnotexecutable.
TheComponentModelof.NET
• Differenttypesofcomponents.– Visual–likeVisualBasiccontrolswhichcanbedeployedinatoolboxasaniconfor“draganddrop”inawindowformcontainer
– Non-visual–knownas.NETcomponent
TheComponentModelof.NET• A.NETcomponentcanbe
– Local(.dll),canonlybeaccessedlocally(withinsameapplicaQondomain),insamemachine
– Remote(distributed)(.exe),canbeaccessedremotelyinsamemachineordifferentmachines.
• A.NETDLLcomponentcanbedeployed– asaprivatecomponent,whichknowsthetargetclient
– asasharedpubliccomponent,whichdoesnotknowthetargetclient.
• ADLLcomponentcanbeplugged-intoWindowsform,WebformofanotherDLLorapplicaQon.
Using Lib.dll NameSpace Lib
Test.dllor
Test.exe
Lib.dll
CLR Host
Reference
Compile Time
(b) At run time process
(a) At compile time processtest.dll or.exe Lib.dll
Application Domain
TheConnecQonModelof.NET
• .NETcomponentcomposi(ons– ComponentcomposiQonsenablethecomponentreuseineitheraggrega(oncomposi(onsorcontainmentcomposi(ons.
• Containmentcomposi(ons:ifarequesttotheoutercomponentneedshelpsfromaninnercomponenttherequestisforwardedtothatinnercomponent.
• Theoutercomponentdoesnotexposetheinterfaceoftheinnercomponent.
• Theclientisblindofthehandleroftherequest.TheouterM2()delegatesarequesttotheinnerM()methodofinnercomponent
.NETaggrgaQoncomposiQons• Inaggrega(oncomposi(ontheserviceofinnercomponenthandsoutitsservicedirectlytotheclientofoutercomponent.– Theoutercomponentexposestheinterfacesofinnercomponent.
– TheinnerM()methodofinnercomponentbecomespartofinterfacetotheoutercomponent
• A.NETcomponentcanalsobecomposedbymixedaggregaQonsandcontainmentsinaflatstructureornestedcomposiQonsinmulQplelevelsindepth.
Delegates
• The.NETDelegateisamethodtype(areferencetoamethod)whichissimilartofunc(onpointerinC++,butitistype-safeandsecure.
• Adelegatewilldelegateacontrolflowtoitsregisteredeventhandlerwhentheeventisraised.ExampleofdesignpaBernobserver(likeeventlistenerinJava).
• AninstanceofaDelegatecanholdasta(cmethodofaclassoramethodofacomponentoramethodofanobjectitself.
• TwotypesofDelegates:SingleCastorMul(Cast.
SingleCastDelegateASingleCastDelegatecanonlydelegateonemethodataQmeDelegate int MyDelegate();!!public class MyClass !{ public int ObjMethod() {- - - }!static public int StaticMethod () {- - - } }!!public class Drive { !Static public void Main() !{ Myclass c = new MyClass();! int x;! MyDelegate dlg = new MyDelegate(c.objMethod()); ! x=dlg();! dlg = new MyDelegate (MyClass.StaticMethod());! x=dlg();! }}!
SingleCastDelegate
• Asseeninthisexample,MyDelegateisaDelegatewhichreferencesanymethodwithintreturntypeandwithoutanyparameter.
• ThesignaturesofobjMethodandStaticMethodmatchtheDelegateMyDelegate.
• Thefirstdlg()invokesobjMethodandtheseconddlg()invokestheclassmethodStaticMethod.
MulQCastDelegate• AMul(CastDelegatehasavoidreturntypeandcanbindmulQple
methodsanditwillinvokethemintheorderofregistraQons.Example:
Delegate void MultiDelegate();!MultiDelegate mdlg = null;!mdlg += new MultiDelegate (Method1);!mdlg += new MultiDelegate (Method2);!!• RegistraQonisdoneby+= DelegateoperaQonand
unregistraQonisdoneby-= operation.• TheDelegateplaysaroleoflistener,andeventhandlermust
registerthislistenertobeabletohandletheeventoncetheeventisfired.
ThecommunicaQonofComponentsbyEventandDelegate
• Aneventisamessagesentbyanobject(theeventsource)toinvokeanacQon.Theobjectthatinterceptstheeventandhandlesitistheeventtarget.
• Event-drivencommunica(onmodelbetweencomponentsorwithinsamecomponent.
• TheDelegateclassisthecommunicaQonchannelclassbetweeneventsourceandeventtarget.
• EventscanbepredefinedsuchaseventstriggeredbyaWindowsFormcomponent.Adevelopercanalsodefineacustomevent.
ThecommunicaQonofComponentsbyEventandDelegate
1. Createadelegateclass.PublicdelegatevoidDelegateStart();
2. Createaclasscontainingadelegatefield,ClassMyClass{publiceventDelegateStartEventStart; ---
3. DefineaneventhandlerpublicvoidhandleEvent(){---}
4. Binddelegateeventwitheventhandlerviaeventlistener,triggeranevent,invoketheeventhandler.
PublicstaQcvoidMain(){MyClassEventObj=newMyClass(); EventObj.EventStart+=newDelegateStart(handleEvent); EventObj.EventStart(); ___
}
RemoQngConnectorsfor.NETDistributedComponents
• AcomponentoraclientcannotdirectlyaccessaremotecomponentrunningindifferentapplicaQondomaininsameordifferentprocessesunlessusingRemoQngchannelconnecQon.
• Themarshalingmakesitpossibletoinvokearemotemethodofadistributedcomponent.
• Therearetwowaystomarshalanobject:inMBV(MarshalbyValue)serverpassesacopyofobjecttoclientorinMarshalbyReference(MBR)clientcreatesaproxyofaremoteobject.
• Whenaremotecomponentmustrunataremotesite,MBRistheonlychoice.
• SimilartoRMIinJava
RemoQngAsynchronousCallbackInvocaQonBetweenDistributed.NETComponents
• TheRemoQngasynchronouscallbackisbasedonRemo(ngDelegate.ItwillnotblockouttheclientwhilewaiQngfornoQficaQonfromremotecomponents.
• Forexample,someonewantstobenoQfiedoncethestockpricesreachesaspecifiedlevel.InsteadofpoolingthestockpricealltheQme,whynotlettheservernoQfyyouandyoucandowhateveryouwanttodo.
• Insomeothercases,thejobsonserverwilltakeverylongtocomplete,whynotlettheservernoQfyyouwhenthejobisdone.
• Whenclientmakesasynchronouscalltoremotemethodofremotecomponent,itpassesacallbackmethodtoservertobecalledbacklatethroughRemo(ngDelegate.
NETComponentDeployments
• A.NETcomponentcanbedeployedasprivatecomponentorpublicsharedcomponentinanassemblyfile.Theassemblyisanatomicdeployment(distribuQon)unitin.NETFramework.
• Aprivatecomponentknowsthecomponentwhereitwillbeplugged-in.Apublicsharedcomponentdoesnotknowwhichcomponentwilluseitself.
• Itmustbepublished(registered)inacentralizedrepositoryGlobalAssemblyCache(GAC).Asharedcomponentsupportsside-by-sidemulQpleversioncomponentexecuQon.
PrivateDeployment
• APrivatecomponentmustbedeployedinasamedirectoryofitsclientorsub-directoryofwheretheclientis.Itisthesimplestdeploymentdonebycopyingallcomponentstowheretheclientis.
• Theundeploymentisdonebysimplyremovingallrelated.dllcomponentsfromthedirectory.Aprivatecomponentdoesnotsupportversioningcontrolandforin-housedevelopmentwithinacompany.Thefollowingshowsanexampleofprivatedeployment
top related