View
223
Download
3
Category
Preview:
Citation preview
https://www.halvorsen.blog
https://www.halvorsen.blog/documents/programming/web/aspnet
ASP.NETWebProgramming
Hans-PetterHalvorsen
ASP.NETWebProgramming
Hans-PetterHalvorsen
Copyright©2017
E-Mail:hans.p.halvorsen@usn.no
Web:https://www.halvorsen.blog
https://www.halvorsen.blog
3
TableofContents1 Introduction......................................................................................................................5
1.1 VisualStudio...............................................................................................................5
1.2 C#................................................................................................................................6
1.3 .NETFramework.........................................................................................................6
1.4 Object-OrientedProgramming(OOP)........................................................................6
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..............................................................................................................10
2.2.5 EditorsandDesigners........................................................................................11
2.2.6 Propertieswindow............................................................................................12
2.2.7 BuildandDebugTools.......................................................................................13
3 IntroductiontoWebProgramming.................................................................................14
3.1 Introduction..............................................................................................................14
3.2 WebBrowser............................................................................................................15
3.3 HTML.........................................................................................................................15
3.4 CSS............................................................................................................................16
3.5 JavaScript..................................................................................................................16
4 TableofContents
Tutorial:ASP.NETandWebProgramming
3.6 ASP.NET....................................................................................................................17
3.7 AJAX/ASP.NETAJAX.................................................................................................17
3.8 Silverlight..................................................................................................................17
4 IntroductiontoASP.NET..................................................................................................19
4.1 Introduction..............................................................................................................19
4.2 ASP.NETWebPages..................................................................................................21
4.3 ASP.NETSPA.............................................................................................................21
4.4 ASP.NETMVC............................................................................................................21
4.5 ASP.NETWebForms.................................................................................................22
5 ASP.NETWebForms........................................................................................................23
5.1 HelloWorldExample................................................................................................23
6 InternetInformationServices(IIS)..................................................................................27
6.1 WebServer...............................................................................................................27
7 WorkingwithDatabasesinASP.NET...............................................................................28
7.1 DatabaseSystems.....................................................................................................28
7.1.1 MirosoftSQLServer...........................................................................................28
7.2 SQL............................................................................................................................28
7.3 SQLServer+ASP.NET...............................................................................................30
7.3.1 SimpleDatabaseExamplee...............................................................................30
7.4 ADO.NET...................................................................................................................32
7.4.1 Example.............................................................................................................32
8 WebServices...................................................................................................................36
5
1 IntroductionASP.NETisaframeworkforcreatingwebsites,appsandserviceswithHTML,CSSandJavaScript.
1.1 VisualStudioMicrosoftVisualStudioisanintegrateddevelopmentenvironment(IDE)fromMicrosoft.ItcanbeusedtodevelopconsoleandgraphicaluserinterfaceapplicationsalongwithWindowsFormsapplications,websites,webapplications,andwebservicesinbothnativecodetogetherwithmanagedcodeforallplatformssupportedbyMicrosoftWindows,WindowsPhone,WindowsCE,.NETFramework,.NETCompactFrameworkandMicrosoftSilverlight.
Belowweseetheintegrateddevelopmentenvironment(IDE)inVisualStudio:
Newprojectsarecreatedfromthe“NewProject”window:
6 Introduction
Tutorial:ASP.NETandWebProgramming
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.
1.4 Object-OrientedProgramming(OOP)
7 Introduction
Tutorial:ASP.NETandWebProgramming
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 VisualStudio2.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:ASP.NETandWebProgramming
2.2.2 NewProject
Thefirstthingyoudowhenyouwanttocreateanewapplicationistocreateanewproject.
ThiscanbedonefromtheStartPage:
OrfromtheFilemenu:
Thenthe“NewProject”windowappears:
10 VisualStudio
Tutorial:ASP.NETandWebProgramming
Inthiswindowyouwillselectanappropriatetemplatebasedonwhatkindofapplicationyouwanttocreate,andanameandlocationforyourprojectandsolution.
Themostcommonapplicationsare:
• WindowsFormApplication• ConsoleApplication• WPFApplication• ASP.NETWebApplication• SilverlightApplication
2.2.3 SolutionExplorer
Solutionsandprojectscontainitemsthatrepresentthereferences,dataconnections,folders,andfilesthatyouneedtocreateyourapplication.Asolutioncontainercancontainmultipleprojectsandaprojectcontainertypicallycontainsmultipleitems.
2.2.4 Toolbox
TheToolboxcontainsallthenecessarycontrols,etc.youneedtocreateyouruserinterface.SeeFigurebelow.
11 VisualStudio
Tutorial:ASP.NETandWebProgramming
TheToolboxcontainsallthecontrols,etc.wecanuseinouruserinterface.
Inordertousetheminouruserinterface,wejustdraganddropthemtothe“Form”,asshownbelow:
2.2.5 EditorsandDesigners
VisualStudiohasdifferenteditorsanddesigntools.
GraphicalUserInterfaceDesigner:
12 VisualStudio
Tutorial:ASP.NETandWebProgramming
CodeEditor:
2.2.6 Propertieswindow
EachcontrolwehaveonouruserinterfacehaslotsofPropertieswecanset.
ThisisdoneinthePropertieswindow:
13 VisualStudio
Tutorial:ASP.NETandWebProgramming
2.2.7 BuildandDebugTools
InVisualStudiowehavelotsofBuildandDebuggingTools.
Buildmenu:
BelowweseetheBuildmenu:
Themostusedtoolis“BuildSolution”(ShortcutKey:F6).
Debugmenu:
BelowweseetheDebugmenu:
Themostusedtoolis“StartDebugging”(ShortcutKey:F5).
14
3 IntroductiontoWebProgramming
3.1 IntroductionTodaymostoftheapplicationsfocusontheInternet,wheretheapplicationscanbeviewedinastandardWebBrowser.StaticWebpagesarebasedonHTMLandCSS.Inordertocreatemoreadvancedapplications,weneedmorepowerfultools.
Ausefulwebsiteforlearningmoreaboutwebdevelopment:http://www.w3schools.com
Importantframeworksandtoolsforcreatingdynamicwebpages:
• ASP.NET• AJAX/ASP.NETAJAX• JavaScript
15 IntroductiontoWeb
Tutorial:ASP.NETandWebProgramming
• Silverlight
Theseframeworksandtoolswillbeexplainedbelow.
3.2 WebBrowserThepurposeofawebbrowseristoreadHTMLdocumentsandcomposethemintovisualoraudiblewebpages.ThebrowserdoesnotdisplaytheHTMLtags,butusesthetagstointerpretthecontentofthepage.
TodaywehavethefollowingmajorWebBrowsers:
• InternetExplorer(byMicrosoft)• Firefox(byMozilla)• Chrome(byGoogle)• Safari(byApple)• Opera(byOperafromNorway)
3.3 HTMLHTML,whichstandsforHyperTextMarkupLanguage,isthepredominantmarkuplanguageforwebpages.HTMListhebasicbuilding-blocksofwebpages.
16 IntroductiontoWeb
Tutorial:ASP.NETandWebProgramming
HTMLiswrittenintheformofHTMLelementsconsistingoftags,enclosedinanglebrackets(like<html>),withinthewebpagecontent.HTMLtagsnormallycomeinpairslike<h1>and</h1>.Thefirsttaginapairisthestarttag,thesecondtagistheendtag(theyarealsocalledopeningtagsandclosingtags).Inbetweenthesetagswebdesignerscanaddtext,tables,images,etc.
BelowweseeasimpleaHTMLwebpage:
<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>
AusefulwebsiteforlearningmoreaboutHTML:http://www.w3schools.com/html
3.4 CSSWebbrowserscanalsorefertoCascadingStyleSheets(CSS)todefinetheappearanceandlayoutoftextandothermaterial.
TheW3C,maintainerofboththeHTMLandtheCSSstandards
AusefulwebsiteforlearningmoreaboutCSS:http://www.w3schools.com/css
3.5 JavaScriptJavaScriptisanobject-orientedscriptinglanguagebasicallyusedtocreatedynamicwebpages.JavaScriptisprimarilyusedintheformofclient-sideJavaScript,implementedaspartofawebbrowserinordertoprovideenhanceduserinterfacesanddynamicwebsites.
BelowweseeasimpleaHTMLwebpagewithJavaScript:
<!DOCTYPE html> <html> <body> <h1>My First JavaScript</h1> <p>Click the button to display the date.</p> <p id="demo"></p> <button type="button" onclick="myFunction()">Try it</button> <script> function myFunction() { document.getElementById("demo").innerHTML = Date(); }
17 IntroductiontoWeb
Tutorial:ASP.NETandWebProgramming
</script> </body> </html>
AusefulwebsiteforlearningmoreaboutJavaScript:http://www.w3schools.com/js
3.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.
3.7 AJAX/ASP.NETAJAXAJAXisanacronymforAsynchronousJavaScriptandXML.AJAXisagroupofinterrelatedwebdevelopmentmethodsusedontheclient-sidetocreateinteractivewebapplications.WithAjax,webapplicationscansenddatato,andretrievedatafrom,aserverasynchronously(inthebackground)withoutinterferingwiththedisplayandbehavioroftheexistingpage.
ASP.NETAJAXisasetofextensionstoASP.NETdevelopedbyMicrosoftforimplementingAJAXfunctionality.
3.8 SilverlightMicrosoftSilverlightisanapplicationframeworkforwritingandrunningbrowserplug-insorotherrichinternetapplications,withfeaturesandpurposessimilartothoseofAdobeFlash.Therun-timeenvironmentforSilverlightisavailableasaplug-informostwebbrowsers.SilverlightisalsooneofthetwoapplicationdevelopmentplatformsforWindowsPhone7/8.
ThelatestversionisSilverlight5.0.
18 IntroductiontoWeb
Tutorial:ASP.NETandWebProgramming
SilverlightisbasedonWPF,soinSilverlightapplications,userinterfacesaredeclaredinExtensibleApplicationMarkupLanguage(XAML)andprogrammedusingasubsetofthe.NETFramework.
19
4 IntroductiontoASP.NET4.1 IntroductionASP.NETisawebapplicationframeworkdevelopedbyMicrosofttoallowprogrammerstobuilddynamicwebsites,webapplicationsandwebservices.
ASP.NETisaframeworkfrocreatingwebsites,appsandserviceswithHTML,CSSandJavaScript.
WebSite:http://www.asp.net
ASP.NETsupportsdifferentapproachesformakingwebsitesorwebpages.
• ASP.NETWebPagesusesasinglepagemodelthatmixescodeandHTMLmarkup.• ASP.NETSPA(SinglePageApplication)• ASP.NETWebFormsusescontrolsandanevent-modelforcomponent-based
development. • ASP.NETMVC(ModelViewController)valuesseparationofconcernsandenables
easiertest-drivendevelopment.
Youcanmixandmatchthesetechniqueswithinoneapplicationdependingonyourneeds.
20 IntroductiontoASP.NET
Tutorial:ASP.NETandWebProgramming
Video:http://www.asp.net/aspnet/overview/making-websites-with-aspnet/making-websites-with-aspnet
NewWebProjectDialog:
SelectProjectName,LoctionandSolutionName.
Next,seelctthetemplateyouwanttouse.
21 IntroductiontoASP.NET
Tutorial:ASP.NETandWebProgramming
4.2 ASP.NETWebPagesInASP.NETWebPagesyouincludeservercodedirectlyintotheHTMLsyntax,similartoPHPandClassicASP.
ASP.NETWebPagesusesSingePageModel(Theserver-sidecodeismixedinbetweentheHTML).ItusesthetheRazorsyntax(.cshtmlfiles)
AtoolcalledMicrosoftWebMatrixisoptimizedforthisdevelopmentmodel,butyoucanalsouseVisualStudioifyouwantto.
http://www.w3schools.com/aspnet
4.3 ASP.NETSPASPA–SinglePageApplication
Formoreinformation:http://www.asp.net/single-page-application
4.4 ASP.NETMVCMVC–Model-View–Controller
22 IntroductiontoASP.NET
Tutorial:ASP.NETandWebProgramming
Anewdevelopmentmodelwhereyousplityourdevelopmentinto3parts/components:ModelsforData,ViewsforDisplayandControllersforInput.
4.5 ASP.NETWebFormsASP.NETissimiliartothedesktopdevelopmentmodelusedinWPF. GUI(*.aspxfiles)andCode(*.aspx.cs)isseparated.
InthisdocumentwewillfocusonASP.NETWebForms.
23
5 ASP.NETWebFormsThemainfocusinthistutorialwillbeASP.NETWebForms.
5.1 HelloWorldExampleWhenyouarefinished,yourWebAppshouldlooksomethinglikethis:
WhenyouenteryourNameintheTextBoxandclicktheOKButton,theprogramshouldrespondwithagreetings.
SeelctCreateNewProject:
24 ASP.NETWebForms
Tutorial:ASP.NETandWebProgramming
Youhavelotsofchoiceshere–butwejustwanttocreateaverysimpleWebFormApp.
CreateNewWebForm:
WinForm1.aspxPage:UsedtocreatetheGUI/HMI
25 ASP.NETWebForms
Tutorial:ASP.NETandWebProgramming
HelloworldExample–GUI:
WebForm1.aspx.cs:
26 ASP.NETWebForms
Tutorial:ASP.NETandWebProgramming
RunningtheApplication(F5):
Congratulations,youhavecreatedyourfirstASP.NETWebFormsapplication.
27
6 InternetInformationServices(IIS)
6.1 WebServerThetermwebservercanrefertoeitherthehardware(thecomputer)orthesoftware(thecomputerapplication)thathelpstodeliverwebcontentthatcanbeaccessedthroughtheInternet.
Themostcommonuseofwebserversistohostwebsites,butthereareotherusessuchasgaming,datastorageorrunningenterpriseapplications.
• IIS-InternetInformationServices, MicrosoftWindows• ApacheWebServer, OpenSource, Cross-platform:UNIX,Linux,OSX,Windows,...• Nginx (pronounced"enginex") -Hasbecomeverypopularlatly• GWS(GoogleWebServer)• etc.
28
7 WorkingwithDatabasesinASP.NET
Today,mostofthewebsitesandwebpagesusesadatabasetostoredatathatisvisibleonthewebpage,e.g.Facebook,Instagram,Twitter,etc.
7.1 DatabaseSystemsTherearelotsofdifferentdatabasesystems,orDBMS–DatabaseManagementSystems,suchas:
• MicrosoftSQLServero Enterprise,Developerversions,etc.o Expressversionisfreeofcharge
• Oracle• MySQL(Oracle,previouslySunMicrosystems)-MySQLcanbeusedfreeofcharge
(opensourcelicense),WebsitesthatuseMySQL:YouTube,Wikipedia,Facebook• MariaDB(“TheNewMySQL”)• MicrosoftAccess• IBMDB2• Sybase• …lotsofothersystems
7.1.1 MirosoftSQLServer
MicrosoftisthevendorofSQLServer.WehavedifferenteditionsofSQLServer,whereSQLServerExpressisfreetodownloadanduse.WewillfocusonSQLServerinthistutorial.
7.2 SQLSQL(StructuredQueryLanguage)isadatabasecomputerlanguagedesignedformanagingdatainrelationaldatabasemanagementsystems(RDBMS).
29 WorkingwithDatabasesinASP.NET
Tutorial:ASP.NETandWebProgramming
SQL,isastandardizedcomputerlanguagethatwasoriginallydevelopedbyIBMforquerying,alteringanddefiningrelationaldatabases,usingdeclarativestatements.
SQLispronounced/ˌɛskjuːˈɛl/ (letterbyletter) or/ˈsiːkwəl/ (asaword).
WhatcanSQLdo?
• SQLcanexecutequeriesagainstadatabase• SQLcanretrievedatafromadatabase• SQLcaninsertrecordsinadatabase• SQLcanupdaterecordsinadatabase• SQLcandeleterecordsfromadatabase• SQLcancreatenewdatabases• SQLcancreatenewtablesinadatabase• SQLcancreatestoredproceduresinadatabase• SQLcancreateviewsinadatabase• SQLcansetpermissionsontables,procedures,andviews
EvenifSQLisastandard,manyofthedatabasesystemsthatexisttodayimplementtheirownversionoftheSQLlanguage.InthisdocumentwewillusetheMicrosoftSQLServerasanexample.
HerearesomeexamplesofSQLqueries:
30 WorkingwithDatabasesinASP.NET
Tutorial:ASP.NETandWebProgramming
InthisTutorialwewillfocusonMicrosoftSQLServer.SQLServerusesT-SQL(Transact-SQL).T-SQLisMicrosoft'sproprietaryextensiontoSQL.T-SQLisverysimilartostandardSQL,butinadditionitsupportssomeextrafunctionality,built-infunctions,etc.
InordertousedatabasesinourapplicationsweneedtoknowStructuredQuerylanguage(SQL).FormoreinformationaboutSQL,seethefollowingTutorial:StructuredQueryLanguage(SQL).
TheTutorialsareavailablefrom:https://www.halvorsen.blog
7.3 SQLServer+ASP.NETSQLServer+ASP.NET=PowerfulWebApplications
7.3.1 SimpleDatabaseExamplee
CreateaDatabasecalledLIBRARYandaBOOKtableinSQLServer.EntersomeTestdataintotheBOOKtable.
Filla“GridView”withdatafromtheDatabaseTable(BOOK),asshownbelow
31 WorkingwithDatabasesinASP.NET
Tutorial:ASP.NETandWebProgramming
Usethe“Wizard”inordertocreateallthe“magic”youneedinyourapplication:
Whenfinishingthe“Wizard”,your.aspxpageshouldlooksomethinglikethis
Asyousee-NoCodeneededtobewritteninthisexampleJ
32 WorkingwithDatabasesinASP.NET
Tutorial:ASP.NETandWebProgramming
ThisisOKforquickdemos–butforprofessionalapplications,youneedtousesomehardcoreADO.NETorsimiliarframeworks.
7.4 ADO.NETADO.NET(ActiveXDataObjectfor.NET)isasetofcomputersoftwarecomponentsthatprogrammerscanusetoaccessdataanddataservices.ItisapartofthebaseclasslibrarythatisincludedwiththeMicrosoft.NETFramework.Itiscommonlyusedbyprogrammerstoaccessandmodifydatastoredinrelationaldatabasesystems,thoughitcanalsoaccessdatainnon-relationalsources.
7.4.1 Example
Thistime:CreateeverythingfromscratchusingC#codeandADO.NET. Filla“DropDownList”withBookNamesfromtheDatabase PrinttheAuthorNamebasedontheselectedBookNameonthescreen,seebelow.
Your.aspxpageshouldlooksomethinglikethis:
33 WorkingwithDatabasesinASP.NET
Tutorial:ASP.NETandWebProgramming
Your.aspx.cspageshouldlooksomethinglikethis:
34 WorkingwithDatabasesinASP.NET
Tutorial:ASP.NETandWebProgramming
ThePage_load()methodisexecutedwhentheWebPageisloaded.InthissimpleexampleweputallthecodeintotheEventHandlerfortheDropDownList.ThecodecouldbeimprovedbycreatingaseparateClasswhereyouputthiscodeintoaMethod.
TheFillBookListmethodisasfollows:
ThecodecouldbeimprovedbycreatingaseparateClasswhereyoucreatethisMethod.
35 WorkingwithDatabasesinASP.NET
Tutorial:ASP.NETandWebProgramming
AllkindogconfigurationshouldbestoredintheWeb.configfile,includingDatabaseConnectionStrings,etc.
36
8 WebServicesInordertosharedatabetweendevicesoverInternet,WebServicesisthesolution.
InASP.NETthereareseveralalternativesforcreatingsuchWebServices.
SeetheTutorial“WebServiceswithExamples”formoredetails.
VisualStudioandASP.NEThaspowerfulfeaturesforcreatingWebServices:
• ASMXWebService(TraditionalWebWerviceusingSOAP)• ASP.NETWebAPI(ThemodernWebServiceusingREST,Web2.0)
ASP.NETWebProgramming
Hans-PetterHalvorsen
Copyright©2017
E-Mail:hans.p.halvorsen@usn.no
Web:https://www.halvorsen.blog
https://www.halvorsen.blog
Recommended