the philosophy of · the role of the common language runtime (clr) • the common language runtime...

119
Copyright © Intertech, Inc 2014 Rev: 27 1-1 Chapter 1 The Philosophy of .NET Objectives: Understand the scope of the .NET platform Understand the role of the Common Type System (CTS) Understand the role of the Common Language Specification (CLS) Understand the role of the Common Language Runtime (CLR) Know the distinction between an assembly, namespace and type Understand the role of the Common Intermediate Language (CIL) Understand the role of the Common Language Infrastructure (CLI) Work with the C# command line compiler (csc.exe) Survey several popular .NET languages and IDEs

Upload: others

Post on 06-Mar-2021

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Copyright©Intertech,Inc2014Rev:27 1-1

Chapter 1  

ThePhilosophyof.NET

Objectives:

Understandthescopeofthe.NETplatform

UnderstandtheroleoftheCommonTypeSystem(CTS)

UnderstandtheroleoftheCommonLanguageSpecification(CLS)

UnderstandtheroleoftheCommonLanguageRuntime(CLR)

Knowthedistinctionbetweenanassembly,namespaceandtype

UnderstandtheroleoftheCommonIntermediateLanguage(CIL)

UnderstandtheroleoftheCommonLanguageInfrastructure(CLI)

WorkwiththeC#commandlinecompiler(csc.exe)

Surveyseveralpopular.NETlanguagesandIDEs

Page 2: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-2 Copyright©Intertech,Inc2014 Rev:27

Overview

Thepointofthisfirstchapteristoprovideafoundationfortheremainderoftheclass.

Hereweexaminesomecoretopicsofthe.NETworld,includingtheroleofassemblies,namespacesandtypes.Wewillalsospendsometimeexaminingvariousimportant.NETspecificationsandservices,includingtheCTS,CLSandCLR.

Thefinalaspectofthischapteristosurveyanumberoflanguages(andtools)whichcanbeusedtobuildmanagedcode,includingC#,VBandC++/CLI.

Withthisfoundationinplace,youwillhavetheproperfoundationtobuild.NETsolutionsusingC#andyourIDEofchoice.

Page 3: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-3

A First Look at the .NET Platform               

• TheC#programminglanguage,andtheMicrosoft.NETplatform,werefirstreleasedcirca2003.

• Priortothereleaseof.NET,theComponentObjectModel(COM)wasthepreferredwaytobuildapplicationsforMicrosoftWindowsusingMicrosofttechnologies.

• YoumayhaveheardCOMdescribedusingotherrelatedtermssuchasActiveXorOLEautomation.

• WhileCOMapplicationsdidprovideanumberofbenefits…

• COMwasafairlycomplexprogrammingdiscipline.

• Developersneededtomanuallymanagememory.

• COMalsodemandedprogrammersimplementagooddealofinterfaces,authorcomplexdescriptionsoftheircode(viaIDL)andregistercomponents.

• WhileCOMisstillusedtoday,mostmoderndaydesktopapplicationsandwebsitesconstructedwithMicrosofttechnologiesmakeuseofthe.NETplatform.

• Dobeawarethatthe.NETplatformdoessupportinteroperabilitywithCOMapplications.

• Itispossibletobuilda.NETapplicationwhichmakesuseofCOMlibraries,andviceversa!COMapplicationscanalsomakeuseof.NETlibraries.

• .NETandCOMinteroperabilityisnotcoveredinthiscourse;howeveraskyourinstructorifyouhaveinterestinthetopic.

• SowhatexactlyistheMicrosoft.NETplatform?Fromahighlevel,.NETis:

• Arobustruntimeenvironmentforsoftwarecomponents.

• Aplatformforbuildingalltypesofsoftware(webanddesktopapplications).

• Alanguageagnosticprogrammingplatform.

• AsetofspecificationssubmittedtoECMAInternationaltoallowportstonon‐Windowsoperatingsystems.

• Acollectionofcodelibrariesonecanuseasastartingpointforcustomapplicationdevelopment.

Page 4: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-4 Copyright©Intertech,Inc2014 Rev:27

• The.NETplatformrunsontopoftheunderlyingoperatingsystem.

• WindowsVistaandhighershipwiththe.NETplatformpreinstalled.

• WindowsXPcanbeconfiguredusingthefreelydownloadable.NETplatforminstallernameddotnetfx.exe(theexactnameoftheexecutablewillbebasedonwhichversionof.NETyouareinstalling).

• OtherOSs(Mac,Linux,Solaris,etc.)requireinstallationofanECMA‐compliant.NETdistribution(moreinformationattheendofthischapter).

• Considerthefollowinghigh‐levelfirstlookatthe.NETplatform,withfurtherdetailsonthenextpage.

Page 5: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-5

• Hereareafewkeyterms.NETdevelopersshouldbeawareof(eachofwhichwillbedetailedlaterinthischapter):

• CommonTypeSystem(CTS):Astandardfortypedefinitionsandfunctionalitythat.NETlanguages*can*support.

• CommonLanguageSpecification(CLS):AsubsetoftheCTSthatall.NETlanguages*must*support.

• CommonLanguageRuntime(CLR):Aruntimeforexecuting.NETcodewithgarbagecollection,securitychecks,typeverification,threadmanagement,assemblyresolutionandotherruntimeservices.

• CommonIntermediateLanguage(CIL):All.NETlanguagescompiletothisplatform‐independentlanguage.Thisistheonetruelanguageof.NET(languagessuchasC#orVBarehigherlevelabstractions).

• Assemblies:AnewnameandformatforEXEandDLLfiles.Moreinformationon“assemblies”abitlaterinthischapter.

Page 6: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-6 Copyright©Intertech,Inc2014 Rev:27

The Role of the Common Type System (CTS) 

• TheCommonTypeSystem(CTS)isaformalspecificationdescribinghow"types"mustbedefinedtoworkinthe.NETworld.

• "Type"isageneraltermdescribingthefundamentalprogrammingconstructsusedwhenbuildinga.NETprogram(classes,interfaces,enumerations,structuresanddelegates).

• TheCTSsolvesmanylanguage‐interoperabilityissues,asall.NETlanguagessharethesameintrinsicdatatypes.

• Youwilllearnabouteachofthesetypesoverthenextseveralchapters.

• Any.NETlanguageisfreetodefineitsowncorrespondingkeywordsforeachintrinsicbasicdatatype(e.g.,int,long,short,string,bool).

• Althougheachlanguagewillhaveuniquekeywordsforfundamentaldatatypes,theyareshorthandnotationsforthecorresponding.NETdatatype.

• The.NETdatatypesaredefinedinakeynamespacenamedSystem.

• Someexceptionsdoexist.Forexample,languagesmayvaryontheirsupportforunsignedtypes,andmaynothavespecifickeywords.

Page 7: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-7

• HereisasummaryofC#,VBandC++/CLIkeywordsforfundamentaldatatypes.

• Againnotice,thateachC#keywordisashorthandforacorrespondingdatatypeintheSystemnamespace.

.NETDataType C#Keyword VBKeyword

C++/CLIKeyword

System.Byte byte Byte char

System.SByte sbyte SByte signedchar

System.Int16 short Short short

System.Int32 int Integer intorlong

System.Int64 long Long __int64

System.Uint16 ushort UShort unsignedshort

System.Uint32 uint UInteger unsignedintorunsignedlong

System.Uint64 ulong ULong unsigned__int64

System.Single float Single float

System.Double double Double double

System.Object object Object Object

System.Char char Char __wchar_t

System.String string String String

System.Decimal decimal Decimal Decimal

System.Boolean bool Boolean bool

Page 8: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-8 Copyright©Intertech,Inc2014 Rev:27

• BecauseC#keywordsforfundamentaldatatypesareshorthandnotationsforthecorresponding.NETdatatype,thefollowingcodeisfunctionallyequivalent:

• NoticethattheC#intkeywordisreallyjustSystem.Int32.

private static void MakeSomeInts() { // Create a 32-bit integer with the C# keyword. int i = 22; Console.WriteLine("The value of i is {0}", i); // Create another 32-bit integer using the .NET // system type. Int32 i2 = new Int32(); i2 = 22; Console.WriteLine("The value of i2 is {0}", i2); }

• MostprogrammerswillprefertousetheC#keywords(int,double,short,bool,etc.)todefinesimpledatatypes.

• However,itisveryimportanttorememberthattheC#keywordsarefunctionallyequivalenttothecorresponding.NETdatatype.

• Forexample,becausetheintkeywordisashorthandforSystem.Int32,youwillfindthatthe“simpledatatypes”havebuiltinfunctionality!

• WewillexplorethistopicinmoredetailinChapter4;howeverconsiderthefollowingscreenshot.Noticehowtheintdatatypesupports“real”functionality,includingthefollowingpublicmethods.

Page 9: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-9

The Role of the Common Language Specification (CLS) 

• TheCommonLanguageSpecification(CLS)isasubsetoftheCTS.

• TheCLSdefinestheminimalfeaturesalanguagemustsupporttobeconsidereda.NETlanguage.

• IfacomplierabidesbytheCLSrules,allother.NETlanguagescanusetheresultingbinariesinauniformmanner.

• Byandlarge,onlydeveloperscreatinganew.NETlanguagecompilerneedtoengrossthemselvesinthefulldetailsoftheCLS(orCTS).

• Nevertheless,itisenlighteningtoexaminesomeoftheserulesfirsthand.

• CLSrule:AllclassesultimatelyderivefromSystem.Object:

• WewillseethedetailsofSystem.Objectlaterinthisclass.

• Forthetimebeing,simplyunderstandthateverythinginthe.NETuniverse(integers,databaseconnections,webpages,etc.)havethefollowingsharedfunctionality.

// The top-most class in the .NET world: System.Object public class Object { // Reference equality by default. Override for value semantics. public virtual bool Equals(object obj); // Get hash value for object. public virtual int GetHashCode(); // RTTI for this object. public Type GetType(); // Override to produce state data in string format. public virtual string ToString(); // Override to cleanup resources (non-deterministic destruction) protected virtual void Finalize(); // System.Object also defines two static functions. public static bool Equals(object objA, object objB); public static bool ReferenceEquals(object objA, object objB); }

Page 10: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-10 Copyright©Intertech,Inc2014 Rev:27

• CLSrule:Everyclasshasexactlyonedirectbaseclassbutmayimplementmultipleinterfaces.

• LikeJava,theCLSdoesnotsupportmultipleinheritanceforclasstypes.C++developerstakenote!

• LikeJava,theCLSallowsaclasstoimplementmultipleinterfaces.

• Itispossibleforaninterfacetohavemultiplebaseinterfaces.Inotherwords,multipleinterfaceinheritanceissupported.

• YouwilllearnaboutinterfacesinChapter3.

• CLSrule:Everytypeinanassemblymustspecifyitsvisibility.Althoughagivenlanguagemayhaveuniquekeywords,thebasicvisibilitysettingsare:

• Public:visibletoanyone,anywhere.

• Private:onlyvisibletomembersofthedefiningtype.

• Protected:onlyvisibletomembersofthedefiningtypeormembersofderivedtypes.

• Internal:visibletoanytypedefinedwithintheassembly.

• InC#,thedefaultaccessmodifierfora(non‐nested)typeisinternal.

• Thedefaultaccessmodifierforamemberofatype(amethod,property,datamember,constructor,nestedtype,etc.)isprivate.

• WewillexaminethesedefaultsinmoredetailsbeginninginChapter2,howeverhereisascreenshotthatillustratestheC#accessmodifierdefaults.

Page 11: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-11

The Role of the Common Language Runtime (CLR) 

• TheCommonLanguageRuntime(CLR)istheenginewhichmanagesyour.NETapplications.TheCLRprovidesseveralusefulservices,including:

• Memorymanagementviaagarbagecollector.WhencreatingobjectsinC#,theCLRwillautomaticallyremoveyourmemorywhenitisnolongerused.

• Locatingexternallibrariesforthecurrentapplication.TheCLRwilllocateandloadanyexternallibrariesagivenapplicationrequires.

• Performingsecuritycheckswhenrequired,coordinatingthreads,handlingfileIO,etc.

• Inmanycases,youwillnotneedtodirectlyinteractwiththeCLR,howeveritispossible.

• Forexample,theSystem.GCclassallowsyoutointeractwiththegarbagecollector(however,youwillseldom,ifeverneedtodoso).

• Atthesystemlevel,thecruxoftheCLRiscontainedwithinalibrarynamedmscoree.dll(the“Microsoftcoreexecutionengine”).

• Anapplicationwhichrunsunderthewatchfuleyeofmscoree.dlliscalledmanagedcode.

• Incontrast,VB6/COM/nativeC++applicationsareallunmanagedcode….theCLRhasnoideawhattodowiththem.

• Theonlywaymanagedandunmanagedcodecancommunicateisthroughthe.NETinteroperabilitylayer.

Page 12: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-12 Copyright©Intertech,Inc2014 Rev:27

The Role of .NET Base Class Libraries 

• The.NETplatformshipswithalargebodyofexistingcodetermedtheBaseClassLibraries(BCL).

• TheBLCisalsoknownastheFrameworkClassLibrary(FCL).

• ProgrammersusetheBCLasastartingpointfornewapplicationdevelopment.

• TheBCLprovidestypeswhichcanbeusedtobuildwebsites,desktopapplications,communicatewithrelationaldatabasesandmany,manyotherservices.

• TheBCLorganizesitshugesetofservicesusingaconceptcallednamespaces.

• Anamespaceisalogical,hierarchicalorganizationoftypessimilartoJavapackages.

• All.NETtypes“live”inanamespace.Touseatype,youmustrefertoitusingitsfullyqualifiedname(i.e.,includingthenamespace).

• Namespaces,inturn,arepackedupintovariousassemblies.Recallthatan“assembly”isjustanewtermforaDLLorEXEbuiltwitha.NETcompiler.

• Whiletherearemanyassemblies,thereisoneparticularassemblywhichall.NETapplicationshaveautomaticaccessto:mscorlib.dll.

• Remember:Youalwayshaveaccesstomscorlib.dllwhenyoubuildanynew.NETproject‐youcan’tgetridofit(norwouldyouwantto)!

• Mscorlib.dllcontainsdozensofcommonlyusednamespaces,withtheirrelatedtypes.

• Asyouwillsee,mscorlib.dllhasfunctionalityforfileIOoperations,basicsecurityandthreading,XMLmanipulation,andothertasks.

• ThislibraryalsodefinestheSystemdatatypes(Int32,String,Boolean,etc.).

• Inshort,mscorlib.dlldefinesanumberofveryimportantprimitivesany.NETprogramislikelytorequire.

• Giventhis,itiscertainlyworthyourtimeinvestigatingwhatisinthisall‐important.NETlibrary.

Page 13: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-13

• Hereismscorlib.dlasseenintheVisualStudioobjectbrowsertool.

• Thissingle*.dllassemblyhasbeenorganizedintonumerousnamespaces.

• Eachnamespacehassomenumberoftypes.

• Eachtypeassomenumberofmembers(constructors,functions,properties,events,etc.)

• Here,wearelookingattheBinaryReaderclasstype,intheSystem.IOnamespace,ofthemscorlib.dllassembly.

• Alwaysremember!Assemblieshavenamespacesandnamespaceshavetypes.

Page 14: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-14 Copyright©Intertech,Inc2014 Rev:27

• Assumingyouhavereferencedthecorrectassembly,youcanaccessatypedefinedwithinanamespaceinacoupleofdifferentways.

• Youcanusethefullyqualifiedtypename,e.g.,namespace.typename.

• Forexample,theConsoleclasslivesintheSystemnamespace:

class TesterMain { public static void Main() { // Namespace.TypeName.Method System.Console.WriteLine("Hello world"); } }

• Sincetypingnamespacesistedious,most.NETlanguagesprovideashortcutmechanism.

• C#hasa'using'keyword(notethecaseandsemicolon):

using System; using System.Drawing; using System.Collections;

• Incontrast,VBhasan'Imports'keyword(notethelackofasemicolon):

Imports System Imports System.Drawing Imports System.Collections

Page 15: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-15

• Hereisanexamplewhichmakesuseoftwonamespacesinmscorlib.dll.

• Becauseofthe“usingstatements”,wecandirectlyuseConsoleandArrayList.

• Ifwedidnothavethese“usingstatements”,wewouldhavetoqualifyConsoleandArrayList.

• Also,becausethesetwonamespacesarewithinmscorlib.dll,wedidnotneedtomanuallyreferenceanyexternallibraries(recall,wealwayshaveaccesstomscorlib.dll!)

using System; using System.Collections; namespace Test { class TesterMain { public static void Main() { // Use the System.Console class Console.WriteLine("Hello world"); // Use the System.Collections.ArrayList class. ArrayList myList; myList = new ArrayList(); } } }

• The.NETbaseclasslibrariesprovidemany,manymoreassembliesbeyondmscorlib.dll.

• Eachassemblycontainsmorenamespaces,whichcontainmoretypes.

• Forexample,theSystem.Data.dllassemblycontainscoretypesforcommunicatingwithrelationaldatabases.

• TheSystem.Core.dllassemblycontains(amongotherthings)thecoretypesforusingLINQAPIs.

• WhenyoumakeanewprojectwithVisualStudio,youwillautomaticallybegivenasetofreferencedlibrariestouse.

• Ifyouneedtousesomethinginanassemblynotinitiallyreferenced,youwillneedtodosomanually.

• YouwillseehowtoworkwiththisaspectofVisualStudiolaterintheclass.

Page 16: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-16 Copyright©Intertech,Inc2014 Rev:27

• Clearly,yourrealchallengeasa.NETdeveloperistolearnaboutthewealthofnamespacesandtypesfoundwithinthe.NETbaseclasslibraries.

• MSDN(yourlocalhelpsystem,whichisalsoavailableonline)hasaspecificbookthatdescribeseachandeveryassembly,namespaceandallthecontainedtypes.

• Hereyouwillfindamplesamplecode,detailsofatype’sfunctionalityandnumerousotherdetails.

• Lookupthetopic".NETFrameworkClassLibrary"forfulldetails.

Page 17: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-17

The Role of Common Intermediate Language (CIL)       

• .NETlanguagecompilersdonotemitnativeplatformcode.

• Rather,theyemitplatform‐independentinstructionscalledtheCommonIntermediateLanguage(CIL).

• CILisnotinterpreted.Itisjust‐in‐timecompiled(JITed)atruntime.

• YoumayseeCILreferredtobyafewothernames:ILorMSIL.

• CILisjust‐in‐timecompiled(JITed)tothetargetplatformatruntime.

• Ablockofcode(method)isJITedwhenitisfirstcalledbyaclient.TheJITedversionofthecodeiscachedforsubsequentuse.

• Alternately,youcanusethengen.exeutilitytopre‐JITanentireassemblyatthetimeofinstallation.

• Surprisingly,pre‐JITingdoesnotalwaysmeanbetterperformance.UIintensiveapplicationsseemtobenefitthemostfrompre‐JITing.

Page 18: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-18 Copyright©Intertech,Inc2014 Rev:27

Viewing an Assembly’s Internals with ildasm.exe 

• Fromaphysicallevel,mostassembliesareasingleDLLorEXEfile.

• Thisbinaryfile(theassembly)isacollectionoftypes(classes,interfaces,structures,enumerations,delegates)withinsomenumberofnamespaces.

• Beawarethatthenameoftheassemblydoesnotneedtomatchthenameofthecontainednamespace(s).

• Aswell,itisperfectlypossibleforthesamenamespacetobedefinedacrossmultipleassemblies.

• YoucaninvestigatethecontentsofanassemblyusingtoolssuchasILDasm.exe:

• ThistooldisplaysthemanifestofanassemblyandtheinternalCILcodeinstructions.

• Thistoolshipswiththe.NETSDK.

Page 19: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-19

• EveryassemblycontainsaMANIFESTthatdocumentskeypiecesofassemblyinformation,includingthefollowing:

• Theassemblyversion,culture,optionalsecuritysettings,optionalresources,andoptional‘strongname’information(moredetailslater).

• Anyassemblylevelattributes.

• Alistofallexternalassembliesrequiredbythecurrentassembly.

• YouwilllearnmoreabouttheMANIFESTlaterinthisclasswhenwetalkabouthowtheCLRlocatesandloadsassemblies(AppendixA).

Page 20: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-20 Copyright©Intertech,Inc2014 Rev:27

• Assembliescontaintypemetadatathatdescribeeachtypeintheassembly.

• Youcanviewthemetadataofanassemblybypressingthe“ctrl+m”keystrokeinILDasm.exe.

• Metadataisaveryimportantaspectofmoreadvanced.NETprogrammingtechniques,including“reflection”.

• Althoughthiscoursedoesnotcoverreflectionindetail,youwillbeintroducedtothetopicwhereappropriate.

• FYI:Metadataisactuallyveryuseful.Forexample,theIntelliSensefeatureofVisualStudioreadsmetadatatodisplayyourchoicesinthecodeeditor.

Page 21: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-21

A Survey of .NET Languages        

• Oneofthecorestrengthsofthe.NETplatformisthedeepleveloflanguageinteroperability.

• Assembliescanbedevelopedandusedbyany.NETlanguage.

• All.NETlanguagesusethesamenamespaces,sametypes,andsameruntimefacilities.Infact,all.NETlanguagesmakeuseofthesamebaseclasslibraries.

• Outofthebox,the.NETSDKincludestheVB,C#,C++/CLIandF#programminglanguages.

• VB(alsoknownasVB.NET):

• VBasweknowittodayhaslittleincommonwitholderversionsofBASIC.

• UnlikeVB6(orearlier)VBmoderndayVBisjustasobjectorientedasJava,C#orC++.

• C#(pronounced“seesharp”):

• C#isanewmemberoftheCfamilyoflanguages,andthereforehasasimilarlookandfeeltothatofC++orJava.

• However,C#hasanumberofuniquefeatures,programmingconstructsandkeywordswhicharenotfoundinJava.

• LikeothermembersoftheCfamily,C#preferstersecodestatementsandkeywords,usescurlybracketstodefinealevelofscope,andterminatesstatementswithasemi‐colon.

• C++/CLI:

• C++developersusingtheMicrosoftcompilercanusesomenewkeywordstobuild.NETassembliesratherthannativebinaries.

• ThislanguageiscommonlyusedtowraplegacyC++typesandexposethemto.NET.

• F#:

• F#isalanguagewhichbeganshippingwith.NET4.0.

• Thisisa"functional"language,whichfavorsmathematicalexpressions(functions)astheunitofwork.

• However,unlikepurefunctionallanguages(suchasSchemeorLISPproper),F#hasobjectorientatedaspectsandaccesstothe.NETframeworkclasslibraries.

Page 22: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-22 Copyright©Intertech,Inc2014 Rev:27

• Beawarethatnumerousother.NET‐awarelanguagesexist,allofwhichhavebeendevelopedbyvendorsotherthanMicrosoft.

• .NETcompilersexistforRuby,COBOL,Python,Eiffel,Pascal,andmore.

• Checkouthttp://www.dotnetlanguages.netformoredetails(clickontheResourceslinkonthetopofthepagetoseethefollowinglist).

Page 23: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-23

Platform Independent .NET Development 

• Asmentionedearlierinthischapter,the.NETplatformisnotlimitedtotheWindowsfamilyofoperatingsystems.

• Youcancreateandexecute.NETassembliesonavarietyofoperatingsystemsincludingMacOSX,SolarisandnumerousLinuxdistributions.

• YoucanalsouseC#and.NETtobuildiOSandAndroidapplications.

• Tounderstandhowthisispossible,thereisyetanotheracronymtolearn:CLI.

• MicrosofthassubmittedspecificationsontheC#programminglanguage,theCLR,andasubsetofthe.NETbaseclasslibrariestoECMAInternational.

• Collectively,thesedocumentsaretermedthe"CommonLanguageInfrastructure"orCLI.

• Thisprovidesthemeansforexternal(non‐MS)companiesandindividualstocreatecustombuildsofthe.NETplatform.

• ThisclasswillfocusonMicrosoft’simplementationoftheC#languageandthe.NETplatform.

• However,itisworthpointingoutapopularalternative...

Page 24: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-24 Copyright©Intertech,Inc2014 Rev:27

• TheMonoproject(http://www.mono‐project.com)isanopensourcedistributionoftheC#languageand.NETplatformtotheUnix‐basedoperatingsystem(includingMacOSX).

• Monoincludes,amongotherthings,aC#compiler,aVBcompiler,andimplementationsofWindowsForms,ASP.NET,ADO.NET,andthebaseclasslibraries.

• AssembliesbuiltusingMonoareECMAcompliantand,therefore,canbeexecutedonanyOSsupportingthe.NETplatform.

Page 25: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-25

Building C# Applications Using the Command Line Compiler     

• Althoughmostdeveloperswillbuild.NETapplicationsusingavisualIDE,itisimportanttoknowhowtoworkwiththecommandlinetools.

• AsusefulasavisualIDEmightbe,severaladvancedfeatures(suchasnativegenerationofCIL,constructionof“multi‐file”assemblies,andsoon)canonlybedoneatthecommandline.

• Aswell,manyimportant.NETAPIs(suchasWCF)requireuseofcommandlinetools.

• BothVBandC#provideacommandlinecompilernamedvbc.exeandcsc.exe,respectively.

• Thesecommandlinecompilersareincludedwiththe.NETSDKandarefreelydownloadablefromMicrosoft.

• AssumewehavethefollowingC#sourcecode,createdinasimpletexteditor.

• RememberthatC#isacasesensitiveprogramminglanguage.

• AllC#keywordsareinlowercase.

• Thus,“using”issyntacticallycorrect.However,“Using”or“USING”arecompilererrors.

• Likewise,Writeline()is*not*thesameasWriteLine().

• All.NETnamespaces,typesandtypemembersfollowPascalnamingconventions(uppercasethefirstletterofeverywordoracronym[System.Console,System.Collections.ArrayList,SqlConnection]).

Page 26: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-26 Copyright©Intertech,Inc2014 Rev:27

• Nowlet’sgettoknowthecoreoptionsoftheC#compiler.

• Thefirstpointofinterestistounderstandhowtospecifythesortofoutputfileyouareinterestedinbuilding(e.g.,consoleapplication,DLL,Windowsapplication,etc.).

• Eachchoiceisassignedaspecificflag,whichissentintocsc.exe.

CompilerOption MeaninginLife

/out Usedtospecifythenameoftheoutputfile(e.g.,MyAssembly.dll,WordProcessingApp.exe,etc.).

/target:exe ThisoptionwillbuildanEXEconsoleapplication.

Thisisthedefaultfileoutputtypeandthusmaybeomitted.

/target:library ThisoptionwillbuildaDLLassembly.

/target:winexe ThisoptionwillbuildanexecutableWindowsGUIapplication.

• TocompiletheTestApp.csfileasaconsoleapplication,youwouldusethefollowingcommandset:

• Youwillseeadditionaloptionsofthecommandlinecompilerinyourupcominglab.

csc /target:exe TestApp.cs

Page 27: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-27

Building C# Applications Using Visual IDEs            

• Whileitisimportanttoknowhowtoworkwiththecommandlinetoolsofthe.NETSDK,fewprogrammerswouldwanttobuildacomplexapplicationusingthelowlevelcompiler.

• Thankfully,many.NETIntegratedDevelopmentEnvironments(IDEs)exist.

• Somearefreeandopensource,otherscomeatacost.

• Inourclass,wewilluseMicrosoftVisualStudio.

• ThisIDEisthepreferredprofessionaltoolfor.NETdevelopers.

• VScomesinmanydifferentversions,eachofwhichsupportsvariouslevelsoftoolsandfeatures.

• Consulthttp://www.microsoft.com/visualstudio/eng/products/comparefordetailsofwhatissupportedineacheditionofthetool(andtherelatedcost!)

Page 28: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-28 Copyright©Intertech,Inc2014 Rev:27

• IfyoudonothaveacopyofVisualStudio,anddonotwishtospendthemoneytoobtainacopy,youshouldknowabouttheMicrosoftExpressfamilyofproducts.

• MicrosofthasreleasedacompletelyfreesetofIDEswhichfallunderthe“Express”familyoftools.

• YoucandownloadanExpresseditionofC#,VB,C++,WebDevelopmentIDEandSQLServer.

• TheseExpressIDEsareperfectforthoseworkingonsmallerscale.NETapplication,studentsorforpersonaluseathome.

• Byandlarge,Expressproductsare“lightweight”versionsoftheVisualStudioIDE.

• Consulthttp://www.microsoft.com/visualstudio/eng/products/comparefordetails.

Page 29: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

Copyright©Intertech,Inc2008Rev:4 1-29

• InadditiontotheseMicrosoftIDEs,manyopensourceIDEsexistaswell.

• OneverypopularopensourceIDEisSharpDevelop(alsoknownas#Develop).

• ThisIDEhasanintegrateddebugger,visualdesigners,andsupportformultiple.NETprogramminglanguages.

• Consulthttp://www.icsharpcode.net/OpenSource/SD/Default.aspxfordetails.

Lab Exercise: Up and Running with C#

Page 30: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

ThePhilosophyof.NET

1-30 Copyright©Intertech,Inc2014 Rev:27

Chapter Summary                      

• Thekey.NETcomponentsare:

• CommonLanguageInfrastructure(CLI):AsetofECMAstandardsthatenableplatform‐independent.NET.

• CommonTypeSystem(CTS):Astandardfortypedefinitionsandfunctionalitythat.NETlanguagesCANsupport.

• CommonLanguageSpecification(CLS):AsubsetoftheCTSthatall.NETlanguagesMUSTsupport.

• CommonLanguageRuntime(CLR):Alibraryofutilityclassesforbuildingdesktop,web,oranytypeofapplicationandaruntimeforexecuting.NETcodewithgarbagecollectionandtypeverification.

• CommonIntermediateLanguage(CIL):All.NETlanguagescompiletothisplatform‐independentlanguage.

• Assemblies:Anewnameandstructurefor.exeand.dllfiles.

• .NETislanguageagnostic,butmostdevelopmentwillbeineitherC#orVB.

• C#isalanguagespecificallydesignedtobuildmanagedcode.

• ModerndayVBhaslittletodowithVB6.Nowadays,VBisjustasobjectorientedasC++,C#orJava.

Page 31: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Copyright©Intertech,Inc2014Rev:4 1-1

Chapter 1  

IntroducingWPF

Objectives:

UnderstandthemotivationbehindWPF

Examinethevarious‘flavors’ofWPFapplications

OverviewtheservicesprovidedbyWPF

ExaminethecoreWPFassembliesandnamespaces

WorkwiththeWindowandApplicationclasstypes

LearnthesyntaxofXAML

UnderstandtheXAML/coderelationship

Page 32: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-2 Copyright©Intertech,Inc2014 Rev:4

ChapterOverview

Everyfewyearsorso,MicrosoftintroducesanewGUItoolkit.Sincethereleaseof.NET3.0,thelatestdesktopGUItoolkitisWindowsPresentationFoundation(WPF).

Inthisintroductorychapter,youwillunderstandthemotivationbehindWPF,learnthesyntaxofXAML,examinethecoreprogrammingmodel,andsurveyseveralWPFservices.Also,youwilloverviewtheWPFsupportprovidedbyVisualStudioandbeintroducedtotheroleofExpressionBlend.

Asyouwouldexpect,thischapterprovidesafoundationfortheremainderoftheclass.

Page 33: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-3

The Motivation Behind WPF                  

• Historicallyspeaking,buildingadesktopUIundertheWindowsOSinvolvedusingahandfulofkeyservices:

• User32:Providedthecoderequiredtocreatewindows,controls,andapplicationinfrastructure.

• GDI:Providedaframeworkforrendering2Dgraphicaldata.

• DirectX:Ifanapplicationrequiredhigh‐performancegraphicalrendering(multimediaapplications,videogames,richinteractivefrontends,andsoon),DirectXwasthewaytodoso.

• AlthoughWindowsprogrammerscouldmakeuseoftheseservicesusingrawC/C++,manyUItoolkitswereintroducedovertheyears:

• VB6,MFC,WindowsForms,GDI+,andsoon.

• EachoneofthemwassimplyawrapperaroundUser32/GDI.

• ThesetoolkitsstillviewedDirectXasan‘external’service.

• WindowsPresentationFoundation(WPF)isamanagedGUItoolkitthatshippedbeginningwith.NET3.0.

• ThecoreWPFobjectmodelissimilar,butnotidenticalto,WindowsForms.

• ThereleaseofWPFdoesnotimplythatWindowsFormsisobsolete.

• Infact,the.NETplatformwillsupportthisAPIforyearstocome.

Page 34: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-4 Copyright©Intertech,Inc2014 Rev:4

• BeforethereleaseofWPF,UIdeveloperswereforcedtomasteranumberofrelated,butultimatelyindependent,APIs.

• Thisrequireddevelopersto‘switchgears’whenmovingfromonetask(e.g.,buildingamainwindow)toanother(e.g.,3Dgraphicalrendering).

• Theendresultwasaveryasymmetricalwaytoprogram.

• ConsidertheGUIdevelopmentworldbefore.NET3.0:

DesiredFunctionality Pre‐.NET3.0Solution

Forms, dialog boxes, controls

Windows Forms, VB6, MFC, and so on

2D graphics System.Drawing.dll (e.g., GDI+) or raw C-based GDI

3D graphics DirectX

Streaming video Windows Media Player API or third party APIs

Fixed / Flow documents Third party APIs

• WiththereleaseofWPF,thingshaveimprovedconsiderably.

• YounowhaveasinglesymmetricalmannerinwhichtointeractwiththenecessaryGUIinfrastructure.

• ConsidertheGUIdevelopmentworldasof.NET3.0andhigher:

DesiredFunctionality .NET3.0andHigherSolution

Forms, dialog boxes, controls

Windows Presentation Foundation

2D graphics Windows Presentation Foundation

3D graphics Windows Presentation Foundation

Streaming video Windows Presentation Foundation

Fixed / Flow documents Windows Presentation Foundation

Page 35: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-5

Page 36: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-6 Copyright©Intertech,Inc2014 Rev:4

• Beyondofferingaunifiedprogrammingmodel,WPFalsoprovidesaclearseparationofconcerns.

• ItispossibletoseparatethelookandfeelofaGUIapplicationfromtheprogramminglogicthatdrivesit.

• ThisisachievedusinganXML‐basedgrammartermedXAML(‘zam‐el’).

• WhilemostWPFapplicationswillmakeuseofXAML,doingsoisentirelyoptional.

• Thisseparationofconcerns(viaXAML)makesitmuchsimplerforgraphicaldesignerstobuildveryrich,professionalUIs.

• GraphicallymindedindividualscanusededicateddesigntoolssuchasMicrosoftExpressionBlendtogeneratetheXAML.

• TheseXAMLfilescanthenbepassedtotheprogrammingteamtoaddlogictodrivetheUI(eventhandlers,methodoverrides,andsoon).

• Asyouwillseeintheclass,aMicrosoftBlendprojectusesexactlythesameformatasaVisualStudioproject.

• BeyondtheintroductionofXAML,WPFalsoprovidesagoodnumberofintegratedservices,including(butnotlimitedto)thefollowing:

• Anumberoflayoutmanagersthatprovidefullcontroloverplacementandrepositioningofcontent.

• Abuilt‐instyleengine,whichallowsyoutodefine‘themes’foraWPFapplication.

• Nativeuseofvectorgraphics,whichallowsanimagetobeautomaticallyresizedtofitthesizeandresolutionofthescreenhostingtheapplication.

• ArichtypographyAPIsuchassupportforXPS(XMLPaperSpecification)documents,fixeddocuments(WYSIWYG),flowdocuments,anddocumentannotations(e.g.,aStickyNotesAPI).

• Integrated2Dand3Drenderingservices/animationservices,whichleverageDirectXforhardwareacceleration.Infact,allrendering,eventherenderingofUIelements(buttons,andsoon)ispreformedviaDirectX.

• InteroperabilitywithpreviousUIframeworks.Forexample,aWPFprogramcanuseWindowsFormscontrolsorActiveXcontrols.Aswell,aWindowsFormsappcanuseWPFcontrols.

• Supportforaudioandvideomedia.

• Supportfortouchscreendevelopment(asof.NET4.0).

Page 37: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-7

• Overall,WPFcanbeconsidereda‘supercharged’UIframework.

• WPFisextremelyusefulwhenyouneedtobuildhighlyinteractive,stylizedfrontends.

• Real‐timerotationof3Dbarcharts,spinningaportionofaUItoa45‐degreeangle,anddynamicshadowingonarenderedimageareallpossible.

• ConsiderthefollowingWPFapplication(anexampleprojectfromExpressionBlend):

• Clickingonanyofthestylizedbuttonsonthebottomoftheapplicationwillrotateandanimatea3Dmotorcycleprototype.

• Eachbuttonsupportsacustomanimation,performedwhenthecursortravelsoverthesurface.

• Noticethedropshadows,angledtextblocks,etc.

• WhileallofthiscouldbedonewithoutWPF,doingsowouldrequireaconsiderableamountofcomplexcode.Here,amajorityoftheUIisdrivenbyXAML.

Page 38: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-8 Copyright©Intertech,Inc2014 Rev:4

• BecauseWPFapplicationsaresographicallyintensive,aproduction‐levelWPFapplicationmayrequiretheaidofaprofessionalgraphicdesigner.

• Youmayagreethatmost.NETprogrammersarenotthebestofartists.

• Likewise,mostartistsarenotthebestof.NETprogrammers.

• UsingXAMLandtoolssuchasVisualStudioandExpressionBlend,eachpartoftheteamcanusededicatedtools,thusincreasingefficiencyindevelopment.

• RememberthatthesameVisualStudioWPFapplicationcanbeopenedinExpressionBlend(andviceversa).

• ThisisnottosuggestthatyoucannotuseWPFtobuild‘traditional’GUIs(graypushbuttons,agridofdata,amenusystem,andsoon).

• YoucancertainlyuseWPFtobuildtraditionalbusinessapplications.

• However,thisAPIisstronglygearedfornext‐generationGUIapplications.

• WPFisclosertothe‘Hollywoodvision’ofwhatcomputerapplicationsshouldlooklike(e.g.,3Dspinninge‐mailmessages,glowinganimatedblocksoftext,andthelike).

EvenifyouareinterestedinbuildingatypicalLOBapplication,WPFcanstillprovideanumberofkeybenefits.

• TheWPF‘content’modeland‘template’modelmakeitveryeasytocustomizecontrols.

• ALOBapplicationcanaddabitof“eyecandy”(animationsandvisualeffects)withjustafewlinesofXAML.

Page 39: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-9

The Flavors of WPF Applications 

• LikeWindowsForms,WPFcanbeusedtobuildtraditionaldesktopapplications.

• Somepossibilitiesincludemediaviewers,thickclientfrontendstointeractwithremotedatasources,andwordprocessors.

• Atminimum,thisflavorofWPFapplicationwillmakeuseoftheWindowandApplicationtypes,inadditiontovariousUIelements(statusbars,menusystems,dialogs,andsoon).

• Youwilllearnaboutthesetypesinthischapter.

• Likeotherdesktopapplications,WPFdesktopappscanbedeployedviaastandardsetupprogramorClickOncedeployment.

• Ofcourse,thetargetmachinemusthavethe.NET3.0orhigherruntimeinstalledtosupportWPFapplications.

• WPFdesktopappscanmakeuseofapage‐basedsystem,whichallowsanapplicationtoadoptaweb‐likenavigationalstructure.

• Pagenavigationappsmaintain‘Next’and‘Previous’buttons,ahistorylist,andtheabilitytosharedatabetweenpages.

• ThistypeofWPFappmakesuseofvariousPageobjectshostedwithinaNavigationWindow.

• IfyouareinterestedinthisflavorofWPFprogram,consultAppendixC.

Page 40: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-10 Copyright©Intertech,Inc2014 Rev:4

• WPFcanalsobeusedtobuildanewvarietyof‘smartclients’wheretheappisembeddedintoahostingbrowser.

• ThisflavorofWPFistermedanXBAP(XAMLBrowserApplication).

• Likenavigationallybasedapps,XBAPsconsistofanumberofPageobjects.

• Theyaredeployedfromaremotewebserver(likeaClickOnceapp)andintegrateintothenavigationalstructureofthehost.

• XBAPsmaybehostedwithinInternetExplorerorFirefox.

• ThiscoursewillnotformallycoverXBAPconstruction,howeverbewarethateverythingyoulearnaboutWPFappliesdirectlytoXBAP.

• ThefundamentaldifferenceishowanXBAPisdeployed.

• DobeawarethatVisualStudiodoesprovideaWPFBrowserApplicationprojecttemplatewhichyoumaywishtoexplore.

• Also,lookupthetopicWPFXAMLBrowserApplicationsOverviewinthe.NETFrameworkSDKformoreinformationifyouareinterested.

Page 41: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-11

The WPF and Silverlight Relationship  

• Silverlightisaweb‐centricsubsetof.NET/WPF/XAMLfunctionality.

• Silverlightmakesitpossibletobuildhighlyinteractivewebplug‐ins.ConsiderSilverlighttobeMicrosoft’sanswertoAdobeFlash.

• SilverlightallowsdeveloperstouseC#orVisualBasictobuildobject‐orientedplug‐ins.

• Silverlightapplicationscanrunonmultipleoperatingsystems(currentlyWindowsandMacOSXandvariousLinuxdistributionsviatheopensourceMoonlightproject).

• Silverlightcanbehostedbymultiplebrowsers(IE,Safari,Opera,andFirefox).

• ThiscoursedoesnotdirectlycoverSilverlight.

• ThegoodnewsisthatSilverlightappsareessentiallytrimmeddownWPFapps.

• Thus,ifyouunderstandtheWPFprogrammingmodel,youwillhavenoproblembuildingSilverlightprograms.

• Consulthttp://silverlight.net/formoredetails.

Page 42: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-12 Copyright©Intertech,Inc2014 Rev:4

The WPF Documentation System 

• Duringtheremainderofthisclass,youwillbeexposedtoagoodnumberofWPFtechnologiesandapplicationtypes.

• Thiswillprovideyouwithasolidfoundationonwhichtobuild.

• Consultthe.NETFrameworkSDKdocumentationforadditionalinformation.

• Simplyopenthe‘WindowsPresentationFoundation’sectionofthe.NETFrameworkdocumentation.

• Youwillfindmanysampleprojects,whitepapers,andcodeexampleswithinthesuppliedWPFdocumentation.

• Also,theControlssectiondocumentsthefullfunctionalityofeachWPFcontrol(properties,methods,events).

• Doyourselfafavorandbesuretoconsultthehelpsystemduringthiscourse,andonceyouareusingWPFbackintheworkplace.

Page 43: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-13

Core WPF Assemblies and Namespaces            

• Likeany.NETtechnology,WPFisrepresentedbyseveralassemblies.

• TheVisualStudioWPFprojecttemplatesautomaticallysetreferencestothecoreassemblies.

• However,ifyoubuildWPFappsusingotherIDEsorviamsbuild.exe,youwillneedtosetassemblyreferencesmanually.

• Thefollowingkeylibrariesaremanaged.NETassemblies.

WPFAssembly MeaninginLife

WindowsBase.dll Defines the base infrastructure of WPF, including dependency properties support.

While this assembly contains types used within the WPF framework, the majority of these types can be used within other .NET applications.

PresentationCore.dll This assembly defines numerous types that constitute the foundation of the WPF GUI layer.

PresentationFramework.dll This assembly—the ‘meatiest’ of the three—defines the WPF controls types, animation and multimedia support, data binding support, and other WPF services.

For all practical purposes, this is the assembly you will spend most of your time working with directly.

System.Xaml.dll This library (which is new to .NET 4.0) provides types to process and manipulate XAML at runtime.

Page 44: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-14 Copyright©Intertech,Inc2014 Rev:4

• Althoughtheseassembliesprovidehundredsoftypeswithinnumerousnamespaces,considerthispartiallistofWPFnamespaces:

• Youwillencounterothernamespacesduringtheremainderofthisclass.

• Again,consultthe.NETFrameworkSDKdocumentationforfulldetails.

WPFNamespace MeaninginLife

System.Windows Here you will find core types such as Application and Window that are required by any WPF desktop project.

System.Windows.Controls Here you will find all of the expected WPF widgets, including types to build menu systems, tool tips, and numerous layout managers.

System.Windows.Markup This namespace defines a number of types that allow XAML markup and the equivalent binary format, BAML, to be parsed.

System.Windows.Media Within these namespaces you will find types to work with animations, 3D rendering, text rendering, and other multimedia primitives.

System.Windows.Navigation This namespace provides types to account for the navigation logic employed by XAML browser applications / desktop navigation apps.

System.Windows.Shapes This namespace defines basic geometric shapes (Rectangle, Polygon, etc.) used by various aspects of the WPF framework.

Page 45: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-15

The Role of the Application Class 

• RegardlessofwhichflavorofWPFapplicationyoucreate,theywillallmakeuseoftheSystem.Windows.Applicationtype.

• ThisclassrepresentsaglobalrunninginstanceofaWPFapplication.

• Itencapsulatesanumberofcoreservicessuchashandlingmessages,trappingunhandledexceptions,definingcommonapplicationdata,andmore.

• UnlikeWindowsForms,theWPFApplicationclassexposesmostservicesasinstance‐levelmembers.

• Therefore,youwillneedtocreateaclassextendingApplication.

• Thisclassiscommonlytermedtheapplicationobject.

• AWPFapplicationwillonlyhaveasingleApplicationobject.

Page 46: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-16 Copyright©Intertech,Inc2014 Rev:4

• TheApplicationclassdefinesanumberofkeyservices.

• Hereisapartiallistofimportantmembers:

ApplicationProperty MeaninginLife

Current This static property provides access to the global WPF application object.

This allows any window (or page) to access the application, which is very helpful in that the app object tends to define core functionality for all owned objects (resources, and so on).

MainWindow Allows you to get or set the main window of the WPF application.

StartupUri Typically used within a XAML description to define the resource containing the definition of the main window.

Properties Allows you to define application-wide variables using name / value pairs.

Similar in concept to a ‘session variable’ in a web app in that any part of your WPF program has access to this data.

Windows Provides access to each Window owned by the current WPF application which makes it simple to iterate over open windows to change their states.

Startup

Exit

These are two key events that almost all WPF application objects will handle.

DispatcherUnhandledException This event fires when a WPF throws an unhandled exception. This is your last chance to handle the error before the user is presented with a Windows error dialog box.

Page 47: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-17

• TheapplicationobjectwilldefinetheMain()methodofyourprogram,whichmustbemarkedwiththe[STAThread]attribute.

• ThisattributeensuresthatanylegacyCOMobjects,ActiveXcontrols,andtheWPFcontrolsloadintoathread‐safeenvironment.

• IfyoudonotmarkyourMain()methodwiththe[STAThread]attribute,youwillreceivearuntimeexception.

• HereisasimpleWPFapplicationobject:

// C# class MyApp : Application { [STAThread] static void Main() { // Create an instance of MyApp. // Handle events, run the application, // launch the main window, etc. } }

' VB Class MyApp Inherits Application <STAThread> _ Shared Sub Main() ' Create an instance of MyApp. ' Handle events, run the application, ' launch the main window, etc. End Sub End Class

• YourMain()methodwillbetheplacewhereyoutypicallywanttohandletheStartup,Exit,andDispatcherUnhandledExceptionevents.

• Also,yourapplicationobjectcandefineanynumberofapplication‐widedatapoints.

• Youwillbuildamorecompleteapplicationobjectlaterinthischapter.

• Fornow,examinetheroleoftheWindowclass.

Page 48: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-18 Copyright©Intertech,Inc2014 Rev:4

The Role of the Window Type 

• InadditiontotheApplicationtype,mostdesktopWPFapplicationswillmakeuseoftheWindowtype.

• Thisrepresentsthemainwindowofyourapp,aswellasanycustomdialogboxes.

• Asyoucansee,Windowgainsagooddealoffunctionalityfromitsinheritancechain.

• Youwillcometoknowtheroleofmanyofthesebaseclassesduringtheremainderofthisclass.

• Hereisahigh‐leveloverviewoftheroleofeachclassintheWindow’sinheritancechain.

• TheContentControlparentclassallowsderivedtypestohostasinglepieceof‘content’.

• WPFcontentcanbecomposedofanysortofUIelements.

• MostWPFcontrolsalsohaveContentControlintheirinheritancechain.

• Also,theWindowandPagetypesextendContentControl.

Page 49: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-19

• TheWPFcontentmodelallowsyoutoradicallychangethecompositionofacontrolwithminimalfuss.

• Bywayofanexample,aButtoncouldmaintainaninnerStackPanelas‘content’.

• TheStackPanelcontainsanEllipseandLabel.

• Youwillexaminethecontentmodelinalaterchapter.Fornow,hereisasimpleexampleinXAML.

<!-- A Button containing a StackPanel as content. --> <Button Height = "150" Width = "120"> <StackPanel> <Ellipse Fill = "Orange" Height = "75" Width = "75"/> <Label Content = "OK!" FontSize = "20" HorizontalAlignment = "Center" /> </StackPanel> </Button>

• TheControlparentclassdefinesanumberofmembersthatgivederivedtypes(includingWindow)theircorelookandfeel.

• Propertiesexisttoestablishthecontrol’sopacity,taborderlogic,backgroundcolor,fontsettings,andsoforth.

• TheControltypealsoprovidestheinfrastructuretoapplytemplatesandstylestoaUIwidget.

• FrameworkElementisanotherkeyparentclasstomanyUIwidgetsinthatitprovidesmemberstocontrolsize,tooltips,mousecursor,andothersettings.

• ThisclassalsoprovidessupportforWPFanimationanddatabindingservices.

• UIElementprovidesthegreatestamountoffunctionality:

• Eventstoprocessmouseandinputfocus.

• Propertiestocontrolfocus,visibility,andgeometrictransformation.

Page 50: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-20 Copyright©Intertech,Inc2014 Rev:4

• VisualprovidesderivedtypesthecoreinfrastructuretorendertheirUIoutput.

• Visualprovideshit‐testingsupportandcoordinatestransformation.

• VisualisalsotheconnectionbetweenWPFandtheDirectXsubsystem.

• AnytypeextendingVisualcanberenderedonaWindow.

• DependencyObjectistheparentthatprovidesderivedtypestheabilitytoworkwiththeWPF‘dependencyproperty’model.

• Asyouwillseelater,adependencypropertymakesitpossibleforapropertytoreceiveinputfrommultiplelocations.

• ThisiskeypartofWPF’stemplate,animation,anddatabindingservices.

• Finally,DispatcherObjectprovidesaccesstotheWPFapp’slower‐leveleventqueueviatheDispatcherproperty.

• WPFmakesuseofasingle‐threadaffinitymodel,hencetheuseof[STAThread]inyourMain()method.

Page 51: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-21

Building a WPF Application (XAML‐free) 

• NowthatyoubetterunderstandthecoreservicesprovidedbyApplicationandWindow,itistimetobuildasimpleWPFapplication.

• ThisapplicationwillnotbecreatedusingXAML(recallthatXAMListechnicallyoptional).

• Rather,thisapplicationwilltakethe‘100%code’approach.

• AlthoughWPFapplicationsarenotrequiredtouseXAML,apurecodeapproachisnotnecessarilyrecommended.

• ThisapproachdoesnothonortheseparationofconcernsbetweenGUIlayoutandfunctionality.

• However,itisimportanttounderstandhowtoworkwithWPFtypesincode,evenwhenyouaremakinguseofXAML.

• RecallthattheSystem.Windows.ApplicationclassrepresentsarunninginstanceofaWPFapp.

• UnlikeWindowsForms,theApplicationtypeexposesitscorefunctionalityasinstance‐level(ratherthanstatic)members.

• Thus,aWPFappwillhaveaclasstypethatextendsApplication.

• TheothercriticaltypeisWindow,whichrepresentsatopmostwindowordialogbox.

• Thistypeistypicallysubclassedforstrongtyping.However,thisisnotrequired.

• ConsiderthefollowingsimpleC#WPFappthathandlessomekeyevents.

• TheStartupeventmakesuseoftheStartupEventHandlerdelegate.

• TheExiteventmakesuseofExitEventHandler.

• ItalsodealswithanyunhandledexceptionsbyhandlingtheDispatcherUnhandledExceptionevent.

• ThiseventmakesuseoftheDispatcherUnhandledExceptionEventHandlerdelegate,whichisamemberoftheSystem.Windows.Threadingnamespace.

• NoticetheincomingDispatcherUnhandledExceptionEventArgsgivesaccesstotheerrorinformationandprovidesawaytocleartheexception.

Page 52: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-22 Copyright©Intertech,Inc2014 Rev:4

// C# // A Simple WPF Application written without XAML. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace SimpleWPFApp { class MyWPFApp : Application { [STAThread] static void Main() { // Handle key events and then run the application. MyWPFApp app = new MyWPFApp(); app.Startup += new StartupEventHandler(AppStartUp); app.Exit += new ExitEventHandler(AppExit); app.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(AppUnhandledException); // Fires the Startup event. app.Run(); } static void AppUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { MessageBox.Show(e.Exception.Message, "Unhandled error!!"); e.Handled = true; } static void AppExit(object sender, ExitEventArgs e) { MessageBox.Show("App has exited"); } static void AppStartUp(object sender, StartupEventArgs e) { // Create a Window object and set some basic properties. Window mainWindow = new Window(); mainWindow.Title = "My First WPF App!"; mainWindow.Height = 200; mainWindow.Width = 300; mainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen; mainWindow.Show(); } } }

Page 53: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-23

• InVB,thepreviousexamplecouldbeauthoredasso:

• NoticeitmakesuseoftheAddHandlerstatementtohookintoevents.

• Thisisnecessarybecauselocalvariables(e.g.,theApplicationobject)cannotbedeclaredusingtheWithEventskeyword.

' VB ' A Simple WPF Application, written without XAML. Imports System Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Threading Namespace SimpleWPFApp ' This first example defines a single class type to ' represent the application itself and the main window. Class MyWPFApp Inherits Application <STAThread> _ Shared Sub Main() ' Handle key events and then run the application. Dim app As New MyWPFApp() AddHandler app.Startup, AddressOf AppStartUp AddHandler app.Exit, AddressOf AppExit AddHandler app.DispatcherUnhandledException, AddressOf AppUnhandledException app.Run() End Sub Shared Sub AppUnhandledException(ByVal sender As Object, _ ByVal e As DispatcherUnhandledExceptionEventArgs) MessageBox.Show(e.Exception.Message, "Unhandled error!!") e.Handled = True End Sub Shared Sub AppExit(ByVal sender As object, ByVal e As ExitEventArgs) MessageBox.Show("App has exited") End Sub Shared Sub AppStartUp(ByVal sender As Object, _ ByVal e As StartUpEventArgs) ' Create a Window object and set some basic properties. Dim mainWindow As new Window() mainWindow.Title = "My First WPF App!" mainWindow.Height = 200 mainWindow.Width = 300 mainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen mainWindow.Show() End Sub End Class End Namespace

Page 54: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-24 Copyright©Intertech,Inc2014 Rev:4

• HereisastronglytypedWindow‐derivedclassthatencapsulatesthedetailsofthemainwindow.

• NoticeitextendsWindowandsetscorepropertiesviaconstructorarguments.

• VBprogrammerswouldauthorthesamecodestatementswithinaSubNew().

// C# (VB code would be similar.) class MainWindow : Window { public MainWindow(string windowTitle, int height, int width) { this.Title = windowTitle; this.WindowStartupLocation = WindowStartupLocation.CenterScreen; this.Height = height; this.Width = width; this.Show(); } }

• Atthispoint,youcanupdatetheStartupeventhandler:

• NoteyouarenowcreatingastronglytypedMainWindowobject.

// C# (VB code would be similar.) static void AppStartUp(object sender, StartupEventArgs e) { // Create a MainWindow object. // VB code would use the Dim keyword: // Dim wnd as New MainWindow("My better WPF App!", 200, 300) MainWindow wnd = new MainWindow("My better WPF App!", 200, 300); }

Page 55: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-25

Adding UI Elements (XAML‐free)               

• AddingUIelementstoaWindowtypeisabitdifferentthanworkingwithWindowsForms.

• ThecoreWPFcontrolsaredefinedwithintheSystem.Windows.Controlsnamespace(notSystem.Windows.Forms).

• TheeventssentfromWPFcontrolsmakeuseofvariousnewdelegatessuchasRoutedEventHandler.

• Moredetailson‘routedevents’willcomelaterintheclass.

• Mostimportantly,anytypeextendingContentControl(includingWindow)canonlycontainasingleUIelementascontent.

• ThisisarequirementoftheWPFcontentmodel.

• WhenaWindowrequiresmultipleUIelements,youarrangethemwithinoneoftheprovidedpaneltypes:Grid,StackPanel,andsoon.

• Thepanelwillthenbethe‘singlepieceofcontent’ownedbytheWindow.

• IfyoudonotplacetheUIiteminapaneltype,thesinglebitofcontentwillbeplacedinthedeadcenterofthewindoworpage.

Page 56: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-26 Copyright©Intertech,Inc2014 Rev:4

• HereisanupdatetotheWindowclass,whichnowcontainsasingleButtonascontent.

• TheClickeventishandledviatheRoutedEventHandlerdelegate.

• TheClickeventhandlerwillsimplyterminatetheentireapplication.

• TheButtonisaddedtotheWindow’scontentviaAddChild().

// C# class MainWindow : Window { // The UI element. private Button btnExitApp = new Button(); public MainWindow(string windowTitle, int height, int width) { // Configure the button and set the child control. btnExitApp.Click += new RoutedEventHandler(btnExitApp_Clicked); btnExitApp.Content = "Exit Application"; btnExitApp.Height = 25; btnExitApp.Width = 100; this.AddChild(btnExitApp); // Configure the window. this.Title = windowTitle; this.WindowStartupLocation = WindowStartupLocation.CenterScreen; this.Height = height; this.Width = width; this.Show(); } private void btnExitApp_Clicked(object sender, RoutedEventArgs e) { // Get a handle to the current application and shut it down. Application.Current.Shutdown(); } }

Page 57: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-27

• WhenyoucreateaWindow,itwillautomaticallybeaddedtotheapplication’sinternalWindowscollection.

• ThisisdoneviasomeconstructorlogicoftheWindowtype.

• RecallthattheApplication.Windowspropertyallowsyoutoaccesseachopenwindowmaintainedbytheapplicationobject.

• HereisahelpermethodthatwilldisplaythetitleofeachwindowownedbytheWPFapplication.

• TheVBcodewouldbesimilar.

// C# (VB code would be similar) static void DisplayTitlesOfAllOpenedWindows() { // Get a handle to the application object. Application appObject = Application.Current; // Print the title of each window in the collection. foreach(Window w in appObject.Windows) MessageBox.Show(w.Title); }

LabExercise:BuildingaWPFApplication(AllCode)

Page 58: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-28 Copyright©Intertech,Inc2014 Rev:4

Building a WPF Application Using XAML             

• TheExtensibleApplicationMarkupLanguage(XAML)isanXML‐basedgrammarfordescribingtreesof.NETobjects.

• XAMLandWPFgohandinhand,butXAMLcanbeusedtodescribeanynon‐generictypethatsupportsadefaultconstructor.

• ObjectsdefinedinXAMLarealwayscreatedusingthedefaultconstructor.

• AXAMLdescriptionofatreeofobjectsmapstoaruntimeobjectmodel.

• InthecaseofWPF,XAMLdescriptionsareadirectmappingtothepropertiesandeventsofthetypebeingdescribed.

• TheopeningelementdefinesthenameoftheclasswithXMLattributesusedtosetthepropertyvaluesandeventhandlernames.

• TheNameattributereferstothenameoftheinstanceoftheclass.

• Considerthefollowing(functionallyidentical)mannerstodeclareaWPFButtonobject.

<!-- Defining a WPF Button in XAML --> <Button Name = "btnClickMe" Height = "40" Width = "100" Content = "Click Me" Click = "btnClickMe_Click"/>

// Defining the same WPF Button in C# code. // (VB code would be similar) Button btnClickMe = new Button(); btnClickMe.Height = 40; btnClickMe.Width = 100; btnClickMe.Content = "Click Me"; btnClickMe.Click += new RoutedEventHandler(btnClickMe_Click);

Page 59: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-29

• Itispossible(althoughnotverypractical)tobuildanentireWPFapplicationusingnothingmorethanXAMLdescriptions.

• RecallthatXAMLisnotlimitedtothedescriptionofGUIelements.

• Any.NETobjectcanbedescribedinXAML,includingaWPF’sApplicationtype,whichhasnoassociateduserinterface.

• HereisaXAMLdescriptionofaWindow‐derivedtype.

• TheXMLnamespacesarerequiredandsimplyqualifythevariousWPFXAMLdefinitions(moreinformationwillcomelaterinthischapteronXAMLnamespaces).

• NoticethatcodesuchaseventhandlerscanbewrappedwithinCDATAsectionscontainedwithin<x:Code>elements.

• ItisnotrecommendedtoinjectcodewithinaXAMLfile,asitviolatestheseparationofconcerns.

<!-- Here is the Window definition --> <Window x:Class = "SimpleXamlApp.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "My Xaml App" Height = "200" Width = "300" WindowStartupLocation = "CenterScreen"> <!-- Define the button content --> <Button Width = "133" Height = "24" Name = "btnExitApp" Click = "btnExitApp_Clicked" Content = "Exit Application"/> <!-- The C# implementation of the button's Click event handler. --> <x:Code> <![CDATA[ private void btnExitApp_Clicked(object sender, RoutedEventArgs e) { // Get a handle to the current app and shut it down. Application.Current.Shutdown(); } ]]> </x:Code> </Window>

Page 60: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-30 Copyright©Intertech,Inc2014 Rev:4

• HerewouldbetheXAMLdescriptionoftheApplicationtypeoftheWPFapplication.

• TheStartupUripropertyisessentiallytheXAMLequivalentofdefiningaMain()method.

• ThispropertyissettotheXAMLresourcecontainingthedefinitionofthemainwindowoftheapplication.

• Althoughitlookslikewearepointingtoanexternalfile(MainWindow.xaml),inrealitythisisthenameofanembeddedbinaryresource(moredetailslater).

<!-- The main method seems to be missing! However, the StartupUri attribute is the functional equivalent. --> <Application x:Class = "SimpleXamlApp.MyApp" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" StartupUri = "MainWindow.xaml" Exit ="AppExit"> <x:Code> <![CDATA[ private void AppExit(object sender, ExitEventArgs e) { MessageBox.Show("App has exited"); } ]]> </x:Code> </Application>

• TheseXAMLfilescannowbecompiledintoa.NETassemblyusingmsbuild.exeandarelatedbuildscript.

• Msbuild.exeisacommandlinetoolthatenablescomplexbuilds.

• Infact,VisualStudiomakesuseofmsbuild.exeinthebackground.

• Thesamebuildscriptcanbeprocessedbymsbuild.exeorVisualStudio.

• Msbuild.exemakesuseofvarious‘targets’thatcontaininstructionsonhowtotransformXAMLdefinitionsintoequivalent.NETcode.

• Yournextlabwillillustratehowtodoso.

• Untilthen,letusdigdeeperintothesyntaxofXAMLitself.

Page 61: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-31

Understanding the Role of XAML 

• AlthoughXAMLisakeyaspectofWPF,fewdeveloperswillneedtoauthorreamsofXAMLbyhand.

• XAML,likeanyXML‐basedgrammar,isverbose,tedious,anderrorprone.

• NumeroustoolssuchasVisualStudioandExpressionBlendwillgenerateXAMLonyourbehalfasyoumakeuseofthetoolitself.

• AlthoughitistruethatWPFdevelopmenttoolswillgenerateXAMLinthebackground,itisimportanttounderstandthebasicsyntax.

• ThiswillallowyoutotweakthegeneratedXAMLiftheneedshouldarise.

• Also,XAMLcanbegenerated,loaded,parsed,andmanipulatedatruntime.

• Tounderstandhowtodoso,aworkingknowledgeofXAML’ssyntaxisuseful.

• ItisimportanttorecallthatXAMLisageneral‐purposemarkuplanguageandisnotlimitedtoWPF.

• XAMLcanalsobefoundwithintheWindowsWorkflowFoundationAPI,whereitisusedtobuildcustomactivitiesandworkflowsviamarkup.

• XAMLisalsousedwithinSilverlightapplications.

• XAMLisalsousedbytheXMLPaperSpecification(XPS),aMicrosofttechnologyfore‐paper.

Page 62: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-32 Copyright©Intertech,Inc2014 Rev:4

• Asdetailedinyournextlab,msbuild.exeusesXAMLdescriptionstogenerateintermediatecodefilesusedduringthecompilationprocess.

• Asanamingconvention,thesefilehavea‘g’infix(forgenerated).

• Forexample,aXAMLfilenamedMyWindow.xamlwillbeusedbymsbuild.exetogenerateaC#filenamedMyWindow.g.csoraVBfilenamedMyWindow.g.vb.

• Withinthesegeneratedfiles,youwillfindcode‐basedequivalentsforvariousaspectsofyourXAMLmarkup.

• XAMLfilesarealsousedtogenerateacompactbinaryformofthemarkuptermedbinarymarkuplanguage(BAML).

• Bydefault,theBAMLisembeddedintoyour.NETassemblyasabinaryresource.

• ThenameofaBAMLresourceisidenticaltothenameoftheoriginalXAMLfile.

• Atruntime,theBAMLisparsedtohydratethestateofyourWPFobjects(windows,applications,controls,andsoon).

• BecauseofBAML,youareseldomrequiredtoshipXAMLfilesalongwithyourcompiledWPFapplication.

• UnlessyouaredynamicallyloadingexternalXAMLfilesintomemory,XAMLfilescanberegardedaslittlemorethaninputtomsbuild.exe.

Page 63: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-33

Establishing WPF‐specific XML Namespaces 

• TherootelementofaXAMLdocumenttypicallydefinestwoXMLnamespacesthatmaptocoreWPFnamespacesandXAMLspecifictokens.

• http://schemas.microsoft.com/winfx/2006/xaml/presentationmapsanumberofWPFnamespacesforusebythecurrent*.xamlfile:

• System.Windows,System.Windows.Controls,System.Windows.Data,System.Windows.Ink,System.Windows.Media,System.Windows.Navigation,etc.

• http://schemas.microsoft.com/winfx/2006/xamlisusedtoincludeXAMLspecifictokens,aswellasasubsetoftypeswithintheSystem.Windows.Markupnamespace.

• Herewouldbea<Window>thatdefinesthesetwoXMLnamespaces.

• GiventhecascadingnatureofXML,allsub‐elementsofthe<Window>haveaccesstothesameinformation.

<Window xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"> </Window>

• Thefirstxmlnsattributeistheprimarynamespaceasithasnotbeenqualifiedwithanamespaceprefix.

• Noticethatthesecondxmlnsattributeasbeengiventhe‘x’prefix.Thisissimplytoavoidambiguitywiththeothernamespacedefinitions.

• LikeanyXMLprefix,theactualnameisirrelevant.Thus,thefollowing<Window>definitionisalsopermissiblealthoughmoreverbose.

<Window xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:XamlSpecificStuff = "http://schemas.microsoft.com/winfx/2006/xaml"> </Window>

Page 64: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-34 Copyright©Intertech,Inc2014 Rev:4

• Ifyoudidusethe'XamlSpecificStuff'prefix,anyXAMLkeywordinthedefiningscopewouldnowneedtomakeuseofthisratherverbosetag.

• Considerthefollowing<Application>rootelement,whichillustratesthesimplicityof‘x’asatagprefixfortheXAML‐centricnamespace.

<Application XamlSpecificStuff:Class="SimpleXamlApp.MyApp" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: XamlSpecificStuff = "http://schemas.microsoft.com/winfx/2006/xaml" StartupUri = "MainWindow.xaml" Exit="AppExit"> <XamlSpecificStuff:Code> <![CDATA[ private void AppExit(object sender, ExitEventArgs e) { MessageBox.Show("App has exited"); } ]]> </XamlSpecificStuff:Code> </Application>

• BeyondthetwokeyXMLnamespaces,XAMLmakesitpossibletodefinecustomxmlnsvaluesthatmaptocustomassemblies.

• Thiscanbehelpfulwhenyourmarkupneedstorefertotypesdefinedinexternallibraries.

• Theclr‐namespacetokenisusedtodothisverything.

• Youwillseewhythiscanbequiteusefuloverthecourseofthisclass.

• HereisasimpleexamplethatmakesthetypesintheSystemnamespaceofmscorlib.dllavailablewithinthecurrent<Window>.

• Ifyouaremappingtoanamespaceinthecurrentassembly,theassemblyqualifierisoptionalasseeninthesecondXMLnamespacelisting.

<Window xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:CorLib = "clr-namespace:System;assembly=mscorlib" xmlns:MyTypes = "clr-namespace:SomeNamespaceInMyAssembly"> </Window>

Page 65: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-35

The Role of XAML Type Converters 

• WPFsupportsseveralintrinsic‘typeconverters’.

• Theirjobistomapsimplestringvaluesintocomplexobjects.

• Consider,forexample,theactofsettingtheBackgroundpropertytothestring‘Green’.

• Incode,theBackgroundpropertyexpectsaBrush‐derivedtype.

• Furthermore,theHeightandWidthpropertiesexpectdoublevalues,notstrings.

• Regardless,thefollowingXAMLworksasexpected.

<Button Name = "myButton" Height = "100" Width = "100" Content = "Click Me!" Background = "Green"> </Button>

• Behindthescenes,thesestringvalues(‘100’,‘100’and‘Green’)aretransformedintodoublesandaSolidColorBrushobjectviatypeconverters.

• WPFsupportsnumeroustypeconverters,allofwhichderivefromtheSystem.ComponentModel.TypeConverterbaseclass.

• Forexample,theBrushConvertertypewasusedtomap‘Green’intoabrushobject.

• Whileyoucouldmakedirectuseoftypeconvertersincode,thereisusuallynocompellingreasontodoso.

• Inthevastmajorityofthecases,thecorrecttypeconverterwillbeusedatcompilationtime.

Page 66: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-36 Copyright©Intertech,Inc2014 Rev:4

XAML‐specific Elements and Attributes 

• Strictlyspeaking,XML‐basedgrammarsdonotsupporttruekeywords.

• However,XMLparserscanbeprogrammedtolookforspecialtokensthatwillbetreatedinaspecial,customizedmanner.

• ThesameistrueforXAMLasitdefinesanumberoftokensthatcanberegardedas‘keywords’inageneralsense.

• ManyoftheseareusedtocontrolhowtheXAMLmarkupisprocessedatcompiletimeviamsbuild.exe.

• BecausetheseXAML‐specifictokensarepartoftheXAMLnamespace,manyofthemmusttakeanx:prefix(x:Name,x:Code,x:Class,andsoforth).

• Asyouwillsee,asaconvenience,sometokenssuchasNamedonotrequireanx:prefix.

XAMLKeyword MeaninginLife

Array Used to represent a .NET array type in XAML.

ClassModifier Allows you to define the visibility of the class type (internal or public) denoted by the Class keyword.

DynamicResource Allows you to make reference to a WPF resource that should be monitored for changes.

FieldModifier Allows you to define the visibility of a type member (internal, public, private, protected) for any named sub-element of the root (e.g., a <Button> within a <Window> element).

Key Allows you to establish a key value for a XAML item that will be placed into a resource dictionary.

Name This allows you to specify the generated C# name of a given XAML element.

Null Represents a null reference.

Static Allows you to make reference to a static member of a type.

StaticResource Allows you to make reference to a WPF resource that should not be monitored for changes.

Page 67: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-37

Type This is the XAML equivalent of the C# typeof operator / VB GetType operator. It will yield a System.Type based on the supplied name.

Page 68: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-38 Copyright©Intertech,Inc2014 Rev:4

• Asyouhaveseenearlierinthischapter,thex:Classandx:CodetokensareXAMLtokens.

• AWindoworApplicationcanspecifyanx:Classattributeinitsopeningdefinitionandisusedtodefinethenameoftheclasstypeinthecodefiles.

• The<x:Code>XAMLelementcanbeusedtoembedcodewithinaXAMLfile.

• Hereisa<Window>elementthatdefinesthex:Classattribute:

<!-- The x:Class attribute will be used by msbuild.exe to Define a C# or VB class type to represent the code of this XAML. --> <Window x:Class = "MyWPFApp.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"> </Window>

Page 69: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-39

Controlling Type / Member Naming and Visibility  

• Thex:ClassModifier/x:FieldModiferattributesallowyoutocontrolthevisibilityofamemberintherelatedcodefile.

• AXAMLfileisoftenpairedwithaC#orVBcodefilewhereyouauthoreventhandlers,helpermethods,andsoforth.

• Anadditionalcompile‐timegeneratedcodefile(*.g.cs/*.g.vb)willbeusedtocontaintheXAML=>codeobjectmapping,controldeclarations,andmore.

• Ifyoudonotmakeuseofthex:ClassModifer/x:FieldModiferattributes,theitemwillbedefinedusingthedefaultvisibilityofthe.NETlanguage.

• Inmostcases,youwillnotneedtochangethesedefaults.

• Asaresult,youwillnotfrequentlyneedtomakeuseofthex:ClassModifierorx:FieldModifertokens.

Page 70: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-40 Copyright©Intertech,Inc2014 Rev:4

• Asanexample,however,considerthefollowinguseofthex:ClassModifierandx:FieldModifierattributes.

• Thiswillbeusedbymsbuild.exetodeclareacodefilecontaininganinternalclasswithapublicButton.

• TheVBcodewouldbesimilar,usingtheFriendkeywordratherthantheC#‐specificinternalkeyword.

<!-- This class will now be internal. If using a code file, the partial class must also be defined as internal. --> <Window x:Class = "MyWPFApp.MainWindow" x:ClassModifier="internal" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"> <!-- This button will be public in the generated code file. --> <Button x:Name = "myButton" Content = "OK" x:FieldModifier = "public"/> </Window>

// C# code (VB code would be similar) internal partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector { public System.Windows.Controls.Button myButton; … }

Page 71: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-41

• Noticethattheprevious<Button>hasbeendefinedusingthex:Nameattribute.

• WhenyouaredeclaringaniteminXAML,youcanassignavaluetothex:Nameattribute.

• Thisbecomesthenameofthevariableinthecodefile.

• Becausetheneedtodefinenamesforelementsissocommon,XAMLprovidesashortcut.

• IfthetypeextendsFrameworkElement,youcanomitthex:prefixandsimplyuseName.

• However,ifthetypedoesnotextendFrameworkElement,youmustusex:Name.

• Whenindoubt,x:Namewillalwaysworkwhenyouwishtonameanelement.

• Therefore,theprevious<Button>couldalsobedefinedasfollows:

<Button Content="OK" Name = "myButton" x:FieldModifier = "public"/>

Page 72: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-42 Copyright©Intertech,Inc2014 Rev:4

Property‐Element Syntax  

• Withinthescopeofanopeningelement,youwillbeabletosetvaluestothepropertiesandeventsofthetype.

• Forexample,thefollowing<Button>setstheHeightandWidthvaluesandhandlestheClickevent.

• ThenameassignedtotheClickeventwilltypicallymaptoamethodinyourcodefile.

• However,thiscouldalsobeamethodina<x:Code>scopeofthedefiningXAMLfile.

<Button Name = "myButton" Height = "100" Width = "100" Click = "myButton_Click" Content="OK"/>

• Here,Height,Width,andClickwereassignedvaluesthatcouldbecapturedasasimplestring.

• However,manypropertiesofWPFclassesdonotoperateondatathatrepresentssimplestringvalues.

• Forexample,somepropertiesrequirefull‐blownobjects(complexbrushes,pens,andsoon).

• XAMLproperty‐elementsyntaxallowsyoutoassigncomplexobjectvaluestoaproperty.

• Thissyntaxdefinesasubscopescoperepresentingapropertyofthedefiningtype.

• Withinthisscope,youcandescribetheobjecttobeusedforthepropertyassignment.

• Theformatfollowsthefollowingtemplate:

<DefiningType> <DefiningType.PropertyOnDefiningType> <!-- data used to set property --> </DefiningType.PropertyOnDefiningType> </DefiningType>

Page 73: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-43

• Considerthefollowingsyntax,whichsetstheBackgroundpropertyofaButtontoaLinearGradientBrushtypeusingproperty‐elementsyntax.

• TheassociatedimageshowsyouhowthisbuttonwouldlookwhenrenderedbyaXAMLparser.

<Button Name = "myButton" Height = "100" Width = "100" Content = "Click Me!"> <Button.Background> <LinearGradientBrush StartPoint = "0,0" EndPoint = "1,1"> <GradientStop Color = "Blue" Offset = "0" /> <GradientStop Color = "Yellow" Offset = "0.25" /> <GradientStop Color = "Green" Offset = "0.75" /> <GradientStop Color = "Pink" Offset = "0.50" /> </LinearGradientBrush> </Button.Background> </Button>

• Whileproperty‐elementsyntaxismostcommonlyusedtoassigncomplexobjectstoproperties,itispossibletoassignsimplestringdatatoo.

• Youdonotgainmuchbydoingso,however,asyoucouldsimplyuseanattributeintheopeningelement.

• Thus,thefollowingmarkupisfunctionallyequivalent:

<!-- OK, but verbose --> <Button x:Name = "myButton" Height = "100" Width = "100" Content = "Click Me!"> <Button.Background> Pink </Button.Background> </Button>

<Button x:Name = "myButton" Height = "100" Width = "100" Content = "Click Me!" Background = "Pink"> </Button>

Page 74: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-44 Copyright©Intertech,Inc2014 Rev:4

Attached‐Property Syntax  

• WPFalsomakesuseofaconcepttermed‘attachedproperty’syntax.

• Oneuseofattachedpropertiesistomakeitpossibleforasub‐elementtoassignapropertyvalueonaparentelement.

• Inthiscase,thetemplatetouselookslikethefollowing:

<ParentType> <ChildType ParentType.PropertyName = "Value"> </ChildType> </ParentType>

• Themostcommonuseofattached‐propertysyntaxistopositionUIelementswithinoneoftheWPFpaneltypes(Grid,DockPanel,andsoon).

• Youwilldiveintothesepanelsinsomedetaillater.However,hereisanexampleofattached‐propertysyntax.

<Window x:Class = "FunWithAttachedPropeties.Window1" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Fun with Attached Properties" Height = "300" Width = "300"> <DockPanel LastChildFill = "True"> <!-- Dock items to the panel using attached properties. --> <Label DockPanel.Dock = "Top" Name = "lblInstruction" FontSize = "15" Content = "Label One"/> <Label DockPanel.Dock = "Left" Name = "lblMake" Content = "Label Two"/> <Label DockPanel.Dock = "Right" Name = "lblColor" Content = "Label Three"/> <Label DockPanel.Dock = "Bottom" Name = "lblPetName" Content = "Label Four"/> <Button Name = "btnOK">OK</Button> </DockPanel> </Window>

Page 75: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-45

• Understandthatattachedpropertiescannotbeusedasageneral‐purposesyntaxthatcanbeusedtosetanypropertyonaparentelement.

• TheIntelliSenseofVisualStudiowillshowyouvalidattachedpropertiesforagivenelement.

• Inreality,attachedpropertiesareaspecializedformofaWPF‐specificconcepttermeddependencyproperty.

• Thus,attached‐propertysyntaxcanonlyworkifthepropertysupportsthecorrectdependencypropertyinfrastructure.

• SeeAppendixBformoreinformationondependencyproperties.

Page 76: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-46 Copyright©Intertech,Inc2014 Rev:4

The Role of XAML Markup Extensions 

• Althoughthemajorityofpropertyvaluescanbeassignedusingstringsorviaproperty‐elementsyntax,somepropertyvaluescannot,asinthefollowingcases:

• Youwishtoassignapropertyvaluetoanobjectcreatedelsewhere(incode,asalogicalresource,andsoforth).

• Youwishtoassignapropertytoavaluecalculatedatruntime.

• Fortheseandotherreasons,XAMLsupportsmarkupextensions.

• Inanutshell,markupextensionsareusedtosetpropertyvaluesinnonstandardways.

• Again,thesenonstandardwaystypicallyinvolvereferringtoobjectsallocatedelsewhereordatacomputedatruntime.

• Likeatypeconverter,markupextensionshaveaclass‐basedequivalentintheWPFlibraries.

• Andliketypeconverters,theseclassesseldomneedtobeuseddirectlyinyourcode.

• AXAMLmarkupextensionisencasedwithincurlybracketsatthetimeyouassignapropertyvalue.

• Hereisageneraltemplatetofollow.

<DefiningType DefiningTypeProperty = "{x:MarkUpExtension Value}" > </DefiningType>

• XAMLprovidesanumberofmarkupextensions,severalofwhichyouexaminedintheprevioustableofXAMLtokens.

• Forexample,Array,Null,Static,Type,StaticResource,andDynamicResourcearemarkupextensions.

Page 77: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-47

• Youwillseetheuseofmanymarkupextensionduringtheremainderofthisclass.

• Inthemeantime,hereareafewexamples.

• AssumeyouwishtosettheContentpropertyforasetofLabels.

• Thevaluesaretobecomputedatruntime,basedonvariousstaticpropertiesoftheSystem.Environmenttype.

• Asyoumayknow,System.Environmentisdefinedinmscorlib.dll.Therefore,youmustdefineanewXMLnamespace(namedCorLib)thatmapstothislibrary.

• Notetheuseofthe{x:Static}markupextension.

<Window x:Class = "FunWithMarkUpExtensions.Window1" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:CorLib = "clr-namespace:System;assembly=mscorlib" Title = "Fun with Markup Extensions" Height = "300" Width = "300"> <StackPanel> <Label Content = "{x:Static CorLib:Environment.MachineName}"/> <Label Content = "{x:Static CorLib:Environment.OSVersion}"/> <Label Content = "{x:Static CorLib:Environment.ProcessorCount}"/> </StackPanel> </Window>

Page 78: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-48 Copyright©Intertech,Inc2014 Rev:4

• Nowconsidertheuseofthe{x:Type}markupextension,whichextractstypeinformationforagivenmember:

• {x:Type}istheXAMLequivalentofcallingType.GetType().

• Assumethefollowingupdatetothe<StackPanel>type.

• NoticetheLabelsnowcontainthefullyqualifiednameofthetype.

<StackPanel> <Label Content = "{x:Type Label}" /> <Label Content = "{x:Type Page}" /> <Label Content = "{x:Type CorLib:Boolean}" /> </StackPanel>

LabExercise:BuildingaWPFApplication(allXAML)

Page 79: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-49

Separation of Concerns Using Code Files           

• FewWPFapplicationswilltakethe100%codeor100%XAMLapproachasyouhaveseenthusfar.

• Inreality,a‘middleoftheroad’approachisrecommended.

• SimilartoanASP.NETwebapplication,WPFallowsyoutohaveaC#(orVB)filethatworksinconjunctionwitharelatedXAMLfile.

• TheXAMLfileisonlyconcernedwithUIdescriptionsdefinedviamarkup.

• Thecodefileisconcernedwithprogramminglogic.

• ElementsdefinedinXAMLcanbeaccessedinthecodefileandviceversaifrequired.

• Todoso,youshouldassignaNamepropertytotheXAMLelement.

• HereisthesimpleWPFapplicationyetagain,thistimemakinguseofcodefiles.

• Asanamingconvention,codefileshave‐xaml‐embeddedwithinthefilename.However,thisisnotrequired.

• Recallfromyourpreviouslabthattheauto‐generated*.g.cs/*.g.vbfilecompletesyourpartialclassdefinition.

• TheInitializeComponent()methodisdefinedwithinanauto‐generated*.g.cs/*.g.vbfile.

Page 80: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-50 Copyright©Intertech,Inc2014 Rev:4

// MainWindow.xaml.cs using System; using System.Windows; using System.Windows.Controls; namespace SimpleXamlApp { public partial class MainWindow : Window { public MainWindow() { // This method is defined // within the generated MainWindow.g.cs file. InitializeComponent(); } private void btnExitApp_Clicked(object sender, RoutedEventArgs e) { // Get a handle to the current application and shut it down. Application.Current.Shutdown(); } } }

• TheApplicationdefinitioncouldalsomakeuseofthecode‐fileapproach.

• TheXAMLfilewouldstillcontaintheStartupUripropertysettingandsoon.

// MyApp.xaml.cs using System; using System.Windows; using System.Windows.Controls; namespace SimpleXamlApp { public partial class MyApp : Application { private void AppExit(object sender, ExitEventArgs e) { MessageBox.Show("App has exited"); } } }

Page 81: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-51

• Thecode‐fileapproachisthedefaultbehaviorofVisualStudioWPFapps.

• WhenyouselecttheWPFprojecttemplatefromtheFile|NewProjectmenu,youaregivenanApplication‐derivedtypeandinitialWindow‐derivedtype.

• Eachtypeiscomposedofa*.cs/*.vbfile,*.xamlfile,andtheauto‐generated*.g*file.

• Collectively,thesethreepartialclassdefinitionsprovidecompletefunctionality.

Page 82: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-52 Copyright©Intertech,Inc2014 Rev:4

Visual Studio  WPF Designer Support          

• WPFapplicationscanbebuiltusingnothingmorethanasimpletexteditor,a.NETlanguagecompiler(C#,VB),andmsbuild.exe.

• However,doingsoforalarge‐scaleprojectwouldbetediousanderrorprone.

Thankfully,VisualStudiohasintegratedWPFprogrammingsupportthatincludesthefollowing:

• WPFprojecttemplates.

• IntegratedXAMLeditors.

• AWPF‐awareToolbox/Propertieswindow.

Page 83: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-53

• TheNewProjectdialogboxprovidesanumberofWPFprojecttemplates.

• TheWPFApplicationiconisusedtobuildatraditionaldesktopexecutable.

• TheWPFBrowserApplicationprojecttemplateprovidesastartingpointforXBAPdevelopment.

• YoualsohaveprojecttypesforcustomWPFcontrollibraries.

Page 84: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-54 Copyright©Intertech,Inc2014 Rev:4

• TheWPFdesignerallowsyoutoviewnotonlythewindow/pageitselfbuttheunderlyingXAML.

• YoucanbuildtheUIofyourformusingtheWPFToolboxandrelatedVSPropertieswindow.

• Asanalternative,youcandirectlyauthorXAMLmarkuptochangetheUIofthewindowyouareconstructing.

• NoticetheXAMLeditorsupportstheexpectedIntelliSense.

Page 85: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-55

• TheXAMLeditoralsoprovidestheabilitytogenerateeventhandlersforeventsdeclaredviaXAML.

• Whenyouenterthenameofaneventforagivenwidget,youwillfindaNewEventHandlerpopupwindow.

• Selectingthisoptionwillgenerateanameforyoureventhandler.

• Thecorrespondingcodefilewillcontainthehandler.

• Thecorresponding*.g.cs/*.g.vbfilewillcontaintheeventwire‐uplogic.

Page 86: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

1-56 Copyright©Intertech,Inc2014 Rev:4

• Aswell,VisualStudiohasasophisticatedPropertieseditorforselectedWPFelements.

• ThissupportisfarsuperiortowhatwasfoundinearlierversionsofVisualStudio.

• Youcannowfindtoolstogeneratebrushes,configuredatabinding,resourcemanagementandsoforth.

• Alsonoticethe"lightningbolt"buttonprovidesadifferentwaytohandleevents(justlikeyouwoulddoforanASP.NETorWindowsFormsapplication).

• BesuretotakethetimetoexplorethePropertieswindowduringyourlabtime.

LabExercise:BuildingaWPFApplication(CodeFiles)

Page 87: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

IntroducingWPF

Copyright©Intertech,Inc2014Rev:4 1-57

Chapter Summary                    

• WPFisanew,superchargedGUItoolkitthatshipswith.NET3.0andhigher.

• WPFintegratesseveralpreviousAPIsanddesktopprogrammingmodelsintoaunifiedobjectmodel.

• WPFintroducesXAML,amarkuplanguageusedtodescribetreesof.NETobjects.

• XAML+Code=Applications.However,aWPFapplicationcanbewrittenusing100%pureXAML,100%purecode,orviacodefiles.

Page 88: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Copyright © Intertech, Inc 2014 Rev: 4 1-1

Chapter 1

Introducing Windows Communication Foundation

Objectives:

Understand the motivation behind WCF

Learn the "ABCs" of building a WCF application

Learn to define and implement a WCF service contract

Survey WCF binding options

Learn to establish the address of a WCF service

Explore some common WCF development tools

Page 89: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-2 Copyright © Inc 2014 Rev: 4

Chapter Overview

This chapter will introduce you to the Windows Communication Foundation (WCF) API. Here you will learn about the problems WCF attempts to solve, study the ABC’s (addresses, bindings, and contracts) of building a WCF application, and explore some common WCF development tools.

The information presented here will function as the foundation for the remainder of the class.

Page 90: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-3

A Working Definition of Windows Communication Foundation (WCF)

• WCF is a .NET 3.0 (and higher) API that allows you to build distributed systems.

• WCF is unique in that you can select from many types of bindings. This fact alone makes WCF a very flexible framework.

• A single WCF service could be exposed via an HTTP binding for outwardly facing callers and via a TCP binding for in-house callers.

• The underlying plumbing details can be relegated to *.config files, which make it very simple to change bindings and other details on the fly.

• WCF makes extensive use of interface-based programming techniques.

• When you create a WCF service, you typically begin by defining the interfaces that model the functionality callers can expect to find at a given location.

• These .NET interfaces can be used by the runtime to generate WSDL definitions based on your choice of bindings.

• WCF makes heavy use of .NET attributes to qualify how the runtime should handle client / service interactions.

• Recall that attributes are essentially code annotations.

• WCF attributes are used to control data formatting, binding settings, security details, SOAP message formatting, and more.

• Attributes are useless unless another piece of software reflects over them.

• In this case, the ‘other piece of software’ could be the .NET runtime as well as WCF development tools.

Page 91: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-4 Copyright © Inc 2014 Rev: 4

• WCF is heavily influenced by XML web services and Service-Oriented Architectures (SOAs) in general.

• Like an XML web service, WCF services make use of contracts, explicit boundaries and supports the use of various WS-* specifications.

• Based on your choice of binding, you may gather support for various WS-* standards (or not).

• However, a WCF service does not have to use web-service-centric bindings.

• If you wish, you can opt for P2P bindings, IPC (named pipes) bindings, TCP bindings or MSMQ bindings.

• The underlying binding is decoupled from the service itself.

• Therefore, changing bindings on the fly is very straightforward.

• In a nutshell, as of .NET 3.0 (and higher), WCF is the preferred way to build distributed systems.

• The original distributed .NET APIs (such as System.Runtime.Remoting and System.Web.Services) are still supported by the .NET platform.

• Furthermore, Visual Studio still has templates for ‘traditional’ ASP.NET XML web service project workspaces.

• Nevertheless, WCF is the heir apparent of these previous distributed APIs.

• Appendix A provides an overview of several distributed Windows APIs which were used prior to WCF.

• If you are new to the creation of distributed systems on the Windows OS, you are encouraged to read Appendix A during this course.

• Be sure to ask your instructor if you have any questions.

Page 92: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-5

A Brief Word Regarding Migration to WCF

• WCF does provide some support for migrating existing XML web services / .NET remoting applications into the WCF programming model.

• Doing so, however, may offer little benefit. In fact, it could entail a good amount of work.

• As a good rule of thumb, existing XML web services / .NET remoting applications should remain as-is.

• This course does not cover migrating existing distributed systems into the WCF programming model.

• The class assumes you intend to build new WCF services, hosts, and clients.

• MSDN Online provides a few articles which examine the details of migrating existing systems to WCF.

• If you are interested in migrating from .NET remoting to WCF, look up the article From .NET Remoting to the Windows Communication Foundation (WCF).

• If you are interested in migrating from ASP.NET XML web services to WCF, look up the article Migrating ASP.NET Web Services to WCF.

• On a related note, WCF makes it possible to build new WCF services which communicate with legacy COM+ components.

• As you may know, COM+ provides a set of runtime services to COM-based or .NET-based DLLs.

• COM+/WCF integration is not part of the formal lecture materials for this class.

• Appendix B illustrates how to interact with legacy COM+ components.

• As well, your lab book includes a COM+ integration lab, which you may choose to do on your own time, if the topic is of interest.

Page 93: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-6 Copyright © Inc 2014 Rev: 4

The All-Important WCF Documentation

• The core programming model of WCF is actually quite simple:

• You can configure a WCF service using little more than a handful of attributes.

• Custom hosts can be constructed using 4 lines of code and a server side *.config file.

• Client applications can generate proxies to communicate with the remote service with a few mouse clicks.

• However, as we know all too well, the devil is in the details.

• In this class will focus on the core aspects of the programming model, which will be useful for a majority of your WCF projects.

• Be sure to consult the .NET Framework SDK documentation for WCF topics not directly addressed in this course.

Page 94: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-7

• The SDK documentation provides a number of excellent code examples, white papers, and tutorials.

• Simply look up the Windows Communication Foundation selection of the help system and dive in.

• You will see specific parts of this help system during your lecture / lab time.

Page 95: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-8 Copyright © Inc 2014 Rev: 4

The Motivation behind WCF

• Each of the previously examined distributed APIs can still be used directly within the .NET platform.

• However, WCF provides a single unified model to access these previously diverse technologies.

• WCF integrates the services of previous distributed technologies (.NET remoting, XML web services, MSMQ, P2P, and so on) into a streamlined API.

• Without WCF, the wide array of distributed technologies made it difficult to pick the right tool for the job.

• The core problem was each API was an island unto itself (different programming models, different fundamental data types, different ways to define contracts, among other issues).

• This was further complicated by the fact that several of these technologies overlapped in the services they provide (i.e., providing numerous ways to do the same thing).

• Even when a .NET developer selected what appear to be the ‘correct’ technologies for the task at hand, maintaining and configuring such an application was complex at best.

• WCF provides a rich software fabric that complements the distributed technologies it exposes, including the following examples:

• Support for strongly typed, as well as untyped, messages. This approach allows .NET applications to share custom types simply and efficiently, while software created using other platforms such as Java can consume streams of loosely typed XML.

• Support for several bindings (raw HTTP, HTTP + SOAP, TCP, MSMQ, and named pipes) to allow you to choose the most appropriate plumbing to transport data.

• Tracing, messaging, and performance counter APIs.

• Security APIs, including a new security feature named CardSpace.

• Transactional and peer-to-peer (P2P) APIs.

Page 96: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-9

WCF Assemblies and Core Namespaces

• WCF exposes its functionality using two core .NET assemblies.

• When you select a Visual Studio WCF project template, these assemblies are automatically referenced.

WCF Assembly Meaning in Life

System.Runtime.Serialization.dll Defines namespaces and types that can be used for serializing and deserializing objects within the WCF framework.

System.ServiceModel.dll This is the core assembly that contains the core types used to build any sort of WCF application.

• In addition, the CardSpace API is represented by the System.IdentityModel.dll assembly.

• This WCF technology allows you to establish and manage digital identities within a WCF application, using a ‘business card’ façade.

• This course does not address the CardSpace API, so be sure to consult the .NET Framework SDK documentation for details if you are interested.

The System.IdentityModel.dll assembly does define a number of WCF security primitives, independent from CardSpace.

• Therefore, even if you are not using CardSpace itself, you may need to reference System.IdentityModel.dll when programming with WCF security.

• You will examine this assembly later in the course when you examine WCF security.

Page 97: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-10 Copyright © Inc 2014 Rev: 4

• The core WCF assemblies define a number of new namespaces and numerous .NET types.

• Here is a breakdown of the core WCF namespace.

• Be aware that many WCF applications will only require using a subset of these namespaces, such as System.ServiceModel and System.Runtime.Serialization.

• Many of the remaining namespaces are used behind the scenes by proxy generation tools, etc.

WCF Namespace Meaning in Life

System.Runtime.Serialization Defines numerous types that are used to control how data is serialized and deserialized within the WCF framework.

Many of these types are WCF-centric attributes (DataContract, DataMember, and so on).

System.ServiceModel This is the core WCF namespace and defines binding and hosting types, as well as basic security, queuing, and transactional types.

System.ServiceModel.Activation

System.ServiceModel.Activation.Configuration

Defines types which can be used to customize and configure how a process activates contained services.

System.ServiceModel.Channels This namespace defines a number of types used to build client side proxies, as well as types which allow for programmatic manipulation of various binding properties

System.ServiceModel.ComIntegration Types used to allow WCF to communicate with COM+ objects.

System.ServiceModel.Configuration Defines types that provide programmatic access to the sections of WCF configuration files.

System.ServiceModel.Description Defines types that provide an object model to the addresses, bindings, and contracts defined within WCF configuration files.

System.ServiceModel.MsmqIntegration Contains types to integrate with the

Page 98: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-11

Microsoft Message Queuing Service (MSMQ) runtime.

System.ServiceModel.Security Defines a number of WCF security primitives.

System.ServiceModel.Web Defines types which allow you to directly interact with an HTTP request / response.

Page 99: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-12 Copyright © Inc 2014 Rev: 4

The Composition of a WCF Application

• A typical WCF application involve three interrelated software components:

• The WCF Service assembly: This *.dll contains the classes and interfaces that represent the overall functionality you are exposing to external callers.

• The WCF Service host: This software module is the entity that hosts your WCF service assembly. Programmatically, this is accomplished by an instance of the ServiceHost class.

• The WCF client: This is the application that accesses the service’s functionality through an intervening proxy.

• The WCF service assembly is a ‘normal’ .NET class library defining a set of types.

• However, these types are decorated with numerous WCF-specific attributes.

• Using these attributes, you can control data type representation, control which aspects of a WCF service are accessible to callers, and more.

• The service host can be any .NET application domain.

• You could host a WCF service using a simple console application, or via a desktop GUI (Windows Forms, WPF).

• You could host a WCF service using a custom Windows Service.

• You can also host WCF objects using IIS. In this case, you have no need to build the host logic manually, as you are given a free ServiceHost object.

• Windows Server machines can host WCF services using the Windows Activation Service (WAS).

• You will evaluate your hosting options in more detail in the next chapter.

Page 100: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-13

• Regardless of the hosting type, the host will need to specify the necessary remoting infrastructure.

• These include endpoints, transport layers, dynamic discovery of metadata, and so on.

• This sort of information can either be hardcoded within the host assembly or specified via an external *.config file.

• Most WCF apps will opt for *.config file as this allows you to change the plumbing without recompiling / redeploying your software.

• WCF clients communicate with WCF services using an intervening proxy.

• Any type of .NET application can be the client of a WCF service, including other WCF services.

• You could build this proxy by hand, but typically you’ll want to leverage Visual Studio.

• Client side plumbing can also configured using *.config files or using 100% code.

• The following diagram illustrates the high-level composition of a WCF application.

• Remember, if you are using a web-service binding, the client application can be created in any software framework (Java, .NET, COM, C, etc).

• If you are using an IPC or TCP based binding, the client will be limited to .NET applications.

• More options of binding choices in just a bit…

Page 101: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-14 Copyright © Inc 2014 Rev: 4

• While the previous diagram captures the basic composition of a WCF application, it hides a number of lower level details.

• Specifically, when a client proxy calls a WCF service, a number of additional layers of interception (channels, transports, dispatchers) are put in place automatically.

• As well, when the WCF service returns data to the client, a similar set of interceptors are put in place for the host.

• In WCF, the term ‘channel’ represents a layer of interception, which can perform pre- and post- processing.

• Based on which binding you are making use of, the WCF runtime will insert a set of channel objects.

• Each channel object is in charge of a specific task, such as encoding message data, propagating a distributed transaction, performing security checks, et.al.

• On the client side, the lower level details can be understood as so:

• The proxy makes the initial call to a remove method.

• The request data passes through some number of channels, which again are configured based on the selected binding.

• The final channel on the client side is termed the ‘transport channel’, which does the actual task of forwarding the final configured message to the host.

Page 102: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-15

• On the host side, the lower level details breakdown as so:

• The first channel on the host side is also the transport channel, which receives the sent message.

• The message is sent through some number of channels, which again are configured based on the selected binding.

• The message is then passed to a dispatcher object, which converts the agnostic message into a .NET method call.

• Here then, is a diagram which represents a possible client / service interaction in greater detail.

• Here, the diagram illustrates a client proxy invoking a remote method.

• When the method returns a value, the process is reversed.

Page 103: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-16 Copyright © Inc 2014 Rev: 4

• It is worth noting, that the WCF channel architecture can be extended with custom channels to provide additional layers of interception.

• We will not be covering the creation of custom channels in this course.

• Consult the .NET Framework SDK documentation for further details if you are so interested.

• Simply look up the topic, Extending the Channel Layer.

Page 104: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-17

The ABC’s of WCF

• Hosts and clients communicate by agreeing on the ABC’s that describe the WCF service’s functionality:

• Address: The location of the service. In code, this is represented with a System.Uri type, but the value is typically stored in *.config files.

• Binding: WCF ships with a number of different bindings that dictate network protocols, encoding mechanisms, and the transport layer.

• Contract: A description of each method exposed from the WCF service. This may also include descriptions of custom data types, message layout information and error code data.

• A new WCF service project typically begins by defining and implementing contracts first.

• After that point, you typically select the binding you wish to use to allow external callers to communicate with the service.

• Finally, you will specify an address. As you will see, the format of an address will differ based on your choice of bindings.

Page 105: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-18 Copyright © Inc 2014 Rev: 4

The Role of WCF Service Contracts

• In WCF, a ‘contract’ is an agnostic way of describing a service’s functionality. Specifically a WCF contract can express:

• Service Contract Information: Methods on the service which can be called by the client.

• Data Contract Information: Descriptions of custom data types used by said methods.

• Fault Contract Information: Descriptions of any error information raised by the service.

• Message Contract Information: Used to control how a message is formatted, which can be useful for interoperability with proprietary message formats.

• When defining service contracts, you typically do so by defining strongly typed CLR interfaces.

• The interfaces are adorned with various WCF attributes to control how the runtime interacts with these types.

Page 106: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-19

• System.ServiceModel defines the basic attributes you will use on a day-to-day basis.

• Here you will find the key attributes, [ServiceContract] and [OperationContract].

• More exotic attributes are found within the System.Runtime.Serialization.dll assembly. They allow you to fine-tune how custom data is represented.

• Assume you have created a new .NET class library project named WcfMathService with Visual Studio.

• Also assume you have set references to System.ServiceModel.dll and imported the System.ServiceModel namespace.

Page 107: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-20 Copyright © Inc 2014 Rev: 4

• The first step is to define the WCF contract exposed by your service.

• The interface itself is adorned with the [ServiceContract] attribute, maps a .NET interface to an agnostic service contract.

• Each method of the interface is adorned with the [OperationContract] attribute.

• You will see further details of these attributes later in the class.

// C# [ServiceContract] public interface IBasicMath { [OperationContract] int Add(int x, int y); [OperationContract] int Subtract(int x, int y); }

' VB <ServiceContract()> _ Public Interface IBasicMath <OperationContract()> _ Function Add(ByVal x As Integer, ByVal y As Integer) As Integer <OperationContract()> _ Function Subtract(ByVal x As Integer, ByVal y As Integer) As Integer End Interface

Page 108: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-21

• Once defined, any class type can implement the interface.

• WCF will not expose contracts implemented on structures!

• They must be class types, as they will be allocated to the managed heap.

• Recall that .NET structures are allocated on the stack.

// C# (contract must be implemented on a class type!) public class SimpleCalc : IBasicMath { public int Add(int x, int y) { return x + y; } public int Subtract(int x, int y) { return x - y; } }

' VB (contract must be implemented on a class type!) Public Class SimpleCalc Implements IBasicMath Public Function Add(ByVal x As Integer, _ ByVal y As Integer) As Integer Implements IBasicMath.Add Return x + y End Function Public Function Subtract(ByVal x As Integer, _ ByVal y As Integer) As Integer Implements IBasicMath.Add Return x - y End Function End Class

Page 109: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-22 Copyright © Inc 2014 Rev: 4

• Strictly speaking, .NET interfaces are not required when defining a WCF contract.

• The [ServiceContract] type can be applied to class types, as well.

• However, interfaces are *strongly recommended* when defining contracts. In this way, you can easily use contracts on new classes.

• In fact, best practice states you should also model service contracts via interface types; however here is a simple example in C#.

// C# (VB code would be similar). // This is not Recommended! Make use of interfaces! [ServiceContract] public class ServiceTypeAsContract { [OperationContract] public void SomeMethod() { /* Some interesting code. */ } [OperationContract] public void AnotherMethod() { /* Some interesting code. */ } }

• Once this service *.dll has been compiled, you will be able to build any sort of host to expose its services using the specified bindings.

• At that point, you can generate proxies for external callers.

• However, before this point, you need to understand your WCF binding options.

Page 110: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-23

Examining WCF Binding Options

• WCF ships with many predefined bindings, all of which are defined within the System.ServiceModel namespace.

• Each is tailored to a specific remoting need.

• Remember, any WCF binding can be configured in code or *.config files (or a combination of both).

• If none of these default binding fit the bill, you are free to create your own by extending the CustomBinding type.

• Creating custom bindings will not be examined in this course.

• Look up the topic Custom Bindings if you are interested.

Page 111: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-24 Copyright © Inc 2014 Rev: 4

• Simply put, a WCF "binding" specifies the following characteristics:

• The transport layer used to move data (HTTP, MSMQ, named pipes, TCP, etc).

• The communications used by the transport (one-way fire and forget, request-reply, duplex).

• The encoding mechanism used to deal with the data itself (XML, binary, Message Transport Optimization Mechanism [MTOM] and so on).

• Any supported web service protocols, if permitted by the binding, such as WS-Security, WS-Transactions, WS-Reliability, and so forth.

• Each WCF binding has a predefined set of default settings.

• In many cases, you will use a binding out-of-the-box, accepting each default setting.

• However, any of the WCF binding settings can be changed as you see fit.

• While WCF bindings are typically established in configuration files, you can also establish the same settings in code.

• If you configure the binding in a configuration file, you will use an element name which has a lower case initial letter (ex: <basicHttpBinding>).

• If you configure a binding in code, you will use an identically named class, which uses an upper case initial letter (ex: BasicHttpBinding).

• Also be aware that in code, WS is always capitalized (WSHttpBinding). In configuration, the ‘ws’ is in lowercase (wsHttpBinding).

• You’ll learn how to change binding settings beginning in Chapter 2.

Page 112: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-25

• The first set of bindings will expose a WCF service using web service based protocols.

• Clearly, if you require the furthest reach possible (multiple operating systems, multiple programming architectures such as COM, .NET, and JAVA EE), these are the bindings to focus on.

• All of these types encode data based on XML representation and use HTTP (or HTTPS) on the wire.

WCF Binding Class WCF Binding Element Meaning in Life

BasicHttpBinding <basicHttpBinding> This is the WCF equivalent of building an ASP.NET XML web service.

Support for BP 1.1, but no support for WS-* specifications.

WSHttpBinding <wsHttpBinding> A web service binding that supports WS-* features (transactions, reliable messaging, addressing).

WSDualHttpBinding <wsDualHttpBinding> A web service binding that supports WS-* features and duplex contracts (e.g., the service and client can send messages back and forth).

WSFederationHttpBinding

<wsFederationHttpBinding>

A web service binding that supports WS-* features and the WS federated security protocol.

We will not examine federated security in this class.

Page 113: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-26 Copyright © Inc 2014 Rev: 4

• The next step of bindings will expose a WCF service using TCP / Interprocess Communication (IPC) protocols.

• The caller and service must both be .NET applications.

• Given this, TCP/IPC bindings are only useful for inwardly facing application on the same network / same machine.

• All data is encoded in a compact binary format.

• The client and service can make full use of the .NET Common Type System.

WCF Binding Class WCF Binding Element Meaning in Life

NetTcpBinding <netTcpBinding> A secure and optimized binding suitable for cross-machine communication between .NET applications.

NetNamedPipeBinding <netNamedPipeBinding> A secure, reliable, optimized IPC binding for on-same-machine communication between .NET applications.

NetPeerTcpBinding <netPeerTcpBinding> Provides a secure binding for peer-to-peer (P2P) network applications.

P2P computing will not be examined in this class.

Page 114: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-27

• If you are attempting to integrate with a MSMQ server, the NetMsmqBinding and MsmqIntegrationBinding bindings are of immediate interest.

• These bindings support loosely coupled applications, failure isolation, load leveling, and disconnected operations.

WCF Binding Class WCF Binding Element Meaning in Life

NetMsmqBinding <netMsmqBinding> A queued binding that is suitable for cross-machine communication between .NET applications.

MsmqIntegrationBinding <msmqIntegrationBinding> This binding can be used to enable WCF applications to send and receive messages to and from existing MSMQ applications that use COM, native C++, or the types defined in the System.Messaging namespace.

Page 115: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-28 Copyright © Inc 2014 Rev: 4

• This course will not examine how to build WCF services that interact with Microsoft Message Queue (MSMQ).

• Consult the .NET Framework SDK documentation if you are interested in MSMQ integration services.

• The topic ‘Queues in WCF’ is a good starting point.

• The final core binding to be aware of is WebHttpBinding.

• This simple binding allows you service to receive calls via REST, POX and JSON patterns.

• You will be introduced to RESTful WCF services later in this class.

Page 116: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-29

A Summary of Commonly Used Bindings

• Although the number of bindings can appear a bit daunting, in practice, most WCF services will make use of the following key bindings:

• BasicHttpBinding: A basic BP 1.1 web service.

• WSHttpBinding: Web service binding which supports WS-* protocols.

• NetTcpBinding: Perfect for .NET-to-.NET distributed applications.

• NetNamedPipeBinding: Perfect for fast, same machine communication, between .NET applications.

• To further simplify matters, consider the following table which documents how these key binding account for transport, encoding and interoperability.

• Message Transport Optimization Mechanism (MTOM) can be used to help optimize transportation of very large payloads.

WCF Binding Transport Layer Encoding Interoperable beyond .NET?

BasicHttpBinding HTTP/HTTPS Text by default, MTOM if configured

Yes!

WSHttpBinding HTTP/HTTPS Text by default, MTOM if configured

Yes!

NetTcpBinding TCP Binary No!

NetNamedPipeBinding IPC Binary No!

Page 117: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-30 Copyright © Inc 2014 Rev: 4

Establishing a WCF Address

• Once your contract and bindings have been established, your last task is to configure an address.

• Addresses are obviously important as this allows the caller to know the location of the service.

• Every WCF service is mapped to an address, which specifies the location of the service and the transport schema to access it.

• The syntax used to express the address will differ based on the type of binding selected (HTTP-based, named pipes, TCP-based, or MSMQ-based).

• From a high level, all WCF addresses can be represented with the following template:

• Scheme: The transport protocol (HTTP, TCP, etc.).

• machineName: Fully qualified domain name of the machine.

• Port: This is optional in many cases. The default for HTTP bindings is port 80.

• Path: The path to the WCF service.

scheme://<machineName>[:Port]/Path

• If you are using an HTTP-based protocol, the address takes the following form:

• HTTPS can be used rather than HTTP if you require SSL connections.

• The default port for HTTP is port 80; HTTPS defaults to 443.

http://localhost:8080/MyWcfServices/ServiceOne

• If you are using an TCP-based protocol, the address takes the following form:

• If you do not specify a port, TCP bindings default to 808.

net.tcp://localhost:8080/MyWcfServices/ServiceOne

Page 118: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

Copyright © Intertech, Inc 2014 Rev: 4 1-31

• If you are using an MSMQ-based protocol, the address takes the following form:

• Ports have no meaning in MSMQ-based protocols. Rather, you specify the type of queue (public, private) queue name.

net.msmq://localhost/private$/MyQ

• When using named pipes, the address takes the following form:

• Port numbers are not used with named pipes.

• Because named pipes can only be used for same machine calls, you must specify localhost or the exact machine name.

net.pipe://localhost/MyWcfServices/ServiceOne

• At this point you are ready to build your first WCF service.

• To keep this first lab simple, you will not manually create a custom host or custom client.

• Rather, you will leverage a WCF testing tool, WcfTestClient.exe.

• This application functions as a makeshift host and client for testing and debugging purposes.

Lab Exercise: Introducing Windows Communication Foundation

Page 119: The Philosophy of · The Role of the Common Language Runtime (CLR) • The Common Language Runtime (CLR) is the engine which manages your .NET applications. The CLR provides several

Introducing Windows Communication Foundation

1-32 Copyright © Inc 2014 Rev: 4

Chapter Summary

• Windows Communication Foundation (WCF) is the preferred API for building distributed applications.

• The major goal of WCF is to integrate the current remoting APIs (MSMQ, TCP, named pipes, web services, and so on) under a unified umbrella.

• WCF is service oriented and revolves around addresses, bindings, and contracts (the ABC’s).

• WCF bindings allow you to expose a service in a manner fitting to the caller (in-house, outwardly facing, same machine, etc).

• WCF makes use of several attributes to control how functionality is exposed and consumed by clients and hosts.

• The WcfTestClient.exe application makes it simple to test WCF services using a default host / client.