* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download ASP.NET and Web Programming
Microsoft Jet Database Engine wikipedia , lookup
Microsoft Access wikipedia , lookup
Relational model wikipedia , lookup
Clusterpoint wikipedia , lookup
Database model wikipedia , lookup
Team Foundation Server wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
UniversityCollegeofSoutheastNorway ASP.NET WebProgramming Hans-PetterHalvorsen,2016.11.01 http://home.hit.no/~hansha TableofContents 1 Introduction........................................................................................................................4 1.1 VisualStudio.................................................................................................................4 1.2 C#.................................................................................................................................5 1.3 .NETFramework...........................................................................................................5 1.4 Object-OrientedProgramming(OOP)..........................................................................5 2 VisualStudio........................................................................................................................7 2.1 Introduction.................................................................................................................7 2.2 GettingStarted.............................................................................................................7 2.2.1 IntegratedDevelopmentEnvironment(IDE)........................................................7 2.2.2 NewProject...........................................................................................................8 2.2.3 SolutionExplorer...................................................................................................9 2.2.4 Toolbox..................................................................................................................9 2.2.5 EditorsandDesigners..........................................................................................10 2.2.6 Propertieswindow..............................................................................................11 2.2.7 BuildandDebugTools.........................................................................................12 3 IntroductiontoWebProgramming...................................................................................13 3.1 Introduction...............................................................................................................13 3.2 WebBrowser..............................................................................................................14 3.3 HTML..........................................................................................................................14 3.4 CSS..............................................................................................................................15 3.5 JavaScript...................................................................................................................15 2 3 TableofContents 3.6 ASP.NET......................................................................................................................16 3.7 AJAX/ASP.NETAJAX...................................................................................................16 3.8 Silverlight....................................................................................................................16 4 IntroductiontoASP.NET...................................................................................................18 4.1 Introduction...............................................................................................................18 4.2 ASP.NETWebPages...................................................................................................20 4.3 ASP.NETSPA...............................................................................................................20 4.4 ASP.NETMVC.............................................................................................................20 4.5 ASP.NETWebForms..................................................................................................21 5 ASP.NETWebForms.........................................................................................................22 5.1 HelloWorldExample..................................................................................................22 6 InternetInformationServices(IIS)....................................................................................26 6.1 WebServer.................................................................................................................26 7 WorkingwithDatabasesinASP.NET.................................................................................27 7.1 DatabaseSystems......................................................................................................27 7.1.1 MirosoftSQLServer............................................................................................27 7.2 SQL.............................................................................................................................27 7.3 SQLServer+ASP.NET.................................................................................................29 7.3.1 SimpleDatabaseExamplee.................................................................................29 7.4 ADO.NET.....................................................................................................................31 7.4.1 Example...............................................................................................................31 8 WebServices.....................................................................................................................35 9 Example:WeatherSystem................................................................................................36 Tutorial:ASP.NETandWebProgramming 1 Introduction ASP.NETisaframeworkforcreatingwebsites,appsandserviceswithHTML,CSSand JavaScript. 1.1 VisualStudio MicrosoftVisualStudioisanintegrateddevelopmentenvironment(IDE)fromMicrosoft.It canbeusedtodevelopconsoleandgraphicaluserinterfaceapplicationsalongwith WindowsFormsapplications,websites,webapplications,andwebservicesinbothnative codetogetherwithmanagedcodeforallplatformssupportedbyMicrosoftWindows, WindowsPhone,WindowsCE,.NETFramework,.NETCompactFrameworkandMicrosoft Silverlight. Belowweseetheintegrateddevelopmentenvironment(IDE)inVisualStudio: Newprojectsarecreatedfromthe“NewProject”window: 4 5 Introduction 1.2 C# C#ispronounced“seesharp”.C#isanobject-orientedprogramminglanguageandpartof the.NETfamilyfromMicrosoft.C#isverysimilartoC++andJava.C#isdevelopedby MicrosoftandworksonlyontheWindowsplatform. 1.3 .NETFramework The.NETFramework(pronounced“dotnet”)isasoftwareframeworkthatrunsprimarilyon MicrosoftWindows.Itincludesalargelibraryandsupportsseveralprogramminglanguages whichallowlanguageinteroperability(eachlanguagecanusecodewritteninother languages).The.NETlibraryisavailabletoalltheprogramminglanguagesthat.NET supports.Programswrittenforthe.NETFrameworkexecuteinasoftwareenvironment, knownastheCommonLanguageRuntime(CLR),anapplicationvirtualmachinethat providesimportantservicessuchassecurity,memorymanagement,andexceptionhandling. TheclasslibraryandtheCLRtogetherconstitutethe.NETFramework. 1.4 Object-OrientedProgramming(OOP) Tutorial:ASP.NETandWebProgramming 6 Introduction Object-orientedprogramming(OOP)isaprogramminglanguagemodelorganizedaround "objects"ratherthan"actions"anddataratherthanlogic.Historically,aprogramhasbeen viewedasalogicalprocedurethattakesinputdata,processesit,andproducesoutputdata. ThefirststepinOOPistoidentifyalltheobjectsyouwanttomanipulateandhowthey relatetoeachother,anexerciseoftenknownasdatamodeling.Onceyou'veidentifiedan object,yougeneralizeitasaclassofobjectsanddefinethekindofdataitcontainsandany logicsequencesthatcanmanipulateit.Eachdistinctlogicsequenceisknownasamethod.A realinstanceofaclassiscalledan“object”oran“instanceofaclass”.Theobjectorclass instanceiswhatyouruninthecomputer.Itsmethodsprovidecomputerinstructionsand theclassobjectcharacteristicsproviderelevantdata.Youcommunicatewithobjects-and theycommunicatewitheachother. ImportantfeatureswithOOPare: • • • • ClassesandObjects Inheritance Polymorphism Encapsulation Simulawasthefirstobject-orientedprogramminglanguage.Simulawasdevelopedinthe 1960sbyKristenNygaardfromNorway. Java,Python,C++,VisualBasic.NETandC#arepopularOOPlanguagestoday. SinceSimula-typeobjectsarereimplementedinC++,JavaandC#theinfluenceofSimulais oftenunderstated.ThecreatorofC++(1979),BjarneStroustrup(fromDenmark),has acknowledgedthatSimulawasthegreatestinfluenceonhimtodevelopC++. Tutorial:ASP.NETandWebProgramming 2 VisualStudio 2.1 Introduction HomepageofVisualStudio:http://www.microsoft.com/visualstudio ThereexistdifferentversionsofVisualStudio,suchasVisualStudioExpress(free),Visual StudioProfessional,VisualStudioPremiumandVisualStudioUltimate. 2.2 GettingStarted 2.2.1 IntegratedDevelopmentEnvironment(IDE) TheVisualStudioproductfamilysharesasingleintegrateddevelopmentenvironment(IDE) thatiscomposedofseveralelements:theMenubar,Standardtoolbar,varioustoolwindows dockedorauto-hiddenontheleft,bottom,andrightsides,aswellastheeditorspace.The toolwindows,menus,andtoolbarsavailabledependonthetypeofprojectorfileyouare workingin. BelowweseetheVisualStudioIDE(IntegratedDevelopmentEnvironment): 7 8 2.2.2 VisualStudio NewProject Thefirstthingyoudowhenyouwanttocreateanewapplicationistocreateanewproject. ThiscanbedonefromtheStartPage: OrfromtheFilemenu: Thenthe“NewProject”windowappears: Tutorial:ASP.NETandWebProgramming 9 VisualStudio Inthiswindowyouwillselectanappropriatetemplatebasedonwhatkindofapplicationyou wanttocreate,andanameandlocationforyourprojectandsolution. Themostcommonapplicationsare: • • • • • WindowsFormApplication ConsoleApplication WPFApplication ASP.NETWebApplication SilverlightApplication 2.2.3 SolutionExplorer Solutionsandprojectscontainitemsthatrepresentthereferences,dataconnections, folders,andfilesthatyouneedtocreateyourapplication.Asolutioncontainercancontain multipleprojectsandaprojectcontainertypicallycontainsmultipleitems. 2.2.4 Toolbox TheToolboxcontainsallthenecessarycontrols,etc.youneedtocreateyouruserinterface. SeeFigurebelow. Tutorial:ASP.NETandWebProgramming 10 VisualStudio TheToolboxcontainsallthecontrols,etc.wecanuse inouruserinterface. Inordertousetheminouruserinterface,wejustdrag anddropthemtothe“Form”,asshownbelow: 2.2.5 EditorsandDesigners VisualStudiohasdifferenteditorsanddesigntools. GraphicalUserInterfaceDesigner: Tutorial:ASP.NETandWebProgramming 11 VisualStudio CodeEditor: 2.2.6 Propertieswindow EachcontrolwehaveonouruserinterfacehaslotsofPropertieswecanset. ThisisdoneinthePropertieswindow: Tutorial:ASP.NETandWebProgramming 12 2.2.7 VisualStudio BuildandDebugTools InVisualStudiowehavelotsofBuildandDebuggingTools. Buildmenu: BelowweseetheBuildmenu: Themostusedtoolis“BuildSolution”(ShortcutKey:F6). Debugmenu: BelowweseetheDebugmenu: Themostusedtoolis“StartDebugging”(ShortcutKey:F5). Tutorial:ASP.NETandWebProgramming 3 IntroductiontoWeb Programming 3.1 Introduction TodaymostoftheapplicationsfocusontheInternet,wheretheapplicationscanbeviewed inastandardWebBrowser.StaticWebpagesarebasedonHTMLandCSS.Inordertocreate moreadvancedapplications,weneedmorepowerfultools. Ausefulwebsiteforlearningmoreaboutwebdevelopment:http://www.w3schools.com Importantframeworksandtoolsforcreatingdynamicwebpages: • • • ASP.NET AJAX/ASP.NETAJAX JavaScript 13 14 • IntroductiontoWeb Silverlight Theseframeworksandtoolswillbeexplainedbelow. 3.2 WebBrowser ThepurposeofawebbrowseristoreadHTMLdocumentsandcomposethemintovisualor audiblewebpages.ThebrowserdoesnotdisplaytheHTMLtags,butusesthetagsto interpretthecontentofthepage. TodaywehavethefollowingmajorWebBrowsers: • • • • • InternetExplorer(byMicrosoft) Firefox(byMozilla) Chrome(byGoogle) Safari(byApple) Opera(byOperafromNorway) 3.3 HTML HTML,whichstandsforHyperTextMarkupLanguage,isthepredominantmarkuplanguage forwebpages.HTMListhebasicbuilding-blocksofwebpages. Tutorial:ASP.NETandWebProgramming 15 IntroductiontoWeb HTMLiswrittenintheformofHTMLelementsconsistingoftags,enclosedinanglebrackets (like<html>),withinthewebpagecontent.HTMLtagsnormallycomeinpairslike<h1>and </h1>.Thefirsttaginapairisthestarttag,thesecondtagistheendtag(theyarealso calledopeningtagsandclosingtags).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 CSS WebbrowserscanalsorefertoCascadingStyleSheets(CSS)todefinetheappearanceand layoutoftextandothermaterial. TheW3C,maintainerofboththeHTMLandtheCSSstandards AusefulwebsiteforlearningmoreaboutCSS:http://www.w3schools.com/css 3.5 JavaScript JavaScriptisanobject-orientedscriptinglanguagebasicallyusedtocreatedynamicweb pages.JavaScriptisprimarilyusedintheformofclient-sideJavaScript,implementedaspart ofawebbrowserinordertoprovideenhanceduserinterfacesanddynamicwebsites. 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(); } Tutorial:ASP.NETandWebProgramming 16 IntroductiontoWeb </script> </body> </html> AusefulwebsiteforlearningmoreaboutJavaScript:http://www.w3schools.com/js 3.6 ASP.NET ASP.NETisawebapplicationframeworkdevelopedbyMicrosofttoallowprogrammersto builddynamicwebsites,webapplicationsandwebservices. ASP.NETispartoftheVisualStudiopackage. ItwasfirstreleasedinJanuary2002withversion1.0ofthe.NETFramework,andisthe successortoMicrosoft'sActiveServerPages(ASP)technology.ASP.NETisbuiltonthe CommonLanguageRuntime(CLR),allowingprogrammerstowriteASP.NETcodeusingany supported.NETlanguage,suchasC#andVB.NET. ASP.NETwebpagesorwebpage,knownofficiallyasWebForms],arethemainbuildingblock forapplicationdevelopment.Webformsarecontainedinfileswithan“.aspx”extension. 3.7 AJAX/ASP.NETAJAX AJAXisanacronymforAsynchronousJavaScriptandXML.AJAXisagroupofinterrelated webdevelopmentmethodsusedontheclient-sidetocreateinteractivewebapplications. WithAjax,webapplicationscansenddatato,andretrievedatafrom,aserver asynchronously(inthebackground)withoutinterferingwiththedisplayandbehaviorofthe existingpage. ASP.NETAJAXisasetofextensionstoASP.NETdevelopedbyMicrosoftforimplementing AJAXfunctionality. 3.8 Silverlight MicrosoftSilverlightisanapplicationframeworkforwritingandrunningbrowserplug-insor otherrichinternetapplications,withfeaturesandpurposessimilartothoseofAdobeFlash. Therun-timeenvironmentforSilverlightisavailableasaplug-informostwebbrowsers. SilverlightisalsooneofthetwoapplicationdevelopmentplatformsforWindowsPhone7/8. ThelatestversionisSilverlight5.0. Tutorial:ASP.NETandWebProgramming 17 IntroductiontoWeb SilverlightisbasedonWPF,soinSilverlightapplications,userinterfacesaredeclaredin ExtensibleApplicationMarkupLanguage(XAML)andprogrammedusingasubsetofthe.NET Framework. Tutorial:ASP.NETandWebProgramming 4 IntroductiontoASP.NET 4.1 Introduction ASP.NETisawebapplicationframeworkdevelopedbyMicrosofttoallowprogrammersto builddynamicwebsites,webapplicationsandwebservices. ASP.NETisaframeworkfrocreatingwebsites,appsandserviceswithHTML,CSSand JavaScript. WebSite:http://www.asp.net ASP.NETsupportsdifferentapproachesformakingwebsitesorwebpages. • • • • ASP.NETWebPagesusesasinglepagemodelthatmixescodeandHTMLmarkup. ASP.NETSPA(SinglePageApplication) ASP.NETWebFormsusescontrolsandanevent-modelforcomponent-based development. ASP.NETMVC(ModelViewController)valuesseparationofconcernsandenables easiertest-drivendevelopment. Youcanmixandmatchthesetechniqueswithinoneapplicationdependingonyourneeds. 18 19 IntroductiontoASP.NET Video:http://www.asp.net/aspnet/overview/making-websites-with-aspnet/making-websites-with-aspnet NewWebProjectDialog: SelectProjectName,LoctionandSolutionName. Next,seelctthetemplateyouwanttouse. Tutorial:ASP.NETandWebProgramming 20 IntroductiontoASP.NET 4.2 ASP.NETWebPages InASP.NETWebPagesyouincludeservercodedirectlyintotheHTMLsyntax,similartoPHP andClassicASP. ASP.NETWebPagesusesSingePageModel(Theserver-sidecodeismixedinbetweenthe HTML).ItusesthetheRazorsyntax(.cshtmlfiles) AtoolcalledMicrosoftWebMatrixisoptimizedforthisdevelopmentmodel,butyoucan alsouseVisualStudioifyouwantto. http://www.w3schools.com/aspnet 4.3 ASP.NETSPA SPA–SinglePageApplication Formoreinformation:http://www.asp.net/single-page-application 4.4 ASP.NETMVC MVC–Model-View–Controller Tutorial:ASP.NETandWebProgramming 21 IntroductiontoASP.NET Anewdevelopmentmodelwhereyousplityourdevelopmentinto3parts/components: ModelsforData,ViewsforDisplayandControllersforInput. 4.5 ASP.NETWebForms ASP.NETissimiliartothedesktopdevelopmentmodelusedinWPF. GUI(*.aspxfiles)and Code(*.aspx.cs)isseparated. InthisdocumentwewillfocusonASP.NETWebForms. Tutorial:ASP.NETandWebProgramming 5 ASP.NETWebForms ThemainfocusinthistutorialwillbeASP.NETWebForms. 5.1 HelloWorldExample Whenyouarefinished,yourWebAppshouldlooksomethinglikethis: WhenyouenteryourNameintheTextBoxandclicktheOKButton,theprogramshould respondwithagreetings. SeelctCreateNewProject: 22 23 ASP.NETWebForms Youhavelotsofchoiceshere–butwejustwanttocreateaverysimpleWebFormApp. CreateNewWebForm: WinForm1.aspxPage:UsedtocreatetheGUI/HMI Tutorial:ASP.NETandWebProgramming 24 ASP.NETWebForms HelloworldExample–GUI: WebForm1.aspx.cs: Tutorial:ASP.NETandWebProgramming 25 ASP.NETWebForms RunningtheApplication(F5): Congratulations,youhavecreatedyourfirstASP.NETWebFormsapplication. Tutorial:ASP.NETandWebProgramming 6 InternetInformation Services(IIS) 6.1 WebServer Thetermwebservercanrefertoeitherthehardware(thecomputer)orthesoftware(the computerapplication)thathelpstodeliverwebcontentthatcanbeaccessedthroughthe Internet. Themostcommonuseofwebserversistohostwebsites,butthereareotherusessuchas gaming,datastorageorrunningenterpriseapplications. • • • • • IIS-InternetInformationServices, MicrosoftWindows ApacheWebServer, OpenSource, Cross-platform:UNIX,Linux,OSX,Windows,... Nginx (pronounced"enginex") -Hasbecomeverypopularlatly GWS(GoogleWebServer) etc. 26 7 WorkingwithDatabasesin ASP.NET Today,mostofthewebsitesandwebpagesusesadatabasetostoredatathatisvisibleon thewebpage,e.g.Facebook,Instagram,Twitter,etc. 7.1 DatabaseSystems Therearelotsofdifferentdatabasesystems,orDBMS–DatabaseManagementSystems, suchas: • • • • • • • • MicrosoftSQLServer o 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,whereSQL ServerExpressisfreetodownloadanduse.WewillfocusonSQLServerinthistutorial. 7.2 SQL SQL(StructuredQueryLanguage)isadatabasecomputerlanguagedesignedformanaging datainrelationaldatabasemanagementsystems(RDBMS). 27 28 WorkingwithDatabasesinASP.NET 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,manyofthedatabasesystemsthatexisttodayimplementtheir ownversionoftheSQLlanguage.InthisdocumentwewillusetheMicrosoftSQLServeras anexample. HerearesomeexamplesofSQLqueries: Tutorial:ASP.NETandWebProgramming 29 WorkingwithDatabasesinASP.NET InthisTutorialwewillfocusonMicrosoftSQLServer.SQLServerusesT-SQL(Transact-SQL). T-SQLisMicrosoft'sproprietaryextensiontoSQL.T-SQLisverysimilartostandardSQL,but inadditionitsupportssomeextrafunctionality,built-infunctions,etc. InordertousedatabasesinourapplicationsweneedtoknowStructuredQuerylanguage (SQL).FormoreinformationaboutSQL,seethefollowingTutorial:StructuredQuery Language(SQL) TheTutorialsareavailablefrom:http://home.hit.no/~hansha 7.3 SQLServer+ASP.NET SQLServer+ASP.NET=PowerfulWebApplications 7.3.1 SimpleDatabaseExamplee CreateaDatabasecalledLIBRARYandaBOOKtableinSQLServer.EntersomeTestdatainto theBOOKtable. Filla“GridView”withdatafromtheDatabaseTable(BOOK),asshownbelow Tutorial:ASP.NETandWebProgramming 30 WorkingwithDatabasesinASP.NET Usethe“Wizard”inordertocreateallthe“magic”youneedinyourapplication: Whenfinishingthe“Wizard”,your.aspxpageshouldlooksomethinglikethis Asyousee-NoCodeneededtobewritteninthisexampleJ Tutorial:ASP.NETandWebProgramming 31 WorkingwithDatabasesinASP.NET ThisisOKforquickdemos–butforprofessionalapplications,youneedtousesome hardcoreADO.NETorsimiliarframeworks. 7.4 ADO.NET ADO.NET(ActiveXDataObjectfor.NET)isasetofcomputersoftwarecomponentsthat programmerscanusetoaccessdataanddataservices.Itisapartofthebaseclasslibrary thatisincludedwiththeMicrosoft.NETFramework.Itiscommonlyusedbyprogrammersto accessandmodifydatastoredinrelationaldatabasesystems,thoughitcanalsoaccessdata innon-relationalsources. 7.4.1 Example Thistime:CreateeverythingfromscratchusingC#codeandADO.NET. Filla “DropDownList”withBookNamesfromtheDatabase PrinttheAuthorNamebasedon theselectedBookNameonthescreen,seebelow. Your.aspxpageshouldlooksomethinglikethis: Tutorial:ASP.NETandWebProgramming 32 WorkingwithDatabasesinASP.NET Your.aspx.cspageshouldlooksomethinglikethis: Tutorial:ASP.NETandWebProgramming 33 WorkingwithDatabasesinASP.NET ThePage_load()methodisexecutedwhentheWebPageisloaded.Inthissimpleexample weputallthecodeintotheEventHandlerfortheDropDownList.Thecodecouldbe improvedbycreatingaseparateClasswhereyouputthiscodeintoaMethod. TheFillBookListmethodisasfollows: ThecodecouldbeimprovedbycreatingaseparateClasswhereyoucreatethisMethod. Tutorial:ASP.NETandWebProgramming 34 WorkingwithDatabasesinASP.NET AllkindogconfigurationshouldbestoredintheWeb.configfile,includingDatabase ConnectionStrings,etc. Tutorial:ASP.NETandWebProgramming 8 WebServices InordertosharedatabetweendevicesoverInternet,WebServicesisthesolution. InASP.NETthereareseveralalternativesforcreatingsuchWebServices. SeetheTutorial“WebServiceswithExamples”formoredetails. VisualStudioandASP.NEThaspowerfulfeaturesforcreatingWebServices: • • ASMXWebService(TraditionalWebWerviceusingSOAP) ASP.NETWebAPI(ThemodernWebServiceusingREST,Web2.0) 35 9 Example:WeatherSystem BelowweseeanexampleofaWebSitecreatedinASP.NET.TheWebSitepresentweather datafromtheWeatherstationlocatedatTelemarkUniversityCollege. Formoreinformation,pleasevisit: http://home.hit.no/~hansha/weather.htm 36 Hans-PetterHalvorsen,M.Sc. E-mail:[email protected] Blog:http://home.hit.no/~hansha/ UniversityCollegeofSoutheastNorway www.usn.no