Introduction to Visual Studio and C
Transcription
Introduction to Visual Studio and C
UniversityCollegeofSoutheastNorway IntroductiontoVisual StudioandC# HANS-PETTERHALVORSEN,2016.09.26 http://home.hit.no/~hansha TableofContents 1. Introduction......................................................................................................................5 1.1. VisualStudio...............................................................................................................5 1.2. C#................................................................................................................................6 1.3. .NETFramework.........................................................................................................6 1.4. Object-OrientedProgramming(OOP)........................................................................7 2. VisualStudio......................................................................................................................8 2.1. Introduction................................................................................................................8 2.2. GettingStarted...........................................................................................................8 2.2.1. IntegratedDevelopmentEnvironment(IDE).......................................................8 2.2.2. NewProject.........................................................................................................9 2.2.3. SolutionExplorer...............................................................................................10 2.2.4. Toolbox..............................................................................................................11 2.2.5. EditorsandDesigners........................................................................................12 2.2.6. Propertieswindow............................................................................................12 2.2.7. BuildandDebugTools.......................................................................................13 3. WindowsProgramming...................................................................................................15 3.1. Introduction..............................................................................................................15 3.1.1. WindowsForms.................................................................................................15 3.1.2. WPF...................................................................................................................16 3.2. HelloWorld...............................................................................................................16 4. GettingStartedwithC#...................................................................................................19 2 3 TableofContents 4.1. Introduction..............................................................................................................19 4.2. DataTypesandVariables..........................................................................................19 4.2.1. Booleantype.....................................................................................................20 4.2.2. Numerictypes:Integrals,FloatingPoint,Decimal............................................20 4.2.3. Stringtype.........................................................................................................20 4.2.4. Arrays................................................................................................................21 4.3. ControlFlow.............................................................................................................21 4.3.1. TheifStatement................................................................................................21 4.3.2. TheswitchStatement........................................................................................22 4.4. Loops.........................................................................................................................23 4.4.1. ThewhileLoop..................................................................................................23 4.4.2. ThedoLoop.......................................................................................................23 4.4.3. TheforLoop......................................................................................................24 4.4.4. TheforeachLoop...............................................................................................24 4.5. Methods...................................................................................................................24 4.5.1. NonstaticMethods............................................................................................25 4.5.2. StaticMethods..................................................................................................25 4.6. Namespaces..............................................................................................................26 4.7. Classes......................................................................................................................26 4.7.1. Constructor........................................................................................................27 4.8. Properties.................................................................................................................29 4.9. NamingConvention..................................................................................................31 5. MoreObject-orientedTechniques..................................................................................33 5.1. Inheritance................................................................................................................33 5.2. Polymorphism...........................................................................................................34 5.3. Encapsulation...........................................................................................................35 Tutorial:IntroductiontoVisualStudioandC# 4 TableofContents 6. ExceptionHandling..........................................................................................................36 7. WindowsFormsExample................................................................................................38 8. WebProgramming..........................................................................................................44 8.1. Introduction..............................................................................................................44 8.2. HTML.........................................................................................................................44 8.3. WebBrowser............................................................................................................44 8.4. CSS............................................................................................................................45 8.5. JavaScript..................................................................................................................45 8.6. ASP.NET....................................................................................................................45 8.7. AJAX/ASP.NETAJAX.................................................................................................46 8.8. Silverlight..................................................................................................................46 9. DatabaseProgramming...................................................................................................47 9.1. ADO.NET...................................................................................................................47 Tutorial:IntroductiontoVisualStudioandC# 1. Introduction InthisTutorialwewilluseVisualStudioandC#.C#istheprogramminglanguage,while VisualStudioisthedevelopmentenvironment. Usefullinks: VisualStudio:http://msdn.microsoft.com/en-us/library/dd831853.aspx C#:http://msdn.microsoft.com/en-us/library/kx37x362.aspx 1.1. VisualStudio MicrosoftVisualStudioisanintegrateddevelopmentenvironment(IDE)fromMicrosoft.It canbeusedtodevelopconsoleandgraphicaluserinterfaceapplicationsalongwith WindowsFormsapplications,websites,webapplications,andwebservicesinbothnative codetogetherwithmanagedcodeforallplatformssupportedbyMicrosoftWindows, WindowsPhone,WindowsCE,.NETFramework,.NETCompactFrameworkandMicrosoft Silverlight. Belowweseetheintegrateddevelopmentenvironment(IDE)inVisualStudio: 5 6 Introduction Newprojectsarecreatedfromthe“NewProject”window: 1.2. C# C#ispronounced“seesharp”.C#isanobject-orientedprogramminglanguageandpartof the.NETfamilyfromMicrosoft.C#isverysimilartoC++andJava.C#isdevelopedby MicrosoftandworksonlyontheWindowsplatform. 1.3. .NETFramework The.NETFramework(pronounced“dotnet”)isasoftwareframeworkthatrunsprimarilyon MicrosoftWindows.Itincludesalargelibraryandsupportsseveralprogramminglanguages whichallowlanguageinteroperability(eachlanguagecanusecodewritteninother languages).The.NETlibraryisavailabletoalltheprogramminglanguagesthat.NET supports.Programswrittenforthe.NETFrameworkexecuteinasoftwareenvironment, knownastheCommonLanguageRuntime(CLR),anapplicationvirtualmachinethat providesimportantservicessuchassecurity,memorymanagement,andexceptionhandling. TheclasslibraryandtheCLRtogetherconstitutethe.NETFramework. Tutorial:IntroductiontoVisualStudioandC# 7 1.4. Introduction Object-OrientedProgramming(OOP) Object-orientedprogramming(OOP)isaprogramminglanguagemodelorganizedaround "objects"ratherthan"actions"anddataratherthanlogic.Historically,aprogramhasbeen viewedasalogicalprocedurethattakesinputdata,processesit,andproducesoutputdata. ThefirststepinOOPistoidentifyalltheobjectsyouwanttomanipulateandhowthey relatetoeachother,anexerciseoftenknownasdatamodeling.Onceyou'veidentifiedan object,yougeneralizeitasaclassofobjectsanddefinethekindofdataitcontainsandany logicsequencesthatcanmanipulateit.Eachdistinctlogicsequenceisknownasamethod.A realinstanceofaclassiscalledan“object”oran“instanceofaclass”.Theobjectorclass instanceiswhatyouruninthecomputer.Itsmethodsprovidecomputerinstructionsand theclassobjectcharacteristicsproviderelevantdata.Youcommunicatewithobjects-and theycommunicatewitheachother. ImportantfeatureswithOOPare: • • • • ClassesandObjects Inheritance Polymorphism Encapsulation Simulawasthefirstobject-orientedprogramminglanguage.Simulawasdevelopedinthe 1960sbyKristenNygaardfromNorway. Java,Python,C++,VisualBasic.NETandC#arepopularOOPlanguagestoday. SinceSimula-typeobjectsarereimplementedinC++,JavaandC#theinfluenceofSimulais oftenunderstated.ThecreatorofC++(1979),BjarneStroustrup(fromDenmark),has acknowledgedthatSimulawasthegreatestinfluenceonhimtodevelopC++. Tutorial:IntroductiontoVisualStudioandC# 2. VisualStudio 2.1. Introduction HomepageofVisualStudio:http://www.microsoft.com/visualstudio ThereexistdifferentversionsofVisualStudio,suchasVisualStudioExpress(free),Visual StudioProfessional,VisualStudioPremiumandVisualStudioUltimate. 2.2. GettingStarted 2.2.1. IntegratedDevelopmentEnvironment(IDE) TheVisualStudioproductfamilysharesasingleintegrateddevelopmentenvironment(IDE) thatiscomposedofseveralelements:theMenubar,Standardtoolbar,varioustoolwindows dockedorauto-hiddenontheleft,bottom,andrightsides,aswellastheeditorspace.The toolwindows,menus,andtoolbarsavailabledependonthetypeofprojectorfileyouare workingin. BelowweseetheVisualStudioIDE(IntegratedDevelopmentEnvironment): 8 9 2.2.2. VisualStudio NewProject Thefirstthingyoudowhenyouwanttocreateanewapplicationistocreateanewproject. ThiscanbedonefromtheStartPage: OrfromtheFilemenu: Thenthe“NewProject”windowappears: Tutorial:IntroductiontoVisualStudioandC# 10 VisualStudio Inthiswindowyouwillselectanappropriatetemplatebasedonwhatkindofapplicationyou wanttocreate,andanameandlocationforyourprojectandsolution. Themostcommonapplicationsare: • • • • • WindowsFormApplication ConsoleApplication WPFApplication ASP.NETWebApplication SilverlightApplication 2.2.3. SolutionExplorer Solutionsandprojectscontainitemsthatrepresentthereferences,dataconnections, folders,andfilesthatyouneedtocreateyourapplication.Asolutioncontainercancontain multipleprojectsandaprojectcontainertypicallycontainsmultipleitems. Tutorial:IntroductiontoVisualStudioandC# 11 VisualStudio 2.2.4. Toolbox TheToolboxcontainsallthenecessarycontrols,etc.youneedtocreateyouruserinterface. SeeFigurebelow. TheToolboxcontainsallthecontrols,etc.wecanuse inouruserinterface. Inordertousetheminouruserinterface,wejustdrag anddropthemtothe“Form”,asshownbelow: Tutorial:IntroductiontoVisualStudioandC# 12 2.2.5. VisualStudio EditorsandDesigners VisualStudiohasdifferenteditorsanddesigntools. GraphicalUserInterfaceDesigner: CodeEditor: 2.2.6. Propertieswindow EachcontrolwehaveonouruserinterfacehaslotsofPropertieswecanset. Tutorial:IntroductiontoVisualStudioandC# 13 VisualStudio ThisisdoneinthePropertieswindow: 2.2.7. BuildandDebugTools InVisualStudiowehavelotsofBuildandDebuggingTools. Buildmenu: BelowweseetheBuildmenu: Themostusedtoolis“BuildSolution”(ShortcutKey:F6). Debugmenu: BelowweseetheDebugmenu: Tutorial:IntroductiontoVisualStudioandC# 14 VisualStudio Themostusedtoolis“StartDebugging”(ShortcutKey:F5). Tutorial:IntroductiontoVisualStudioandC# 3. WindowsProgramming 3.1. Introduction WhencreatingordinaryWindowsapplications,wecanselectbetweenthefollowing: • • WindowsFormsApplication WPFApplications(WindowsPresentationFoundation) WindowsFormsisthestandardwayofcreatingWindowsapplicationsandhasexistedin manyyears,evenbefore.NET1.0(2002)wasintroduced.WPFisanewapproachfrom creatingWindowsapplicationsandwasintroducedwith.NETFramework3.0(2006). ForexamplehastheVisualStudioIDEbeenentirelyrewrittenusingWPF. WindowsFormsApplicationandWPFApplicationswillbeexplainedinmoredetailbelow. 3.1.1. WindowsForms WindowsFormsisthestandardwayofcreatingWindowsapplications. Select“WindowsFormsApplication”inthe“NewProject”window: 15 16 3.1.2. WindowsProgramming WPF DevelopedbyMicrosoft,theWindowsPresentationFoundation(orWPF)isacomputersoftwaregraphicalsubsystemforrenderinguserinterfacesinWindows-basedapplications. WPFisintendedtotakeoverforthetraditionalWindowsForms. ThegraphicaluserinterfaceinWPFisdesignedusingXAML(ExtensibleApplicationMarkup Language). XAML: Followingthesuccessofmarkuplanguagesforwebdevelopment,WPFintroducesanew languageknownaseXtensibleApplicationMarkupLanguage(XAML),whichisbasedonXML. XAMLisdesignedasamoreefficientmethodofdevelopingapplicationuserinterfaces Select“WPFApplication”inthe“NewProject”window: 3.2. HelloWorld Westartbycreatingatraditional“HelloWorld”applicationusingWindowsForms.The applicationisshownbelow: Tutorial:IntroductiontoVisualStudioandC# 17 WindowsProgramming TheVisualStudioIDElookslikethis: InthisprojectweuseasimpleTextBox(textBox1)andwhenwestarttheprogramthetext “HelloWorld”iswrittentotheTextBox. Thecodeisasfollows: using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Tutorial:IntroductiontoVisualStudioandC# 18 WindowsProgramming private void Form1_Load(object sender, EventArgs e) { textBox1.Text = "Hello World"; } } } Tutorial:IntroductiontoVisualStudioandC# 4. GettingStartedwithC# C#isamodernObject-orientedprogramminglanguage. Object-orientedprogramming(OOP)isaprogrammingparadigmusing"objects"–data structuresconsistingofdatafieldsandmethodstogetherwiththeirinteractions–todesign applicationsandcomputerprograms.Programmingtechniquesmayincludefeaturessuchas dataabstraction,encapsulation,messaging,modularity,polymorphism,andinheritance. 4.1. Introduction Inthischapterwewillstartwiththebasicallprogramminglanguageshave:… • • • DataTypesandVariables ControlFlow:If-Else,etc. Loops:WhileLoops,ForLoops,etc. Furtherwewillintroducethefollowing: • • • • • Namespaces Classes DataFields Methods Properties InthenextchapterwewillgomoreindepthofwhatObject-orientedprogrammingisand introducethefollowingimportantOOPtopics: • • • Inheritance Polymorphism Encapsulation Note!C#iscase-sensitive. 4.2. DataTypesandVariables 19 20 GettingStartedwithC# “Variables”aresimplystoragelocationsfordata.Youcanplacedataintothemandretrieve theircontentsaspartofaC#expression.Theinterpretationofthedatainavariableis controlledthrough“Types”. TheC#simpletypesconsistof: • • • Booleantype Numerictypes:Integrals,FloatingPoint,Decimal Stringtype 4.2.1. Booleantype Booleantypesaredeclaredusingthekeyword“bool”.Theyhavetwovalues:“true”or “false”.Inotherlanguages,suchasCandC++,booleanconditionscanbesatisfiedwhere0 meansfalseandanythingelsemeanstrue.However,inC#theonlyvaluesthatsatisfya booleanconditionistrueandfalse,whichareofficialkeywords. Example: bool content = true; bool noContent = false; 4.2.2. Numerictypes:Integrals,FloatingPoint, Decimal Example: int i=35; long y=654654; float x; double y; decimal z; 4.2.3. Stringtype Example: string myString=”Hei på deg”; Specialcharactersthatmaybeusedinstrings: Tutorial:IntroductiontoVisualStudioandC# 21 GettingStartedwithC# 4.2.4. Arrays Example: int[] myInts = { 5, 10, 15 }; 4.3. ControlFlow Tobeabletocontroltheflowinyourprogramisimportantineveryprogramminglanguage. Thetwomostimportanttechniquesare: • • TheifStatement TheswitchStatement 4.3.1. TheifStatement Theifstatementisprobablythemostusedmechanismtocontroltheflowinyour application. Anifstatementallowsyoutotakedifferentpathsoflogic,dependingonagivencondition. Whentheconditionevaluatestoabooleantrue,ablockofcodeforthattrueconditionwill execute.Youhavetheoptionofasingleifstatement,multipleelseifstatements,andan optionalelsestatement. Example: bool myTest; Tutorial:IntroductiontoVisualStudioandC# 22 GettingStartedwithC# myTest=false; if (myTest==false) MessageBox.Show("Hello"); Ifwehavemorethanonelineofcodethatthatshallbeexecuted,weneedtousebraces, e.g.: bool myTest; myTest=false; if (myTest == false) { MessageBox.Show("Hello1"); MessageBox.Show("Hello2"); } Formorecomplexlogicweusetheif…elsestatement. Example: bool myTest; myTest=true; if (myTest == false) { MessageBox.Show("Hello1"); } else { MessageBox.Show("Hello2"); } Oryoucanusenestedif…elseifsentences. Example: int myTest; myTest=2; if (myTest == 1) { MessageBox.Show("Hello1"); } else if (myTest == 2) { MessageBox.Show("Hello2"); } else { MessageBox.Show("Hello3"); } 4.3.2. TheswitchStatement Anotherformofselectionstatementistheswitchstatement,whichexecutesasetoflogic dependingonthevalueofagivenparameter.Thetypesofthevaluesaswitchstatement operatesoncanbebooleans,enums,integraltypes,andstrings. Tutorial:IntroductiontoVisualStudioandC# 23 GettingStartedwithC# Example: switch (myTest) { case 1: MessageBox.Show("Hello1"); break; case 2: MessageBox.Show("Hello2"); break; default: MessageBox.Show("Hello3"); break; } 4.4. Loops InC#wehavedifferentkindofloops: • • • • Thewhileloop Thedoloop Theforloop Theforeachloop 4.4.1. ThewhileLoop Awhileloopwillcheckaconditionandthencontinuestoexecuteablockofcodeaslongas theconditionevaluatestoabooleanvalueoftrue. Example: int myInt = 0; while (myInt < 10) { MessageBox.Show("Inside Loop: " + myInt.ToString()); myInt++; } MessageBox.Show("Outside Loop: " + myInt.ToString()); 4.4.2. ThedoLoop Adoloopissimilartothewhileloop,exceptthatitchecksitsconditionattheendofthe loop.Thismeansthatthedoloopisguaranteedtoexecuteatleastonetime.Ontheother hand,awhileloopevaluatesitsbooleanexpressionatthebeginningandthereisgenerally noguaranteethatthestatementsinsidetheloopwillbeexecuted,unlessyouprogramthe codetoexplicitlydoso. Example: Tutorial:IntroductiontoVisualStudioandC# 24 GettingStartedwithC# int myInt = 0; do { MessageBox.Show("Inside Loop: " + myInt.ToString()); myInt++; } while (myInt < 10); MessageBox.Show("Outside Loop: " + myInt.ToString()); 4.4.3. TheforLoop Aforloopworkslikeawhileloop,exceptthatthesyntaxoftheforloopincludes initializationandconditionmodification.forloopsareappropriatewhenyouknowexactly howmanytimesyouwanttoperformthestatementswithintheloop. Example: for (int i = 0; i < 10; i++) { MessageBox.Show("Inside Loop: " + myInt.ToString()); myInt++; } MessageBox.Show("Outside Loop: " + myInt.ToString()); 4.4.4. TheforeachLoop Aforeachloopisusedtoiteratethroughtheitemsinalist.Itoperatesonarraysor collections. Example: string[] names = { "Elvis", "Beatles", "Eagles", "Rolling Stones" }; foreach (string person in names) { MessageBox.Show(person); } 4.5. Methods Methodsareextremelyusefulbecausetheyallowyoutoseparateyourlogicintodifferent units.Youcanpassinformationtomethods,haveitperformoneormorestatements,and retrieveareturnvalue.Thecapabilitytopassparametersandreturnvaluesisoptionaland dependsonwhatyouwantthemethodtodo. Methodsaresimilartofunctions,procedureorsubroutineusedinotherprogramming languages.Thedifferenceisthatamethodisalwaysapartofaclass. Example: public void ShowCarColor(string color) Tutorial:IntroductiontoVisualStudioandC# 25 GettingStartedwithC# { MessageBox.Show("My Car is: " + color); } WelearnmoreaboutmethodsintheClassessectionbelow. Wehave2kindsofMethods: • • StaticMethods NonstaticMethods(InstanceMethod) StaticMethodsbelongstothewholeclass,whilenonstaticMethodsbelongtoeachinstance createdfromtheclass. 4.5.1. NonstaticMethods Example: Wedefinetheclass: class Car { //Nonstatic/Instance Method public void SetColor(string color) { MessageBox.Show("My Car is: " + color); } } Thenweuseit: Car myCar = new Car(); //We create an Instance of the Class myCar.SetColor("blue"); //We call the Method 4.5.2. StaticMethods Example: Wedefinetheclass: class Boat { //Static Method public static void SetColor(string color) { MessageBox.Show("My Boat is: " + color); } } Tutorial:IntroductiontoVisualStudioandC# 26 GettingStartedwithC# Thenweuseit: Boat.SetColor("green"); i.e.,wedon’tneedtocreateanobject/instantiatingtheclassbeforeweusetheStatic Method. 4.6. Namespaces NamespacesareC#programelementsdesignedtohelpyouorganizeyourprograms.They alsoprovideassistanceinavoidingnameclashesbetweentwosetsofcode.Implementing Namespacesinyourowncodeisagoodhabitbecauseitislikelytosaveyoufromproblems laterwhenyouwanttoreusesomeofyourcode. YouspecifytheNamespacesyouwanttouseinthetopofyourcode. Example: WhenyoucreateanewWindowsFormsapplication,thefollowingdefaultnamespaceswill beincluded. using using using using using using using using … System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; Itisjusttoaddmorewhenyouneedit. MoreaboutNamespaceslater. 4.7. Classes ThefirststepinOOPistoidentifyalltheobjectsyouwanttomanipulateandhowthey relatetoeachother,anexerciseoftenknownasdatamodeling.Onceyou'veidentifiedan object,yougeneralizeitasaclassofobjectsanddefinethekindofdataitcontainsandany logicsequencesthatcanmanipulateit.Eachdistinctlogicsequenceisknownasamethod.A realinstanceofaclassiscalledan“object”oran“instanceofaclass”.Theobjectorclass instanceiswhatyouruninthecomputer.Itsmethodsprovidecomputerinstructionsand theclassobjectcharacteristicsproviderelevantdata.Youcommunicatewithobjects-and theycommunicatewitheachother. Tutorial:IntroductiontoVisualStudioandC# 27 GettingStartedwithC# EverythinginC#isbasedonClasses.Classesaredeclaredbyusingthekeywordclass followedbytheclassnameandasetofclassmemberssurroundedbycurlybraces. AclassnormallyconsistsofMethods,FieldsandProperties. Everyclasshasaconstructor,whichiscalledautomaticallyanytimeaninstanceofaclassis created.Thepurposeofconstructorsistoinitializeclassmemberswhenaninstanceofthe classiscreated.Constructorsdonothavereturnvaluesandalwayshavethesamenameas theclass. Example: Wedefinethefollowingclass: class Car { public string color; //Field //Method public void ShowCarColor() { MessageBox.Show("My Car is: " + color); } } Thenwecanuseit: Car myCar = new Car(); //We create an Instance of the Class myCar.color = "blue"; //We set a value for the color Field myCar.ShowCarColor(); //We call the Method Theresultisasfollows: 4.7.1. Constructor Thepurposeofconstructorsistoinitializeclassmemberswhenaninstanceoftheclassis created. Example: WecanuseaConstructortocreatea“default”colorforourcar. Wedefinetheclass: Tutorial:IntroductiontoVisualStudioandC# 28 GettingStartedwithC# class Car { public string color; //Field //Constructor - Used to initialize the Class public Car() { color="green"; } //Method public void ShowCarColor() { MessageBox.Show("My Car is: " + color); } } Thenwecanuseit: Car myCar = new Car(); //We create an Instance of the Class myCar.ShowCarColor(); //We call the Method myCar.color = "blue"; //We set a value for the color Field myCar.ShowCarColor(); //We call the Method Theresultsareasfollows: … Example: Wecanalsodothefollowing: class Car { public string color; //Field //Constructor - Used to initialize the Class public Car(string initColor) { color = initColor; Tutorial:IntroductiontoVisualStudioandC# 29 GettingStartedwithC# } //Method public void ShowCarColor() { MessageBox.Show("My Car is: " + color); } } Thenweuseit: Car myCar = new Car("green"); //We create an Instance of the Class myCar.ShowCarColor(); //We call the Method Newfeature:InitializationanobjectwithoutaConstructor: InC#4.0wecandothefollowing: WedefinetheClass(withoutanycontructor): class Car { public string color; //Field public string model; //Field //Method public void ShowCarColor() { MessageBox.Show("My Car Color is: " + color); MessageBox.Show("My Car Model is: " + model); } } Thenwedothefollowing: Car myCar = new Car {color="white", model="2004"}; myCar.ShowCarColor(); //We call the Method 4.8. Properties Propertiesprovidetheopportunitytoprotectafieldinaclassbyreadingandwritingtoit throughtheproperty.Inotherlanguages,thisisoftenaccomplishedbyprograms implementingspecializedgetterandsettermethods.C#propertiesenablethistypeof protectionwhilealsolettingyouaccessthepropertyjustlikeitwasafield. Example: WedefineaClasswithPropertiesandaMethod: class Car { Tutorial:IntroductiontoVisualStudioandC# 30 GettingStartedwithC# public string Name {get; set;} public string Color {get; set;} public void ShowCarProperties() { MessageBox.Show("My Car Name is: " + Name); MessageBox.Show("My Car Color is: " + Color); } } Thenwecanuseit: Car myCar = new Car(); myCar.Name="Volvo"; myCar.Color="Blue"; myCar.ShowCarProperties(); Theresultsare: … Sofar,theonlyclassmembersyou'veseenareFields,Properties,Methods,and Constructors.Hereisacompletelistofthetypesofmembersyoucanhaveinyourclasses: • • • • • • • • • Constructors Destructors(oppositeofConstructors) Fields Methods Properties Indexers Delegates Events NestedClasses Tutorial:IntroductiontoVisualStudioandC# 31 4.9. GettingStartedwithC# NamingConvention Thereisdifferentnameconventionforhowtospecifyyourvariables,classesandMethods, etc. Camelnotation: Forvariablesandparameters/argumentswenormallyuse“Camelnotation”. Examples: string myCar; int number; string backColor; →InCamelcasingthefirstletterofanidentifierislowercaseandthefirstletterofeach subsequentconcatenatedwordiscapitalized. Pascalnotation: Forclasses,methodsandproperties,wenormallyuse“Pascalnotation”. Examples: class Car { void ShowCarColor() { … } } →InPascalcasingthefirstletterintheidentifierandthefirstletterofeachsubsequent concatenatedwordarecapitalized. ForNamespacesweusePascalcasingandadotseparator. Examples: System.Drawing System.Collections.Generics Controls: Forcontrolsonyouruserinterfaceweeitheruse“Pascalnotation”or“Hungariannotation”, butsticktooneofthem! Examples: “Pascalnotation”: LoginName LoginPassword Tutorial:IntroductiontoVisualStudioandC# 32 GettingStartedwithC# “Hungariannotation”: txtName txtPassword lblName btnCancel Where“txt”meansitisaTextControl,“lbl”aLabelControl,“btn”aButtonControl,etc. Acronyms: Casingofacronymsdependsonthelengthoftheacronym.Allacronymsareatleasttwo characterslong.Ifanacronymisexactlytwocharacters,itisconsideredashortacronym.An acronymofthreeormorecharactersisalongacronym. Ingeneral,youshouldnotuseabbreviationsoracronyms.Thesemakeyournamesless readable.Similarly,itisdifficulttoknowwhenitissafetoassumethatanacronymiswidely recognized. Butifyoumust,therulesareasfollows: ShortacronymExamples(twocharacters): DBRate ApropertynamedDBRateisanexampleofashortacronym(DB)usedasthefirstwordofa Pascal-casedidentifier. ioChannel AparameternamedioChannelisanexampleofashortacronym(IO)usedasthefirstword ofacamel-casedidentifier. LongacronymExamples(threeormorecharacters): XmlWriter AclassnamedXmlWriterisanexampleofalongacronymusedasthefirstwordofaPascalcasedidentifier. htmlReader AparameternamedhtmlReaderisanexampleofalongacronymusedasthefirstwordofa camel-casedidentifier. Tutorial:IntroductiontoVisualStudioandC# 5. MoreObject-oriented Techniques InthischapterwewillintroducethefollowingObject-orientedtechniques: • • • Inheritance Polymorphism Encapsulation 5.1. Inheritance Inheritanceisoneoftheprimaryconceptsofobject-orientedprogramming.Itallowsyouto reuseexistingcode.Througheffectiveemploymentofreuse,youcansavetimeinyour programming. Example: WedefinetheBaseclass: class Car { public void SetColor(string color) { MessageBox.Show("My Car is: " + color); } } ThenwedefineanewclassthatinheritsfromtheBaseClass: class Volvo : Car { //In this simple Example this class does nothing! } Thenwestartusingtheclasses: Car myCar = new Car(); myCar.SetColor("blue"); Volvo myVolvo = new Volvo(); 33 34 MoreObject-orientedTechniques myVolvo.SetColor("green"); Asyoucanseewecanusethe“SetColor()”MethodthathasbeendefinedintheBaseClass. 5.2. Polymorphism Anotherprimaryconceptofobject-orientedprogrammingisPolymorphism.Itallowsyouto invokederivedclassmethodsthroughabaseclassreferenceduringrun-time. Example: WestartwithaBaseClass: class Car { public virtual void CarType() { MessageBox.Show("I am a Car"); } } Thevirtualmodifierindicatestoderivedclassesthattheycanoverridethismethod. Thenwecreate3newClassesthatderivefromtheBaseClass: class Volvo : Car { public override void CarType() { MessageBox.Show("I am a Volvo"); } } class Ford : Car { public override void CarType() { MessageBox.Show("I am a Ford"); } } class Toyota : Car { public override void CarType() { MessageBox.Show("I am a Toyota"); } } These3classesinherittheCarclass.EachclasshasaCarType()methodandeachCarType() methodhasanoverridemodifier.Theoverridemodifierallowsamethodtooverridethe virtualmethodofitsbaseclassatrun-time. Thenwecanuseit: Car[] car = new Car[4]; car[0] = new Car(); Tutorial:IntroductiontoVisualStudioandC# 35 MoreObject-orientedTechniques car[1] = new Volvo(); car[2] = new Ford(); car[3] = new Toyota(); foreach (Car carmodel in car) { carmodel.CarType(); } Theresultis: … … … →ThisisPolymorphism. 5.3. Encapsulation Encapsulationmeansthattheinternalrepresentationofanobjectisgenerallyhiddenfrom viewoutsideoftheobject'sdefinition.Typically,onlytheobject'sownmethodscandirectly inspectormanipulateitsfields. WecansetdifferentAccessrightsonClassesandMethods: Tutorial:IntroductiontoVisualStudioandC# 6. ExceptionHandling Inprogrammingerrorandexceptionhandlingisveryimportant.C#hasbuilt-inandreadyto usemechanismtohandlethis.Thismechanismisbasedonthekeywordstry,catch,throw andfinally. Exceptionsareunforeseenerrorsthathappeninyourprograms.Mostofthetime,youcan, andshould,detectandhandleprogramerrorsinyourcode.Forexample,validatinguser input,checkingfornullobjects,andverifyingthevaluesreturnedfrommethodsarewhat youexpect,areallexamplesofgoodstandarderrorhandlingthatyoushouldbedoingallthe time. However,therearetimeswhenyoudon'tknowifanerrorwilloccur.Forexample,youcan't predictwhenyou'llreceiveafileI/Oerror,runoutofsystemmemory,orencountera databaseerror.Thesethingsaregenerallyunlikely,buttheycouldstillhappenandyouwant tobeabletodealwiththemwhentheydooccur.Thisiswhereexceptionhandlingcomesin. Whenexceptionsoccur,theyaresaidtobe“thrown”.C#usesthekeywordstry,catch,throw andfinally.Itworkslikethis:Amethodwilltrytoexecuteapieceofcode.Ifthecodedetects aproblem,itwillthrowanerrorindication,whichyourcodecancatch,andnomatterwhat happens,itfinallyexecutesaspecialcodeblockattheend. Thesyntaxisasfollows: MyMethod() { try { ... //Do Something that can cause an Exception } catch { ... //Handle Exceptions } finally { ... //Clean Up } } Example: public void WriteDaqData(double analogDataOut) { Task analogOutTask = new Task(); 36 37 AOChannel myAOChannel; try { myAOChannel = analogOutTask.AOChannels.CreateVoltageChannel( aoChannel, "myAOChannel", 0, 5, AOVoltageUnits.Volts ); AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter(analogOutTask.Stream); writer.WriteSingleSample(true, analogDataOut); } catch (Exception e) { string errorMessage; errorMessage = e.Message.ToString(); } finally { analogOutTask.Stop(); } } Tutorial:IntroductiontoVisualStudioandC# ExceptionHandling 7. WindowsForms Example Inthischapterwewillgothroughalargeexample.Inthisexamplewewillcreatean applicationinVisualStudiothatcontrolsthefollowingwatertankprocess: Thepurposeistocontrolthelevelinthewatertank.Inordertocommunicatewiththe physicalprocess,weuseaNIUSB-6008DAQdevice: Wewillnotshowallthedetailsinthecode,butfocusonthestructure. BelowweseetheuserinterfacewehavecreatedinVisualStudio: 38 39 WindowsFormsExample BelowweseetheVisualStudioproject: Westartwithdefiningtheclassesweneedinourapplication. IntheSolutionExplorerwehavedefineda“Classes”folderwhereweputalltheclasseswe create: Tutorial:IntroductiontoVisualStudioandC# 40 WindowsFormsExample Inordertocreatenewclassesweright-clickintheSolutionExplorerandselect“Add-New Item…”: NextweselecttheClassiteminthe“AddNewItem”window: Tutorial:IntroductiontoVisualStudioandC# 41 WindowsFormsExample Classes: Westartwiththe“Daq”ClassthatcontainslogicforreadingandwritingtotheDAQdevice: //Include necessary Namespaces using System; using System.Collections.Generic; using System.Linq; using System.Text; using NationalInstruments; using NationalInstruments.DAQmx; namespace Tuc.Control //We define a useful namespace { public class DaqData { public string aiChannel; public string aoChannel; //Constructor public DaqData(...) { ... } //Method public double ReadDaqData() { ... } //Method public void WriteDaqData(...) { ... } } } Tutorial:IntroductiontoVisualStudioandC# 42 WindowsFormsExample Itisgoodpracticetocreateanewfileforeachnewclasswedefine.Thenwestartby definingameaningfulNamespace.NextwedefineourClasswithnecessaryFields, PropertiesandMethods. WealsoneedtoincludethenecessaryNamespaceourClasswillneed.Inthisexamplewe haveincludedsome3.partyAssembliesfromNationalInstruments: using NationalInstruments; using NationalInstruments.DAQmx; TheseAssembliescontainsthedrivertotheNIUSB-6008DAQdeviceweareusing. TheAssembliesweusemustbeaddedinthe“References”folderintheSolutionExplorer: MainApplication: InourmainapplicationwestartwithincludingourNamespace: using using using using using using using using using using using using NationalInstruments; NationalInstruments.UI; NationalInstruments.UI.WindowsForms; System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; Tuc.Control; namespace Control_Application { public partial class Form1 : Form { ... } } Tutorial:IntroductiontoVisualStudioandC# 43 WindowsFormsExample Itisalsoagoodideatocreatedifferentregionsinordertostructureyourcodebetter.This canbedonelikethis: //Comment # region ... //Your Code # endregion InthiswayourMainApplicationmaylooklikethis: Tutorial:IntroductiontoVisualStudioandC# 8. WebProgramming 8.1. Introduction TodaymostoftheapplicationsfocusontheInternet,wheretheapplicationscanbeviewed inastandardWebBrowser.StaticWebpagesarebasedonHTMLandCSS.Inordertocreate moreadvancedapplications,weneedmorepowerfultools. Importantframeworksandtoolsforcreatingdynamicwebpages: • • • • ASP.NET AJAX/ASP.NETAJAX JavaScript Silverlight Theseframeworksandtoolswillbeexplainedbelow. SeetheTutorial“ASP.NETandWebProgramming”formoredetails. 8.2. HTML HTML,whichstandsforHyperTextMarkupLanguage,isthepredominantmarkuplanguage forwebpages.HTMListhebasicbuilding-blocksofwebpages. HTMLiswrittenintheformofHTMLelementsconsistingoftags,enclosedinanglebrackets (like<html>),withinthewebpagecontent.HTMLtagsnormallycomeinpairslike<h1>and </h1>.Thefirsttaginapairisthestarttag,thesecondtagistheendtag(theyarealso calledopeningtagsandclosingtags).Inbetweenthesetagswebdesignerscanaddtext, tables,images,etc. 8.3. WebBrowser ThepurposeofawebbrowseristoreadHTMLdocumentsandcomposethemintovisualor audiblewebpages.ThebrowserdoesnotdisplaytheHTMLtags,butusesthetagsto interpretthecontentofthepage. 44 45 WebProgramming TodaywehavethefollowingmajorWebBrowsers: • • • • • InternetExplorer(byMicrosoft) Firefox(byMozilla) Chrome(byGoogle) Safari(byApple) Opera(byOperafromNorway) 8.4. CSS WebbrowserscanalsorefertoCascadingStyleSheets(CSS)todefinetheappearanceand layoutoftextandothermaterial. TheW3C,maintainerofboththeHTMLandtheCSSstandards 8.5. JavaScript JavaScriptisanobject-orientedscriptinglanguagebasicallyusedtocreatedynamicweb pages.JavaScriptisprimarilyusedintheformofclient-sideJavaScript,implementedaspart ofawebbrowserinordertoprovideenhanceduserinterfacesanddynamicwebsites. 8.6. ASP.NET ASP.NETisawebapplicationframeworkdevelopedbyMicrosofttoallowprogrammersto builddynamicwebsites,webapplicationsandwebservices. ASP.NETispartoftheVisualStudiopackage ItwasfirstreleasedinJanuary2002withversion1.0ofthe.NETFramework,andisthe successortoMicrosoft'sActiveServerPages(ASP)technology.ASP.NETisbuiltonthe CommonLanguageRuntime(CLR),allowingprogrammerstowriteASP.NETcodeusingany supported.NETlanguage,suchasC#andVB.NET. ASP.NETwebpagesorwebpage,knownofficiallyasWebForms],arethemainbuildingblock forapplicationdevelopment.Webformsarecontainedinfileswithan“.aspx”extension. Select“ASP.NETApplication”inthe“NewProject”window: Tutorial:IntroductiontoVisualStudioandC# 46 WebProgramming 8.7. AJAX/ASP.NETAJAX AJAXisanacronymforAsynchronousJavaScriptandXML.AJAXisagroupofinterrelated webdevelopmentmethodsusedontheclient-sidetocreateinteractivewebapplications. WithAjax,webapplicationscansenddatato,andretrievedatafrom,aserver asynchronously(inthebackground)withoutinterferingwiththedisplayandbehaviorofthe existingpage. ASP.NETAJAXisasetofextensionstoASP.NETdevelopedbyMicrosoftforimplementing AJAXfunctionality. 8.8. Silverlight MicrosoftSilverlightisanapplicationframeworkforwritingandrunningbrowserplug-insor otherrichinternetapplications,withfeaturesandpurposessimilartothoseofAdobeFlash. Therun-timeenvironmentforSilverlightisavailableasaplug-informostwebbrowsers. SilverlightisalsooneofthetwoapplicationdevelopmentplatformsforWindowsPhone7/8. ThelatestversionisSilverlight5.0. SilverlightisbasedonWPF,soinSilverlightapplications,userinterfacesaredeclaredin ExtensibleApplicationMarkupLanguage(XAML)andprogrammedusingasubsetofthe.NET Framework. Tutorial:IntroductiontoVisualStudioandC# 9. DatabaseProgramming Mostoftoday’sapplicationsuseabackenddatabasetostoreimportantdata,e.g.,Facebook, Twitter,etc. InordertousedatabasesinourapplicationsweneedtoknowStructuredQuerylanguage (SQL).FormoreinformationaboutSQL,seethefollowingTutorial: StructuredQueryLanguage(SQL) Inadditionyouneedtoknowaboutdatabasesystems.Wehavedifferentkindofdatabase systemsandlotsofdifferentvendors.SincethisTutorialisaboutVisualStudioandC#,we willuseMicrosoftSQLServer.Formoreinformationaboutdatabasesystemsingeneraland speciallySQLServer,seethefollowingTutorial: IntroductiontoDatabaseSystems TheTutorialsareavailablefrom:http://home.hit.no/~hansha 9.1. ADO.NET ADO.NET(ActiveXDataObjectfor.NET)isasetofcomputersoftwarecomponentsthat programmerscanusetoaccessdataanddataservices.Itisapartofthebaseclasslibrary thatisincludedwiththeMicrosoft.NETFramework.Itiscommonlyusedbyprogrammersto accessandmodifydatastoredinrelationaldatabasesystems,thoughitcanalsoaccessdata innon-relationalsources. 47 Hans-PetterHalvorsen,M.Sc. E-mail:hans.p.halvorsen@hit.no Blog:http://home.hit.no/~hansha/ UniversityCollegeofSoutheastNorway www.usn.no