building applicaons in c#cdn.cs50.net/2011/fall/seminars/c_sharp/c_sharp.pdf · • allows...
TRANSCRIPT
Hello
• CS50TF‘09,‘10• CSconcentratorclassof2011• WorkedonWindowsHomeandSmallBusinessServer2011asaninterninRedmond,WA
• NowengineerintheApplica-onVirtualiza-onteamattheMicroso9NewEnglandResearchandDevelopmentCenter(NERD)
Microso9NERD
• Teams:– Applica-onVirtualiza-on– Microso9Research– SharepointWorkspace2010– Office365– Microso9Lync– Interac-veEntertainmentBusiness– Microso9Adver-sing– Microso9‐NovellInteroperabilityLab
• Address:1MemorialDriveinCambridge• h\p://microso9cambridge.com
• Allowsapplica-onstoruninseparatevirtualenvironments,elimina-ngconflictswithotherapplica-onsorwithdifferentversionsofthesameapplica-on.
• Previouslyincompa-bleappscanberunsimultaneously
• Fullyfunc-onalWindowsappsarestreamedondemandtousers’desktops
• Weworkonverylargescalesystems• Moreath\p://microso9cambridge.com/Teams/Applica-onVirtualiza-on/tabid/83/Default.aspx
TOC1. IntrotoC#2. HelloWorld3. Object‐Orientedconcepts4. Collec-ons5. ControlFlow6. FileI/O7. StringsandREGEX8. XMLandLINQQueries9. Excep-onHandling10. Debugging
IntrotoC#• Object‐orientedprogramminglanguage• Type‐safetyguaranteed– cannotstoredataofonetypeinaloca-oncorrespondingtoadifferenttype
– cannothaveunini-alizedvariables• Garbagecollec-on–automa-cmemorymanagement(noneedtoworryaboutfreeingmemoryyouallocated)
• Built‐indatastructuresthathandletheirownsizing• Excep-onhandlingallowsdetec-onandrecoveryfromerrorsduringexecu-onofyourcode
IntrotoC#(2)• CodeissandboxedintoaVirtualExecu-onSystemwhichensuressafecodeexecu-onandmemorymanagement
• C#comeswiththe.NETFrameworkClassLibrary,whichmeansitispackedwithlibrariesthatsimplifymanycommontasksthatyouwouldotherwisehavetocode:– XMLandstringparsing– webprogramming– datastructures– scalablenetworksandserverprogramming– databasemanagement– GUIprogramming,andothers…
• Parallelprogrammingmadeeasy(ParallelCompu-ngPla=orm–takescareofthelowerlevelcodingforyou)
IntrotoC#(3)• Standardtypesarebuilt‐in• YoucancreateyourcustomtypesthroughOO
• C#enablescomponent‐orientedprogramming,whichmeansyoucancreateself‐containedunitsoffunc-onalitythatcancommunicate
• Yourcodeisalivingecosystem–extensibleandeasytomaintain.
• Thegoalistoallowyoutospendmore-meontheconceptsandlessonlower‐leveldetails.Itenablesyoutothinkmoreaboutyoursolu-onandtheabstractmodelbehindit.
DevelopmentEnvironment• SomebenefitsofusingVisualStudio2010:– Mul-tudeoflanguagesyoucanuse(VisualC#,VisualC++,VB)–the.NETlanguagesalluseacommontypesystem
– Auto‐Complete– Auto‐formapng
– Cross‐plaqormdevelopment– Mul-tudeofcodetemplatesandstubs– Debuggingmadeeasy
– IntegratedGUIdesigntools– IntegratedTes-ngtools
DevelopmentEnvironment(2)• Sourcecontrol• Candevelopanythingfromaconsoleappto:– clouddevelopment,– GUIapps,– webservers,– webapps,– tes-ngframeworks,– Windows8apps,– WindowsPhoneapps,– Officeadd‐ins,– toverylargecollabora-veprojects
TOC1. IntrotoC#2. HelloWorld3. Object‐Orientedconcepts4. Collec-ons5. ControlFlow6. FileI/O7. StringsandREGEX8. XMLandLINQQueries9. Excep-onHandling10. Debugging
Basics
• Usingstatement• Referencing• Namespace‐seehierarchydenotedusing.– System– System.Collec-ons– System.Collec-ons.Generic
• Class• Method• DEMO
TOC1. IntrotoC#2. HelloWorld3. Object‐Orientedconcepts4. Collec-ons5. ControlFlow6. FileI/O7. StringsandREGEX8. XMLandLINQQueries9. Excep-onHandling10. Debugging
ObjectOriented
• Programmingwithclassesmakesformoreextensiblecode(allowingyouforinstancetodefineyourowntypesandcontrolwhatisaccessible
• Encapsula-on=hideinternalimplementa-ondetailsofaclass(datahiding,thisisprivate)
• Abstrac-on=publicinterfaceofaclass,theexternaldetailssuchasac-onsthattheclasscanperform(thisisvisibletoeveryone)
OO(2)
• Tocreateanobjectofthetypedefinedinaclass,weneedtoinstan-atethatclass.Tobeabletodoso,theclassmustdefineaconstructor:
myClassfoo=newmyClass();• Constructorscanbeoverloaded–wecancreateseveralmethodswiththesamenamebutdifferentparameters(thusdifferentsignatures)
OO(3)
• Modifiers– private–onlyaccessibleinsidetheclass– public–accessiblebyeveryone– sta-c–dataandmethodsthatcanbeaccessedwithoutcrea-nganinstanceoftheclass
– const–forconstants• Scope:Namespaces,classes,andmethods
OO(4)
• Amethodinaclassisafunc-on–it’sbasicallyanac-onthatanobjectdefinedbytheclasscantake
• Apropertyinaclassisadataitemwhosereadandwriteaccessisdefinedbyyou(requireagetandaset:
public class Student {
//privately set private string _name; public string Name { //public read get return _name; }
}
OO(5)
• Inheritance:aclasscaninheritallcharacteris-csandac-onsfromaparentclass
• Thechildclasscanhaveitsownprivatedata,addedmethodsthatarenotfoundintheparent,orredefinethebehaviorofinheritedmethods
• Aclasscanonlyinheritfromoneparent
• DEMO
TOC1. IntrotoC#2. HelloWorld3. Object‐Orientedconcepts4. Collec-ons5. ControlFlow6. FileI/O7. StringsandREGEX8. XMLandLINQQueries9. Excep-onHandling10. Debugging
Arrays// Single-dimensional int[] array1 = new int[10];
// Declare and set values for a single-dimensional array int[] array2 = new int[] { 1, 2, 3 };
// OR int[] array2 = { 1, 2, 3 };
// Declare a 2D array int[,] twoDimensionalArray1 = new int[2,1];
// Declare and set 2D array int[,] twoDimensionalArray2 = { { 1 }, { 2 } };
ArrayIni-aliza-onandIndexing
Class Program
{ static void Main()
{ int[] array = new int[10];
for(int i=0; i < array.Length; i++)
array[i] = i*i; }
}
ArrayClassSta-cMethods
• void Clear(array, index, len) – setsarangetonull,orzero,orfalse,dependingontheelementtypeofthearray
• int BinarySearch(array, value, comparer) –returnseithertheindexofthesearchedvalue,oranega-venumberifthevalueisnotfound
• void ForEach(action) – performs the action on each element of the array
GenericCollec-ons
• Workwithbuilt‐inanddeveloper‐definedtypes(thus“Generic”–alltypesyoudefineinheritfromobject)
• Immediatebenefits:typesafety• AredefinedintheSystem.Collec-ons.Genericnamespace
• Providealargevariety,readyforyouruse:Lists,Dic-onaries,SortedLists,LinkedLists,SortedDic-onaries,Sets,Stacks,Queues,andmore…
List<T>
• Unlikeanarray,aListdynamicallysizesasneeded
• Ifyouneedsequen-alaccesstoelements,useaLinkedList<T>
• Listssupportaddinganelementorarangeofelementsattheendofthelist(AddandAddRange)
Dic-onary<Tkey,Tvalue>
• Usefulmethods:– ContainsKey,– ContainsValue,– Remove(removesthevalueassociatedwiththepassedkey)
– Clear– Add(willthrowanexcep-onifkeyalreadyexistsmustcheckifthedictcontainsthekeyyoutrytoadd)
– TryGetValue(getsthevalueassociatedwiththekeyyou’repassingtoit)
MoreAdvanced
• Forfuturedevelopmentinterests:
Thread‐safecollec-ons(ConcurrentDic-onary)
ReadilyusableinSystem.Threading.Tasks.Parallel
(generallythetaskparallellibrarymakesmul-threadedprogrammingprojectssimplertodevelopbytakingcareofsomelowerleveldetails)
ControlFlow
• If/else,switch,for,while,dowhile,arethesame
• FOREACHstatement–neatsincewehavedatastructuresthathaveanenumeratordefinedonthem(suchaslists,dicts,etc)foreach(varkeyvalueindic-onary){…}DEMOfordatastructuresbundledwithStringsdemo
TOC1. IntrotoC#2. HelloWorld3. Object‐Orientedconcepts4. Collec-ons5. ControlFlow6. FileI/O7. StringsandREGEX8. XMLandLINQQueries9. Excep-onHandling10. Debugging
StringsandREGEX
• Built‐intypescharandstring• EmptystringisString.Emptyor“”
• Unassignedstringisanull• Caneasilycreatestringsfromotherobjectsbycalling.ToString()
• String.Compare(string,string)
• String.Concat(string,string)• String.Split(tokenChar)
REGEX(1)• Regularexpressionsenableyoutoperformpa\ernmatching
• RequireusingSystem.Text.RegularExpression
• Steps:– Defineapa\ernyouwishtomatch(thisisoftypestring)
– Regexexpression=newRegex(pa\ern);– expression.IsMatch(stringYouWishToMatch);
OR– MatchCollec-onlist=expression.Matches(stringYouWishToMatch);
(thisisthesetofallmatchesbyapplyingtheregexrepeatedly)
REGEX(2)• Pa\erns:
?matchesprecedingelement0or1+matchesprecedingelement1ormore-mes*Matchesprecedingelement0ormore\dmatchesdecimaldigit(equivalentto[0‐9])\wmatchesanalphanumericchar(equivto[a‐zA‐Z_0‐9]{p}matchesprecedingelementexactlyp-mes{p,q}matchesprecedingelementatleastpbutlessthanq-mes.matchesanycharacterexcept\n[]matchesthecharacterwithinthebrackets[^]NOT(e.g,[^0‐9]matcheseverythingnot0thru9)\smatchesaspace
REGEX(3)• Groups:youcandesignategroupswithinyourpa\ernusing()
• Examplepa\erns:
[0‐9]*
\d{3}\w+
([a‐zA‐Z^0‐9]){3,5}(\d*(\w+))
(\d*(\w+)?)+
FILEI/O
• CoveredinStringsREGEXDEMO:– Pathbuilder– Readingfromastream– Wri-ngtoastream– Alsofeatured:star-ngachildprocessandclosingthatprocess
TOC1. IntrotoC#2. HelloWorld3. Object‐Orientedconcepts4. Collec-ons5. ControlFlow6. FileI/O7. StringsandREGEX8. XMLandLINQQueries9. Excep-onHandling10. Debugging
XMLandLINQ• Thissec-onwillshowyouhoweasyitistocreateanXMLparserwithjustafewlinesofcode
• LINQisthequeryingmechanism(canbeusedforalsofordatabases)
• Wewillneed:– usingSystem.Xml.Linq
– usingSystem.Xml– usingSystem.Collec-ons.Generic
XMLExamples• AnXMLelementcorrespondstotheXElementtype:
<courses> <course Title = “CS50” Location = /> <course Title = “CS121” Location =
“Maxwell Dworkin” /> … </courses>
• Herecourseisanelement,TitleandLoca-onarea\ributes.WecanstorethemusingtheXElementtype;moreoverwecannavigatea\ributesstoringthemusingtypeXA\ribute.
XMLExamples<students> <student> <name>Barney</name> <class>2013</class> <house>Currier</house> </student> … </students>
<!--Here we just have a simple key-value pair arrangement and no attributes(value of name=Barney for instance)-->
SepngXMLelementsXElement xmlDocument =
new XElement(“students”, new XElement(“student”, new XElement(“name”), new XElement(“class”), new XElement(“house”) ) );
• Nowwehavetosetthevaluesoftheelementswejustcreated: XElement student=xmlDocument.Element(“student”); student.SetElementValue(“name”, “Mike”); //you can see that an XElement stores a //key-value pair – great for storing in a dict
QueryingXML• YouneedtofirstsettherootelementoftheXML:Root=XElement.Load(“C:\Foo\bar.xml”);
• Toaccessallelementsundertherootnode:Root.Elements()
• Topickthevalueofthefirstelement:Root.Elements().First().FirstA\ribute.Value
QueryingXML
• LINQqueryisverysimilartotheSQLqueryyou’refamiliarwith:
FROMelementinRoot.Elements()
SELECTelement
WHERE(…)
No-cethattheFROMactslikeaforeach
VS2010andXMLsinProjects
• ItisnotsufficienttoaddtheXMLfiletoyourprojectsolu-on
• YoumustalsosetintheXMLfile’sProper-estabthe“CopytoOutputDirectory”to“CopyAlways”
• ThisdoesnotapplyifyourXMLisfromaURL(thenyoudon’tincludeacopyofit,youjustpasstheURLpathtotheLoadmethod).
TOC1. IntrotoC#2. HelloWorld3. Object‐Orientedconcepts4. Collec-ons5. ControlFlow6. FileI/O7. StringsandREGEX8. XMLandLINQQueries9. Excep-onHandling10. Debugging
Excep-ons(1)
• Excep-onsserveasameanstoreportfailures,classify,andhandlethem
• Excep-onsencapsulatealltheinforma-onaboutanerrorinasingleclass‐touseexcep-onsaddausingstatementforusingSystem.Excep-on;
• Allexcep-onsderivefromtheSystem.Excep-onclass
Excep-ons(2)
• TheSystem.Excep-onclassprovidesseveralusefulproper-esfordebugging:– Message– StackTrace– HelpLink(op-onalURL)– Data(thisisadic-onary)– InnerExcep-on(ifanexcep-oniswrappedintoadifferenttypeofexcep-on)
• Howto“throw”anexcep-on:thrownewSystem.Excep-on();
Excep-ons(3)
• Standardexcep-ontypes:– ArgumentExcep-on– ArgumentNullExcep-on– DivideByZeroExcep-on– NullReferenceExcep-on– InvalidOpera-onExcep-on– IndexOutOfRangeExcep-on– OutOfMemoryExcep-on– StackOverFlowExcep-on– SystemExcep-on
Excep-ons(4)–HandlingLogic• Try‐Catchblock:youexecutecodeintheTryblockwhichmaythrowanexcep-onofaspecifictypewhichyouthenhandleinthecatchblock:try { int foo = 3/0;
} catch(DivideByZeroException e) { Console.Writeline(“Why did you divide by
zero?”); }
Excep-ons(5)–HandlingLogic• Try‐Catchblock:youmayhavemul-plecatchblocksfordifferenttypesofexcep-onssuchthatdependingontheexcep-onyouexecuteadifferentblockofcode.
• Example:catch(SystemException e1) { …} catch(ArgumentException e2) {…} catch(InvalidOperationException e3) {…}
Excep-ons(6)–HandlingLogic
• Catchblockscanswallowerrors–ifyoujustloganerrormessageinyourcatchblockanddonothandletherootcauseoftheerror,thenyouwillfallintothebaddesignprac-cecalled“swallowinganexcep-on”.
• Ifyourapplica-onthrowsanexcep-onthatisunhandledbyacatchblockwillresultinanapplica-oncrash.
Excep-ons(7)–HandlingLogic
• Try‐Finally–thefinallyblockofcodeexecutesregardlessofwhetherornotanexcep-onwasthrowninthetryblock;thefinallyblockexecutesimmediatelya9erthetryblock
• Try‐Catch‐Finally‐mayhavemul-plecatchblocks,asbefore,butalwaysasinglefinallyblock.
• DEMO
MoreAdvanced
• IFyouenterasitua-oninwhichitisunsafetocon-nue(securityrisksforexample,memorycorrup-on,etc.),insteadofusinganexcep-onuseSystem.Environment.FailFast.
• FailFastimmediatelyterminatestheapplica-on
• Suchtermina-onsareshownintheeventlogfortheapplica-on(intheWindowseventlog)
1. IntrotoC#2. BasicSyntax3. HelloWorld4. Object‐Orientedconcepts5. Datastructures6. ControlFlow7. FileI/O8. REGEX9. Excep-onHandling10. Debugging[DEMO]
Morereferences
• h\p://msdn.microso9.com• Alwaysgoodtouse:F12allowsyoutotraveltothedefini-onofatypethatbelongstoareferencedlibrary