asp.net and web programming · pdf file · 2017-11-284.4 asp.net mvc ... c# is very...

37
https://www.halvorsen.blog https://www.halvorsen.blog/documents/programming/web/aspnet ASP.NET Web Programming Hans-Petter Halvorsen

Upload: ngohuong

Post on 11-Mar-2018

222 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

https://www.halvorsen.blog

https://www.halvorsen.blog/documents/programming/web/aspnet

ASP.NETWebProgramming

Hans-PetterHalvorsen

Page 2: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

ASP.NETWebProgramming

Hans-PetterHalvorsen

Copyright©2017

E-Mail:[email protected]

Web:https://www.halvorsen.blog

https://www.halvorsen.blog

Page 3: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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

Page 4: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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

Page 5: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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:

Page 6: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties 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)

Page 7: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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++.

Page 8: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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):

Page 9: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

9 VisualStudio

Tutorial:ASP.NETandWebProgramming

2.2.2 NewProject

Thefirstthingyoudowhenyouwanttocreateanewapplicationistocreateanewproject.

ThiscanbedonefromtheStartPage:

OrfromtheFilemenu:

Thenthe“NewProject”windowappears:

Page 10: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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.

Page 11: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

11 VisualStudio

Tutorial:ASP.NETandWebProgramming

TheToolboxcontainsallthecontrols,etc.wecanuseinouruserinterface.

Inordertousetheminouruserinterface,wejustdraganddropthemtothe“Form”,asshownbelow:

2.2.5 EditorsandDesigners

VisualStudiohasdifferenteditorsanddesigntools.

GraphicalUserInterfaceDesigner:

Page 12: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

12 VisualStudio

Tutorial:ASP.NETandWebProgramming

CodeEditor:

2.2.6 Propertieswindow

EachcontrolwehaveonouruserinterfacehaslotsofPropertieswecanset.

ThisisdoneinthePropertieswindow:

Page 13: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

13 VisualStudio

Tutorial:ASP.NETandWebProgramming

2.2.7 BuildandDebugTools

InVisualStudiowehavelotsofBuildandDebuggingTools.

Buildmenu:

BelowweseetheBuildmenu:

Themostusedtoolis“BuildSolution”(ShortcutKey:F6).

Debugmenu:

BelowweseetheDebugmenu:

Themostusedtoolis“StartDebugging”(ShortcutKey:F5).

Page 14: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

14

3 IntroductiontoWebProgramming

3.1 IntroductionTodaymostoftheapplicationsfocusontheInternet,wheretheapplicationscanbeviewedinastandardWebBrowser.StaticWebpagesarebasedonHTMLandCSS.Inordertocreatemoreadvancedapplications,weneedmorepowerfultools.

Ausefulwebsiteforlearningmoreaboutwebdevelopment:http://www.w3schools.com

Importantframeworksandtoolsforcreatingdynamicwebpages:

• ASP.NET• AJAX/ASP.NETAJAX• JavaScript

Page 15: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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.

Page 16: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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(); }

Page 17: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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.

Page 18: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

18 IntroductiontoWeb

Tutorial:ASP.NETandWebProgramming

SilverlightisbasedonWPF,soinSilverlightapplications,userinterfacesaredeclaredinExtensibleApplicationMarkupLanguage(XAML)andprogrammedusingasubsetofthe.NETFramework.

Page 19: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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.

Page 20: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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.

Page 21: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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

Page 22: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

22 IntroductiontoASP.NET

Tutorial:ASP.NETandWebProgramming

Anewdevelopmentmodelwhereyousplityourdevelopmentinto3parts/components:ModelsforData,ViewsforDisplayandControllersforInput.

4.5 ASP.NETWebFormsASP.NETissimiliartothedesktopdevelopmentmodelusedinWPF. GUI(*.aspxfiles)andCode(*.aspx.cs)isseparated.

InthisdocumentwewillfocusonASP.NETWebForms.

Page 23: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

23

5 ASP.NETWebFormsThemainfocusinthistutorialwillbeASP.NETWebForms.

5.1 HelloWorldExampleWhenyouarefinished,yourWebAppshouldlooksomethinglikethis:

WhenyouenteryourNameintheTextBoxandclicktheOKButton,theprogramshouldrespondwithagreetings.

SeelctCreateNewProject:

Page 24: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

24 ASP.NETWebForms

Tutorial:ASP.NETandWebProgramming

Youhavelotsofchoiceshere–butwejustwanttocreateaverysimpleWebFormApp.

CreateNewWebForm:

WinForm1.aspxPage:UsedtocreatetheGUI/HMI

Page 25: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

25 ASP.NETWebForms

Tutorial:ASP.NETandWebProgramming

HelloworldExample–GUI:

WebForm1.aspx.cs:

Page 26: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

26 ASP.NETWebForms

Tutorial:ASP.NETandWebProgramming

RunningtheApplication(F5):

Congratulations,youhavecreatedyourfirstASP.NETWebFormsapplication.

Page 27: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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.

Page 28: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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).

Page 29: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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:

Page 30: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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

Page 31: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

31 WorkingwithDatabasesinASP.NET

Tutorial:ASP.NETandWebProgramming

Usethe“Wizard”inordertocreateallthe“magic”youneedinyourapplication:

Whenfinishingthe“Wizard”,your.aspxpageshouldlooksomethinglikethis

Asyousee-NoCodeneededtobewritteninthisexampleJ

Page 32: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

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:

Page 33: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

33 WorkingwithDatabasesinASP.NET

Tutorial:ASP.NETandWebProgramming

Your.aspx.cspageshouldlooksomethinglikethis:

Page 34: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

34 WorkingwithDatabasesinASP.NET

Tutorial:ASP.NETandWebProgramming

ThePage_load()methodisexecutedwhentheWebPageisloaded.InthissimpleexampleweputallthecodeintotheEventHandlerfortheDropDownList.ThecodecouldbeimprovedbycreatingaseparateClasswhereyouputthiscodeintoaMethod.

TheFillBookListmethodisasfollows:

ThecodecouldbeimprovedbycreatingaseparateClasswhereyoucreatethisMethod.

Page 35: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

35 WorkingwithDatabasesinASP.NET

Tutorial:ASP.NETandWebProgramming

AllkindogconfigurationshouldbestoredintheWeb.configfile,includingDatabaseConnectionStrings,etc.

Page 36: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

36

8 WebServicesInordertosharedatabetweendevicesoverInternet,WebServicesisthesolution.

InASP.NETthereareseveralalternativesforcreatingsuchWebServices.

SeetheTutorial“WebServiceswithExamples”formoredetails.

VisualStudioandASP.NEThaspowerfulfeaturesforcreatingWebServices:

• ASMXWebService(TraditionalWebWerviceusingSOAP)• ASP.NETWebAPI(ThemodernWebServiceusingREST,Web2.0)

Page 37: ASP.NET and Web Programming · PDF file · 2017-11-284.4 ASP.NET MVC ... C# is very similar to C++ and Java. ... ASP.NET and Web Programming Code Editor: 2.2.6 Properties window

ASP.NETWebProgramming

Hans-PetterHalvorsen

Copyright©2017

E-Mail:[email protected]

Web:https://www.halvorsen.blog

https://www.halvorsen.blog