1 / 19

Th e Microsof t .NET Framework • Th e Commo n Languag e Runtime • Commo n Languag e Specification

Microsof t Visua l Studio 2005/2008 an d th e .NE T Framework (C ) Richar d R . Eckert. Th e Microsof t .NET Framework • Th e Commo n Languag e Runtime • Commo n Languag e Specification – Programmin g Languages • C# , Visua l Basic , C++ , lot s o f others • Manage d Module s (Assemblies)

dugan
Download Presentation

Th e Microsof t .NET Framework • Th e Commo n Languag e Runtime • Commo n Languag e Specification

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MicrosoftVisualStudio 2005/2008 andthe.NETFramework (C)RichardR.Eckert TheMicrosoft.NETFramework •TheCommonLanguageRuntime •CommonLanguageSpecification –ProgrammingLanguages •C#,VisualBasic,C++,lotsofothers •ManagedModules(Assemblies) •MSIL •The.NETFrameworkClassLibrary (C)RichardR.Eckert

  2. .NETArchitecture (C)RichardR.Eckert Compilationinthe.NET Framework Common Language Runtime

  3. Namespace •Acollectionofrelatedclassesandtheirmethods •FCLiscomposedofnamespaces •NamespacesarestoredinDLLassemblyfiles •.NETapplicationsmusthave“references”tothese DLLssothattheircodecanbelinkedin •AlsoshouldbeincludedinaC#programwiththeusing declaration –e.g.usingSystem.Windows.Forms; –Ifleftout,youmustgivethefullyqualifiednameofanyclassmethodorpropertyyouuse,e.g. System.Windows.Forms.MessageBox.Show(…); •SomethinglikeapackageinJava (C)RichardR.Eckert SomeImportant.NetNamespaces •SystemCoredata/auxiliaryclasses •System.CollectionsResizablearrays+othercontainers •System.DataADO.NETdatabaseaccessclasses •System.DrawingGraphicalOutputclasses(GDI+) •System.IOClassesforfile/streamI/O •System.NetClassestowrapnetworkprotocols •System.ThreadingClassestocreate/managethreads •System.WebHTTPsupportclasses •System.Web.ServicesClassesforwritingwebservices •System.Web.UICoreclassesusedbyASP.NET •System.Windows.FormsClassesforWindowsGUIapps •Seeonlinehelpon‘ClassLibrary’ (C)RichardR.Eckert

  4. C# •Anewcomponent&objectorientedlanguage -Emphasisontheuseofclasses •PowerofC++andeaseofuseofVisualBasic •CombinesthebestaspectsofC++andJava -ConceptuallysimplerandmoreclearthanC++ •Muchsmallercodefilesandexecutables -MorestructuredthanVisualBasic -MorepowerfulthanJava -Manygreatnewconstructs •SyntaxverysimilartoC/C++ -Noheaderfiles •Managedpointersonly -"Almostnopointers"�"almostnobugs" (C)RichardR.Eckert C#Classes -“Fields”:Datamembers(likeC++variables) -“Methods”:Codemembers(likeC++functions) -“Properties”:In-betweenmembersthatexposedata •Totheuserprogramtheylooklikedatafields •Withintheclasstheylooklikecodemethods •Oftentheyprovidecontrolledaccesstoprivatedatafields -Validitycheckscanbeperformed -Valuescanbeobtainedorchangedaftervaliditychecks »PropertiesuseAccessormethodsget()andset() »get()toretrievethevalueofadatafield…returndata-field; »set()tochangethevalueofadatafield…data-field=value; -OtherclassesusePropertiesjustlikedatafields -"Events":Definethenotificationsaclassiscapableoffiringinresponsetouseractions (C)RichardR.Eckert •Cancontain:

  5. Example:Squareclass publicclassSquare { privateintside_length=1;//AField publicintSide_length//AProperty { get{returnside_length;}//“return”:specifiesvaluegoingout set { if(value>0) side_length=value;//“value”:specifiesvaluethatcameIn else throw(newArgumentOutOfRangeException()); } } publicintarea()//AMethod { return(side_length*side_length); } publicSquare(intside)//TheConstructormethod { side_length=side; }(C)RichardR.Eckert } InstantiatingandUsingtheSquareClass Squaresq=newSquare(10);//ConstructaSquareobjectcalledsq //ofside_length=10 //Instantiatestheobjectandinvokes //theclassconstructor intx=sq.Side_length;//Retrieveobject’sSide_LengthProperty sq.Side_length=15;//Changeobject’sSide_lengthProperty inta=sq.area();//Defineanintegervariableaanduse //theclassarea()methodtocompute //theareaofthesquare MessageBox.Show(“Area=“+a.ToString()); //DisplayresultinaMessageBox //NoteuseofToString()method //toconvertanintegertoastring. //Show()isastaticmethodofMessageBox //class (C)RichardR.Eckert

  6. WindowsForms •AWindowsForm:In.NETit’sjustawindow •Formsdependonclassesinthenamespace‘System.Windows.Forms’ •Formclassisin‘System.Windows.Forms’: -TheheartofeveryWindowsFormsapplicationisaclassderivedfromForm •Aninstanceofthisderivedclassrepresentstheapplication’smainwindow •InheritsmanypropertiesandmethodsfromFormthatdeterminethelookandbehaviorofthewindow -E.g.,Textpropertytochangethewindow’scaption •Application:Anotherimportantclassfrom‘System.Windows.Forms' -ItsstaticmethodRun(…)drivestheWindowsFormapplication •ArgumentistheFormtoberun -Invokedintheprogram’sentrypointfunction:Main() -Causestheprogramtocreatetheformpassedtoitandenterthemessageloop •Form’sconstructorwillrun(typicallycodetosetinitialwindowproperties) -TheformpassedtoRun()hascodetopostaQUITmessagewhenformisclosed -ReturnstoMain()whendoneandprogramterminatesproperly (C)RichardR.Eckert ASimpleWindowsFormAppinC#-- HelloWorld usingSystem.Windows.Forms;//thenamespacecontaining //theFormclass publicclassHelloWorld:System.Windows.Forms.Form {//ourclassisderivedfromForm publicHelloWorld()//ourclassconstructor { this.Text="HelloWorld";//Setthisform’sTextProperty } staticvoidMain()//Application’sentrypoint { Application.Run(newHelloWorld());//Runourform } } (C)RichardR.Eckert

  7. CompilingaC#Applicationfromthe CommandLine •StartaCommandWindowwiththeproperpathstothecompiler/linkerset –Easiestway:FromTaskBar: •‘Start’|‘AllPrograms’|‘MicrosoftVisualStudio2008|‘VisualStudio Tools’|‘VisualStudio2008CommandPrompt’ •StartstheDOSBoxCommandWindow –Navigatetothedirectorycontainingthesourcecodefile(s) –FromthecommandpromptInvoketheC#compilerandlinker –Forexample,tobuildanexecutablefromtheC#sourcefile myprog.cs,typeoneofthefollowing: cscmyprog.cs(easiestway,createsaconsoleapp) csc/target:exemyprog.cs(alsocreatesaconsoleapplication) csc/t:winexemyprog.cs(createsaWindowsexecutable) csc/t:winexe/r:System.dll,System.Windows.Forms.dllmyprog.cs (toprovideaccesstoneeded.NETDLLs) (C)RichardR.Eckert UsingVisualStudiotoDevelopa SimpleC#Application“Manually” •StartVisualStudioasusual •‘File’|‘New’|‘Project’|‘VisualC#’|‘Windows’|‘Empty Project’ •Tocreatetheprogram –‘Project’|‘AddNewItem’ •VisualStudioinstalledtemplates:‘C#CodeFile’ –Thiswillbringupthecodeeditor –TypeinorcopyandpastetheC#sourcecode •Butyoumustalsoprovideaccesstosomeadditional.NETCommonLanguageRuntimeDLLs •Dothisbyadding‘References’: –‘Project’|‘AddReference’…‘.NET’tab –Select:SystemandSystem.Windows.Forms •Buildprojectasusual(‘Build’|‘BuildSolution’) (C)RichardR.Eckert

  8. UsingVisualStudio’sDesignertoDevelopa SimpleC#Application •‘File’|‘New’|‘Project’|‘VisualC#’|‘Windows’|‘Windows FormsApplication’ –Givesa“designerview”oftheWindowsFormtheprojectwillcreate –Alsocreatesskeletoncodeinthree.csfiles,2classes •2Partialclasses:Form1.Designer.cs&Form1.cs+Programclass •Rightclickonform&select‘ViewCode’toseeForm1.cs •Notehowit’sbrokenupinto‘Regions’(+and-boxesontheleft) •Thesecanbeexpandedandcontracted –ToseecodegeneratedbytheVisualStudiodesigner: •InSolutionExplorer,expandForm1.cs&doubleclickon Form1.Designer.cs •Expandthe‘WindowsFormDesignergeneratedcode’Region (C)RichardR.Eckert •StartVisualStudioasusual WhereisMain()? -ExpandtheProgramclass •ThatiswhereMain()is •ItrunstheFormjustasinourmanualcode (C)RichardR.Eckert

  9. ChangingFormProperties •InForm1.Designer.cs,notetheForm’spropertiesthathavebeenpreset –Changecodesothe‘Text’propertyis“ThisisaTest” •ReactivatetheDesignerViewbyclickingonthe‘Form1.cs [design]’tab –Notehowthecaptionoftheformhaschanged •Lookatthe‘Properties’window •Findthe‘Text’PropertyandchangeitbyTyping‘HelloWorld’ –ActivateForm1.Designer.csandnotehowcodehaschanged •InDesignerViewresizetheform(dragitscorners) –notehowtheClientSizepropertychangesinForm1.Designer.cscode •ChangetheBackgroundColorinthePropertiesBoxtored: –Clickon‘BackColor’|downarrow|“custom”tab|redcolorbox –GobacktoForm1.Designer.csandnotechangesincode •Buildandruntheapplication (C)RichardR.Eckert .NETManagedModules(PEAssemblies) •TheresultofbuildingaprogramwithanyofthecompilerscapableofgeneratingMSIL:VC++,C#,VB,others –AlsoILASM(IntermediateLanguageAssembler) –Assembliesaredeploymentunitsof.NETappsstoredas.EXEfiles –‘PortableExecutables’(PEs)toberunbytheCLR •Assemblystructure(contents) –Metadatafullydescribingthecompleteassemblyanditsexternaldependencies •Meanseverymanagedmoduleis“selfdescribing” •Oneofthekeystolanguageinteroperability –Typemetadatadescribingexportedtypesandmethods –MSILcode –Resources •Themanifest Akindorroadmaptotheassembly’scontents Alsocontainspermissionsneededtoruntheassembly •CanexamineAssemblieswithatoolcalledILDASM (C)RichardR.Eckert

  10. TheILDASMDisassembler •Usedtoexamineanassembly’smetadataandcode •StartaCommandWindowwithproperpathto ILDASMset –Easiestway:FromTaskBar: •‘Start’|‘AllPrograms’|‘MicrosoftVisualStudio.NET’|‘Visual Studio.NETTools’| •StartstheDOSBoxCommandWindow –Navigatetothedirectorycontainingtheassembly(.exe) –InvokeILDASM •e.g.,forHelloWorldprogram: ILDASMHelloWorld.exe •Displaysawindowshowingtheassembly’sManifestandtheclassesintheassembly (C)RichardR.Eckert ASessionwithILDASM •DoubleClickon‘Manifest’ –Listofassembliesthatmoduledependson –Assemblyname –Modulesthatmakeuptheassembly •BecauseHelloWorldisasingle-fileassembly,thereisonlyone •ExpandHelloWorldclass –Classcontainstwomethods: •Aconstructor(.ctor) •Main(‘S’meansit’sastaticmethod) –ExpandMain •.entrypointisadirectiveindicatingit’swhereexecutionstarts •CodeinstantiatesaHelloWorldobjectandcallsApplication.Runfortheform –Expand.ctor •CallsparentForm’sconstructor •Puts“HelloWorld”stringonstackandcallsset_Text(…)tosettheform’sTextproperty (C)RichardR.Eckert

  11. Events,Delegates,andHandlers –Events:Resultsofuseractions –Butin.NETeventsarealso“classnotifications” –Classesdefineandpublishasetofeventsthatotherclassescansubscribeto •Whenanobjectchangesitsstate(theeventoccurs),allotherobjectsthatsubscribetotheeventarenotified –Eventsareprocessedbyeventhandlermethods –Theargumentstoaneventhandlermustmatchthoseofafunctionprototypedefinitioncalledadelegate: •Amethodtowhomeventhandlingisdelegated –Amanagedpointertoafunction •Atype-safewrapperaroundaneventhandlercallbackfunction –Handlermustuseparametersspecifiedindelegatearguments •“Attaches”thehandlerfunctiontotheevent •Permitsanynumberofhandlermethodsforagivenevent (C)RichardR.Eckert (C)RichardR.Eckert

  12. (C)RichardR.Eckert (C)RichardR.Eckert

  13. (C)RichardR.Eckert Events,Delegates,Handlers (C)RichardR.Eckert

  14. AnExample–HandlingaPaintEvent •FormclasshasaPainteventtonotifyofwindowexposures •ThedelegateisPaintEventHandler,definedas: publicdelegatevoidPaintEventHandler(objectobjSender,PaintEventArgspea); -Firstargument:sender"object"(whereeventocurred) -Secondargument"PaintEventArgs":provideseventdata •Aclasswithproperties‘Graphics’and‘ClipRectangle’ -‘Graphics’property:containsaninstantiationofthe Graphicsclass(GDI+) »Theclassisusedtodrawonaform(likeaDevice Context) -ClipRectangle:Specifiestheareaofthewindowthatneedstoberedrawn •AnyPainthandlermethodmusthavethesearguments •AndthePainthandlermustbe"attached"tothePainteventofthe Formclass(i.e.,delegatedtothehandler) DefiningthePaintEventHanderandAttaching ittotheEvent •Definingtheform’sPainteventhandlermethod: privatevoidMyPaintHandler(objectobjsender,PaintEventArgspea) { //eventhandlingcodegoeshere }; •Attachingthehandlertotheform’sEvent (delegatingittotheeventhandler): form.Paint+=newPaintEventHandler(MyPaintHandler); – FromnowonMyPaintHandler(-,-)willbecalledanytimethePainteventoccurs •Ahandlercanalsobe“detached”fromanevent: object.event-=newdelegate(method); (C)RichardR.Eckert

  15. DrawingTextinResponsetoaPaintEvent •System.Drawingnamespacecontainsmanyclassesandstructuresfordrawingonawindow •Someofthem: –Bitmap,Brush,Brushes,Color,Font,Graphics,Icon,Image,Pen,Pens,Point,Rectangle,Size •GraphicsClass –RepresentsaGDI+drawingsurface •Likeadevicecontext –Containsmanygraphicsdrawingmethods •SeeHelpon‘Graphicsclass’|‘allmembers’ –Obtainingagraphicsobject: •InPainteventhandler,usesecondargument: –PaintEventArgspeaprovidesaGraphicsobject –Getitwithfollowingcode:Graphicsg=pea.Graphics (C)RichardR.Eckert UsingDrawString()toDrawText •GraphicsDrawString()methodhaslotsofoverloads •Simplest: DrawString(stringstr,Fontfont,Brushbrush,floatx,floaty); –stringclass:analiasforSystem.String •Definesacharacterstring •Alsohasmanymethodstomanipulateastring –Fontclass:givesaWindowsFormprogramaccesstomanyfontswithscalablesizes •AFormhasadefaultFont:It’soneoftheForm’sproperties •OryoucaninstantiateanewFontobject:Lotsofpossibilities(we’llseelater) –BrushorBrushesclass:color/styleofcharacters •Lotsofdifferentstaticcolorproperties,e.g. Brushes.Black,Brushes.Red •OrwecancreateoneofaspecifiedColor Brushbr=newSolidBrush(Color.FromArgb(r,g,b)); Brushbr=newSolidBrush(Color.Red); –Colorstructurehasmanystaticmethodsandproperties –x,y:Locationtodrawstringonwindowclientarea (C)RichardR.Eckert

  16. Hello_in_windowExampleProgram •RespondstoPaintEventbydisplaying‘HelloWorld’inwindow’sclientareausingseveraldifferentBrushes •ManualProject -DefineHandlerandAttachittoPainteventmanually •DesignerProject -SelectthePainteventintheform’sPropertieswindow •Clickonlightningbolt •Doubleclickon"Paint"event -Attachmentofhandlerusingitsdelegateisdoneautomatically -Skeletonhandlercodegeneratedautomatically (C)RichardR.Eckert AnAlternativetoInstallingEventHandlers: OverridinginsteadofAttaching •Inanyclassderivedfrom‘Control’(e.g.‘Form’), itsprotectedOnPaint()andothereventhandlerscanbeoverridden: protectedoverridevoidOnPaint(PaintEventArgspea) { //Paintingcodegoeshere }; -Avoidshavingtoattachthehandlertotheeventusingthedelegate •SeeHelloWorld_overrideexampleprogram (C)RichardR.Eckert

  17. ASeparateClassforMain() •Analternativewayoforganizinga WindowsFormapplication: -DefinetheForminoneclass -PlacetheMain()functioninanotherclass -VisualStudio2008designerdoesthis automatically -Coulddoitmanually •SeeSeparateMainexampleprogram (C)RichardR.Eckert InheritingFormClasses •JustasyourForminheritsfrom ‘System.Windows.Forms.Form’,youcansetupanewFormthatinheritsfromapreviouslydefinedForm •BesureitsMain()includeskeyword‘new’ •AndthatVisualStudioknowswhichclass’Main() istheentrypoint: -Inproject’sPropertiesboxselect‘PropertyPages’icon •‘CommonProperties’|‘General’|Application’|‘Startup Object’ •Select‘InheritHelloWorld’ •SeeHelloWorld_inheritexample (C)RichardR.Eckert

  18. MultipleHandlers •Anadvantageofthedelegatemechanismisthatmultiplehandlersofthesameeventcanbeused •Justattacheachhandlertotheevent -Forexample: Form.Paint+=newPaintEventHandler(PaintHandler1); Form.Paint+=newPaintEventHandler(PaintHandler2); •Andthenwritethehandlers •Eachtimetheeventoccurs,allhandlerswillbecalledinsequence •SeeTwoPaintHandlersexample (C)RichardR.Eckert SomeotherGDI+DrawingMethods –DrawArc(); –DrawEllipse(); –DrawLine(); –DrawPolygon(); –DrawRectangle(); –FillEllipse(); –FillPolygon(); –FillRectangle(); –Lotsofothersin‘Graphics’class •Seeonlinehelponvariousoverloadedformsofcallingthese functions (C)RichardR.Eckert

  19. RandomRectanglesExampleProgram –MakesuseofFillRectangle()GDI+method –‘Random’classcontainsmanymethodstogeneraterandomnumbers Randomr=newRandom(); –InstantiatesanewRandomobjectandseedsthepseudo-randomnumbergenerator •The‘Next()’methodactuallygeneratesthenumber –ManyoverloadedformsofNext() •Gettingarandomcolor: Colorc=Color.fromArgb(r.Next(256),r.Next(256),r.Next(256)); –UseForm’sClientSizePropertytogetwidthandheightofwindow –Drawfilledrectanglewithrandomsizeandcolor: •UseFillRectangle()andMath.Min(),Math.Abs() (C)RichardR.Eckert

More Related