View
47
Download
0
Category
Preview:
Citation preview
UniversityCollegeofSoutheastNorway
http://home.hit.no/~hansha
IntroductiontoVisualStudioandC#
HANS-PETTERHALVORSEN,2016.09.26
2
TableofContents1. 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
3 TableofContents
Tutorial:IntroductiontoVisualStudioandC#
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
4 TableofContents
Tutorial:IntroductiontoVisualStudioandC#
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
5
1. IntroductionInthisTutorialwewilluseVisualStudioandC#.C#istheprogramminglanguage,whileVisualStudioisthedevelopmentenvironment.
Usefullinks:
VisualStudio:http://msdn.microsoft.com/en-us/library/dd831853.aspx
C#:http://msdn.microsoft.com/en-us/library/kx37x362.aspx
1.1. VisualStudioMicrosoftVisualStudioisanintegrateddevelopmentenvironment(IDE)fromMicrosoft.ItcanbeusedtodevelopconsoleandgraphicaluserinterfaceapplicationsalongwithWindowsFormsapplications,websites,webapplications,andwebservicesinbothnativecodetogetherwithmanagedcodeforallplatformssupportedbyMicrosoftWindows,WindowsPhone,WindowsCE,.NETFramework,.NETCompactFrameworkandMicrosoftSilverlight.
Belowweseetheintegrateddevelopmentenvironment(IDE)inVisualStudio:
6 Introduction
Tutorial:IntroductiontoVisualStudioandC#
Newprojectsarecreatedfromthe“NewProject”window:
1.2. C#C#ispronounced“seesharp”.C#isanobject-orientedprogramminglanguageandpartofthe.NETfamilyfromMicrosoft.C#isverysimilartoC++andJava.C#isdevelopedbyMicrosoftandworksonlyontheWindowsplatform.
1.3. .NETFrameworkThe.NETFramework(pronounced“dotnet”)isasoftwareframeworkthatrunsprimarilyonMicrosoftWindows.Itincludesalargelibraryandsupportsseveralprogramminglanguageswhichallowlanguageinteroperability(eachlanguagecanusecodewritteninotherlanguages).The.NETlibraryisavailabletoalltheprogramminglanguagesthat.NETsupports.Programswrittenforthe.NETFrameworkexecuteinasoftwareenvironment,knownastheCommonLanguageRuntime(CLR),anapplicationvirtualmachinethatprovidesimportantservicessuchassecurity,memorymanagement,andexceptionhandling.TheclasslibraryandtheCLRtogetherconstitutethe.NETFramework.
7 Introduction
Tutorial:IntroductiontoVisualStudioandC#
1.4. Object-OrientedProgramming(OOP)Object-orientedprogramming(OOP)isaprogramminglanguagemodelorganizedaround"objects"ratherthan"actions"anddataratherthanlogic.Historically,aprogramhasbeenviewedasalogicalprocedurethattakesinputdata,processesit,andproducesoutputdata.
ThefirststepinOOPistoidentifyalltheobjectsyouwanttomanipulateandhowtheyrelatetoeachother,anexerciseoftenknownasdatamodeling.Onceyou'veidentifiedanobject,yougeneralizeitasaclassofobjectsanddefinethekindofdataitcontainsandanylogicsequencesthatcanmanipulateit.Eachdistinctlogicsequenceisknownasamethod.Arealinstanceofaclassiscalledan“object”oran“instanceofaclass”.Theobjectorclassinstanceiswhatyouruninthecomputer.Itsmethodsprovidecomputerinstructionsandtheclassobjectcharacteristicsproviderelevantdata.Youcommunicatewithobjects-andtheycommunicatewitheachother.
ImportantfeatureswithOOPare:
• ClassesandObjects• Inheritance• Polymorphism• Encapsulation
Simulawasthefirstobject-orientedprogramminglanguage.Simulawasdevelopedinthe1960sbyKristenNygaardfromNorway.
Java,Python,C++,VisualBasic.NETandC#arepopularOOPlanguagestoday.
SinceSimula-typeobjectsarereimplementedinC++,JavaandC#theinfluenceofSimulaisoftenunderstated.ThecreatorofC++(1979),BjarneStroustrup(fromDenmark),hasacknowledgedthatSimulawasthegreatestinfluenceonhimtodevelopC++.
8
2. VisualStudio
2.1. IntroductionHomepageofVisualStudio:http://www.microsoft.com/visualstudio
ThereexistdifferentversionsofVisualStudio,suchasVisualStudioExpress(free),VisualStudioProfessional,VisualStudioPremiumandVisualStudioUltimate.
2.2. GettingStarted
2.2.1. IntegratedDevelopmentEnvironment(IDE)
TheVisualStudioproductfamilysharesasingleintegrateddevelopmentenvironment(IDE)thatiscomposedofseveralelements:theMenubar,Standardtoolbar,varioustoolwindowsdockedorauto-hiddenontheleft,bottom,andrightsides,aswellastheeditorspace.Thetoolwindows,menus,andtoolbarsavailabledependonthetypeofprojectorfileyouareworkingin.
BelowweseetheVisualStudioIDE(IntegratedDevelopmentEnvironment):
9 VisualStudio
Tutorial:IntroductiontoVisualStudioandC#
2.2.2. NewProject
Thefirstthingyoudowhenyouwanttocreateanewapplicationistocreateanewproject.
ThiscanbedonefromtheStartPage:
OrfromtheFilemenu:
Thenthe“NewProject”windowappears:
10 VisualStudio
Tutorial:IntroductiontoVisualStudioandC#
Inthiswindowyouwillselectanappropriatetemplatebasedonwhatkindofapplicationyouwanttocreate,andanameandlocationforyourprojectandsolution.
Themostcommonapplicationsare:
• WindowsFormApplication• ConsoleApplication• WPFApplication• ASP.NETWebApplication• SilverlightApplication
2.2.3. SolutionExplorer
Solutionsandprojectscontainitemsthatrepresentthereferences,dataconnections,folders,andfilesthatyouneedtocreateyourapplication.Asolutioncontainercancontainmultipleprojectsandaprojectcontainertypicallycontainsmultipleitems.
11 VisualStudio
Tutorial:IntroductiontoVisualStudioandC#
2.2.4. Toolbox
TheToolboxcontainsallthenecessarycontrols,etc.youneedtocreateyouruserinterface.SeeFigurebelow.
TheToolboxcontainsallthecontrols,etc.wecanuseinouruserinterface.
Inordertousetheminouruserinterface,wejustdraganddropthemtothe“Form”,asshownbelow:
12 VisualStudio
Tutorial:IntroductiontoVisualStudioandC#
2.2.5. EditorsandDesigners
VisualStudiohasdifferenteditorsanddesigntools.
GraphicalUserInterfaceDesigner:
CodeEditor:
2.2.6. Propertieswindow
EachcontrolwehaveonouruserinterfacehaslotsofPropertieswecanset.
13 VisualStudio
Tutorial:IntroductiontoVisualStudioandC#
ThisisdoneinthePropertieswindow:
2.2.7. BuildandDebugTools
InVisualStudiowehavelotsofBuildandDebuggingTools.
Buildmenu:
BelowweseetheBuildmenu:
Themostusedtoolis“BuildSolution”(ShortcutKey:F6).
Debugmenu:
BelowweseetheDebugmenu:
14 VisualStudio
Tutorial:IntroductiontoVisualStudioandC#
Themostusedtoolis“StartDebugging”(ShortcutKey:F5).
15
3. WindowsProgramming
3.1. IntroductionWhencreatingordinaryWindowsapplications,wecanselectbetweenthefollowing:
• WindowsFormsApplication• WPFApplications(WindowsPresentationFoundation)
WindowsFormsisthestandardwayofcreatingWindowsapplicationsandhasexistedinmanyyears,evenbefore.NET1.0(2002)wasintroduced.WPFisanewapproachfromcreatingWindowsapplicationsandwasintroducedwith.NETFramework3.0(2006).
ForexamplehastheVisualStudioIDEbeenentirelyrewrittenusingWPF.
WindowsFormsApplicationandWPFApplicationswillbeexplainedinmoredetailbelow.
3.1.1. WindowsForms
WindowsFormsisthestandardwayofcreatingWindowsapplications.
Select“WindowsFormsApplication”inthe“NewProject”window:
16 WindowsProgramming
Tutorial:IntroductiontoVisualStudioandC#
3.1.2. WPF
DevelopedbyMicrosoft,theWindowsPresentationFoundation(orWPF)isacomputer-softwaregraphicalsubsystemforrenderinguserinterfacesinWindows-basedapplications.
WPFisintendedtotakeoverforthetraditionalWindowsForms.
ThegraphicaluserinterfaceinWPFisdesignedusingXAML(ExtensibleApplicationMarkupLanguage).
XAML:
Followingthesuccessofmarkuplanguagesforwebdevelopment,WPFintroducesanewlanguageknownaseXtensibleApplicationMarkupLanguage(XAML),whichisbasedonXML.XAMLisdesignedasamoreefficientmethodofdevelopingapplicationuserinterfaces
Select“WPFApplication”inthe“NewProject”window:
3.2. HelloWorldWestartbycreatingatraditional“HelloWorld”applicationusingWindowsForms.Theapplicationisshownbelow:
17 WindowsProgramming
Tutorial:IntroductiontoVisualStudioandC#
TheVisualStudioIDElookslikethis:
InthisprojectweuseasimpleTextBox(textBox1)andwhenwestarttheprogramthetext“HelloWorld”iswrittentotheTextBox.
Thecodeisasfollows:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
18 WindowsProgramming
Tutorial:IntroductiontoVisualStudioandC#
private void Form1_Load(object sender, EventArgs e) { textBox1.Text = "Hello World"; } } }
19
4. GettingStartedwithC#C#isamodernObject-orientedprogramminglanguage.
Object-orientedprogramming(OOP)isaprogrammingparadigmusing"objects"–datastructuresconsistingofdatafieldsandmethodstogetherwiththeirinteractions–todesignapplicationsandcomputerprograms.Programmingtechniquesmayincludefeaturessuchasdataabstraction,encapsulation,messaging,modularity,polymorphism,andinheritance.
4.1. IntroductionInthischapterwewillstartwiththebasicallprogramminglanguageshave:…
• DataTypesandVariables• ControlFlow:If-Else,etc.• Loops:WhileLoops,ForLoops,etc.
Furtherwewillintroducethefollowing:
• Namespaces• Classes• DataFields• Methods• Properties
InthenextchapterwewillgomoreindepthofwhatObject-orientedprogrammingisandintroducethefollowingimportantOOPtopics:
• Inheritance• Polymorphism• Encapsulation
Note!C#iscase-sensitive.
4.2. DataTypesandVariables
20 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
“Variables”aresimplystoragelocationsfordata.YoucanplacedataintothemandretrievetheircontentsaspartofaC#expression.Theinterpretationofthedatainavariableiscontrolledthrough“Types”.
TheC#simpletypesconsistof:
• Booleantype• Numerictypes:Integrals,FloatingPoint,Decimal• Stringtype
4.2.1. Booleantype
Booleantypesaredeclaredusingthekeyword“bool”.Theyhavetwovalues:“true”or“false”.Inotherlanguages,suchasCandC++,booleanconditionscanbesatisfiedwhere0meansfalseandanythingelsemeanstrue.However,inC#theonlyvaluesthatsatisfyabooleanconditionistrueandfalse,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:
21 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
4.2.4. Arrays
Example:
int[] myInts = { 5, 10, 15 };
4.3. ControlFlowTobeabletocontroltheflowinyourprogramisimportantineveryprogramminglanguage.
Thetwomostimportanttechniquesare:
• TheifStatement• TheswitchStatement
4.3.1. TheifStatement
Theifstatementisprobablythemostusedmechanismtocontroltheflowinyourapplication.
Anifstatementallowsyoutotakedifferentpathsoflogic,dependingonagivencondition.Whentheconditionevaluatestoabooleantrue,ablockofcodeforthattrueconditionwillexecute.Youhavetheoptionofasingleifstatement,multipleelseifstatements,andanoptionalelsestatement.
Example:
bool myTest;
22 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
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,whichexecutesasetoflogicdependingonthevalueofagivenparameter.Thetypesofthevaluesaswitchstatementoperatesoncanbebooleans,enums,integraltypes,andstrings.
23 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
Example:
switch (myTest) {
case 1: MessageBox.Show("Hello1"); break;
case 2: MessageBox.Show("Hello2");
break;
default: MessageBox.Show("Hello3"); break; }
4.4. LoopsInC#wehavedifferentkindofloops:
• Thewhileloop• Thedoloop• Theforloop• Theforeachloop
4.4.1. ThewhileLoop
Awhileloopwillcheckaconditionandthencontinuestoexecuteablockofcodeaslongastheconditionevaluatestoabooleanvalueoftrue.
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,exceptthatitchecksitsconditionattheendoftheloop.Thismeansthatthedoloopisguaranteedtoexecuteatleastonetime.Ontheotherhand,awhileloopevaluatesitsbooleanexpressionatthebeginningandthereisgenerallynoguaranteethatthestatementsinsidetheloopwillbeexecuted,unlessyouprogramthecodetoexplicitlydoso.
Example:
24 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
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,exceptthatthesyntaxoftheforloopincludesinitializationandconditionmodification.forloopsareappropriatewhenyouknowexactlyhowmanytimesyouwanttoperformthestatementswithintheloop.
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.Itoperatesonarraysorcollections.
Example:
string[] names = { "Elvis", "Beatles", "Eagles", "Rolling Stones" }; foreach (string person in names) {
MessageBox.Show(person); }
4.5. MethodsMethodsareextremelyusefulbecausetheyallowyoutoseparateyourlogicintodifferentunits.Youcanpassinformationtomethods,haveitperformoneormorestatements,andretrieveareturnvalue.Thecapabilitytopassparametersandreturnvaluesisoptionalanddependsonwhatyouwantthemethodtodo.
Methodsaresimilartofunctions,procedureorsubroutineusedinotherprogramminglanguages.Thedifferenceisthatamethodisalwaysapartofaclass.
Example:
public void ShowCarColor(string color)
25 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
{
MessageBox.Show("My Car is: " + color); }
WelearnmoreaboutmethodsintheClassessectionbelow.
Wehave2kindsofMethods:
• StaticMethods• NonstaticMethods(InstanceMethod)
StaticMethodsbelongstothewholeclass,whilenonstaticMethodsbelongtoeachinstancecreatedfromtheclass.
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); } }
26 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
Thenweuseit:
Boat.SetColor("green");
i.e.,wedon’tneedtocreateanobject/instantiatingtheclassbeforeweusetheStaticMethod.
4.6. NamespacesNamespacesareC#programelementsdesignedtohelpyouorganizeyourprograms.Theyalsoprovideassistanceinavoidingnameclashesbetweentwosetsofcode.ImplementingNamespacesinyourowncodeisagoodhabitbecauseitislikelytosaveyoufromproblemslaterwhenyouwanttoreusesomeofyourcode.
YouspecifytheNamespacesyouwanttouseinthetopofyourcode.
Example:
WhenyoucreateanewWindowsFormsapplication,thefollowingdefaultnamespaceswillbeincluded.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; …
Itisjusttoaddmorewhenyouneedit.
MoreaboutNamespaceslater.
4.7. ClassesThefirststepinOOPistoidentifyalltheobjectsyouwanttomanipulateandhowtheyrelatetoeachother,anexerciseoftenknownasdatamodeling.Onceyou'veidentifiedanobject,yougeneralizeitasaclassofobjectsanddefinethekindofdataitcontainsandanylogicsequencesthatcanmanipulateit.Eachdistinctlogicsequenceisknownasamethod.Arealinstanceofaclassiscalledan“object”oran“instanceofaclass”.Theobjectorclassinstanceiswhatyouruninthecomputer.Itsmethodsprovidecomputerinstructionsandtheclassobjectcharacteristicsproviderelevantdata.Youcommunicatewithobjects-andtheycommunicatewitheachother.
27 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
EverythinginC#isbasedonClasses.Classesaredeclaredbyusingthekeywordclassfollowedbytheclassnameandasetofclassmemberssurroundedbycurlybraces.
AclassnormallyconsistsofMethods,FieldsandProperties.
Everyclasshasaconstructor,whichiscalledautomaticallyanytimeaninstanceofaclassiscreated.Thepurposeofconstructorsistoinitializeclassmemberswhenaninstanceoftheclassiscreated.Constructorsdonothavereturnvaluesandalwayshavethesamenameastheclass.
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
Thepurposeofconstructorsistoinitializeclassmemberswhenaninstanceoftheclassiscreated.
Example:
WecanuseaConstructortocreatea“default”colorforourcar.
Wedefinetheclass:
28 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
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;
29 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
} //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. PropertiesPropertiesprovidetheopportunitytoprotectafieldinaclassbyreadingandwritingtoitthroughtheproperty.Inotherlanguages,thisisoftenaccomplishedbyprogramsimplementingspecializedgetterandsettermethods.C#propertiesenablethistypeofprotectionwhilealsolettingyouaccessthepropertyjustlikeitwasafield.
Example:
WedefineaClasswithPropertiesandaMethod:
class Car {
30 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
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,andConstructors.Hereisacompletelistofthetypesofmembersyoucanhaveinyourclasses:
• Constructors• Destructors(oppositeofConstructors)• Fields• Methods• Properties• Indexers• Delegates• Events• NestedClasses
31 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
4.9. NamingConventionThereisdifferentnameconventionforhowtospecifyyourvariables,classesandMethods,etc.
Camelnotation:
Forvariablesandparameters/argumentswenormallyuse“Camelnotation”.
Examples:
string myCar; int number; string backColor;
→InCamelcasingthefirstletterofanidentifierislowercaseandthefirstletterofeachsubsequentconcatenatedwordiscapitalized.
Pascalnotation:
Forclasses,methodsandproperties,wenormallyuse“Pascalnotation”.
Examples:
class Car { void ShowCarColor() { … } }
→InPascalcasingthefirstletterintheidentifierandthefirstletterofeachsubsequentconcatenatedwordarecapitalized.
ForNamespacesweusePascalcasingandadotseparator.
Examples:
System.Drawing System.Collections.Generics
Controls:
Forcontrolsonyouruserinterfaceweeitheruse“Pascalnotation”or“Hungariannotation”,butsticktooneofthem!
Examples:
“Pascalnotation”:
LoginName LoginPassword
32 GettingStartedwithC#
Tutorial:IntroductiontoVisualStudioandC#
“Hungariannotation”:
txtName txtPassword lblName btnCancel
Where“txt”meansitisaTextControl,“lbl”aLabelControl,“btn”aButtonControl,etc.
Acronyms:
Casingofacronymsdependsonthelengthoftheacronym.Allacronymsareatleasttwocharacterslong.Ifanacronymisexactlytwocharacters,itisconsideredashortacronym.Anacronymofthreeormorecharactersisalongacronym.
Ingeneral,youshouldnotuseabbreviationsoracronyms.Thesemakeyournameslessreadable.Similarly,itisdifficulttoknowwhenitissafetoassumethatanacronymiswidelyrecognized.
Butifyoumust,therulesareasfollows:
ShortacronymExamples(twocharacters):
DBRate
ApropertynamedDBRateisanexampleofashortacronym(DB)usedasthefirstwordofaPascal-casedidentifier.
ioChannel
AparameternamedioChannelisanexampleofashortacronym(IO)usedasthefirstwordofacamel-casedidentifier.
LongacronymExamples(threeormorecharacters):
XmlWriter
AclassnamedXmlWriterisanexampleofalongacronymusedasthefirstwordofaPascal-casedidentifier.
htmlReader
AparameternamedhtmlReaderisanexampleofalongacronymusedasthefirstwordofacamel-casedidentifier.
33
5. MoreObject-orientedTechniques
InthischapterwewillintroducethefollowingObject-orientedtechniques:
• Inheritance• Polymorphism• Encapsulation
5.1. InheritanceInheritanceisoneoftheprimaryconceptsofobject-orientedprogramming.Itallowsyoutoreuseexistingcode.Througheffectiveemploymentofreuse,youcansavetimeinyourprogramming.
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();
34 MoreObject-orientedTechniques
Tutorial:IntroductiontoVisualStudioandC#
myVolvo.SetColor("green");
Asyoucanseewecanusethe“SetColor()”MethodthathasbeendefinedintheBaseClass.
5.2. PolymorphismAnotherprimaryconceptofobject-orientedprogrammingisPolymorphism.Itallowsyoutoinvokederivedclassmethodsthroughabaseclassreferenceduringrun-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.Theoverridemodifierallowsamethodtooverridethevirtualmethodofitsbaseclassatrun-time.
Thenwecanuseit:
Car[] car = new Car[4]; car[0] = new Car();
35 MoreObject-orientedTechniques
Tutorial:IntroductiontoVisualStudioandC#
car[1] = new Volvo(); car[2] = new Ford(); car[3] = new Toyota(); foreach (Car carmodel in car) { carmodel.CarType(); }
Theresultis:
… … …
→ThisisPolymorphism.
5.3. EncapsulationEncapsulationmeansthattheinternalrepresentationofanobjectisgenerallyhiddenfromviewoutsideoftheobject'sdefinition.Typically,onlytheobject'sownmethodscandirectlyinspectormanipulateitsfields.
WecansetdifferentAccessrightsonClassesandMethods:
36
6. ExceptionHandlingInprogrammingerrorandexceptionhandlingisveryimportant.C#hasbuilt-inandreadytousemechanismtohandlethis.Thismechanismisbasedonthekeywordstry,catch,throwandfinally.
Exceptionsareunforeseenerrorsthathappeninyourprograms.Mostofthetime,youcan,andshould,detectandhandleprogramerrorsinyourcode.Forexample,validatinguserinput,checkingfornullobjects,andverifyingthevaluesreturnedfrommethodsarewhatyouexpect,areallexamplesofgoodstandarderrorhandlingthatyoushouldbedoingallthetime.
However,therearetimeswhenyoudon'tknowifanerrorwilloccur.Forexample,youcan'tpredictwhenyou'llreceiveafileI/Oerror,runoutofsystemmemory,orencounteradatabaseerror.Thesethingsaregenerallyunlikely,buttheycouldstillhappenandyouwanttobeabletodealwiththemwhentheydooccur.Thisiswhereexceptionhandlingcomesin.
Whenexceptionsoccur,theyaresaidtobe“thrown”.C#usesthekeywordstry,catch,throwandfinally.Itworkslikethis:Amethodwilltrytoexecuteapieceofcode.Ifthecodedetectsaproblem,itwillthrowanerrorindication,whichyourcodecancatch,andnomatterwhathappens,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();
37 ExceptionHandling
Tutorial:IntroductiontoVisualStudioandC#
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(); } }
38
7. WindowsFormsExample
Inthischapterwewillgothroughalargeexample.InthisexamplewewillcreateanapplicationinVisualStudiothatcontrolsthefollowingwatertankprocess:
Thepurposeistocontrolthelevelinthewatertank.Inordertocommunicatewiththephysicalprocess,weuseaNIUSB-6008DAQdevice:
Wewillnotshowallthedetailsinthecode,butfocusonthestructure.
BelowweseetheuserinterfacewehavecreatedinVisualStudio:
39 WindowsFormsExample
Tutorial:IntroductiontoVisualStudioandC#
BelowweseetheVisualStudioproject:
Westartwithdefiningtheclassesweneedinourapplication.
IntheSolutionExplorerwehavedefineda“Classes”folderwhereweputalltheclasseswecreate:
40 WindowsFormsExample
Tutorial:IntroductiontoVisualStudioandC#
Inordertocreatenewclassesweright-clickintheSolutionExplorerandselect“Add-NewItem…”:
NextweselecttheClassiteminthe“AddNewItem”window:
41 WindowsFormsExample
Tutorial:IntroductiontoVisualStudioandC#
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(...) { ... } } }
42 WindowsFormsExample
Tutorial:IntroductiontoVisualStudioandC#
Itisgoodpracticetocreateanewfileforeachnewclasswedefine.ThenwestartbydefiningameaningfulNamespace.NextwedefineourClasswithnecessaryFields,PropertiesandMethods.
WealsoneedtoincludethenecessaryNamespaceourClasswillneed.Inthisexamplewehaveincludedsome3.partyAssembliesfromNationalInstruments:
using NationalInstruments; using NationalInstruments.DAQmx;
TheseAssembliescontainsthedrivertotheNIUSB-6008DAQdeviceweareusing.
TheAssembliesweusemustbeaddedinthe“References”folderintheSolutionExplorer:
MainApplication:
InourmainapplicationwestartwithincludingourNamespace:
using NationalInstruments; using NationalInstruments.UI; using NationalInstruments.UI.WindowsForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Tuc.Control; namespace Control_Application { public partial class Form1 : Form {
... } }
43 WindowsFormsExample
Tutorial:IntroductiontoVisualStudioandC#
Itisalsoagoodideatocreatedifferentregionsinordertostructureyourcodebetter.Thiscanbedonelikethis:
//Comment # region
... //Your Code # endregion
InthiswayourMainApplicationmaylooklikethis:
44
8. WebProgramming
8.1. IntroductionTodaymostoftheapplicationsfocusontheInternet,wheretheapplicationscanbeviewedinastandardWebBrowser.StaticWebpagesarebasedonHTMLandCSS.Inordertocreatemoreadvancedapplications,weneedmorepowerfultools.
Importantframeworksandtoolsforcreatingdynamicwebpages:
• ASP.NET• AJAX/ASP.NETAJAX• JavaScript• Silverlight
Theseframeworksandtoolswillbeexplainedbelow.
SeetheTutorial“ASP.NETandWebProgramming”formoredetails.
8.2. HTMLHTML,whichstandsforHyperTextMarkupLanguage,isthepredominantmarkuplanguageforwebpages.HTMListhebasicbuilding-blocksofwebpages.
HTMLiswrittenintheformofHTMLelementsconsistingoftags,enclosedinanglebrackets(like<html>),withinthewebpagecontent.HTMLtagsnormallycomeinpairslike<h1>and</h1>.Thefirsttaginapairisthestarttag,thesecondtagistheendtag(theyarealsocalledopeningtagsandclosingtags).Inbetweenthesetagswebdesignerscanaddtext,tables,images,etc.
8.3. WebBrowserThepurposeofawebbrowseristoreadHTMLdocumentsandcomposethemintovisualoraudiblewebpages.ThebrowserdoesnotdisplaytheHTMLtags,butusesthetagstointerpretthecontentofthepage.
45 WebProgramming
Tutorial:IntroductiontoVisualStudioandC#
TodaywehavethefollowingmajorWebBrowsers:
• InternetExplorer(byMicrosoft)• Firefox(byMozilla)• Chrome(byGoogle)• Safari(byApple)• Opera(byOperafromNorway)
8.4. CSSWebbrowserscanalsorefertoCascadingStyleSheets(CSS)todefinetheappearanceandlayoutoftextandothermaterial.
TheW3C,maintainerofboththeHTMLandtheCSSstandards
8.5. JavaScriptJavaScriptisanobject-orientedscriptinglanguagebasicallyusedtocreatedynamicwebpages.JavaScriptisprimarilyusedintheformofclient-sideJavaScript,implementedaspartofawebbrowserinordertoprovideenhanceduserinterfacesanddynamicwebsites.
8.6. ASP.NETASP.NETisawebapplicationframeworkdevelopedbyMicrosofttoallowprogrammerstobuilddynamicwebsites,webapplicationsandwebservices.
ASP.NETispartoftheVisualStudiopackage
ItwasfirstreleasedinJanuary2002withversion1.0ofthe.NETFramework,andisthesuccessortoMicrosoft'sActiveServerPages(ASP)technology.ASP.NETisbuiltontheCommonLanguageRuntime(CLR),allowingprogrammerstowriteASP.NETcodeusinganysupported.NETlanguage,suchasC#andVB.NET.
ASP.NETwebpagesorwebpage,knownofficiallyasWebForms],arethemainbuildingblockforapplicationdevelopment.Webformsarecontainedinfileswithan“.aspx”extension.
Select“ASP.NETApplication”inthe“NewProject”window:
46 WebProgramming
Tutorial:IntroductiontoVisualStudioandC#
8.7. AJAX/ASP.NETAJAXAJAXisanacronymforAsynchronousJavaScriptandXML.AJAXisagroupofinterrelatedwebdevelopmentmethodsusedontheclient-sidetocreateinteractivewebapplications.WithAjax,webapplicationscansenddatato,andretrievedatafrom,aserverasynchronously(inthebackground)withoutinterferingwiththedisplayandbehavioroftheexistingpage.
ASP.NETAJAXisasetofextensionstoASP.NETdevelopedbyMicrosoftforimplementingAJAXfunctionality.
8.8. SilverlightMicrosoftSilverlightisanapplicationframeworkforwritingandrunningbrowserplug-insorotherrichinternetapplications,withfeaturesandpurposessimilartothoseofAdobeFlash.Therun-timeenvironmentforSilverlightisavailableasaplug-informostwebbrowsers.SilverlightisalsooneofthetwoapplicationdevelopmentplatformsforWindowsPhone7/8.
ThelatestversionisSilverlight5.0.
SilverlightisbasedonWPF,soinSilverlightapplications,userinterfacesaredeclaredinExtensibleApplicationMarkupLanguage(XAML)andprogrammedusingasubsetofthe.NETFramework.
47
9. DatabaseProgrammingMostoftoday’sapplicationsuseabackenddatabasetostoreimportantdata,e.g.,Facebook,Twitter,etc.
InordertousedatabasesinourapplicationsweneedtoknowStructuredQuerylanguage(SQL).FormoreinformationaboutSQL,seethefollowingTutorial:
StructuredQueryLanguage(SQL)
Inadditionyouneedtoknowaboutdatabasesystems.Wehavedifferentkindofdatabasesystemsandlotsofdifferentvendors.SincethisTutorialisaboutVisualStudioandC#,wewilluseMicrosoftSQLServer.FormoreinformationaboutdatabasesystemsingeneralandspeciallySQLServer,seethefollowingTutorial:
IntroductiontoDatabaseSystems
TheTutorialsareavailablefrom:http://home.hit.no/~hansha
9.1. ADO.NETADO.NET(ActiveXDataObjectfor.NET)isasetofcomputersoftwarecomponentsthatprogrammerscanusetoaccessdataanddataservices.ItisapartofthebaseclasslibrarythatisincludedwiththeMicrosoft.NETFramework.Itiscommonlyusedbyprogrammerstoaccessandmodifydatastoredinrelationaldatabasesystems,thoughitcanalsoaccessdatainnon-relationalsources.
Hans-PetterHalvorsen,M.Sc.
E-mail:hans.p.halvorsen@hit.no
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no
Recommended