117
Unit -1 Views of Web Programming 1. Introduction to Server Side Programming What is server-side website programming? Web browsers communicate with web servers using the HyperText Transport Protocol (HTTP). When you click a link on a web page, submit a form, or run a search, an HTTP request is sent from your browser to the target server. The request includes a URL identifying the affected resource, a method that defines the required action (for example to get, delete, or post the resource), and may include additional information encoded in URL parameters (the field-value pairs sent via a query string), as POST data (data sent by the HTTP POST method), or in associated cookies. Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP response message. The response contains a status line indicating whether or not the request succeeded (e.g. "HTTP/1.1 200 OK" for success). The body of a successful response to a request would contain the requested resource (e.g. a new HTML page, or an image, etc...), which could then be displayed by the web browser. Static sites The diagram below shows a basic web server architecture for a static site (a static site is one that returns the same hard coded content from the server whenever a particular resource is requested). When a user wants to navigate to a page, the browser sends an HTTP "GET" request specifying its URL. The server retrieves the requested document from its file system and returns an HTTP response containing the document and a success status (usually 200 OK). If the file cannot be retrieved for some reason, an error status is returned (see client error reponses and server error reponses). Dynamic sites

Unit -1 Views of Web Programming 1. Introduction to Server

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Unit -1 Views of Web Programming 1. Introduction to Server

Unit-1

ViewsofWebProgramming

1.IntroductiontoServerSideProgramming

Whatisserver-sidewebsiteprogramming?

Web browsers communicate with web servers using theHyperTextTransportProtocol(HTTP).When you click a link on awebpage, submit a form, or run a search, anHTTPrequest is sent from your browser to the target server. The request includes a URLidentifyingtheaffectedresource,amethodthatdefinestherequiredaction(forexampletoget,delete,orposttheresource),andmayincludeadditionalinformationencodedinURLparameters (the field-value pairs sent via a query string), as POST data (data sent bytheHTTPPOSTmethod),orinassociatedcookies.Webserverswaitforclientrequestmessages,processthemwhentheyarrive,andreplytotheweb browserwith anHTTP responsemessage. The response contains a status lineindicatingwhetherornottherequestsucceeded(e.g."HTTP/1.1200OK"forsuccess).Thebodyofasuccessfulresponsetoarequestwouldcontaintherequestedresource(e.g.anewHTMLpage,oranimage,etc...),whichcouldthenbedisplayedbythewebbrowser.Staticsites

Thediagrambelowshowsabasicwebserverarchitecture forastaticsite (astaticsite isone that returns the same hard coded content from the server whenever a particularresourceisrequested).Whenauserwantstonavigatetoapage,thebrowsersendsanHTTP"GET"requestspecifyingitsURL.TheserverretrievestherequesteddocumentfromitsfilesystemandreturnsanHTTPresponsecontainingthedocumentandasuccessstatus(usually200OK).Ifthefilecannotberetrievedforsomereason,anerrorstatusisreturned(seeclienterrorreponsesandservererrorreponses).

Dynamicsites

Page 2: Unit -1 Views of Web Programming 1. Introduction to Server

Adynamicwebsiteisonewheresomeoftheresponsecontentisgenerateddynamicallyonlywhenneeded.OnadynamicwebsiteHTMLpagesarenormallycreatedby insertingdatafromadatabaseintoplaceholdersinHTMLtemplates(thisisamuchmoreefficientwayofstoring large amounts of content than using static websites). A dynamic site can returndifferentdataforaURLbasedoninformationprovidedbytheuserorstoredpreferences,andcanperformotheroperationsaspartofreturningaresponse(e.g.sendingnotifications).Mostofthecodetosupportadynamicwebsitemustrunontheserver.Creatingthiscodeisknownas"server-sideprogramming"(orsometimes"back-endscripting").Thediagrambelowshowsasimplearchitectureforadynamicwebsite.Asinthepreviousdiagram,browserssendHTTPrequeststotheserver,thentheserverprocessestherequestsandreturnsappropriateHTTPresponses.Requestsforstaticresourcesarehandledinthesamewayasforstaticsites(staticresourcesareanyfilesthatdon'tchange—typically:CSS,JavaScript,Images,pre-createdPDFfilesetc).

Requests fordynamicresourcesare instead forwarded(2) toserver-sidecode(shown inthediagramasaWebApplication).For"dynamicrequests"theserverinterpretstherequest,readsrequiredinformationfromthedatabase(3),combinestheretrieveddatawithHTMLtemplates(4),andsendsbackaresponsecontainingthegeneratedHTML(5,6).

1. WhyServerSideProgramming?Thoughitistechnicallyfeasibletoimplementalmostanybusinesslogicusingclientsideprograms,logicallyorfunctionallyitcarriesnogroundwhenitcomestoenterpriseapplications(e.g.banking,airticketing,e-shoppingetc.).Tofurtherexplain,goingbytheclientsideprogramminglogic;abankhaving10,000customerswouldmeanthateachcustomershouldhaveacopyoftheprogram(s)inhisorherPCwhichtranslatesto10,000programs!Inaddition,thereareissueslikesecurity,resourcepooling,concurrentaccessandmanipulationstothedatabasewhichsimplycannotbehandledbyclientsideprograms.Theanswertomostoftheissuescitedaboveis??ServerSideProgramming?.Figure-1illustratesServersidearchitectureinthesimplestterms.

Page 3: Unit -1 Views of Web Programming 1. Introduction to Server

2. AdvantagesofServerSideProgramsThelistbelowhighlightssomeoftheimportantadvantagesofServerSideprograms.i. AllprogramsresideinonemachinecalledtheServer.Anynumberofremote

machines(calledclients)canaccesstheserverprograms.ii. Newfunctionalitiestoexistingprogramscanbeaddedattheserversidewhich

theclients?canadvantagewithouthavingtochangeanythingfromtheirside.iii. Migratingtonewerversions,architectures,designpatterns,addingpatches,

switchingtonewdatabasescanbedoneattheserversidewithouthavingtobotheraboutclients?hardwareorsoftwarecapabilities.

iv. Issues relating to enterprise applications like resource management,concurrency,sessionmanagement,securityandperformancearemanagedbyservicesideapplications.

v. Theyareportableandpossessthecapabilitytogeneratedynamicanduser-basedcontent(e.g.displayingtransactioninformationofcreditcardordebitcarddependingonuser?schoice).

3. TypesofServerSidePrograms

Ø ActiveServerPages(ASP)Ø JavaServletsØ JavaServerPages(JSPs)Ø EnterpriseJavaBeans(EJBs)Ø PHP

To summarize, the objective of server side programs is to centrally manage allprograms relating to a particular application (e.g. Banking, Insurance, e-shopping,etc). Clients with bare minimum requirement (e.g. Pentium II, Windows XPProfessional,MSInternetExplorerandan internetconnection)canexperiencethepowerandperformanceof aServer (e.g. IBMMainframe,UnixServer, etc) fromaremote location without having to compromise on security or speed. More

Page 4: Unit -1 Views of Web Programming 1. Introduction to Server

importantly,serverprogramsarenotonlyportablebutalsopossessthecapabilitytogeneratedynamicresponsesbasedonuser’srequest.

2.BrowserObject

ObjectBrowserTheObjectBrowserletsyouselectandexaminethenamespaces,classes,methods,andotherprogrammingsymbolsavailableforuseinyourproject.YoucanopentheObjectBrowserfromtheViewmenu,byclickingtheObjectBrowserbuttononthemaintoolbar,orbytypingCTRL+ALT+J.Therearethreepanes:anObjectspaneontheleft,aMemberspaneontheupperright,andaDescriptionpaneonthelowerright.IfyouresizetheObjectBrowserintoasinglecolumn,theObjectspanemovestothetop,theMemberspanetothemiddle,andtheDescriptionpanetothebottom.IntheObjectspane,iconsidentifyhierarchicalstructuressuchas.NETFrameworkandCOMcomponents,namespaces,typelibraries,interfaces,enums,andclasses.Youcanexpandthesestructurestorevealorderedlistsoftheirmembers.Properties,methods,events,variables,constants,andothercontaineditemsarelistedintheMemberspane.DetailsontheitemselectedintheObjectspaneorMemberspaneappearintheDescriptionpane.Thebrowsingscopedropdownlistletsyouspecifyany.NETFrameworkversioninstalledonyourcomputer.Itcanalsobenarrowedtotheprojectsyouaredevelopingandthecomponentstheyreference,orexpandedtoincludeallofthe.NETFramework,allCOMcomponentsinstalledonyourcomputer,andallexternalcomponentsthatyoucanaccess.Youalsocanspecifyacustomsetoffolderstobrowse.Formoreinformation,seeHowto:ModifytheBrowsingScopeintheObjectBrowser.FormoreinformationabouthowtousetheObjectBrowser,seeBrowsingThroughCodeandComponents.Foraguidetotheiconsdisplayed,seeClassViewandObjectBrowserIcons.Thistopicisorganizedintothefollowingsections:

• ObjectBrowserToolbar• ObjectsPane• MembersPane• DescriptionPane• SymbolHelp

ObjectBrowserToolbarTheObjectBrowsertoolbarletsyoudefinethebrowsingscope,searchforobjects,navigateintheObjectsandMemberspanes,addreferencestoaproject,selectalogicalorphysicalview,selectitemstobedisplayed,andsortthoseitemsasyouwant.BrowseMenu

Page 5: Unit -1 Views of Web Programming 1. Introduction to Server

SpecifiesthebrowsingscopefortheObjectspane.Youcannarrowthescopetothecurrentsolution,orexpandthescopetoincludeeveryavailablecomponent.Withinanyscope,youcanuseSearch todisplaya subsetof theavailable components.YoualsocanselectEditCustomComponentSettodefinetheCustomComponentSetbrowsingscope.

AllComponents

Displaysobjectsinallofthe.NETFramework,thecurrentsolutionanditsreferencedcomponents, and any other components that you have added by selecting EditCustomComponentSet.

<FrameworkVersions>

Youcanselecttodisplayobjectsforaspecificversionofthe.NETFrameworkandthe.NETCompactFramework. For example, if youhave .NETFramework2.0 and the.NET Framework 3.0 on your computer, you can choose to display only .NETFramework3.0.Registeredthird-partyframeworksmayalsobedisplayed.

MySolution

Displaysobjectsinthecurrentsolutionanditsreferencedcomponents.CustomComponentSet

DisplaysobjectsinanycomponentsthatyouhaveaddedbyselectingEditCustomComponentSet.

EditCustomComponentSet

DisplaystheEditCustomComponentSetDialogBox.YoualsocanclicktheBrowse(...)buttontodisplaythisdialogbox.Allowsyoutoselectobjecthierarchiesfromyourprojects, from components referenced in your projects, and from externalcomponents.

SearchMenuTheSearchmenuletsyoulocateobjectsintheObjectspane.Youcaneitherselectaprevioussearchstringorenteranewone.TheresultsaredisplayedintheObjectspaneasafilteredsublistofitsoriginalcontent.ToredisplaythecompleteBrowsescope,clickClearSearch.Asearch returns all symbol names in the current browsing scopewhere the search stringmatchesanypartofthesymbolname.Forexample,asearchonthestring"MyObject"willreturnthenames"MyObject,""MyObjectTest"and"CMyObject."Searchesarecase-sensitive.SearchString

Allowsyoutoselectastringfromthedropdownmenu,ortoenteranewsearchstring.Youcanenterthefullnameofasymbolorasubstringthatappearsinmanysymbols.

Search

Click this button to display just those objects in theBrowse scopewhose namesincludetheSearchString.Thestringishighlightedineachsymbolnamewhereitismatched.

ClearSearch

Page 6: Unit -1 Views of Web Programming 1. Introduction to Server

ClickthisbuttontocleartheSearchStringfieldanddisplayallavailableobjectsintheBrowsescope.

ToolbarButtonsTheObjectBrowsertoolbarbuttonsletsyounavigateintheObjectspaneandtheMemberspane,andtoaddreferencestoaproject.

Back

Navigatestothepreviouslyselecteditem.Keepclickingthisbuttontonavigatethroughpreviouslyselecteditemsuntilyoureachthefirstitembrowsed.TheBackandForwardbuttonsmovethroughahistorylistofpreviouslybrowseditems.

Forward

BecomesavailablewhenyouclicktheBackbutton.Navigatestothenextitemselected.Keepclickingthisbuttontoreturntothemostrecentitemselected.TheBackandForwardbuttonsmovethroughahistorylistofitemspreviouslybrowsed.

AddtoReferencesinSelectedProject

InsertsareferencetotheselectedcomponentintotheprojectcurrentlyselectedinSolutionExplorer.Formoreinformation,seeHowto:AddorRemoveReferencesinVisualStudio.

ObjectBrowserSettingsTheObjectBrowserSettingsmenuontheObjectBrowsertoolbarletsyouselectaparticularviewoftheobjectsinthecurrentBrowsescope,andtospecifywhichoftheavailableobjectswillbedisplayed.Theavailablechoicesareinthefollowinglist.SomeofthesecommandsarealsoavailablefromtheshortcutmenusintheObjectsandMemberspanes.ViewNamespaces

Whenselected,thehighest-levelitemsintheObjectspanearelogicalnamespaces.Namespacesstoredinmultiplephysicalcontainersaremerged.Theseexpandtoshowtheclasstypesthatarecontained.

ViewContainers

Whenselected,thehighest-levelitemsintheObjectspanearephysicalcontainers,suchascomponents,assemblies,sourcebrowser(.bsc)files,andoutputtypelibraries(.tlb).Theseexpandtoshowthenamespacesthatarecontained.

ShowBaseTypes

TogglesdisplayofbasetypesintheObjectspane.

Page 7: Unit -1 Views of Web Programming 1. Introduction to Server

ShowDerivedTypes

TogglesdisplayofderivedtypesintheObjectspane.AvailableonlyforVisualC++projectsandthe.NETFramework.

ShowHiddenTypesandMembers

TogglesdisplayofhiddentypesintheObjectspaneandhiddenmembersintheMemberspane.

ShowPublicMembers

Membersthatarepublicaredisplayedforuserswhoareusingtheclasses.ShowProtectedMembers

Membersthatarepublicorprotectedaredisplayedforuserswhoareextendingtheclasses.

ShowPrivateMembers

Membersofallaccessibilitylevelsaredisplayedforuserswhoareimplementingandusingtheclasses.

ShowOtherMembers

Membersthatdonotfallintothecategoryofpublic,protected,private,orinheritedaredisplayed.Examples:InthefollowingVisualBasiccode,"Friend"isincludedinthiscategory:FriendSubTest()EndSubInthefollowingVisualC#code,"internal"isincludedinthiscategory:internalvoidInternalF(){}

ShowInheritedMembers

TogglesdisplayofinheritedmembersintheMemberspane.ShowExtensionMethods

TogglesthedisplayofextensionmethodsintheMemberspane.Formoreinformation,seeExtensionMethods(C#ProgrammingGuide)andExtensionMethods(VisualBasic).

ObjectsPaneTheObjectspanedisplaysanexpandablelistofsymbolswhosetop-levelnodesrepresentcomponentsornamespacesavailableinthecurrentbrowsingscope.Thesetop-levelnodestypicallycontainsymbolsthatcontainothersymbols.Toexpandanodeselectedinthelist,clickitsplus(+)signorpresstheplus(+)keyonthekeypad.WhenyouselectanitemintheObjectspane,itsmembersaredisplayedintheMemberspane,anddetailsontheitemappearintheDescriptionpane.Expandinganodeprovidesadditionalinformationaboutasymbol.Whenyouexpandacomponent,itsnamespacesarelisted.Expandinganamespaceliststheclassesthataredefinedinit.Baseclasses,implementedinterfaces,extensionmethods,andavailableoverridesarealsolisted.Nestedobjectsareflattenedandlistedaspeers.Forexample,ifparentclassCMyClassincludesasubclassCNestedClass,thesetwoclassesaredisplayedassiblingswithintheir

Page 8: Unit -1 Views of Web Programming 1. Introduction to Server

namespace.TheirObjectBrowsernodesarelabeledCMyClassandCMyClass::CnestedClassinVisualC++andCMyClass.CnestedClassinVisualC#andVisualBasic,toindicatethattheformerclasscontainsthelatter.ObjectsPaneShortcutMenuRight-clickingasymboldisplaystheObjectspaneshortcutmenu.InadditiontotheObjectBrowserSettingscommandslistedearlier,oneormoreofthefollowingcommandscanappearonthismenu,dependingonthesymbolselected:

BrowseDefinition

Takesyoutotheprimarynode(typicallytoplevel)fortheselectedsymbolintheObjectBrowser.

FindAllReferences

PerformsasearchonthecurrentlyselectedobjectsymbolusingtheoptionsspecifiedontheFindSymbol,FindandReplaceWindow.DisplaysresultsintheFindSymbolResultsWindowwindow.

FilterToType

DisplaysonlytheselectedtypeintheObjectspane,andthemembersofthattypeintheMemberspane.

Copy

Copiesasymbolreferencethatcanbepastedintoadesigner;alsocopiesthefullpathandnameoftheselecteditemtotheClipboard.

Remove

LetsyouremoveanexternalcomponentfromthecurrentbrowsingscopebyusingtheSelectedComponentsdialogbox.

ViewNamespaces

Whenselected,thehighest-levelitemsintheObjectspanearelogicalnamespaces.Namespacesstoredinmultiplephysicalcontainersaremerged.Theseexpandtoshowtheclasstypesthatarecontained.

ViewContainers

Whenselected,thehighest-levelitemsintheObjectspanearephysicalcontainers,suchasprojects,components,assemblies,sourcebrowser(.bsc)files,andoutputtypelibraries(.tlb).Thesecanbeexpandedtoshowthenamespacestheycontain.

SortAlphabetically

Objectsarelistedalphabeticallybytheirnamesinascendingorder(AtoZ).SortbyObjectType

Objectsarelistedinorderoftheirtype,suchasbaseclasses,followedbyderivedclasses,interfaces,methods,andsoforth.

SortbyObjectAccess

Page 9: Unit -1 Views of Web Programming 1. Introduction to Server

Objectsarelistedinorderoftheiraccesstype,suchaspublicorprivate.GroupbyObjectType

Objectsaresortedintogroupsbytype,suchasclasses,interfaces,properties,methods,andsoforth.

GoToDeclaration

Takesyoutothedeclarationofthesymbolinthecode,ifavailable.ThisisavailableonlyinVisualC++projects.

GoToDefinition

Takesyoutothedefinitionofthesymbolinthecode,ifavailable.GoToReference

Takesyoutoareferencetothesymbolinthecode,ifavailable.MembersPaneEachobjectcancontainsuchmembersasproperties,methods,events,constants,variables,andenumvalues.SelectinganobjectintheObjectspanedisplaysitsmembersintheMemberspane.DetailsontheitemselectedintheMemberspaneappearintheDescriptionpane.MembersPaneShortcutMenuRight-clickanymemberintheMemberspanetodisplaytheshortcutmenu.Thismenuletsyousearch,sort,andcopymembersindependentlyfromtheirparentobjects.Thisshortcutmenualsoincludescommandsthatletyouspecifywhichmemberstodisplay,forexamplewhethertoviewhiddenorinheritedmembers.

FindAllReferences

PerformsasearchonthecurrentlyselectedmembersymbolusingtheoptionsspecifiedontheFindSymbol,FindandReplaceWindow.DisplaysresultsintheFindSymbolResultsWindowwindow.

Copy

Copiesasymbolreferencethatcanbepastedintoadesigner;alsocopiesthefullpathandnameoftheselecteditemtotheClipboard.

GroupByMemberType

Membersareorganizedbytype.ShowPublicMembers

Membersthatarepublicaredisplayedforuserswhoareusingtheclasses.ShowProtectedMembers

Membersthatarepublicorprotectedaredisplayedforuserswhoareextendingtheclasses.

ShowPrivateMembers

Page 10: Unit -1 Views of Web Programming 1. Introduction to Server

Membersofallaccessibilitylevelsaredisplayedforuserswhoareimplementingandusingtheclasses.

ShowOtherMembers

Membersthatdonotfallintothecategoryofpublic,protected,private,orinheritedaredisplayed.Examples:InthefollowingVisualBasiccode,"Friend"isincludedinthiscategory:FriendSubProcedure()EndSubInthefollowingVisualC#code,"internal"isincludedinthiscategory:internalvoidInternalF(){}

ShowInheritedMembers

TogglesdisplayofinheritedmembersintheMemberspane.SortAlphabetically

Membersarelistedalphabeticallybytheirnamesinascendingorder(AtoZ).SortbyMemberType

Membersarelistedinorderoftheirtype,suchasbases,followedbyinterfaces,followedbymethods,andsoforth.

SortbyMemberAccess

Membersarelistedinorderoftheiraccesstype,suchaspublicorprivate.DescriptionPaneTheDescriptionpanedisplaysdetailedinformationaboutthecurrentlyselectedobjectormember.YoucancopydatafromtheDescriptionpanetotheClipboard,andthenpasteitintotheCodeEditor.Theinformationdisplayeddependsontheselectionandcanincludethefollowing:

• Nameandparentobject.• Propertiesandattributes.• Syntaxintheprogramminglanguageoftheactiveproject.• Linkstorelatedobjectsandmembers.• Descriptions,comments,andHelptext.• Versionofthe.NETFrameworkinwhichtheobjectormemberisincluded.

Thetypeofsymbolselecteddetermineswhatinformationisdisplayed.BrowseDefinitionTheBrowseDefinitioncommandisavailableontheshortcutmenuoftheDescriptionpane,andfordeeplynestednodesintheObjectBrowser.ItisalsoavailableontheshortcutmenusoftheCodeEditor,ClassView,andtheFindSymbolResultswindowwhenasymbolisselected.Ifthesymbolisdefinedinyourcode,thesourcefileopensintheCodeEditorandscrollstothedefinition.Ifthesymbolisa.NETFrameworkclassorCOMcomponent,GoToDefinitionselectsitsprimarynodeintheObjectspane,listsitsmembersintheMemberspane,anddisplaysdetailsonthesymbolintheDescriptionpane.

3.ASPFundamentals

WhatisASP?

Page 11: Unit -1 Views of Web Programming 1. Introduction to Server

ASPstandsforActiveServerPages.MicrosoftintroducedActiveServerPagesinDecember1996,beginningwithVersion3.0.MicrosoftofficiallydefinesASPas:“ActiveServerPagesisanopen,compile-freeapplicationenvironmentinwhichyoucancombineHTML,scripts,andreusableActiveXservercomponentstocreatedynamicandpowerfulWeb-basedbusinesssolutions.ActiveServerpagesenablesserversidescriptingforIISwithnativesupportforbothVBScriptandJscript

4.UnderstandingActiveServerPagesObjectsandComponents

Introduction

COMcomponentsarethekeytobuildingpowerful,real-worldWebapplications.Componentsprovidefunctionalitythatyouuseinyourscriptstoperformspecializedtasks,suchasexecutingfinancialtransactionsorvalidatingdata.ASPalsoprovidesasetofbasecomponentsthatyoucanusetogreatlyenhanceyourscripts.AboutComponentsACOMcomponentisareusable,programmaticbuildingblockthatcontainscodeforperformingataskorsetoftasks.Componentscanbecombinedwithothercomponents(evenacrossnetworks)tocreateaWebapplication.COMcomponentsexecutecommontaskssothatyoudonothavetocreateyourowncodetoperformthesetasks.Forexample,youcanuseastocktickercomponenttodisplaythelateststockquotesonaWebpage.However,itwouldbedifficulttocreateascriptthatprovidesthesamefunctionality.Also,thescriptwouldnotbeasreusableasacomponent.

Advantages

Ifyouarenewtoscripting,youcanwritescriptsthatusecomponentswithoutknowinganythingabouthowthecomponentworks.ASPcomeswithbasecomponentsthatyoucanuseimmediately.Forexample,youcanusetheActiveXDataObjects(ADO)componentstoadddatabaseconnectivitytoyourWebpages.Additionalcomponentscanalsobeobtainedfromthird-partydevelopers.IfyouareaWebapplicationdeveloper,componentsarethebestwaytoencapsulateyourbusinesslogicintoreusable,securemodules.Forexample,youcoulduseacomponenttoverifycreditcardnumbersbycallingthecomponentfromascriptthatprocessessalesorders.Becausetheverificationisisolatedfromtheorderprocess,youcanupdatethecomponentwhenthecreditcardverificationprocesschanges,withoutchangingyourorderprocess.Also,sinceCOMcomponentsarereusable,youcouldreusethecomponentinotherscriptsandapplications.OnceyouhaveinstalledacomponentonyourWebserver,youcancallit

Page 12: Unit -1 Views of Web Programming 1. Introduction to Server

fromaASPserver-sidescript,anISAPIextension,anothercomponentontheserver,oraprogramwritteninanotherCOM-compatiblelanguage.YoucancreatecomponentsinanyprogramminglanguagethatsupportstheComponentObjectModel(COM),suchasC,C++,Java,VisualBasic,ornumerousscriptinglanguages.(IfyouarefamiliarwithCOMprogramming,COMcomponentsarealsoknownasAutomationservers.)TorunontheWebserver,yourCOMcomponentscannothaveanygraphicaluserinterfaceelements,suchastheVisualBasicMsgBoxfunction;graphicalinterfaceelementswouldonlybeviewableontheserver,andnotthebrowser.CreatinganInstanceofaComponent'sObjectAcomponentisexecutablecodecontainedinadynamic-linklibrary(.dll)orinanexecutable(.exe)file.Componentsprovideoneormoreobjects,selfcontainedunitsofcodewhichperformspecificfunctionswithinthecomponent.Eachobjecthasmethods(programmedprocedures)andproperties(behaviouralattributes).

UsingObjects

Touseanobjectprovidedbyacomponent,youcreateaninstanceoftheobjectandassignthenewinstancetoavariablename.UsetheASPServer.CreateObjectmethodortheHTML<OBJECT>tagtocreatetheobjectinstance.Useyourscriptinglanguage'svariableassignmentstatementtogiveyourobjectinstanceaname.Whenyoucreatetheobjectinstance,youmustprovideitsregisteredname(PROGID).ForthebasecomponentsprovidedwithASP,youcangetthePROGIDfortheobjectsfromthereferencepages(seeInstallableComponentsforASP).Forexample,theAdRotatorcomponentrandomlyrotatesthroughaseriesofgraphicaladvertisements.TheAdRotatorcomponentprovidesoneobject,calledtheAdRotatorobject,whosePROGIDis"MSWC.AdRotator."TocreateaninstanceoftheAdRotatorobject,useoneofthefollowingstatements:VBScript:<%SetMyAds=Server.CreateObject("MSWC.AdRotator")%>JScript:<%varMyAds=Server.CreateObject("MSWC.AdRotator")%>IfyouarealreadyfamiliarwithVBScriptorJScript,notethatyoudonotusethescriptinglanguage'sfunctionforcreatinganewobjectinstance(CreateObjectinVBScriptorNewinJScript).YoumustusetheASPServer.CreateObjectmethod;otherwise,ASPcannottrackyouruseoftheobjectinyourscripts.

YoucanalsousetheHTML<OBJECT>tagtocreateanobjectinstance.YoumustsupplytheRUNATattributewithavalueofServer,andyoumustprovidetheIDattributesettothevariablenameyouwilluseinyourscripts.Youcanidentifytheobjectbyusingeitherits

Page 13: Unit -1 Views of Web Programming 1. Introduction to Server

registeredname(PROGID)oritsregisterednumber(CLSID).Thefollowingexampleusestheregisteredname(PROGID)tocreateaninstanceoftheAdRotatorobject:<OBJECTRUNAT=ServerID=MyAdsPROGID="MSWC.AdRotator"></OBJECT>Thefollowingexampleusestheregisterednumber(CLSID)tocreateaninstanceoftheAdRotatorobject:

<OBJECTRUNAT=SERVERID=MyAdsCLASSID="Clsid:1621F7C0-60AC-11CF-9427-444553540000"></OBJECT>

CreatingCOMcomponents

ASPsupportsWindowsScriptComponents,Microsoft'spowerfulscriptingtechnologythatyoucanusetocreateCOMcomponents.Specifically,youcanencapsulatecommonscripts,suchasthoseusedfordatabaseaccessorcontentgeneration,intoreusablecomponentsaccessiblefromany.aspfileorprogram.YoucancreateWindowsScriptComponentsbywritingscriptsinalanguagesuchasVBScriptorJScriptwithoutaspecialdevelopmenttool.YoucanalsoincorporateWindowsScriptComponentsintoprogramswritteninCOMcompliantprogramminglanguages,suchasVisualBasic,C++,orJava.ThefollowingisanexampleofaWindowsScriptComponents,writteninVBScript,thatdefinesmethodsforconvertingtemperaturemeasurementsbetweenFahrenheitandCelsius:<SCRIPTLET><RegistrationDescription="ConvertTemp"ProgID="ConvertTemp.Scriptlet"Version="1.00"></Registration><implementsid=Automationtype=Automation><methodname=Celsius><PARAMETERname=F/></method><methodname=Fahrenheit><PARAMETERname=C/></method></implements><SCRIPTLANGUAGE=VBScript>FunctionCelsius(F)Celsius=5/9*(F-32)EndFunction

Page 14: Unit -1 Views of Web Programming 1. Introduction to Server

FunctionFahrenheit(C)Fahrenheit=(9/5*C)+32EndFunction</SCRIPT></SCRIPTLET>BeforeimplementingthisWindowsScriptComponentyoumustsavethisfilewithan.sctextensionandtheninWindowsExplorer,right-clickthisfileandselectRegister.TousethisWindowsScriptComponentinaWebpage,youwoulduseaserver-sidescriptsuchasthefollowing:

<%OptionExplicitDimobjConvertDimsngFvalue,sngCvaluesngFvalue=50sngCvalue=21SetobjConvert=Server.CreateObject("ConvertTemp.Scriptlet")Response.WritesngFvalue&"degreesFahrenheitisequivalentto"&objConvert.Celsius(sngFvalue)&"degreesCelsius<br>"&vbNewLineResponse.WritesngCvalue&"degreesCelsiusisequivalentto"&objConvert.Fahrenheit(sngCvalue)&"degreesFahrenheit<br>"&vbNewLine%>

UsingBuilt-inASPobjects

ASPalsoprovidesbuilt-inobjectsforperformingusefultasksthatsimplifyWebdevelopment.Forexample,youcanusetheRequestobjecttoeasilyaccessinformationassociatedwithanHTTPrequest,suchasuserinputcomingfromHTMLformsorcookies.UnlikeusingtheobjectsprovidedbyaCOMcomponent,youdonotneedtocreateaninstanceofanASPbuilt-inobjecttouseitinyourscripts.TheseobjectsareautomaticallycreatedforyouwhentheASPrequeststartsprocessing.Youaccessthemethodsandpropertiesofabuilt-inobjectinthesamewayinwhichyouaccessthemethodsandpropertiesofacomponent'sobjects,asdescribedinthistopic.CallinganObjectMethodAmethodisanactionyoucanperformonanobjectorwithanobject.Thesyntaxforcallingamethodis:

Object.Methodparameters

Page 15: Unit -1 Views of Web Programming 1. Introduction to Server

Theparametersvarydependingonthemethod.Forexample,youcanusetheWritemethodoftheResponsebuilt-inobjecttosendinformationtothebrowserasshowninthefollowingstatement:

<%Response.Write"HelloWorld"%>NoteSomescriptinglanguagesdonotsupporttheObject.Methodsyntax.Ifyourlanguagedoesnot,youmustaddanentrytotheregistryinordertousethatlanguageasyourprimaryscriptinglanguage.SeeWorkingwithScriptingLanguagesformoreinformation.

SettinganObjectPropertyApropertyisanattributethatdescribestheobject.Propertiesdefineobjectcharacteristics,suchasthetypeoftheobject,ordescribethestateofanobject,suchasenabledordisabled.Thesyntaxis:Object.PropertyYoucansometimesreadandsetthevalueofaproperty.Inaddition,forsomeobjects,youcanalsoaddnewproperties.Forexample,theAdRotatorcomponenthasaproperty,Border,whichspecifieswhethertheadhasaborderarounditanddeterminestheborderthickness.

Thefollowingexpressionspecifiesnoborder:

<%MyAds.Border=0%>Forsomeproperties,youcandisplaythecurrentvaluebyusingtheASPoutputdirective.Forexample,thefollowingstatementreturnsTRUEifthebrowserisstillconnectedtotheserver:

<%=Response.IsClientConnected%>

5.RoleofHTTPProtocolinActiveServerPages

TheRoleofHTTP:->Httpisastatelessprotocol.ItisknownasHypertextTransferprotocol.Itisusedtosendtheclientrequesttothewebserver.AlltheBrowsersuchasgooglechrome,MozillaFirefox,NetscapeandInternetExplorerareclientsthathelpstosendarequesttothewebserver.Afterverificationofcredentials,webserverresponsetheclient'srequestthroughtheHTTPprotocol.

Page 16: Unit -1 Views of Web Programming 1. Introduction to Server

HTTPprotocoldoesnotmaintainthestateofdata.Whenthewebserverdisconnectthenitdoesnotmaintaindata,Itforgetthepreviousinteractions.TorememberthespecificinformationofwebserverASP.NETprovidesnumerouswaystohandlethestateinformationthroughthesessionvariables,cookiesandapplicationvariables.Therearesomeothernewtechniquethatrememberthestateasviewstatecontrolstateandcache.TheWebServer:->Awebserverisasoftwarethatheldyourwebapplication.Aserverwhichprovideswebservices,isknownaswebserver.Therearesomefeaturesarewebserver:-

§ Integratedsecurity§ FileTransferprotocol(FTP)§ MailExchangeServicesetc.Example:-

MicrosoftIISserveriswebserver.IthasintrinsicsupportforclassicASPaswellasASP.NETwebapplications.

WebApplication:->Awebapplicationisacollectionoffiles(*.html,*.aspx,*.asp,imagefilejquery,Databaseetc.).Awebapplicationshaveaspecificlifecycleandprovidenumerousevents.Awebapplicationreferstostatusofawebapplicationatanyinstantoftimepreservingapplication.Stateensuresthatthechangesmadebytheuserwheneverpageisreloaded.Inthistutorialiwilldiscussdifferent"statesofwebapplications".Statearecategorisedintoseveraltypesuchas:

§ Applicationstate§ sessionstate§ viewstateThatdependsonthenatureofinformationtheypreserve.WewillLearn"Global.aspx"filewhichisusedtoimplementapplication-levelandsessionlevelevents.Iwilldiscussthisfilewithareallifeexampleinnexttutorial.

StructureofanApplication:->

ThestructureofanASP.NETWebApplicationincludestheconceptsofthreestructure.

§ ApplicationDomain§ ApplicationLifetime§ ApplicationDirectory

1.)ApplicationDomain:->AnApplicationdomainisactuallyimplementbycommonlanguageRuntime(CLR).Theprimaryobjectiveoftheapplicationdomainistopreventconcurrentlyrunningapplicationsfromenteringintoeachothersdomain.Application

Page 17: Unit -1 Views of Web Programming 1. Introduction to Server

domainprovidesanisolationboundaryforapplication.Thebenefitofapplicationistheindependentexecutionofwebapplications.Themaincomponentsthatheldintheindependentexecutionofapplicationinvirtualdirectory.

Someprimaryapplicationentitiesthatarestoredinthevirtualdirectoryare:-

§ Webpage§ Configurationfiles§ Code-behindfiles§ Global.asaxfile

2.)TheApplicationLifetime:->Applicationlifetimereferstothetimespanforwhichanapplicationdomainpersists.

3.)TheApplicationDirectoryStructure:->Anefficientlydesigneddirectorystructureplaysakeyroleinwebapplicationdevelopment.Ifapplicationdirectoryisefficientthewecanusedallcodeandresourcesamongdifferentdirectorywithoutanyproblem.Theadvantageofusingdirectorystructureisenhancingthereusabilityofanapplication.Itbecomeseasyforyoutoupgradetheapplicationinlongperiodoftimebecauseofitscodefilesandapplicationresources.ASP.NET4.0supportadefaultdirectorystructurewhichprovidesseveralbuilt-indirectoriesforwebapplications.

§ Bin§ App_code§ App_GlobalResources§ App_LocalResources§ App_WebReferences§ App_Data§ App_Browsers§ App_ThemesTheGlobal.asaxApplicationFile:-

TheGlobal.asaxfileresidesintherootdirectoryofanASP.NETWebapplication.EventsStatus,suchasessionstateandapplicationarespecifiedintheGlobal.asaxfile.

§ DifferencebetweenGlobal.asaxfileandwebforms:-ThecodewithintheGlobal.asaxfiledoesnotcontainHTMLandASP.NETtagsinstead,thecodeinthisfilecontainsmethodswithpredefinednames.

ThevariousmethodscorrespondingtotheeventsthatoccursintheGlobal.asaxfilewhicharegivenbelow:-

§ BeginRequest()§ AuthenticateRequest()§ AuthorizeRequest()

Page 18: Unit -1 Views of Web Programming 1. Introduction to Server

§ ResolveRequestcache()§ AcquireRequeststate()§ UpdateRequestcache()§ ReleaseRequestState()§ EndRequest()§ Application_start()§ Session_start()§ Application_Error()§ Session_End§ Application_Disposed()

StatesinASP.NETApplication:-

StateisquiteaninnovativeconceptsinwebapplicationDevelopmentbecauseiteliminatesthedrawbackoflosingstatedataduetoreloadingofawebpage.wecanpreservethestatesoftheapplicationeitherattheserverorclientend.Thesateofawebapplicationhelpyoutostoretherunningtimechangesthathavebeenmadetowebpage.Therearevariousmethodsthatstorethestateinformationonaclientendwhicharegivenbelow:-

§ HiddenFields:->ThecontentofthecontrolissentintheHTTPFormcollectioncontrolalongwithvaluesofothercontrols.Thiscontrolactsasastorageareaforanypage_specificstoringinformation.IwilldiscussthisfieldsindetailsinNexttutorialswithexample.

§ Cookies:->Cookiesisatextfilethatstoredata,suchasuserIDandpreferencesattheclientend.IwilldiscussthisfieldindetailsinNexttutorialswithexample.

§ QueryStrings:-ItisusedtoreferstheinformationstringsaddedatthetheendofaURLtomaintainsthestateofawebapplication.QuerystringsisnotsecurebecausetheirvaluesareexposedtotheInternetthroughtheURL.IwilldiscussthisfieldindetailsinNexttutorials.

TherearevariousmethodsthatstorethestateinformationonaWebserverwhicharegivenbelow:-

• ApplicationState:-ItstoresapplicationdatanotfrequentlymodifiedbytheusersAnobjectoftheHttpApplicationStateclassisusedtostorethestateofASP.NETwebapplication.Iwilldiscussthisstateinnexttutorialwithexamples.

§ Sessionstate:-Itstoresthespecificinformationtoanusersession.AnobjectoftheHttpSessionStateclassisusedtoStorethesessionstateforeachASP.NETwebApplicationthatisexecuted.

§ Profileproperties:-Itstoresauserspecificdatainapersistentform.§ Viewstate:-Viewstatestorespage-specificinformation.whenapageispostedback

totheserver.

Page 19: Unit -1 Views of Web Programming 1. Introduction to Server

HTTPHandlers:-

Httphandlersisusedtohandletheuserrequestsforwebapplicationresources.wecandefinedHttphandlersinthe<HttpHandlers>elementofaconfigurationfile.TherearesomemethodsofIHttpHandlerinterface.

§ ProcessRequest():-ItinvolvedwhenauserrequestisreceivedItprocessestherequestusingtheHttpContextobject,whichispassedasaparameter.

§ IsReusable:-ItisusedtodeterminewhethertheHTTPHandlerobject,accessedusingthetheProcessrequest()method,canbereused.

6.UsingRequestandResponseObjects

RequestandResponsearethepropertiesofthePageclass.TheRequestpropertyallowsyoutoaccesstheHTTPRequestobject,whichcontainsinformation,suchaspathoftherequest,abouttheHTTPrequestforthepage.Itisainputstreamofclient.TheResponsepropertyallowsyoutoaccesstheHTTPResponseobject,whichinturnallowsyoutosenddatatothebrowser as the result of the request.It is an output stream of Client Infact,RequestandResponsepropertiesmapdirectlytoHttpRequestandHttpResponse objects respectively. Therefore, you can directly access these objects inASP.NET pages by using the Request and Response properties.Request=>ReadResponse=>Write

ResponseObjectYoucanusetheResponseobjecttosendoutputtotheclient.MethodsTheResponseobjectdefinesthefollowingmethods.

Method Description

Response.AddHeader SetstheHTMLheadernametovalue.

Response.AppendToLog AddsastringtotheendoftheWebserverlogentryforthisrequest.

Response.BinaryWrite WritesthegiveninformationtothecurrentHTTPoutputwithoutanycharacter-setconversion.

Response.Clear ErasesanybufferedHTMLoutput.

Page 20: Unit -1 Views of Web Programming 1. Introduction to Server

Response.End Stopsprocessingthe.aspfileandreturnsthecurrentresult.

Response.Flush Sendsbufferedoutputimmediately.

Response.Redirect Sendsaredirectmessagetothebrowser,causingittoattempttoconnecttoadifferentURL.

Response.Write WritesavariableortexttothecurrentHTTPoutputasastring.

PropertiesTheResponseobjectdefinesthefollowingproperties.

Property Description

Response.Buffer Indicateswhetherpageoutputisbuffered.

Response.CacheControl SetsaheadertonotifyproxyserversorothercachemechanismswhethertheycancachetheoutputgeneratedbyASP.

Response.Charset Appendsthenameofthecharactersettothecontent-typeheader.Thecharactersetspecifiesforthebrowserhowtodisplaycharacters.

Response.CodePage Setsthecodepagefordataintheintrinsicobjectsforoneresponse.Thecodepagespecifiesfortheserverhowtoencodecharactersfordifferentlanguages.

Response.ContentType SpecifiestheHTTPcontenttypefortheresponse.

Response.CookiesCollection

Specifiescookievalues.Usingthiscollection,youcansetcookievalues.

Response.Expires Specifiesthelengthoftimebeforeapagecachedonabrowserexpires.

Response.ExpiresAbsolute Specifiesthedateandtimeonwhichapagecachedonabrowserexpires.

Response.IsClientConnected Indicateswhethertheclienthasresettheconnectiontotheserver.

Page 21: Unit -1 Views of Web Programming 1. Introduction to Server

Response.LCID SetstheLCIDfordataforoneresponse.TheLCIDreferstohowdates,times,andcurrencyareformattedforaspecificgeographicallocale.

Response.PICS Setthevalueforthepics-labelresponseheadertoindicatethePICScontentrating.

Response.Status Thevalueofthestatuslinereturnedbytheserver.

RequestObjectTheRequestobjectretrievesthevaluesthattheclientbrowserpassedtotheserverduringanHTTPrequest.MethodsTheRequestobjectdefinesthefollowingmethod.

Method Description

Request.BinaryRead RetrievesdatasenttotheserverfromtheclientaspartofaPOSTrequest.

PropertiesTheRequestobjectdefinesthefollowingproperties.

Property Description

Request.ClientCertificateCollection

ThevaluesoffieldsstoredintheclientcertificatethatissentintheHTTPrequest.

Request.CookiesCollection ThevaluesofcookiessentintheHTTPrequest.

Request.FormCollection ThevaluesofformelementsintheHTTPrequestbody.

Request.QueryStringCollection

ThevaluesofvariablesintheHTTPquerystring.

Request.ServerVariablesCollection

Thevaluesofpredeterminedenvironmentvariables.

Request.TotalBytes Read-only;specifiesthetotalnumberofbytestheclientissendinginthebodyoftherequest.

Page 22: Unit -1 Views of Web Programming 1. Introduction to Server

ExampleProgram

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;publicpartialclassRequestResponse:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){}protectedvoidbtnResponse_Click(objectsender,EventArgse){Response.Write("<b><i>RequestType=</i></b>"+Request.RequestType+"</br></br>");Response.Write("<b><i>BrowserName=</b></i>"+Request.Browser.Type+"</br></br>");Response.Write("<b><i>IsJavaScriptSupport=</i></b>"+Request.Browser.JavaScript+"</br></br>");Response.Write("<b><i>IsCookiesSupport=</i></b>"+Request.Browser.Cookies+"</br></br>");Response.Write("<b><i>RequestType=</i></b>"+Request.RequestType+"</br></br>");Response.Write("<b><i>Language=</i></b>"+Request.UserLanguages[0]+"</br></br>");Response.Write("<b><i>IpAddress=</i></b>"+Request.UserHostName+"</br></br>");Response.Write("<b><i>Url=</i></b>"+Request.Url+"</br/></br>");Response.Write("<b><i>UserAgent=</i></b>"+Request.UserAgent+"</br/></br>");Response.Write("<b><i>UserHostName=</i></b>"+Request.UserHostName+"</br></br>");Response.Write("<b><i>PhysicalPath=</i></b>"+Request.PhysicalPath+"</br></br>");

Page 23: Unit -1 Views of Web Programming 1. Introduction to Server

Response.Write("<b><i>PhysicalApplicationPath=</i></b>"+Request.PhysicalApplicationPath+"</br></br>");Response.Write("<b><i>Path=</i></b>"+Request.Path+"</br></br>");Response.Write("<b><i>ApplicationPath=</i></b>"+Request.ApplicationPath+"</br></br>");}}

7.VisualBasicProgrammingFundamentals

StudythenotesofclientserverprogrammingUnit4andUnit5

Unit-2

DevelopingASPApplication

1.UsingApplicationobjects

Page 24: Unit -1 Views of Web Programming 1. Introduction to Server

Whatisanapplicationobject?Applicationobjectisusedtostoretheinformationandaccessvariablesfromanypagein application. Application object is same as session object only the difference issessionobjectisusedtomaintainthesessionforparticularuser.Ifoneuserentersintotheapplicationthensessionidwillcreateforthatparticularuserifheleavesfromtheapplicationthenthesessionidwilldeleted.Iftheyagainenterintotheapplicationtheywill get different session id but application object is same for all users onceapplicationobjectiscreatedthatapplicationobjectisusedthroughouttheapplicationregardlessofuser.Theinformationstoredinapplicationobjectaccessedthroughoutallthepagesinapplication(likedatabaseconnectioninformation)andwecanchangetheapplicationobject inoneplace those changesautomatically reflected inall thepages.

ApplicationObject(IIS)

An Active Server Page application is actually a collection of ASP files in a virtualdirectoryandassociatedsub-directories.TheApplicationobjectisusedtocontrolandmanageall itemsthatareavailabletoallusersofanActiveServerapplication.TheApplicationitemscanbevariablesneededforallusersintheapplication,ortheycanbeinstantiatedobjectsthatprovidespecialserver-sidefunctionality.TheApplicationobject is initializedby IISwhenthe first .asppage fromwithinthegivenvirtualdirectoryisrequested.Itremainsintheserver'smemoryuntileitherthewebserviceisstoppedortheapplicationisexplicitlyunloadedfromthewebserver(usingtheMicrosoftManagementConsole).The syntax, collections, methods and events of the ASP Application object are asfollows:Syntax

Application.method

YoucanusetheApplicationobjecttoshareinformationamongallusersofagivenapplication.AnASP-basedapplicationisdefinedasallthe.aspfilesinavirtualdirectoryanditssubdirectories.BecausetheApplicationobjectcanbesharedbymorethanoneuser,thereareLockandUnlockmethodstoensurethatmultipleusersdonottrytoalterapropertysimultaneously.MethodsTheApplicationobjectdefinesthefollowingmethods.

Method Description

Page 25: Unit -1 Views of Web Programming 1. Introduction to Server

Application.Contents.Remove DeletesanitemfromtheApplicationobject'sContentscollection.

Application.Contents.RemoveAll DeletesallitemsfromtheApplicationobject'sContentscollection.

Application.Lock PreventsotherclientsfrommodifyingApplicationobjectproperties.

Application.Unlock AllowsotherclientstomodifyApplicationobjectproperties.

PropertiesTheApplicationobjectdefinesthefollowingproperties.

Property Description

Application.ContentsCollection

Containsalloftheitemsthathavebeenaddedtotheapplicationthroughscriptcommands.

Application.StaticObjectsCollection

Containsalloftheobjectsaddedtothesessionwiththe<OBJECT>tag.

EventsTheApplicationobjectdefinesthefollowingevents.

Event Description

Application_OnEndEvent

Occurswhentheapplicationquits,aftertheSession_OnEndevent.OnlytheApplicationObjectandServerObjectbuilt-inobjectsareavailable.

Application_OnStartEvent

Occursbeforethefirstnewsessioniscreated,thatis,beforetheSession_OnStartevent.OnlytheApplicationObjectandServerObjectbuilt-inobjectsareavailable.ReferencingtheSessionObject,RequestObject,orResponseObjectobjectsintheApplication_OnStarteventscriptcausesanerror.

2.Programmingwithsessionobject

Page 26: Unit -1 Views of Web Programming 1. Introduction to Server

Sessionscanbeusedtostoreevencomplexdatafortheuserjustlikecookies.Actually,sessionswillusecookiestostorethedata,unlessyouexplicitlytellitnotto.Sessionscan be used easily in ASP.NET with the Session object. We will re-use the cookieexample,andusesessionsinstead.Keepinmindthough,thatsessionswillexpireafteracertainamountofminutes,asconfiguredintheweb.configfile.

TheSessionobject

Whenyouareworkingwithanapplicationonyourcomputer,youopenit,dosomechangesandthenyoucloseit.ThisismuchlikeaSession.Thecomputerknowswhoyouare.Itknowswhenyouopentheapplicationandwhenyoucloseit.However,ontheinternetthereisoneproblem:thewebserverdoesnotknowwhoyouareandwhatyoudo,becausetheHTTPaddressdoesn'tmaintainstate.

ASPsolvesthisproblembycreatingauniquecookieforeachuser.Thecookieissenttotheuser'scomputeranditcontainsinformationthatidentifiestheuser.ThisinterfaceiscalledtheSessionobject.

TheSessionobjectstoresinformationabout,orchangesettingsforausersession.

VariablesstoredinaSessionobjectholdinformationaboutonesingleuser,andareavailabletoallpagesinoneapplication.Commoninformationstoredinsessionvariablesarename,id,andpreferences.TheservercreatesanewSessionobjectforeachnewuser,anddestroystheSessionobjectwhenthesessionexpires.

WhendoesaSessionStart?

Asessionstartswhen:

• AnewuserrequestsanASPfile,andtheGlobal.asafileincludesaSession_OnStartprocedure

• AvalueisstoredinaSessionvariable• AuserrequestsanASPfile,andtheGlobal.asafileusesthe<object>tagto

instantiateanobjectwithsessionscope

WhendoesaSessionEnd?

Asessionendsifauserhasnotrequestedorrefreshedapageintheapplicationforaspecifiedperiod.Bydefault,thisis20minutes.

Ifyouwanttosetatimeoutintervalthatisshorterorlongerthanthedefault,usetheTimeoutproperty.

Theexamplebelowsetsatimeoutintervalof5minutes:

<%Session.Timeout=5%>

Page 27: Unit -1 Views of Web Programming 1. Introduction to Server

UsetheAbandonmethodtoendasessionimmediately:

<%Session.Abandon%>

Note:ThemainproblemwithsessionsisWHENtheyshouldend.Wedonotknowiftheuser'slastrequestwasthefinaloneornot.Sowedonotknowhowlongweshouldkeepthesession"alive".Waitingtoolongforanidlesessionusesupresourcesontheserver,butifthesessionisdeletedtoosoontheuserhastostartalloveragainbecausetheserverhasdeletedalltheinformation.Findingtherighttimeoutintervalcanbedifficult!

Tip:OnlystoreSMALLamountsofdatainsessionvariables!

StoreandRetrieveSessionVariables

ThemostimportantthingabouttheSessionobjectisthatyoucanstorevariablesinit.

TheexamplebelowwillsettheSessionvariableusernameto"DonaldDuck"andtheSessionvariableageto"50":

<%Session("username")="DonaldDuck"Session("age")=50%>

WhenthevalueisstoredinasessionvariableitcanbereachedfromANYpageintheASPapplication:

Welcome<%Response.Write(Session("username"))%>

Thelineabovereturns:"WelcomeDonaldDuck".

YoucanalsostoreuserpreferencesintheSessionobject,andthenaccessthatpreferencetochoosewhatpagetoreturntotheuser.

Theexamplebelowspecifiesatext-onlyversionofthepageiftheuserhasalowscreenresolution:

<%IfSession("screenres")="low"Then%>Thisisthetextversionofthepage<%Else%>Thisisthemultimediaversionofthepage<%EndIf%>

RemoveSessionVariables

Page 28: Unit -1 Views of Web Programming 1. Introduction to Server

TheContentscollectioncontainsallsessionvariables.

ItispossibletoremoveasessionvariablewiththeRemovemethod.

Theexamplebelowremovesthesessionvariable"sale"ifthevalueofthesessionvariable"age"islowerthan18:

<%IfSession.Contents("age")<18thenSession.Contents.Remove("sale")EndIf%>

Toremoveallvariablesinasession,usetheRemoveAllmethod:

<%Session.Contents.RemoveAll()%>

LoopThroughtheContentsCollection

TheContentscollectioncontainsallsessionvariables.YoucanloopthroughtheContentscollection,toseewhat'sstoredinit:

<%Session("username")="DonaldDuck"Session("age")=50dimiForEachiinSession.ContentsResponse.Write(i&"<br>")Next%>

Result:

usernameage

IfyoudonotknowthenumberofitemsintheContentscollection,youcanusetheCountproperty:

<%dimidimjj=Session.Contents.Count

Page 29: Unit -1 Views of Web Programming 1. Introduction to Server

Response.Write("Sessionvariables:"&j)Fori=1tojResponse.Write(Session.Contents(i)&"<br>")Next%>

Result:

Sessionvariables:2DonaldDuck50

LoopThroughtheStaticObjectsCollection

YoucanloopthroughtheStaticObjectscollection,toseethevaluesofallobjectsstoredintheSessionobject:

<%dimiForEachiinSession.StaticObjectsResponse.Write(i&"<br>")Next%>

3.Importanceandusageofcookiesobject

Aspcookies

LikeASPSessions,ASPCookiesareusedtostoreinformationspecifictoavisitorofyourwebsite.Thiscookieisstoredtotheuser'scomputerforanextendedamountoftime. If you set theexpirationdateof the cookie for someday in the future itwillremaintheiruntilthatdayunlessmanuallydeletedbytheuser.

WhatisaCookie?

Acookieisoftenusedtoidentifyauser.Acookieisasmallfilethattheserverembedsontheuser'scomputer.Eachtimethesamecomputerrequestsapagewithabrowser,itwillsendthecookietoo.WithASP,youcanbothcreateandretrievecookievalues.

HowtoCreateaCookie?

The"Response.Cookies"commandisusedtocreatecookies.

Note:TheResponse.CookiescommandmustappearBEFOREthe<html>tag.

Page 30: Unit -1 Views of Web Programming 1. Introduction to Server

Intheexamplebelow,wewillcreateacookienamed"firstname"andassignthevalue"Alex"toit:

<%Response.Cookies("firstname")="Alex"%>

Itisalsopossibletoassignpropertiestoacookie,likesettingadatewhenthecookieshouldexpire:

<%Response.Cookies("firstname")="Alex"Response.Cookies("firstname").Expires=#May10,2012#%>

HowtoRetrieveaCookieValue?

The"Request.Cookies"commandisusedtoretrieveacookievalue.

Intheexamplebelow,weretrievethevalueofthecookienamed"firstname"anddisplayitonapage:

<%fname=Request.Cookies("firstname")response.write("Firstname="&fname)%>

Output:Firstname=Alex

ACookiewithKeys

Ifacookiecontainsacollectionofmultiplevalues,wesaythatthecookiehasKeys.

Intheexamplebelow,wewillcreateacookiecollectionnamed"user".The"user"cookiehasKeysthatcontainsinformationaboutauser:

<%Response.Cookies("user")("firstname")="John"Response.Cookies("user")("lastname")="Smith"Response.Cookies("user")("country")="Norway"Response.Cookies("user")("age")="25"%>

ReadallCookies

Lookatthefollowingcode:

Page 31: Unit -1 Views of Web Programming 1. Introduction to Server

<%Response.Cookies("firstname")="Alex"Response.Cookies("user")("firstname")="John"Response.Cookies("user")("lastname")="Smith"Response.Cookies("user")("country")="Norway"Response.Cookies("user")("age")="25"%>

Assumethatyourserverhassentallthecookiesabovetoauser.

Nowwewanttoreadallthecookiessenttoauser.Theexamplebelowshowshowtodoit(notethatthecodebelowchecksifacookiehasKeyswiththeHasKeysproperty):

<!DOCTYPEhtml><html><body><%dimx,yforeachxinRequest.Cookiesresponse.write("<p>")ifRequest.Cookies(x).HasKeysthenforeachyinRequest.Cookies(x)response.write(x&":"&y&"="&Request.Cookies(x)(y))response.write("<br>")nextelseResponse.Write(x&"="&Request.Cookies(x)&"<br>")endifresponse.write"</p>"next%></body></html>

Output:

firstname=Alex

user:firstname=Johnuser:lastname=Smithuser:country=Norwayuser:age=25

Page 32: Unit -1 Views of Web Programming 1. Introduction to Server

WhatifaBrowserDoesNOTSupportCookies?

Ifyourapplicationdealswithbrowsersthatdonotsupportcookies,youwillhavetouseothermethodstopassinformationfromonepagetoanotherinyourapplication.Therearetwowaysofdoingthis:

1. Add parameters to a URL

YoucanaddparameterstoaURL:

<ahref="welcome.asp?fname=John&lname=Smith">GotoWelcomePage</a>

Andretrievethevaluesinthe"welcome.asp"filelikethis:

<%fname=Request.querystring("fname")lname=Request.querystring("lname")response.write("<p>Hello"&fname&""&lname&"!</p>")response.write("<p>WelcometomyWebsite!</p>")%>

2. Use a form

Youcanuseaform.Theformpassestheuserinputto"welcome.asp"whentheuserclicksontheSubmitbutton:

<formmethod="post"action="welcome.asp">FirstName:<inputtype="text"name="fname"value="">LastName:<inputtype="text"name="lname"value=""><inputtype="submit"value="Submit"></form>

Retrievethevaluesinthe"welcome.asp"filelikethis:

<%fname=Request.form("fname")lname=Request.form("lname")response.write("<p>Hello"&fname&""&lname&"!</p>")response.write("<p>WelcometomyWebsite!</p>")

Aspcookieexpirationdate

Unlikereallifecookies,inASPyoucansethowlongyouwantyourcookiestostayfreshandresideontheuser'scomputer.Acookie'sexpirationcanholdadate;thisdatewillspecifywhenthecookiewillbedestroyed.

Page 33: Unit -1 Views of Web Programming 1. Introduction to Server

Inourexamplebelowwecreateacookiethatwillbegoodfor10daysbyfirsttakingthecurrentdatethenadding10toit.

ASPCode:

<%

'createa10-daycookie

Response.Cookies("brownies")=13

Response.Cookies("brownies").Expires=Date()+10

'createastaticdatecookie

Response.Cookies("name")="SuzyQ."

Response.Cookies("name").Expires=#January1,2009#

%>

Aspcookiearraysorcollections

Upuntilnowwehaveonlybeenabletostoreonevariableintoacookie,whichisquitelimitingifyouwantedtostoreabunchofinformation.However,ifwemakethisonevariableintoacollectionitcanstoreagreatdealmore.Belowwemakeabrowniescollectionthatstoresallsortsofinformation.

ASPCode:

<%

'createabigcookie

Response.Cookies("brownies")("numberEaten")=13

Response.Cookies("brownies")("eater")="George"

Response.Cookies("brownies")("weight")=400

%>

aspretrievingcookievaluesfromacollection

Nowtoiteratethroughthebrowniescollectionwewilluseaforeachloop.Seeourforlooptutorialformoreinformation.

ASPCode:

<%

Page 34: Unit -1 Views of Web Programming 1. Introduction to Server

ForEachkeyInRequest.Cookies("Brownies")

Response.Write("<br/>"&key&"="&_

Request.Cookies("Brownies")(key))

Next

Response.Cookies("brownies")("numberEaten")=13

Response.Cookies("brownies")("eater")="George"

Response.Cookies("brownies")("weight")=400

%>

Display:

numberEaten=13

eater=George

weight=400

4.WorkingwithFileSystemObject(FSO).

WorkingwithFilesusingFSO

FSO:

Filesystemobjectisanobjectmodelwhichisusedtohandlethedrives,folders,andfilesofasystemorserver.

♦IfanuserneedstoworkonDriver,Folder,Filesproperties,methodsoreventsthenthefirststepheneedtosetupis

filesystemobject

♦FilesystemobjectisaninterfacebetweenQTPandthelocalsystem.usingFSOwecancreate/deletefolder,create/delete/read

from/writetotextfiles

♦TheFileSystemObject(FSO)objectmodelallowsyoutousethefamiliarobject.methodsyntaxwitharichsetofproperties,

methods,andeventstoprocessfoldersandfiles

Page 35: Unit -1 Views of Web Programming 1. Introduction to Server

Object/CollectionDescription:

FileSystemObject:

FilesystemobjectisaMainobject.Containsmethodsandpropertiesthatallowyoutocreate,delete,gaininformationabout,andgenerallymanipulatedrives,folders,andfiles.ManyofthemethodsassociatedwiththisobjectduplicatethoseinotherFSOobjects;theyareprovidedforconvenience.

Drive:

DriveisaObject.Containsmethodsandpropertiesthatallowyoutogatherinformationaboutadriveattachedtothesystem,suchasitssharenameandhowmuchroomisavailable.Notethata"drive"isn'tnecessarilyaharddisk,butcanbeaCD-ROMdrive,aRAMdisk,andsoforth.Adrivedoesn'tneedtobephysicallyattachedtothesystem;itcanbealsobelogicallyconnectedthroughanetwork.

Drives:

DrivesareCollection.Providesalistofthedrivesattachedtothesystem,eitherphysicallyorlogically.TheDrivescollectionincludesalldrives,regardlessoftype.Removable-mediadrivesneednothavemediainsertedforthemtoappearinthiscollection.

File:

FileisaObject.Containsmethodsandpropertiesthatallowyoutocreate,delete,ormoveafile.Alsoallowsyoutoquerythesystemforafilename,path,andvariousotherproperties.

Files:

FilesareCollection.Providesalistofallfilescontainedwithinafolder.

Folder:

FolderisaObject.Containsmethodsandpropertiesthatallowyoutocreate,delete,ormovefolders.Alsoallowsyoutoquerythesystemforfoldernames,paths,andvariousotherproperties.

Folders:

FoldersareCollection.ProvidesalistofallthefolderswithinaFolder.

Page 36: Unit -1 Views of Web Programming 1. Introduction to Server

AccessingFileswithFileSystemObjectTheFileSystemObject(FSO)modelprovidesanobject-basedtoolforworkingwithfoldersandfiles.Itallowsyoutousethefamiliarobject.methodsyntaxwitharichsetofproperties,methods,andeventstoprocessfoldersandfiles.YoucanalsoemploythetraditionalVisualBasicstatementsandcommands.TheFSOmodelgivesyourapplicationtheabilitytocreate,alter,move,anddeletefolders,ortodetermine if andwhereparticular folders exist. It alsoenablesyou toget informationaboutfolders,suchastheirnamesandthedatetheywerecreatedorlastmodified.The FSOmodelmakes processing filesmuch easier aswell.When processing files, yourprimarygoal istostoredatainanefficient,easy-to-accessformat.Youneedtobeabletocreatefiles,insertandchangethedata,andoutput(read)thedata.Althoughyoucanstoredatainadatabase,doingsoaddsasignificantamountofoverheadtoyourapplication.Youmaynotwanttohavesuchoverhead,oryourdataaccessrequirementsmaynotcallfortheextrafunctionalityassociatedwithafull-featureddatabase.Inthiscase,storingyourdatainatextfileorbinaryfileisthemostefficientsolution.TheFSOmodel,containedintheScriptingtypelibrary(Scrrun.dll),supportsthecreationandmanipulationoftextfilesthroughtheTextStreamobject;however,theFSOmodeldoesnotsupport binary files. To manipulate binary files, use the FileOpen Function withtheBinarykeyword.ThefollowingobjectsmakeuptheFSOmodel:

Object Description

FileSystemObject Allows you to create, delete, gain information about, andgenerally manipulate drives, folders, and files. Many of themethods associated with this object duplicate those in theotherobjects.

Drive Allowsyoutogatherinformationaboutadriveattachedtothesystem,suchashowmuchroomisavailableandwhatitssharename is. Note that a "drive" under the FSO model isn'tnecessarilyaharddisk:itcanbeaCD-ROMdrive,aRAMdisk,and so forth. A drive also isn't required to be physicallyattached to the system; it can also be logically connectedthroughalocalareanetwork(LAN).

Folder Allowsyoutocreate,delete,ormovefolders,aswellasquerythesystemabouttheirnames,paths,andotherinformation.

Page 37: Unit -1 Views of Web Programming 1. Introduction to Server

File Allowsyoutocreate,delete,ormovefiles,aswellasquerythesystemabouttheirnames,paths,andotherinformation.

TextStream Enablesyoutoreadandwritetextfiles.

Forinformationaboutthevariousproperties,methods,andeventsintheFSOmodel,usetheObjectBrowserinVisualBasicbypressingCTRL+ALT+JandlookingattheScriptingtypelibrary. If theScriptingtype librarydoesnotappear in the list,createareferenceto itasshowninthenextsection.ProgrammingintheFSOModelProgrammingintheFSOmodelentailsthreemaintasks:

• Creating a FileSystemObject object by using the CreateObjectmethod, or bydimensioningavariableasaFileSystemObjectobject.

• Usingtheappropriatemethodonthenewlycreatedobject.• Accessingtheobject'sproperties.

The FSO model is contained in the Scripting type library, which is located in the fileScrrun.dll.Ifyoudon'talreadyhaveareferencetoit,youcancreateone.TocreateareferencetotheScriptingtypelibrary(Scrrun.dll)

1. OntheProjectmenu,clickAddReference,andthenclicktheCOMtab.2. ChooseMicrosoftScriptingRuntimefromtheComponentNamelist,andthen

clickSelect.

Youcannowuse theObjectBrowser toview theFSOmodel'sobjects, collections,properties,methods,events,andconstants.

TocreateaFileSystemObjectobject

• DimensionavariableastypeFileSystemObject,asinthefollowingcode:

DimfsoAsNewFileSystemObject-or-

• Use the CreateObject method to create a FileSystemObject object, as in thefollowingcode:

• fso=CreateObject("Scripting.FileSystemObject")Inthesecondexample,Scriptingisthenameofthetypelibrary,andFileSystemObjectisthenameoftheobjectofwhichyouwanttocreateaninstance.Note ThefirstmethodworksonlyinVisualBasic,whilethesecondmethodworkseitherinVisualBasicorVBScript.

Page 38: Unit -1 Views of Web Programming 1. Introduction to Server

SecurityNote Donotmakedecisionsaboutthecontentsofa filebasedonthe filenameextension.Forexample,afilenamedForm1.vbmaynotbeaVisualBasic.NETsourcefile.

FSO Methods

ThefollowingtableshowsFSOmethodsandthetasksthattheyperform:

Task Command

Createanewobject CreateFolderorCreateTextFile

Deleteafileorfolder DeleteFileorFile.Delete;DeleteFolderorFolder.Delete

Copyanobject CopyFileorFile.Copy;CopyFolderorFolder.Copy

Moveanobject MoveFileorFile.Move;MoveFolderorFolder.Move

Access an existing drive,folder,orfile

GetDrive,GetFolder,orGetFile

NoteTheFSOmodeldoesnotsupportthecreationordeletionofdrives.

Asyoucansee,somefunctionalityintheFileSystemObjectobjectmodelisredundant.Forexample,youcancopyafileusingeithertheCopyFilemethodoftheFileSystemObjectobject,oryoucanusetheCopymethodoftheFileobject.Themethodsworkthesameway;bothversionsareincludedtogiveyoumaximumprogrammingflexibility.Note,however,thatyoudon'tneedtousetheGetmethodsforanewlycreatedobject,sincetheCreatefunctionsalreadyreturnahandletoit.Forexample,ifyoucreateanewfolderusingtheCreateFoldermethod,youdon'tneedtousetheGetFoldermethodtoaccess itsproperties,suchasName,Path,orSize. JustsetavariabletotheCreateFolderfunctiontogain a handle to the newly created folder, and then access its properties, methods, andevents.

Page 39: Unit -1 Views of Web Programming 1. Introduction to Server

DriveInformationTheDriveobjectallowsyoutogetinformationaboutthevariousdrivesattachedtoasystem,eitherphysicallyoroveranetwork.Itspropertiescontainthefollowinginformation:

Property Description

TotalSize Totalsizeofthedrive,inbytes

AvailableSpace,FreeSpace How much space is available on thedrive,inbytes

DriveLetter Letterassignedtothedrive

DriveType Type of drive (removable, fixed,network,CD-ROM,orRAMdisk)

SerialNumber Drive'sserialnumber

FileSystem Typeoffilesystemthedriveuses(FAT,FAT32,orNTFS)

IsReady Whetheradriveisavailableforuse

ShareName,VolumeName Nameoftheshareand/orvolume

Page 40: Unit -1 Views of Web Programming 1. Introduction to Server

Path,RootFolder Pathorrootfolderofthedrive

App.Path, ChDir, ChDrive, and CurDir

If you use the Path property (App.Path), the ChDrive and ChDir statements, ortheCurDirfunction,beawarethattheymayreturnaUniversalNamingConvention(UNC)path (that is, one beginning with \\Server\Share...) rather than a drive path (such ase:\Folder),dependingonhowyourunyourprogramorproject.App.PathreturnsaUNCpathwhen:

• Yourunaprojectafter loading it fromanetworkshare,even if thenetworkshareismappedtoadriveletter.

• Yourunacompiledexecutablefilefromanetworkshare(butonlyifitisrunusingaUNCpath).

ChDrivecannothandleUNCpaths,anditraisesanerrorwhenApp.Pathreturnsone.YoucanhandlethiserrorbyaddingOnErrorResumeNextbeforetheChDrivestatement,orbytestingthefirsttwocharactersofApp.Pathtoseeiftheyarebackslashes.Thecommandpromptalwayshasadrivepathforthecurrentdirectory,soCurDirissettoadrivepath.ChDirdoesnotraiseanerror,butitfailstochangethedirectoryfromadrivepathtoaUNCpath.Theonlyworkaroundforthissituationistolocatealocaldrivethatismappedto the share specified in the UNC path, or to use network commands to create such amapping.IftheprojectisloadedintotheVisualBasicdevelopmentenvironmentfromanetworkshare—either aUNCpathor amappeddrivepath—App.Path returns aUNCpathwhen theprojectisrunandChDrivefailsandraisesanerror.ChDirdoesnotraiseanerror,butitfailstochangethedirectory.Theonlyworkaroundforthissituationistomanuallysetthedriveanddirectory.Ifmorethanonepersoncanopentheprojectonthenetworkshare,youcanuseanMS-DOSenvironmentvariabletogiveeachpersonacustomizedmappingfortheshare.FolderInformationThefollowingtableshowsthemethodsforcarryingoutcommonfoldertasks:

Method Task

FileSystemObject.CreateFolder Createafolder.

Page 41: Unit -1 Views of Web Programming 1. Introduction to Server

Folder.Delete orFileSystemObject.DeleteFolder

Deleteafolder.

Folder.Move orFileSystemObject.MoveFolder

Moveafolder.

Folder.Copy orFileSystemObject.CopyFolder

Copyafolder.

Folder.Name Retrievethenameofafolder.

FileSystemObject.FolderExists Findoutifafolderexistsonadrive.

FileSystemObject.GetFolder Get an instance of anexistingFolderobject.

FileSystemObject.GetParentFolderName Find out the name of a folder's parentfolder.

FileSystemObject.GetSpecialFolder Findoutthepathofasystemfolder.

SequentialTextFilesandFSOSequentialtextfiles(sometimesreferredtoasatextstream)areusefulwhenyouwanttoreadthecontentsofafilewithinaFileSystemObjectobject.Youcanaccesssequentialtextfileswiththesemethods:

Page 42: Unit -1 Views of Web Programming 1. Introduction to Server

Method Task

CreateTextFile, OpenTextFile,orOpenAsTextStream

Createasequentialtextfile.

WriteorWriteLine Adddatatoatextfile.

Read,ReadLine,orReadAll Readdatafromatextfile.

File.MoveorMoveFile Moveafile.

File.CopyorCopyFile Copyafile.

File.DeleteorDeleteFile Deleteafile.

Unit-3

DatabaseProgramminginASP&ASP.Net

1.IntroductiontoActiveXDataObject(ADO)

ActiveXDataObjects(ADO)isanapplicationprograminterfacefromMicrosoftthatletsaprogrammerwritingWindowsapplicationsgetaccesstoarelationalornon-relationaldatabasefrombothMicrosoftandotherdatabaseproviders.Forexample,ifyouwantedtowriteaprogramthatwouldprovideusersofyourWebsitewith

Page 43: Unit -1 Views of Web Programming 1. Introduction to Server

datafromanIBMDB2databaseoranOracledatabase,youcouldincludeADOprogramstatementsinanHTMLfilethatyouthenidentifiedasanActiveServerPage.Then,whenauserrequestedthepagefromtheWebsite,thepagesentbackwouldincludeappropriatedatafromadatabase,obtainedusingADOcode.

WhatisADO?

• ADOisaMicrosofttechnology• ADOstandsforActiveXDataObjects• ADOisaMicrosoftActive-Xcomponent• ADOisautomaticallyinstalledwithMicrosoftIIS• ADOisaprogramminginterfacetoaccessdatainadatabase

AccessingaDatabasefromanASPPage

ThecommonwaytoaccessadatabasefrominsideanASPpageisto:

1. CreateanADOconnectiontoadatabase2. Openthedatabaseconnection3. CreateanADOrecordset4. Opentherecordset5. Extractthedatayouneedfromtherecordset6. Closetherecordset7. Closetheconnection

2.OLEDB

OLEDBisasetofmethods(inearlierdays,thesemighthavebeencalledroutines)forreadingandwritingdata.TheobjectsinOLEDBconsistmainlyofadatasourceobject,asessionobject,acommandobject,andarowsetobject.AnapplicationusingOLEDBwouldusethisrequestsequence:

1. InitializeOLE.

2. Connecttoadatasource.

3. Issueacommand.

4. Processtheresults.

5. ReleasethedatasourceobjectanduninitializedOLE.

Page 44: Unit -1 Views of Web Programming 1. Introduction to Server

OLE once stood for "Object Link Embedding" and "DB" for database. However,Microsoftnolongerascribesthesemeaningstotheletters"OLE"and"DB."

OLEDBdefinesasetofCOMinterfacestoprovideapplicationswithuniformaccesstodatathatisstoredindiverseinformationsources.ThisapproachallowsadatasourcetoshareitsdatathroughtheinterfacesthatsupporttheamountofDBMSfunctionalityappropriatetothedatasource.Bydesign,thehigh-performancearchitectureofOLEDBisbasedonitsuseofaflexible,component-basedservicesmodel.Ratherthanhavingaprescribednumberofintermediary layersbetweentheapplicationandthedata,OLEDBrequiresonlyasmanycomponentsasareneededtoaccomplishaparticulartask.

Forexample,supposeauserwantstorunaquery.Considerthefollowingscenarios:

• ThedataresidesinarelationaldatabaseforwhichtherecurrentlyexistsanODBCdriverbutnonativeOLEDBprovider:TheapplicationusesADOtotalktotheOLEDBProviderfor ODBC, which then loads the appropriate ODBC driver. The driver passes the SQLstatementtotheDBMS,whichretrievesthedata.

• ThedataresidesinMicrosoftSQLServerforwhichthereisanativeOLEDBprovider:TheapplicationusesADOtotalkdirectlytotheOLEDBProviderforMicrosoftSQLServer.Nointermediariesarerequired.

• ThedataresidesinMicrosoftExchangeServer,forwhichthereisanOLEDBproviderbutwhichdoesnotexposeanenginetoprocessSQLqueries:TheapplicationusesADOtotalktotheOLEDBProviderforMicrosoftExchangeandcallsuponanOLEDBqueryprocessorcomponenttohandlethequerying.

• The data resides in theMicrosoft NTFS file system in the form of documents: Data isaccessed by using a native OLE DB provider over Microsoft Indexing Service, whichindexes the content andproperties of documents in the file system to enable efficientcontentsearches.

Inalltheprecedingexamples,theapplicationcanquerythedata.Theuser'sneedsaremetwithaminimumnumberofcomponents. Ineachcase,additionalcomponentsareusedonlyifneeded,andonlytherequiredcomponentsareinvoked.Thisdemand-loadingofreusableandshareablecomponentsgreatlycontributestohighperformancewhenOLEDBisused.

Providersfall intotwocategories:thoseprovidingdataandthoseprovidingservices.Adataproviderowns itsowndata andexposes it in tabular form toyourapplication.Aserviceproviderencapsulatesaservicebyproducingandconsumingdata,augmentingfeatures in yourADOapplications.A serviceprovider can alsobe furtherdefined as aservice component, which must work in conjunction with other service providers orcomponents.

ADOprovidesaconsistent,higherlevelinterfacetothevariousOLEDBproviders.

3.EstablishingconnectiontoSQLServer&MSAccess

ConnectingToSqlServer

Page 45: Unit -1 Views of Web Programming 1. Introduction to Server

Firstofall,let'screateanewdatabasewithSqlServer2000.OpenupyourSqlServer,andcreateanewdatabaseandcallit"Database1".Throughoutthetutorial,wewillbeinneedofonlyonetable.Let'screateanewtable.Designyourtabletobesimilartothefollowing:

Callthistable"Students".OpenVisualStudio,andcreateanewproject.Callitwhateveryouwant.Wewillusethedefaultpagetoinsertnewstudentsintothedatabase.Thepagewillbelookasthefollowingimage:

Notethatthetextboxesarecalled"txtFirstname","txtLastname"and"txtLastname".Thebutton'snameis"btnSubmit".Doubleclickonthesubmitbuttonandplacethefollowingcode.

DimconAsNewSystem.Data.SqlClient.SqlConnectioncon.ConnectionString="datasource=.;initialcatalog=Database1;integratedsecurity=sspi;"DimmyCommandAsNewSystem.Data.SqlClient.SqlCommandmyCommand.CommandText="insertintoStudentsvalues('"&txtFirstname.Text&"','"&txtLastname.Text&"','"&txtAddress.Text&"')"myCommand.Connection=concon.Open()myCommand.ExecuteNonQuery()con.Close()

Notethatallwedidiscreatingaconnectionandacommand,usingtheSystem.Data.SqlClientnamespace.Thenweopenedthedatabase,executedthecommandandthenclosedthedatabaseagain.Noticealsothatthecommandtextwasstraight,wejust

Page 46: Unit -1 Views of Web Programming 1. Introduction to Server

insertedthevaluesintothedatabase,intheorderwecreatedpreviously.NowwewillseehowthisdifferensinAccessDatabase.

IfyouhavetomakemanyASP.NETformslikethis,itisusuallybettertoobtainApexSQLCodetogetstandardizedASP.NETwebformsandreducedevelopmenttime.

ConnectingToMSAccess

OpenAccess2003andcreateanewdatabase.Callit"Database1.mdb".CreateanewtablerelatedtothisdatabasethathasthesamestructureasthetablewecreatedinSQL.Alsocallit"Students"aswell.

Nowcreateanewpageintheproject.Icalledit"newInsert.aspx".Designthepagetohavethesamedesignoftheoldpage(Default.aspx).

NowdoubleclickontheSubmitbuttonandplacethefollowingcode:

DimconAsNewSystem.Data.OleDb.OleDbConnectionDimmyPathAsStringmyPath=Server.MapPath("Database1.mdb")con.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Datasource="&myPath&";"DimmyCommandAsNewSystem.Data.OleDb.OleDbCommandmyCommand.CommandText="insertintoStudents(Firstname,Lastname,Address)values('"&txtFirstname.Text&"','"&txtLastname.Text&"','"&txtAddress.Text&"')"myCommand.Connection=concon.Open()myCommand.ExecuteNonQuery()con.Close()

Thefirstthingyoumightnotice, istheMappathfunction.Thisfunctionretrievesthepathwheretheapplicationis.AndsinceinAccesstheDatabaseisanmdbfile,soweshouldspecifyit'slocationexactly.Andsincewe'regoingtopublishourwebsitelaterontotheweb,thenweshouldplacethatmdbinsideourwebsite.That'swhyweusedMappathinsteadofusingstrictaddressingsuchas"C:/Database1.mdb".

Page 47: Unit -1 Views of Web Programming 1. Introduction to Server

Thesecondthingthatdiffershere,isthenamespacefortheconnectionandthecommand.System.data.OledbClientisthenamespaceusedforaccessinsteadofSystem.data.SqlClient

The most important thing to notice here, is the presence of the arguments in theCommandText:

'Insertintostudents(Firstname,Lastname,Address)values......

This is very important, the connection to the access databasewill notwork if you don'tspecifytheargumentsofthetable.Thisbecomesreallyannoyingifwehaveatablethathasmanycolumnsinit.

Note that inReading from the database, the only thing that differents is the namespace.Createanewpageandcallit"listAll.aspx".Thispagewilllistallthestudentsinthedatabase.

ClicktheSourceTab,andinsertthiscodewithintheformtag:

<tablerunat="server"id="myTable"></table>

Wewillfillthistableatruntime.

DoubleclickonthemiddleofthenewpagetogettheOnLoadevent.Placethefollowingcode:

DimconAsNewSystem.Data.OleDb.OleDbConnectionDimmyPathAsStringmyPath=Server.MapPath("Database1.mdb")con.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Datasource="&myPath&";"DimadpAsNewSystem.Data.OleDb.OleDbDataAdapter("select*fromStudents",con)DimdtAsNewSystem.Data.DataTableadp.Fill(dt)ForiAsInteger=0Todt.Rows.Count-1DimmyRowAsNewHtmlTableRowDimmyCellAsNewHtmlTableCellmyCell.InnerHtml=dt.Rows(i).Item("Firstname")&"&nbsp;"&dt.Rows(i).Item("Lastname")&"&nbsp;("&dt.Rows(i).Item("Address")&")"myRow.Cells.Add(myCell)myTable.Rows.Add(myRow)Next

Here'showthepagelookslikeattheend:

Page 48: Unit -1 Views of Web Programming 1. Introduction to Server

Nothingreallycomplicated,wejustselectedalltheusers,andmadealoopovereveryoneofthem,andprintedouttheirfirstname,lastnameandaddresseachinadifferentrow.Wefiguredoutthenumberofrowsusingthedt.rows.count,whichcountshowmanyrowswehaveinourtable.Thenwesubtractedonebecausethefirstrowstartsatlocationzero.

NotethattheDataAdapteropensthedatabaseautomatically,andthenclosesitbyitself,soyoudon'tworryaboutthisissue.Thenwefilledthedataintoadatatablecalleddt.Itisaninstance of the System.Data.Datatable provided by Visual Studio. The DataTable is veryimportant and easy to work with. Note that we used The DataAdapter only for gettinginformations from the database. To insert or update, use the Command, and open theconnectionmanuallythencloseitafterexecutingthecommand.

4.WorkingwithconnectionandRecordsetobject

Create ADO Connection and Recordset Objects in Visual C# .NET

1. CreateanewVisualC#.NETWindowsapplicationproject.

2. OntheProjectmenu,clickAddReference.3. ClicktheCOMtab.ClickMicrosoftActiveXDataObjects2.XLibrary.4. OpentheCodewindowforForm1.5. Sothatyourdeclarationswillbeform-levelinscope,addthefollowingcodeto

thetopoftheForm1classsection,abovethepublicForm1function:

privateADODB.Connectioncn=newADODB.Connection();privateADODB.Recordsetrs=newADODB.Recordset();privatestringcnStr;privatestringquery;

Page 49: Unit -1 Views of Web Programming 1. Introduction to Server

6. UsethefollowingcodesamplesintheForm1functionbelowInitializeComponent();.ThefirstexamplecreatesaConnectionobjectandconnectstoaSQLServerPubsdatabase.ThesecondexamplecreatesaRecordSetobject.Toconnecttothedatabase:NoteUserID<username>musthavepermissionstoperformtheseoperationsonthedatabase.

//Connectionstring.cnStr="Provider=SQLOLEDB;InitialCatalog=Pubs;DataSource=servername;UserID=<username>;Password=;<strongpassword>";//queryquery="Select*FromAuthors";//ConnectionviaConnectionopenProperty.cn.Open(cnStr,null,null,0);cn.Close();//ConnectionviaConnectionStringProperty.cn.ConnectionString=cnStr;cn.Open(null,null,null,0);cn.Close();

ToretrievetheRecordSetfromdatabase:

//OpenRecordsetviaConnectionobject.cn.Open(cnStr,null,null,0);rs.Open(query,cn,ADODB.CursorTypeEnum.adOpenKeyset,ADODB.LockTypeEnum.adLockOptimistic,-1);rs.Close();cn.Close();//OpenRecordsetwithoutconnectionobject.rs.Open(query,cnStr,ADODB.CursorTypeEnum.adOpenKeyset,ADODB.LockTypeEn

Page 50: Unit -1 Views of Web Programming 1. Introduction to Server

um.adLockOptimistic,-1);rs.Close();

7. ModifytheConnectionStringobjectforyourSQLServer.PressF11tostepthroughthecodeandnotethedifferentwaystocreateaConnectionorRecordSetobject.

5.Usingstoredprocedureswithcommandobject

Astoredproceduresisapre-defined,reusableroutinethatisstoredinadatabase.SQLServercompilesstoredprocedures,whichmakesthemmoreefficienttouse.Therefore,ratherthandynamically building queries in your code, you can take advantage of the reuse andperformancebenefitsof storedprocedures.The following sectionswill showyouhow tomodify theSqlCommandobject tousestoredprocedures.Additionally,you’ll seeanotherreasonwhyparametersupportisanimportantpartoftheADO.NETlibraries.

Executing a Stored Procedure

Inadditiontocommandsbuiltwithstrings,theSqlCommandtypecanbeusedtoexecutestoredprocedures.Therearetwotasksrequiretomakethishappen:lettheSqlCommandobjectknowwhichstoredproceduretoexecuteandtell theSqlCommandobjectthat it isexecutingastoredprocedure.Thesetwostepsareshownbelow:

//1.createacommandobjectidentifying

//thestoredprocedure

SqlCommandcmd=newSqlCommand(

"TenMostExpensiveProducts",conn);

//2.setthecommandobjectsoitknows

//toexecuteastoredprocedure

cmd.CommandType=CommandType.StoredProcedure;

Page 51: Unit -1 Views of Web Programming 1. Introduction to Server

While declaring the SqlCommand object above, the first parameter is set to “Ten MostExpensiveProducts”.ThisisthenameofastoredprocedureintheNorthwinddatabase.Thesecond parameter is the connection object, which is the same as the SqlCommandconstructorusedforexecutingquerystrings.

ThesecondcommandtellstheSqlCommandobjectwhattypeofcommanditwillexecutebysettingitsCommandTypepropertytotheStoredProcedurevalueoftheCommandTypeenum.ThedefaultinterpretationofthefirstparametertotheSqlCommandconstructoristotreatitasaquerystring.BysettingtheCommandTypetoStoredProcedure,thefirstparametertotheSqlCommandconstructorwillbeinterpretedasthenameofastoredprocedure(insteadofinterpretingitasacommandstring).TherestofthecodecanusetheSqlCommandobjectthesameasitisusedinpreviouslessons.

Sending Parameters to Stored Procedures

Usingparametersforstoredproceduresisthesameasusingparametersforquerystringcommands.Thefollowingcodeshowsthis:

//1.createacommandobjectidentifying

//thestoredprocedure

SqlCommandcmd=newSqlCommand(

"CustOrderHist",conn);

//2.setthecommandobjectsoitknows

//toexecuteastoredprocedure

cmd.CommandType=CommandType.StoredProcedure;

//3.addparametertocommand,which

//willbepassedtothestoredprocedure

cmd.Parameters.Add(

newSqlParameter("@CustomerID",custId));

Page 52: Unit -1 Views of Web Programming 1. Introduction to Server

TheSqlCommandconstructorabovespecifiesthenameofastoredprocedure,CustOrderHist,as its first parameter. This particular stored procedure takes a single parameter,named@CustomerID. Therefore,wemust populate this parameter using a SqlParameterobject. The name of the parameter passed as the first parameter to the SqlParameterconstructor must be spelled exactly the same as the stored procedure parameter. ThenexecutethecommandthesameasyouwouldwithanyotherSqlCommandobject.

IntroductionStoredprocedures(sprocs)aregenerallyanorderedseriesofTransact-SQLstatementsbundledintoasinglelogicalunit.Theyallowforvariablesandparameters,aswellasselectionandloopingconstructs.Akeypointisthatsprocsarestoredinthedatabaseratherthaninaseparatefile.

Advantagesoversimplysendingindividualstatementstotheserverinclude:

1. Referredtousingshortnamesratherthanalongstringoftext;therefore,lessnetworktraffiicisrequiredtorunthecodewithinthesproc.

2. Pre-optimizedandprecompiled,sotheysaveanincrementalamountoftimewitheachsproccall/execution.

3. Encapsulateaprocessforaddedsecurityortosimplyhidethecomplexityofthedatabase.

4. Canbecalledfromothersprocs,makingthemreusableandreducingcodesize.

ParameterizationAstoredproceduregivesussomeproceduralcapability,andalsogivesusaperformanceboostbyusingmainlytwotypesofparameters:

• Inputparameters• Outputparameters

Fromoutsidethesproc,parameterscanbepassedineitherbypositionorreference.DeclaringParameters

1. Thename2. Thedatatype3. Thedefaultvalue4. Thedirection

Thesyntaxis:@parameter_name[AS]datatype[=default|NULL][VARYING][OUTPUT|OUT]

Let'snowcreateastoredprocedurenamed"Submitrecord".

Page 53: Unit -1 Views of Web Programming 1. Introduction to Server

FirstopenMicrosoftSQLServer->EnterpriseManager,thennavigatetothedatabaseinwhichyouwanttocreatethestoredprocedureandselectNewStoredProcedure.

SeethebelowStoredProcedurePropertiesforwhattoenter,thenclickOK.

NowcreateanapplicationnamedStoreProcedurein.nettousetheabovesprocs.StoredProcedure.aspxpagecode

Page 54: Unit -1 Views of Web Programming 1. Introduction to Server

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%><!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title>StoreProcedure</title></head><body><formid="form1"runat="server"><div><asp:LabelID="Label1"runat="server"Text="ID"></asp:Label><asp:TextBoxID="TextBox1"runat="server"></asp:TextBox><br/><br/><asp:LabelID="Label2"runat="server"Text="Password"></asp:Label><asp:TextBoxID="TextBox2"runat="server"></asp:TextBox><br/><br/><asp:LabelID="Label3"runat="server"Text="ConfirmPassword"></asp:Label><asp:TextBoxID="TextBox3"runat="server"></asp:TextBox><br/><br/><asp:LabelID="Label4"runat="server"Text="EmailID"></asp:Label><asp:TextBoxID="TextBox4"runat="server"></asp:TextBox><br/><br/><br/><asp:ButtonID="Button1"runat="server"Text="SubmitRecord"OnClick="Button1_Click"/></div></form></body></html>StoredProcedure.aspx.cspagecodeusingSystem;usingSystem.Data;usingSystem.Configuration;usingSystem.Web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts;usingSystem.Web.UI.HtmlControls;usingSystem.Data.SqlClient;publicpartialclass_Default:System.Web.UI.Page{DataSetds=newDataSet();SqlConnectioncon;//HerewedeclaretheparameterwhichwehavetouseinourapplicationSqlCommandcmd=newSqlCommand();SqlParametersp1=newSqlParameter();SqlParametersp2=newSqlParameter();SqlParametersp3=newSqlParameter();

Page 55: Unit -1 Views of Web Programming 1. Introduction to Server

SqlParametersp4=newSqlParameter();protectedvoidPage_Load(objectsender,EventArgse){}protectedvoidButton1_Click(objectsender,EventArgse)

{con=newSqlConnection("server=(local);database=gaurav;uid=sa;pwd=");cmd.Parameters.Add("@ID",SqlDbType.VarChar).Value=TextBox1.Text;cmd.Parameters.Add("@Password",SqlDbType.VarChar).Value=TextBox2.Text;cmd.Parameters.Add("@ConfirmPassword",SqlDbType.VarChar).Value=TextBox3.Text;cmd.Parameters.Add("@EmailID",SqlDbType.VarChar).Value=TextBox4.Text;cmd=newSqlCommand("submitrecord",con);cmd.CommandType=CommandType.StoredProcedure;con.Open();cmd.ExecuteNonQuery();con.Close();}}Whenweruntheapplication,thewindowwilllooklikethis:

AfterclickingthesubmitbuttonthedataisappendedtothedatabaseasseenbelowintheSQLServertablerecord:

Page 56: Unit -1 Views of Web Programming 1. Introduction to Server

6.NetFramework

The .NET Framework is a technology that supports building and running the nextgenerationofapplicationsandXMLWebservices.The.NETFrameworkisdesignedtofulfillthefollowingobjectives:

• Toprovide a consistent object-orientedprogramming environmentwhetherobject code is stored and executed locally, executed locally but Internet-distributed,orexecutedremotely.

• Toprovideacode-executionenvironmentthatminimizessoftwaredeploymentandversioningconflicts.

• Toprovideacode-executionenvironmentthatpromotessafeexecutionofcode,includingcodecreatedbyanunknownorsemi-trustedthirdparty.

• To provide a code-execution environment that eliminates the performanceproblemsofscriptedorinterpretedenvironments.

• Tomake thedeveloperexperienceconsistentacrosswidelyvarying typesofapplications,suchasWindows-basedapplicationsandWeb-basedapplications.

• Tobuildallcommunicationonindustrystandardstoensurethatcodebasedonthe.NETFrameworkcanintegratewithanyothercode

• The.NETFrameworkconsistsofthecommonlanguageruntimeandthe.NETFrameworkclasslibrary.Thecommonlanguageruntimeisthefoundationofthe .NETFramework.Youcanthinkoftheruntimeasanagentthatmanagescodeatexecutiontime,providingcoreservicessuchasmemorymanagement,threadmanagement,andremoting,whilealsoenforcingstricttypesafetyandotherformsofcodeaccuracythatpromotesecurityandrobustness.Infact,theconceptofcodemanagementisafundamentalprincipleoftheruntime.Codethattargetstheruntimeisknownasmanagedcode,whilecodethatdoesnottarget the runtime is known as unmanaged code. The class library is acomprehensive,object-orientedcollectionofreusabletypesthatyoucanusetodevelopapplicationsrangingfromtraditionalcommand-lineorgraphicaluser

Page 57: Unit -1 Views of Web Programming 1. Introduction to Server

interface (GUI) applications to applications based on the latest innovationsprovidedbyASP.NET,suchasWebFormsandXMLWebservices.

• The.NETFrameworkcanbehostedbyunmanagedcomponentsthatloadthecommon language runtime into theirprocessesand initiate theexecutionofmanagedcode,therebycreatingasoftwareenvironmentthatcanexploitbothmanaged and unmanaged features. The .NET Framework not only providesseveral runtime hosts, but also supports the development of third-partyruntimehosts.

• For example, ASP.NET hosts the runtime to provide a scalable, server-sideenvironment formanagedcode.ASP.NETworksdirectlywith theruntime toenable ASP.NET applications and XML Web services, both of which arediscussedlaterinthistopic.

• InternetExplorer is anexampleof anunmanagedapplication thathosts theruntime(intheformofaMIMEtypeextension).UsingInternetExplorertohosttheruntimeenablesyoutoembedmanagedcomponentsorWindowsFormscontrolsinHTMLdocuments.Hostingtheruntimeinthiswaymakesmanagedmobile codepossible, butwith significant improvements that onlymanagedcodecanoffer,suchassemi-trustedexecutionandisolatedfilestorage.

• The following illustration shows the relationship of the common languageruntimeandtheclasslibrarytoyourapplicationsandtotheoverallsystem.Theillustration also shows how managed code operates within a largerarchitecture.

7.Typesofwebsites

Page 58: Unit -1 Views of Web Programming 1. Introduction to Server

1.BlogorPersonalWebsite

WordPressstartedoutasasimplebloggingplatformandquicklyevolvedintoapowerful

CMS. During the last 12 years, those blogging and personal website components didn’t

disappear.

Theyhavebecomemorepolished,sophisticatedandmature.Ifyouaregoingtocreateablog

or personal website, then youwill find plenty of tools tomanage and grow yourWord

Pressquickly.2.BusinessWebsite

WordPress is the easiest way to build a professional looking business website. It is so

powerfulthatmanybignamebrandsareusingWordPresstopowertheirwebsites.Itgives

youeasytoolstoquicklylaunchawebsiteandthenextenditasyourbusinessgrows.3.eCommerce

WordPressisquicklybecomingagotosolutionforbuildinganeCommercewebsites.There

are awesome plugins like WooCommerce, Easy Digital Downloads, and WPEcommerce

Page 59: Unit -1 Views of Web Programming 1. Introduction to Server

which convert your WordPress website into fully functional eCommerce platform. You

canacceptpayments,manageinventory,shipping,taxes,andusersfromthesameroof.4.JobBoard

Several popular sites like SmashingMagazine, Problogger etc use jobboards as an extra

sourceof income.There isagrowingdemandofniche jobboardscateringtheneedsofa

specificindustryorspecialization.

WordPressallowsyoueasilycreateajobboardwhereemployerscanpostjoblistingsand

professionalscanrespondtothem.5.BusinessDirectory

Just like jobboards, there is increasingdemandofnichebusinessdirectoriesontheweb.

TherearesomegreatWordPressbusinessdirectorypluginswhichallowyoutoeasilycreate

abusinessdirectory.

Page 60: Unit -1 Views of Web Programming 1. Introduction to Server

Youcanevencreatewebdirectorythatisnotlimitedtobusinessesalone.6.Question&AnswerWebsite

Want to create your own version of Yahoo Answers, Stack Exchange, or Quora? With

WordPressyoucaneasilycreateaquestionandanswerssite.Combineitwithothertools,

andyoucanbuildyourselfathrivingonlinecommunityofyourown.7.NonProfitsandReligiousWebsites

WordPressisfreeasinfreedom(seeourguidewhyisWordPressfree?).Thismakesitan

idealsolutionfornonprofitorganizations.

WithWordPress plugins you can add donate form and raisemoney by accepting paypal

donations.TherearesomegreatWordPressthemesforchurchesandnonprofits.

Page 61: Unit -1 Views of Web Programming 1. Introduction to Server

8.PortfolioWebsites

Need a place to showcase yourwork?You can easily add a portfolio to yourWordPress

sitewithstunningimagegalleries,andbeautifulsliders.WordPresscanbeusedtoprovidea

verysleekandpolisheduserexperienceforyourportfoliositemakingiteasierforothersto

browseandlearnaboutyourwork.9.OnlineCommunities

WordPresscanbeusedasanonline forumusingthe lightweightbbPress forum.Youcan

evenaddsocialfeaturestoaWordPresssitewithpluginslikeBuddyPress.

Page 62: Unit -1 Views of Web Programming 1. Introduction to Server

10.CouponWebsite

Wanttoearnaffiliatecommissionsfromthousandsofwebsitesofferingspecialdiscountson

theirproductsandservices?UseWordPresstocreateacouponsite.Itallowsyoutoeasily

add,manage,andexpirecoupons.Youruserscanvoteandratecoupons,anditallfitsright

inyourWordPressadminarea.11.AuctionWebsites

WanttorunyourowneBaylikeauctionswebsite?WithWordPress,youcancreateafully

functionalauctionwebsite.Userscanbidonline,makepayments,andyouget toearnby

simplyprovidingaplatformforyournicheindustry.

Page 63: Unit -1 Views of Web Programming 1. Introduction to Server

12.MultilingualWebsites

YoucaninstallWordPressinmanylanguages,butyoucanalsocreateamultilingualwebsite

aswell.SeehoweasyitistocreatemultilingualwebsitesusingWordPress.13.Knowledgebase/WikiWebsites

Wanttoaddadocumentationsectionwithaknowledgebaseorwikilikearticles?WordPress

comes with great plugins that quickly turn your website into an easy to

browseknowledgebasewiki.

Page 64: Unit -1 Views of Web Programming 1. Introduction to Server

14.PodcastingWebsites

WordPressandpodcastinggohandinhand.Mostpopularpodcastersonthewebareusing

WordPress for theirwebsites.Seeourstepbystepguideonhowtostartapodcastwith

WordPress.15.NicheAffiliateWebsites

Want tomake a commission by referring your users to products and services?Here are

thebestaffiliatemarketingtoolsandpluginsavailableforWordPress.Thesetoolswillboost

youraffiliateearningsandmakethingsalotmoreeasier.

Page 65: Unit -1 Views of Web Programming 1. Introduction to Server

16.PhotographyWebsites

Are you a professional or amateur photographer? Want to share your family vacation

photos? With WordPress and Envira Gallery, you can create astonishingly beautiful

photography websites. You can add galleries, albums, titles, captions, lightbox popups,

slideshows,andthebellsandwhistles.

TherearealsotonsofphotographytemplatesavailableforWordPress.17.SchoolorCollegeWebsites

WordPresspowersthousandsofschoolsandcollegewebsitesaroundtheworld.Itissafe,

secure,andeasytomanage.SeeourlistofpopularuniversitiesthatareusingWordPress.

Page 66: Unit -1 Views of Web Programming 1. Introduction to Server

18.PrivateBlogs

Want to keep your WordPress blog to yourself? See how easily you can make your

WordPressblogcompletelyprivate.Runteamprojects,diaries,orwhateveryouwantina

safeenvironmentawayfrompryingeyes.19.FamilyBlogs

With built inmedia and usermanagement system,WordPress is perfect to create small

familywebsites. Create beautifulweddingwebsites, upload family photos, or add family

gossip.WordPresscanprovideendlessfunforallmembersoffamilyage10andup.Seeour

listofbestWordPressthemesforfamilyblogs.

Wehopethisarticlegaveyousomeideasaboutthekindofwebsitesyoucancreatewith

WordPress. Getting started with WordPress is easier with WPBeginner, see how you

canmakethemostoutofWPBeginner’sfreelearningresources.

8.IntrinsicObjectsinASP.NET

Page 67: Unit -1 Views of Web Programming 1. Introduction to Server

•ASP.NEThasanumberofbuilt-inobjectsthatrunonaWebserver•ThefollowingtableliststheASP.NETbuilt-inobjectsandtheirdescription:Providesmethods,properties,andcollectionstoaccessinformationrelatedtotheuser’ssession.SessionProvidesmethodsandpropertiestoaccessinformationrelatedtotheserver.ServerProvidesmethods,properties,andcollectionstoaccessinformationrelatedtotheresponsegeneratedbytheserver.ResponseProvidesmethods,properties,andcollectionstoaccesstheinformationabouttheclientrequestingthepage.RequestProvidesmethodsandpropertiestoaccessinformationrelatedtotheentireWebapplication.Informationisstoredineithervariablesorobjects.DescriptionObject

• TheApplicationObject:TheApplicationobjectprovidesareferencetoanobjectoftheHttpApplicationStateclass.TheApplicationobjectisusedtoaccessinformationthatisdefinedfortheentireWebapplication.Forexample,theconnectionstringusedtoconnecttothedatabasesevercanbestoredintheApplicationobject.ThefollowingtabledescribessomeofthemethodsoftheApplicationobject:YoucanusethefollowingcodesnippettocreateanApplicationobjecthavingthename,MyName,whichstoresthevalue,JohnApplication[“MyName”]=“John”;Youcanusethefollowingcodesnippettolocktheapplicationobject,retrievethevaluefromtheMyNameApplicationobjectcreatedintheprecedingcode,andfinallyreleasethelock:

Application.Lock();• TheRequestObject:TheRequestobjectprovidesareferencetoanobjectofthe

HttpRequestclass.TheobjectenablesASP.NETapplicationstoaccessinformationsentbytheclientduringaWebrequest.ThefollowingtabledescribessomeofthepropertiesoftheRequestobject:YoucanusethefollowingcodesnippettodisplaytheclientinformationsuchastheIPaddress,browsername,andbrowserversiononthepage:

Page 68: Unit -1 Views of Web Programming 1. Introduction to Server

VOIDPAGE_LOAD()

{

//USINGTHEBROWSERPROPERTYOFTHEREQUESTOBJECTTOOBTAINAN

INSTANCE//OFHTTPBROWSERCAPABILITIESWHICHCONTAINTHEDETAILS

ABOUTTHECLIENT//BROWSER

HTTPBROWSERCAPABILITIESBC=REQUEST.BROWSER;

///USINGTHEUSERHOSTADDRESSPROPERTYOFTHEREQUESTOBJECTTO

OBTAIN////THEIPADDRESSOFREQUESTINGCLIENT

LBL1.TEXT=“IPADDRESS=”+REQUEST.USERHOSTADDRESS;

//USINGINSTANCEOFHTTPBROWSERCAPABILITIESFORDISPLAYINGTHE

CLIENTBROWSERDETAILS.

LBL2.TEXT=“BROWSERNAME=”+BC.BROWSER;

LBL3.TEXT=”BROWSERVERSION=”+BC.VERSION;

}

• TheResponseObject:TheResponseobjectprovidesareferencetoanobjectof

theHttpResponseclass.TheobjectenablesASP.NETapplicationstosend

informationtotheclient.Thefollowingtabledescribessomeoftheproperties

oftheResponseobject:

• TheServerObject:TheServerobjectprovidesareferencetoanobjectofthe

HttpServerUtilityclass.Theobjectprovidesmethodsthatcanbeusedto

accessthemethodsandpropertiesoftheWebserver.Thefollowingtable

describessomeofthepropertiesoftheServerobject:

• TheSessionObject:TheSessionobjectprovidesareferencetoanobjectofthe

HttpSessionStateclass.TheobjectenablesASP.NETapplicationstokeepthe

statusoftheclient.TheSessionobjectalsoprovidesaccesstothesessionwide

cache,whichcanbeusedtostoreinformationpertainingtotheclient.The

sessionstartsandendswhentheclientconnectsanddisconnectstoaWeb

site.Thesessionisalsoterminatediftheclientremainsinactiveforaspecific

Page 69: Unit -1 Views of Web Programming 1. Introduction to Server

period.Thedefaulttimeoutperiodis20minutes.Thefollowingtable

describessomeofthepropertiesoftheSessionobject:

Page 70: Unit -1 Views of Web Programming 1. Introduction to Server

Unit-4

ComponentsProgramming

1.UsingThird-PartycomponentsinASP

Components

AdRotatorTheAdRotatorstreamlinestheprocessofsettingupadeliverysystemforyourbannerads.Inaseparatefile,youstoreinformationregardingthebanner.Thecomponentthendeliversarandomlyselectedbannereverytimethepageisloaded.

BrowserCapabilitiesTheBrowsercomponentletsyoudeterminewhatbrowserauserisusingandwhatfeaturesaresupportedbythatbrowser.

CollaborationDataObjects(CDO)TiedinwiththeIISSMTPserver,CDOletsyousendandreceiveemail.WithCDO,forexample,youcanprocessaformwithoutrelyinguponaPerlscriptandCGI.

ContentLinkingThisisahandyobjectforcreatingalinearorsequentialpathwaythroughyoursiteorasubsectionofthesite.Youmaintainasimpletextfilethatliststhefilesinthepropersequence.Simplenextandpreviouslinksthencanbeaddedtothepage,andatableofcontentscanbeeasilygenerated.

ContentRotatorIfyouhaveaneedforrotatingcontent,thiswillbeafavoritecomponent.Itiseasytouseandallowsyoutoadddynamiccontenttoanypagewithoutusingadatabase.Inaseparatetextfile,youstorechunksofHTMLcodethatyouwantalternatelydroppedintoaspaceonthepage.TheContentRotatorwilldisplayoneofthechunkseachtimethepageisreloaded.

DatabaseAccessUsingthiscomponent,youcanhookintoadatabasetowritecontentstothebrowserscreenandtocreateorupdateexistingdatabasefiles.

Third-PartyComponents

Therearenumerousthird-partycomponents—bothfreeandfee-based—availableforASP.Ifyou'rerunningyourownserver,youcaninstallcomponentsatwill.Registeringa.dllisoftentheextentoftheinstallation,soacomponentcanbearealtime-saver.Insteadofspendinghoursre-creatingthewheel,checktoseeifacomponentexiststohandlethetaskathand.

IfyoursiteishostedbyanISP,youmaynotbeabletoinstallyourowncomponentsorevenhavetheminstalled,socheckwithyourISP'ssupportteam.

Page 71: Unit -1 Views of Web Programming 1. Introduction to Server

2.DevelopingCustomComponentsusingvisualBasic

CreatingandUsingComponentsinVisualBasicAcomponentisaclassthatimplementstheSystem.ComponentModel.IComponentinterfaceorthatderivesdirectlyorindirectlyfromaclassthatimplementsIComponent.A.NETFrameworkcomponentisanobjectthatisreusable,caninteractwithotherobjects,andprovidescontroloverexternalresourcesanddesign-timesupport.Animportantfeatureofcomponentsisthattheyaredesignable,whichmeansthataclassthatisacomponentcanbeusedintheVisualStudioIntegratedDevelopmentEnvironment.AcomponentcanbeaddedtotheToolbox,draggedanddroppedontoaform,andmanipulatedonadesignsurface.Noticethatbasedesign-timesupportforcomponentsisbuiltintothe.NETFramework;acomponentdeveloperdoesnothavetodoanyadditionalworktotakeadvantageofthebasedesign-timefunctionality.Acontrolissimilartoacomponent,asbotharedesignable.However,acontrolprovidesauserinterface,whileacomponentdoesnot.Acontrolmustderivefromoneofthebasecontrolclasses:ControlorControl.

When to Create a Component

Ifyourclasswillbeusedonadesignsurface(suchastheWindowsFormsorWebFormsDesigner)buthasnouserinterface,itshouldbeacomponentandimplementIComponent,orderivefromaclassthatdirectlyorindirectlyimplementsIComponent.TheComponentandMarshalByValueComponentclassesarebaseimplementationsoftheIComponentinterface.ThemaindifferencebetweentheseclassesisthattheComponentclassismarshaledbyreference,whileIComponentismarshaledbyvalue.Thefollowinglistprovidesbroadguidelinesforimplementers.

• Ifyourcomponentneedstobemarshaledbyreference,derivefromComponent.• Ifyourcomponentneedstobemarshaledbyvalue,derive

fromMarshalByValueComponent.• Ifyourcomponentcannotderivefromoneofthebaseimplementationsdueto

singleinheritance,implementIComponent.Formoreinformationaboutdesign-timesupport,seeDesign-TimeAttributesforComponentsandExtendingDesign-TimeSupport.

Component Classes

TheSystem.ComponentModelnamespaceprovidesclassesthatareusedtoimplementtherun-timeanddesign-timebehaviorofcomponentsandcontrols.Thisnamespaceincludesthebaseclassesandinterfacesforimplementingattributesandtypeconverters,bindingtodatasources,andlicensingcomponents.Thecorecomponentclassesare:

Page 72: Unit -1 Views of Web Programming 1. Introduction to Server

• Component.AbaseimplementationfortheIComponentinterface.Thisclassenablesobjectsharingbetweenapplications.

• MarshalByValueComponent.AbaseimplementationfortheIComponentinterface.• Container.ThebaseimplementationfortheIContainerinterface.Thisclass

encapsulateszeroormorecomponents.Someoftheclassesusedforcomponentlicensingare:

• License.Theabstractbaseclassforalllicenses.Alicenseisgrantedtoaspecificinstanceofacomponent.

• LicenseManager.ProvidespropertiesandmethodstoaddalicensetoacomponentandtomanageaLicenseProvider.

• LicenseProvider.Theabstractbaseclassforimplementingalicenseprovider.• LicenseProviderAttribute.SpecifiestheLicenseProviderclasstousewithaclass.

Classescommonlyusedfordescribingandpersistingcomponents.• TypeDescriptor.Providesinformationaboutthecharacteristicsforacomponent,

suchasitsattributes,properties,andevents.• EventDescriptor.Providesinformationaboutanevent.• PropertyDescriptor.Providesinformationaboutaproperty.

3.RegisteringwithMicrosoftTransactionService(MTS)

MicrosoftTransactionServerComponentRegistration

ApplicationcomponentsthatrunintheMicrosoftTransactionServerenvironmentarecreatedasdynamiclinklibraries(DLLs).ApplicationcomponentsareregisteredwithMicrosoftTransactionServerusingtheMicrosoftTransactionServerExplorergraphicaluserinterface(GUI)tool.

TypesofRegistrationComponents

Whenyouregistertheapplicationcomponent,youmarkitasoneofthefollowingtypes:

• RequiresaTransactionThecomponentmustruninatransaction.Ifthetransactiondoesnotcurrentlyexist,MicrosoftTransactionServerautomaticallycreatesanewtransactionforeachmethodinvocationonthecomponent.

• SupportsaTransactionThecomponentcanrunwithintheclient'stransaction.Whenanewcomponentiscreated,itscontextinheritsthetransactionfromthecontextoftheinvokingclient.Iftheclientdoesnothaveatransaction,thenewcontextisalsocreatedwithoutone.

• RequiresaNewTransactionThecomponentmustrunwithinitsowntransaction.MicrosoftTransactionServerautomaticallycreatesanewtransactionforeachmethodinvocationonthecomponent.

• DoesNotSupportTransactionsThecomponentdoesnotrunwithinatransaction.Eachmethodinvocationonthecomponentisperformedwithoutasurroundingtransaction,regardlessofwhethertheinvokingclientincludesatransaction.

RegistrationofComponents

Page 73: Unit -1 Views of Web Programming 1. Introduction to Server

HowyouregisteranapplicationcomponentdeterminesifitrunsinaMicrosoftTransactionServer-coordinatedtransaction.

• IftheapplicationcomponentrunsinaMicrosoftTransactionServer-coordinatedtransaction,theOCIconnectionpoolingisalwaysusedandMicrosoftTransactionServeranditsMSDTCcomponentcoordinatethecreation,startup,management,andcommitmentphasesofthetransaction.MicrosoftTransactionServerensuresthatallchangesmadebythecomponentarecommittedifthetransactionsucceeds,orareterminatedifthetransactionfails.

• IftheapplicationcomponentdoesnotruninaMicrosoftTransactionServer-coordinatedtransaction,thecomponentrunsinaMicrosoftTransactionServerenvironment,butthedatabasesthatitaccessesmayormaynottakepartinMSDTC-coordinatedtransactions.IfthetransactionisnotMSDTC-coordinated,theclientapplicationmustcreate,start,manage,andcommitthetransaction.OCIconnectionpoolingmaybeused,dependingupontheinterfaceaccessingthedatabase(suchasOracleProviderforOLEDB,OracleODBCDriver,OO4O,orothers).

MicrosoftTransactionServer-CoordinatedComponentTransaction

ThissectiondescribeshowOCIconnectionpooling,MicrosoftTransactionServer,andMSDTCoperatewithapplicationcomponentsinaMicrosoftTransactionServer-coordinatedtransactionenvironment.

1. TheclientAPI(oneofOracleODBCDriver,OCI,OO4O,ODP.NETorOracleProviderforOLEDB)callsOCIfunctionOraMTSSvcGet()toobtainaservicecontextfromtheOCIconnectionpoolingcomponent.

2. TheOCIconnectionpoolingcomponentenliststhetransactionthatwillbecoordinatedbytheMSDTCcomponentofMicrosoftTransactionServer.

TheOCIserviceandenvironmenthandlesarereturnedtoclientapplications.

3. Theclientapplication:o Performsthedatabaseoperations.o CallsOCIfunctionOraMTSSvcRel()toreleasetheOCIpoolingconnection

obtainedatthebeginningofthetransaction.o CallsSetComplete(tocommitdatabaseoperations)orSetAbort(toterminate

databaseoperations)ontheMicrosoftTransactionServercontextobjectassociatedwiththecomponent.

4. MSDTCperformsthetwo-phasecommitprotocoltoprepareandcommitortoterminatethetransaction.ThisnotifiestheOCIconnectionpoolingcomponentandendsthetransaction.

5. OCIconnectionpoolingisnotifiedandperformsthenecessarystepstocompletephaseone,thepreparephase,andphasetwo,thecommitorterminatephase.

4.CommunicationwithMicrosoftMessageQueueServer(MSMQ)

Page 74: Unit -1 Views of Web Programming 1. Introduction to Server

MessageQueuing(MSMQ)

PurposeMessageQueuing(MSMQ)technologyenablesapplicationsrunningatdifferenttimestocommunicateacrossheterogeneousnetworksandsystemsthatmaybetemporarilyoffline.Applicationssendmessagestoqueuesandreadmessagesfromqueues.Thefollowingillustrationshowshowaqueuecanholdmessagesthataregeneratedbymultiplesendingapplicationsandreadbymultiplereceivingapplications.

WhereApplicableMessageQueuingprovidesguaranteedmessagedelivery,efficientrouting,security,andpriority-basedmessaging.Itcanbeusedtoimplementsolutionstobothasynchronousandsynchronousscenariosrequiringhighperformance.ThefollowinglistshowsseveralplaceswhereMessageQueuingcanbeused.

• Mission-criticalfinancialservices:forexample,electroniccommerce.• Embeddedandhand-heldapplications:forexample,underlyingcommunicationsto

andfromembeddeddevicesthatroutebaggagethroughairportsbymeansofanautomaticbaggagesystem.

• Outsidesales:forexample,salesautomationapplicationsfortravelingsalesrepresentatives.

• Workflow:MessageQueuingmakesiteasytocreateaworkflowthatupdateseachsystem.Atypicaldesignpatternistoimplementanagenttointeractwitheachsystem.Usingaworkflow-agentarchitecturealsominimizestheimpactofchangesinonesystemontheothersystems.WithMessageQueuing,theloosecouplingbetweensystemsmakesupgradingindividualsystemssimpler.

InstallingMessageQueuing(MSMQ)

ThefollowingproceduresshowhowtoinstallMessageQueuing4.0andMessageQueuing3.0.

Page 75: Unit -1 Views of Web Programming 1. Introduction to Server

ToinstallMessageQueuing4.0onWindowsServer2008orWindowsServer2008R2

1. InServerManager,clickFeatures.2. Intheright-handpaneunderFeaturesSummary,clickAddFeatures.3. Intheresultingwindow,expandMessageQueuing.4. ExpandMessageQueuingServices.5. ClickDirectoryServicesIntegration(forcomputersjoinedtoaDomain),then

clickHTTPSupport.6. ClickNext,thenclickInstall.

ToinstallMessageQueuing4.0onWindows7orWindowsVista

1. OpenControlPanel.2. ClickProgramsandthen,underProgramsandFeatures,clickTurnWindows

Featuresonandoff.3. ExpandMicrosoftMessageQueue(MSMQ)Server,expandMicrosoftMessageQueue

(MSMQ)ServerCore,andthenselectthecheckboxesforthefollowingMessageQueuingfeaturestoinstall:

o MSMQActiveDirectoryDomainServicesIntegration(forcomputersjoinedtoaDomain).

o MSMQHTTPSupport.4. ClickOK.5. Ifyouarepromptedtorestartthecomputer,clickOKtocompletetheinstallation.

ToinstallMessageQueuing3.0onWindowsXPandWindowsServer2003

1. OpenControlPanel.2. ClickAddRemoveProgramsandthenclickAddWindowsComponents.3. SelectMessageQueuingandclickDetails.4. EnsurethattheoptionMSMQHTTPSupportisselectedonthedetailspage.5. ClickOKtoexitthedetailspage,andthenclickNext.Completetheinstallation.6. Ifyouarepromptedtorestartthecomputer,clickOKtocompletetheinstallation.

5.DevelopingrealtimewebsiteusingASP

Page 76: Unit -1 Views of Web Programming 1. Introduction to Server

Tutorial1:BuildingYourFirstWebApplicationProject

Thebelowtutorialwalks-throughhowtocreate,buildandrunyourfirstwebappusingC#

andtheASP.NETWebApplicationProjectsupportinVS2005.

CreatingaNewProject

SelectFile->NewProjectwithintheVisualStudio2005IDE.ThiswillbringuptheNew

Projectdialog.Clickonthe“VisualC#”nodeinthetree-viewonthelefthandsideofthe

dialogboxandchoosethe"ASP.NETWebApplication"icon:

Choosewhereyouwanttheprojecttobecreatedondisk(notethatthereisnolongera

requirementforwebprojectstobecreatedunderneaththeinetpub\wwwrootdirectory--

soyoucanstoretheprojectanywhereonyourfilesystem).Thennameitandhitok.

VisualStudiowillthencreateandopenanewwebprojectwithinthesolutionexplorer.By

defaultitwillhaveasinglepage(Default.aspx),anAssemblyInfo.csfile,aswellasa

web.configfile.Allprojectfile-meta-dataisstoredwithinaMSBuildbasedprojectfile.

Page 77: Unit -1 Views of Web Programming 1. Introduction to Server

OpeningandEditingthePage

DoubleclickontheDefault.aspxpageinthesolutionexplorertoopenandeditthepage.

YoucandothisusingeithertheHTMLsourceeditororthedesign-view.Adda"Hello

world"headertothepage,alongwithacalendarservercontrolandalabelcontrol(we'll

usetheseinalatertutorial):

BuildandRuntheProject

HitF5tobuildandruntheprojectindebugmode.Bydefault,ASP.NETWebApplication

projectsareconfiguredtousethebuilt-inVSweb-server(akaCassini)whenrun.The

Page 78: Unit -1 Views of Web Programming 1. Introduction to Server

defaultprojecttemplateswillrunonarandomportasarootsite(forexample:

http://localhost:12345/):

Youcanendthedebugsessionbyclosingthebrowserwindow,orbychoosingtheDebug-

>StopDebugging(Shift-F5)menuitem.

Lookingunderthecovers

Whenyoucompile/buildASP.NETWebApplicationprojects,allcode-behindcode,

embeddedresources,andstandaloneclassfilesarecompiledintoasingleassemblythatis

builtinthe\binsub-directoryunderneaththeprojectroot(note:youcanoptionallychange

thelocationifyouwantto-forexample,tobuilditintoaparentapplicationdirectory).

Ifyouchoosethe"ShowAllFiles"buttoninthesolutionexplorer,youcanseewhatthe

resultofourcompilationoutputlookslike:

Page 79: Unit -1 Views of Web Programming 1. Introduction to Server

ThisworksexactlythesameaswithVisualStudio2003ASP.NETWebApplicationProjects

CustomizingProjectProperties

ASP.NETWebApplicationProjectssharethesameconfigurationsettingsandbehaviorsas

standardVS2005classlibraryprojects.Youaccesstheseconfigurationsettingsbyright-

clickingontheprojectnodewithintheSolutionExplorerinVS2005andselectingthe

"Properties"context-menuitem.Thiswillthenbringuptheprojectproperties

configurationeditor.Youcanusethistochangethenameofthegeneratedassembly,the

buildcompilationsettingsoftheproject,itsreferences,itsresourcestringvalues,code-

signingsettings,etc:

ASP.NETWebApplicationProjectsalsoaddanewtabcalled"Web"totheproject

propertieslist.Developersusethistabtoconfigurehowawebprojectisrunanddebugged.

Page 80: Unit -1 Views of Web Programming 1. Introduction to Server

Bydefault,ASP.NETWebApplicationProjectsareconfiguredtolaunchandrunusingthe

built-inVSWebServer(akaCassini)onarandomHTTPportonthemachine.

Thisportnumbercanbechangedifthisportisalreadyinuse,orifyouwanttospecifically

testandrunusingadifferentnumber:

Alternatively,VisualStudiocanconnectanddebugIISwhenrunningthewebapplication.

TouseIISinstead,selectthe"UseIISWebServer"optionandentertheurlofthe

applicationtolaunch,connect-to,andusewhenF5orControl-F5isselected:

Page 81: Unit -1 Views of Web Programming 1. Introduction to Server

Thenconfiguretheurltothisapplicationintheabovepropertypageforthewebproject.

WhenyouhitF5intheproject,VisualStudiowillthenlaunchabrowsertothatweb

applicationandautomaticallyattachadebuggertotheweb-serverprocesstoenableyouto

debugit.

NotethatASP.NETWebApplicationProjectscanalsocreatetheIISvrootandconfigurethe

applicationforyou.Todothisclickthe"CreateVirtualDirectory"button.

Page 82: Unit -1 Views of Web Programming 1. Introduction to Server

Unit-5

ExtendedMark-upLanguage(XML)

1.IntroductiontoXML

XMLstandsforExtensibleMarkupLanguageandisatext-basedmarkuplanguagederivedfromStandardGeneralizedMarkupLanguage(SGML).

ThistutorialwillteachyoubasicsofXML.ThetutorialisdividedintosectionssuchasXMLBasics,AdvancedXMLandXMLtools.

XMLstandsforExtensibleMarkupLanguage.It isatext-basedmarkuplanguagederivedfromStandardGeneralizedMarkupLanguage(SGML).

XML tags identify the data and are used to store and organize the data, rather thanspecifyinghowtodisplayitlikeHTMLtags,whichareusedtodisplaythedata.XMLisnotgoingtoreplaceHTMLinthenearfuture,butitintroducesnewpossibilitiesbyadoptingmanysuccessfulfeaturesofHTML.

TherearethreeimportantcharacteristicsofXMLthatmakeitusefulinavarietyofsystemsandsolutions:

• XML is extensible: XML allows you to create your own self-descriptive tags, orlanguage,thatsuitsyourapplication.

• XML carries the data, does not present it: XML allows you to store the datairrespectiveofhowitwillbepresented.

• XMLisapublicstandard:XMLwasdevelopedbyanorganizationcalledtheWorldWideWebConsortium(W3C)andisavailableasanopenstandard.

XMLUsage

AshortlistofXMLusagesaysitall:

• XMLcanworkbehindthescenetosimplifythecreationofHTMLdocumentsforlargewebsites.

• XMLcanbeusedtoexchangetheinformationbetweenorganizationsandsystems.

Page 83: Unit -1 Views of Web Programming 1. Introduction to Server

• XMLcanbeusedforoffloadingandreloadingofdatabases.

• XML can be used to store and arrange the data, which can customize your datahandlingneeds.

• XMLcaneasilybemergedwithstylesheetstocreatealmostanydesiredoutput.

• Virtually,anytypeofdatacanbeexpressedasanXMLdocument.

WhatisMarkup?

XMLisamarkuplanguagethatdefinessetofrulesforencodingdocumentsinaformatthatis both human-readable and machine-readable. So what exactly is a markuplanguage?Markupisinformationaddedtoadocumentthatenhancesitsmeaningincertainways,inthatitidentifiesthepartsandhowtheyrelatetoeachother.Morespecifically,amarkup language is a set of symbols that can be placed in the text of a document todemarcateandlabelthepartsofthatdocument.

FollowingexampleshowshowXMLmarkuplooks,whenembeddedinapieceoftext:

<message>

<text>Hello,world!</text>

</message>

Thissnippetincludesthemarkupsymbols,orthetagssuchas<message>...</message>and<text>...</text>.Thetags<message>and</message>markthestartandtheendoftheXMLcodefragment.Thetags<text>and</text>surroundthetextHello,world!.

IsXMLaProgrammingLanguage?

Aprogramminglanguageconsistsofgrammarrulesanditsownvocabularywhichisusedtocreatecomputerprograms.Theseprogramsinstructscomputertoperformspecifictasks.XMLdoesnotqualifytobeaprogramminglanguageasitdoesnotperformanycomputationoralgorithms.ItisusuallystoredinasimpletextfileandisprocessedbyspecialsoftwarethatiscapableofinterpretingXML.

2.Elements

XML elements can be defined as building blocks of an XML. Elements can behave ascontainerstoholdtext,elements,attributes,mediaobjectsorallofthese.

Page 84: Unit -1 Views of Web Programming 1. Introduction to Server

EachXMLdocumentcontainsoneormoreelements,thescopeofwhichareeitherdelimitedbystartandendtags,orforemptyelements,byanempty-elementtag.

SyntaxFollowingisthesyntaxtowriteanXMLelement:

<element-nameattribute1attribute2>

....content

</element-name>

where

• element-name isthenameoftheelement.Thename itscaseinthestartandendtagsmustmatch.

• attribute1,attribute2areattributesoftheelementseparatedbywhitespaces.Anattributedefinesapropertyoftheelement.Itassociatesanamewithavalue,whichisastringofcharacters.Anattributeiswrittenas:

name="value"

name is followed by an= sign and a string value inside double(" ") or single(' ')quotes.

EmptyElementAnemptyelement(elementwithnocontent)hasfollowingsyntax:

<nameattribute1attribute2.../>

ExampleofanXMLdocumentusingvariousXMLelement:

<?xmlversion="1.0"?>

<contact-info>

<addresscategory="residence">

<name>TanmayPatil</name>

<company>TutorialsPoint</company>

<phone>(011)123-4567</phone>

<address/>

</contact-info>

XMLElementsRules

Page 85: Unit -1 Views of Web Programming 1. Introduction to Server

FollowingrulesarerequiredtobefollowedforXMLelements:

• Anelementname cancontainanyalphanumericcharacters.Theonlypunctuationmarkallowedinnamesarethehyphen(-),under-score(_)andperiod(.).

• Namesarecasesensitive.Forexample,Address,address,andADDRESSaredifferentnames.

• Startandendtagsofanelementmustbeidentical.

3.Attributes

AttributesarepartoftheXMLelements.Anelementcanhavemultipleuniqueattributes.Attribute givesmore information about XML elements. To bemore precise, they definepropertiesofelements.AnXMLattributeisalwaysaname-valuepair.

SyntaxAnXMLattributehasfollowingsyntax:

<element-nameattribute1attribute2>

....content..

</element-name>

whereattribute1andattribute2hasthefollowingform:

name="value"

valuehastobeindouble("")orsingle('')quotes.Here,attribute1andattribute2areuniqueattributelabels.

Attributesareusedtoaddauniquelabeltoanelement,placethelabelinacategory,addaBoolean flag, or otherwise associate it with some string of data. Following exampledemonstratestheuseofattributes:

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEgarden[

<!ELEMENTgarden(plants)*>

<!ELEMENTplants(#PCDATA)>

<!ATTLISTplantscategoryCDATA#REQUIRED>

]>

Page 86: Unit -1 Views of Web Programming 1. Introduction to Server

<garden>

<plantscategory="flowers"/>

<plantscategory="shrubs">

</plants>

</garden>

Attributesareusedtodistinguishamongelementsofthesamename.Whenyoudonotwanttocreateanewelementforeverysituation.Hence,useofanattributecanaddalittlemoredetailindifferentiatingtwoormoresimilarelements.

Intheaboveexample,wehavecategorizedtheplantsbyincludingattributecategoryandassigningdifferentvaluestoeachoftheelements.Hencewehavetwocategoriesofplants,oneflowersandothercolor.Hencewehavetwoplantelementswithdifferentattributes.

YoucanalsoobservethatwehavedeclaredthisattributeatthebeginningoftheXML.

AttributeTypesFollowingtableliststhetypeofattributes:

AttributeType Description

StringType It takes any literal string as a value. CDATA is a StringType. CDATA ischaracterdata.Thismeans,anystringofnon-markupcharacters isa legalpartoftheattribute.

TokenizedType Thisismoreconstrainedtype.Thevalidityconstraintsnotedinthegrammarare applied after the attribute value is normalized. The TokenizedTypeattributesaregivenas:

• ID:Itisusedtospecifytheelementasunique.• IDREF:ItisusedtoreferenceanIDthathasbeennamedforanother

element.• IDREFS:ItisusedtoreferenceallIDsofanelement.• ENTITY:Itindicatesthattheattributewillrepresentanexternal

entityinthedocument.• ENTITIES:Itindicatesthattheattributewillrepresentexternal

entitiesinthedocument.

Page 87: Unit -1 Views of Web Programming 1. Introduction to Server

• NMTOKEN:ItissimilartoCDATAwithrestrictionsonwhatdatacanbepartoftheattribute.

• NMTOKENS:ItissimilartoCDATAwithrestrictionsonwhatdatacanbepartoftheattribute.

EnumeratedType Thishasa listofpredefinedvaluesin itsdeclaration.outofwhich, itmustassignonevalue.Therearetwotypesofenumeratedattribute:

• NotationType:ItdeclaresthatanelementwillbereferencedtoaNOTATIONdeclaredsomewhereelseintheXMLdocument.

• Enumeration:Enumerationallowsyoutodefineaspecificlistofvaluesthattheattributevaluemustmatch.

ElementAttributeRulesFollowingaretherulesthatneedtobefollowedforattributes:

• Anattributenamemustnotappearmorethanonceinthesamestart-tagorempty-elementtag.

• An attribute must be declared in the Document Type Definition (DTD) using anAttribute-ListDeclaration.

• Attribute valuesmust not contain direct or indirect entity references to externalentities.

• Thereplacementtextofanyentityreferredtodirectlyorindirectlyinanattributevaluemustnotcontaineitherlessthansign<

4.BrowserCompatibility

XMLWebAuthorwasdevelopedandcontinuouslytestedonthefollowingmajorWebbrowsers:

• Chrome20andnewer,runningondesktopsystems.[Recommendedforoptimalperformanceanduserexperience]

• ChromeforAndroid4.3andnewer,runningonAndroid-enableddevices.• MozillaFirefox19andnewer,runningondesktopsystems.• InternetExplorer9andnewer,runningondesktopsystems.• Opera15andnewer,runningondesktopsystems.• OSXSafari6,runningonOSX.• SafariMobileiOS6,runningoniOSdevices.

Page 88: Unit -1 Views of Web Programming 1. Introduction to Server

AsanHTML5application,itislikelytoworkonotherHTML5compliantbrowsersforvariousplatforms.

KnownIssuesDuetoimplementationparticularities,OxygenXMLWebAuthormayexhibitminorbehavioraldifferences:

• OnAndroiddevicesthecontentcompletionlistofproposalsmightdisplayundefinedelements.Topreventthis,gotoSettings>BandwidthManagement>ReducedatausageandselectOFF.

• OnSafariMobileandChromeforAndroid,thereisnowarningmessageifyouclosethebrowserpagewithoutsavingthechangesmadeinthedocument.

• InputMethodEditor(IME)isfullysupportedonlywhenrunningOxygenXMLWebAuthorinaChromebrowseronaWindowsplatform.

• OnSafariMobile,thenativeBold,Italic,andUnderlineactionsdonotwork.Asaworkaround,usetheframework-specificmarkup.

• OnAndroiddevices,theeditingworksbestwithGoogleKeyboardhavingtheAuto-correctionoptiondisabledandtheShowcorrectionsuggestionsoptionsettoAlwayshidden.Alternatively,youcanuseGooglevoicetyping.

Note:Usingotherkeyboardscanleadtounpredictableresults.Ifyourdocumentgetscorrupted,usetheUndobutton.

• OnSafariMobileversions6and7,thecopy/pastesupportignoresalltextformatting,keepingonlythecontent.

5.Creating&DesigningTags

InthiswalkthroughyouwillcreateanXMLpurchaseorderschemaaspartofaWindowsApplicationproject.Thewalkthroughwillconsistofthreemainsections:

1. CreatingaWindowsApplicationprojectandaddinganXMLschema.2. Creatingarelationaltable:

a. AddinganddefininganewsimpleTypeobject.b. AddinganddefininganewcomplexTypeobject.c. AddinganddefininganewElementobject.

3. EditinggeneratedXMLusingtheXMLeditor.Creating a Windows Application and Adding an XML Schema

To create a new Windows Application project

1. FromtheFilemenu,createanewproject.2. SelectalanguageintheProjectTypespane,andthenselectWindowsApplication.3. NametheprojectSampleSchema.

To add an XML Schema to the project

• FromtheProjectmenu,chooseAddNewItem,thendouble-clicktheXMLSchemaiconintheAddNewItemdialogbox.

Page 89: Unit -1 Views of Web Programming 1. Introduction to Server

TheXMLDesigneropens.Defining Simple and Complex TypesBeforeconstructingtherelationaltable,youwillfirstbuildsimpleandcomplextypedefinitionsthatyouwillusetoformatspecificelementsofthepurchase-orderschema.ThenewtypesarebuiltusingexistingXMLdatatypes,suchasstringandinteger.Firstyouwilldefineasimpletype,whichwillbenamedstateCode.Thissimpletypewillbeusedtolimitthesizeofastringtotwocharacters.

To add an XML simpleType to the project

1. Ifnotalreadyopen,double-clicktheXMLSchema1.xsdfiletobringuptheXMLDesigner.

2. ClicktheXMLSchemataboftheToolboxanddragasimpleTypeontothedesignsurface.

3. ChangethenameofthesimpleTypebyclickingthefirsttextboxintheheaderandreplacingsimpleType1withstateCode.

4. SetthebasetypeforthestateCodetypebyclickingthedrop-downlistintheheaderandselectingstring.

5. NavigatetothefirstcellinthenextrowbypressingtheTABkey.6. Selectfacetfromthedrop-downlist.7. PressTABtogotothenextcellandselectlengthfromthedrop-downlist.8. TABtothethirdcellofthesamerow,andthenenterthevalue2.

ThisrequiresthatthevalueenteredintotheStatefieldbetwocharacters.YourstateCodeshouldlooklikethisinSchemaview:

9. ClicktheXMLtabatthebottomleftofthedesignertoseetheXMLthathasbeenadded:

10. <xs:simpleTypename="stateCode">11. <xs:restrictionbase="xs:string">12. <xs:lengthvalue="2"/>13. </xs:restriction>14. </xs:simpleType>

ThisstateCodesimpletypewillbeusedtodefinetheStateelementwithinthecomplextypeyouwillcreateinthenextsection.ThecomplexTypenamedaddressTypedefinesasetofelementsthatwillappearinanyelementtypedasaddressType.Forexample,abillToelementwillincludeinformationonnames,addresses,anddateswhenitstypeissettothepreviouslydefinedaddressType.Byconstructingthecomplextypeandusingitwithinanelement,youaregeneratinganestedrelationship.Formoreinformation,seeHowto:CreateComplexXMLTypes(XMLDesigner).

To add an XML complexType to the project

1. ClicktheSchemataboftheXMLDesigner.

Page 90: Unit -1 Views of Web Programming 1. Introduction to Server

2. DragacomplexTypefromtheXMLSchemataboftheToolboxontothedesignsurface.

3. ChangecomplexType1toaddressTypetonamethetype.4. AddanXMLattributetoaddressTypebyclickingthefirstcellofthefirstrowand

selectingelementfromthedrop-downlist.5. Inthesecondcolumn,changeelement1toName.6. Inthethirdcolumn,acceptthedefaultvalueofstring.7. AddthefollowingXMLelementsandsettheirnamesandtypesasfollows:

Elementname Datatype

Street string

City string

State stateCode

PostalCode integer

8. YouraddressTypeshouldlooklikethisinSchemaview:

9. 10. ToseetheXMLthathasbeenaddedtoyour.xsdfile,clicktheXMLtabatthebottom

ofthedesigner.YouwillseethefollowingXML:<xs:complexTypename="addressType">

<xs:sequence><xs:elementname="Name"type="xs:string"/>

<xs:elementname="Street"type="xs:string"/><xs:elementname="City"type="xs:string"/><xs:elementname="State"type="stateCode"/><xs:elementname="PostalCode"type="xs:integer"/>

</xs:sequence></xs:complexType>

Creating a Relational TableWhenyoudragtheelementobject fromtheToolboxtothedesignsurface,youarereallyaddinganelementcontaininganunnamedcomplexType.Includingtheunnamedcomplextypedefines the element tobe a relational table.Additional elements can thenbe addedunderthecomplexTypetodefinetherelationfields(orcolumns).IfyoudefineoneofthesenewelementstobeanewunnamedcomplexType,youarecreatinganestedrelationinsideoftheparentrelationwithitsownuniquecolumns.

Page 91: Unit -1 Views of Web Programming 1. Introduction to Server

DefiningnewunnamedcomplextypeelementswithinthePurchaseOrderorItemselementcreates additional nesting in the schema.Within one purchase order there can bemanyItems,andwithineachItem,manyadditionalelements(suchasprice,size,andsoon).Inthefollowingprocedure,anelementItemsisaddedtothepurchaseOrderrelationaltableandtypedasanunnamedcomplexType.Becauseyouaredefininganewrelational table, thiscausesanewelementtoappearonthedesignsurface.Withinthenewitemsrelation,addingtheitemelementandsettingitstypetounnamedcomplexType,createsanotherrelationaltable,whichalsoappearsonthedesignsurface.

To add an XML element to the project

1. ClicktheToolboxandfromtheXMLSchematabdraganelementobjectontothedesignsurface.

2. Changeelement1 toPurchaseOrder tonametheelement.Youcanleavethedatatypeas(PurchaseOrder).

3. Addanelementtothepurchaseorderbyclickingthefirstcellofthefirstrowandselectingelementfromthedrop-downlist.

4. NametheelementshipToandsetitsdatatypetoaddressType.5. AddthefollowingXMLelementsandsettheirnamesandtypesasfollows:

Elementname Datatype

billTo addressType

shipDate date

Items unnamed complexType

6. WhenyoutypetheItemselementtobeanonymous,anadditionalelementisaddedtothedesignsurface,whichisanotherrelationaltable.

7. IntheItemselement,addanelement,nameitItem,andsetitstypetoUnnamedComplexType.YourpurchaseordershouldlooklikethisinSchemaview:

Page 92: Unit -1 Views of Web Programming 1. Introduction to Server

ThefollowingXMLhasnowbeenaddedtoyour.xsdfile:<xs:elementname="PurchaseOrder"><xs:complexType><xs:sequence><xs:elementname="shipTo"type="addressType"/><xs:elementname="billTo"type="addressType"/><xs:elementname="shipDate"type="xs:date"/><xs:elementname="Items"><xs:complexType><xs:sequence><xs:elementname="Item"><xs:complexType><xs:sequence/></xs:complexType></xs:element></xs:sequence></xs:complexType></xs:element></xs:sequence></xs:complexType></xs:element>

Editing the XMLYoucanusetheXMLtaboftheXMLDesignertoedittheXMLthatwasgeneratedwhenyouaddedelementsandtypestothedesignersurface.TheXMLeditorfeaturesIntelliSenseandstatementcompletion.Aninvalidstatementistaggedwitharedwavyline.Restingyourmousepointerovertheincorrectstatementcausesanerrormessagetoappear.

To edit XML

1. ClicktheXMLtaboftheXMLDesignertoviewtheXML.

Page 93: Unit -1 Views of Web Programming 1. Introduction to Server

2. WithintheItemelement,changetheself-closingtag(<xs:sequence/>)intoseparateopeningandclosingtags(<xs:sequence></xs:sequence>).

3. Afterthe<xs:sequence>tagintheItemelement,typethefollowing:4. <xs:elementname="Quantity"type="xs:integer"/>5. <xs:elementname="Price"type="xs:decimal"/>6. <xs:elementname="ProductID"type="xs:integer"/>

Youhavecreatedthreenewelements—Quantity,Price,andProductID—anddefineddatatypesforeach.

7. Nexttype<invalid/>andnotetheredwavylineindicatinganerror.Mouseovertheredwavylinetoseeanerrormessage.ErrorswillappearintheTaskListaswell.

8. Deletethe<invalid/>tagtofixtheerror.9. Savetheschema.

TheXMLbeneaththeItemselementshouldnowlooklikethefollowinginXMLview:<xs:elementname="Items"><xs:complexType><xs:sequence><xs:elementname="Item"><xs:complexType><xs:sequence><xs:elementname="Quantity"type="xs:integer"/><xs:elementname="Price"type="xs:decimal"/><xs:elementname="ProductID"type="xs:integer"/></xs:sequence></xs:complexType></xs:element></xs:sequence></xs:complexType></xs:element>

6.DocumentsStructure

The XML Recommendation states that an XML document has both logical and physicalstructure.Physically,itiscomprisedofstorageunitscalledentities,eachofwhichmayrefertootherentities,similartothewaythatincludeworksintheClanguage.Logically,anXMLdocument consists of declarations, elements, comments, character references, andprocessinginstructions,collectivelyknownasthemarkup.NOTE

Althoughthroughoutthisbookwerefertoan"XMLdocument,"itiscrucialtounderstandthatXMLmaynotexistasaphysicalfileondisk.XMLissometimesusedtoconveymessagesbetweenapplications,suchasfromaWebservertoaclient.TheXMLcontentmaybegeneratedonthefly,forexamplebyaJavaapplicationthataccessesadatabase.Itmaybeformedbycombiningpiecesofseveralfiles,possiblymixedwithoutputfromaprogram.However,inallcases,thebasicstructureandsyntaxofXMLisinvariant.

Page 94: Unit -1 Views of Web Programming 1. Introduction to Server

AnXMLdocumentconsistsofthreeparts,intheordergiven:

1. AnXMLdeclaration(whichistechnicallyoptional,butrecommendedinmostnormalcases)

2. AdocumenttypedeclarationthatreferstoaDTD(whichisoptional,butrequiredifyouwantvalidation)

3. Abodyordocumentinstance(whichisrequired)

Collectively,theXMLdeclarationandthedocumenttypedeclarationarecalledtheXMLprolog.

XML Declaration

TheXMLdeclarationisapieceofmarkup(whichmayspanmultiplelinesofafile)thatidentifiesthisasanXMLdocument.ThedeclarationalsoindicateswhetherthedocumentcanbevalidatedbyreferringtoanexternalDocumentTypeDefinition(DTD).DTDsarethesubjectofchapter4;fornow,justthinkofaDTDasasetofrulesthatdescribesthestructureofanXMLdocument.

TheminimalXMLdeclarationis:

<?xmlversion="1.0"?>

XMLiscase-sensitive(moreaboutthisinthenextsubsection),soit'simportantthatyouuselowercaseforxmlandversion.Thequotesaroundthevalueoftheversionattributearerequired,asarethe?characters.Atthetimeofthiswriting,"1.0"istheonlyacceptablevaluefortheversionattribute,butthisiscertaintochangewhenasubsequentversionoftheXMLspecificationappears.NOTE

Donotincludeaspacebeforethestringxmlorbetweenthequestionmarkandtheanglebrackets.Thestrings<?xmland?>mustappearexactlyasindicated.Thespacebeforethe?>isoptional.NoblanklinesorspacemayprecedetheXMLdeclaration;addingwhitespaceherecanproducestrangeerrormessages.Inmostcases,thisXMLdeclarationispresent.Ifso,itmustbetheveryfirstlineofthedocumentandmustnothaveleadingwhitespace.Thisdeclarationistechnicallyoptional;

Page 95: Unit -1 Views of Web Programming 1. Introduction to Server

caseswhereitmaybeomittedincludewhencombiningXMLstorageunitstocreatealarger,compositedocument.

Actually,theformaldefinitionofanXMLdeclaration,accordingtotheXML1.0specificationisasfollows:

XMLDecl::='<?xml'VersionInfoEncodingDecl?SDDecl?S?'?>'

ThisExtendedBackus-NaurForm(EBNF)notation,characteristicofmanyW3Cspecifications,meansthatanXMLdeclarationconsistsoftheliteralsequence'<?xml',followedbytherequiredversioninformation,followedbyoptionalencodingandstandalonedeclarations,followedbyanoptionalamountofwhitespace,andterminatingwiththeliteralsequence'?>'.Inthisnotation,aquestionmarknotcontainedinquotesmeansthatthetermthatprecedesitisoptional.ThefollowingdeclarationmeansthatthereisanexternalDTDonwhichthisdocumentdepends.SeethenextsubsectionfortheDTDthatthisnegativestandalonevalueimplies.

<?xmlversion="1.0"standalone="no"?>

Ontheotherhand,ifyourXMLdocumenthasnoassociatedDTD,thecorrectXMLdeclarationis:

<?xmlversion="1.0"standalone="yes"?>

TheXML1.0Recommendationstates:"Ifthereareexternalmarkupdeclarationsbutthereisnostandalonedocumentdeclaration,thevalue'no'isassumed."

TheoptionalencodingpartofthedeclarationtellstheXMLprocessor(parser)howtointerpretthebytesbasedonaparticularcharacterset.ThedefaultencodingisUTF-8,whichisoneofsevencharacter-encodingschemesusedbytheUnicodestandard,alsousedasthedefaultforJava.InUTF-8,onebyteisusedtorepresentthemostcommoncharactersandthreebytesareusedforthelesscommonspecialcharacters.UTF-8isanefficientformofUnicodeforASCII-baseddocuments.Infact,UTF-8isasupersetofASCII.3

Page 96: Unit -1 Views of Web Programming 1. Introduction to Server

<?xmlversion="1.0"encoding="UTF-8"?>

ForAsianlanguages,however,anencodingofUTF-16ismoreappropriatebecausetwobytesarerequiredforeachcharacter.ItisalsopossibletospecifyanISOcharacterencoding,suchasinthefollowingexample,whichreferstoASCIIplusGreekcharacters.Note,however,thatsomeXMLprocessorsmaynothandleISOcharactersetscorrectlysincethespecificationrequiresonlythattheyhandleUTF-8andUTF-16.

<?xmlversion="1.0"encoding="ISO-8859-7"?>

Boththestandaloneandencodinginformationmaybesupplied:

<?xmlversion="1.0"standalone="no"encoding="UTF-8"?>

Isthenextexamplevalid?

<?xmlversion="1.0"encoding='UTF-8'standalone='no'?>

Yes,itis.Theorderofattributesdoesnotmatter.Singleanddoublequotescanbeusedinterchangeably,providedtheyareofmatchingkindaroundanyparticularattributevalue.(Althoughthereisnogoodreasoninthisexampletousedoublequotesforversionandsinglequotesfortheother,youmayneedtodosoiftheattributevaluealreadycontainsthekindofquotesyouprefer.)Finally,thelackofablankspacebetween'no'and?>isnotaproblem.NeitherofthefollowingXMLdeclarationsisvalid.

<?XMLVERSION="1.0"STANDALONE="no"?>

<?xmlversion="1.0"standalone="No"?>

Page 97: Unit -1 Views of Web Programming 1. Introduction to Server

Thefirstisinvalidbecausetheseparticularattributenamesmustbelowercase,asmust"xml".Theproblemwiththeseconddeclarationisthatthevalueofthestandaloneattributemustbeliterally"yes"or"no",not"No".(DoIdarecallthisa"noNo"?)

Document Type Declaration

The document type declaration follows the XML declaration. The purpose of this declaration is to announce the root

element (sometimes called the document element) and to provide the location of the DTD.4 The general syntax is:

<!DOCTYPE RootElement (SYSTEM | PUBLIC)

ExternalDeclarations? [InternalDeclarations]? >

where <!DOCTYPE is a literal string, RootElement is whatever you name the outermost element of your hierarchy,

followed by either the literal keyword SYSTEM or PUBLIC. The optionalExternalDeclarations portion is typically

the relative path or URL to the DTD that describes your document type. (It is really only optional if the entire DTD

appears as an InternalDeclaration, which is neither likely nor desirable.) If there

are InternalDeclarations, they must be enclosed in square brackets. In general, you'll encounter far more

cases with ExternalDeclarations than InternalDeclarations, so let's ignore the latter for now. They

constitute the internal subset, which is described in chapter 4.

Let's start with a simple but common case. In this example, we are indicating that the DTD and the XML document

reside in the same directory (i.e., the ExternalDeclarations are contained in the fileemployees.dtd) and that

the root element is Employees:

<!DOCTYPE Employees SYSTEM "employees.dtd">

Similarly,

<!DOCTYPE PriceList SYSTEM "prices.dtd">

indicates a root element PriceList and the DTD is in the local file: prices.dtd.

In the next example, we use normal directory path syntax to indicate a different location for the DTD.

Page 98: Unit -1 Views of Web Programming 1. Introduction to Server

<!DOCTYPE Employees SYSTEM "../dtds/employees.dtd">

As is often the case, we might want to specify a URL for the DTD since the XML file may not even be on the same

host as the DTD. This case also applies when you are using an XML document for message passing or data

transmission across servers and still want the validation by referencing a common DTD.

<!DOCTYPE Employees SYSTEM

"http://somewhere.com/dtds/employees.dtd">

Next, we have the case of the PUBLIC identifier. This is used in formal environments to declare that a given DTD is

available to the public for shared use. Recall that XML's true power as a syntax relates to developing languages that

permit exchange of structured data between applications and across company boundaries. The syntax is a little

different:

<!DOCTYPE RootElement PUBLIC PublicID URI>

The new aspect here is the notion of a PublicID, which is a slightly involved formatted string that identifies the

source of the DTD whose path follows as the URI. This is sometimes known as the Formal Public Identifier (FPI).

For example, I was part of a team that developed (Astronomical) Instrument Markup Language (AIML, IML) for NASA

Goddard Space Flight Center.5 We wanted our DTD to be available to other astronomers. Our document type

declaration (with a root element named Instrument) was:

<!DOCTYPE Instrument PUBLIC

"-//NASA//Instrument Markup Language 0.2//EN"

"http://pioneer.gsfc.nasa.gov/public/iml/iml.dtd">

In this case the PublicID is:

Page 99: Unit -1 Views of Web Programming 1. Introduction to Server

"-//NASA//Instrument Markup Language 0.2//EN"

The URI that locates the DTD is:

http://pioneer.gsfc.nasa.gov/public/iml/iml.dtd

Let's decompose the PublicID. The leading hyphen indicates that NASA is not a standards body. If it were, a plus

sign would replace the hyphen, except if the standards body were ISO, in which case the string "ISO" would appear.

Next we have the name of the organization responsible for the DTD (NASA, in this case), surrounded with double

slashes, then a short free-text description of the DTD ("Instrument Markup Language 0.2"), double slashes, and a

two-character language identifier ("EN" for English, in this case).

Since the XML prolog is the combination of the XML declaration and the document type declaration, for our NASA

example the complete prolog is:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<!DOCTYPE Instrument PUBLIC

"-//NASA//Instrument Markup Language 0.2//EN"

"http://pioneer.gsfc.nasa.gov/public/iml/iml.dtd">

As another example, let's consider a common case involving DTDs from the W3C, such as those for XHTML 1.0.

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 100: Unit -1 Views of Web Programming 1. Introduction to Server

W3C is identified as the organization, "DTD XHTML 1.0 Transitional" is the name of the DTD; it is in English; and the

actual DTD is located by the URI http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd. Similarly, the prolog for

XHTML Basic 1.0 is:

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN"

"http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">

The XHTML Basic 1.0 PublicID is similar but not identical to the XHTML 1.0 case and of course the DTD is

different since it's a different language.

If you noticed that the NASA example uses uppercase for the encoding value UTF-8 and the W3C examples use

lowercase, you may have been bothered because that is inconsistent with what we learned about the case-sensitive

value for the standalone attribute. The only explanation I can offer is that although element and attribute names are

always case-sensitive, attributes values may or may not be. A reasonable guess is that if the possible attribute values

are easily enumerated (i.e., "yes" or "no", or other relatively short lists of choices), then case probably matters.

NOTE

DTD-relatedkeywordssuchasDOCTYPE,PUBLIC,andSYSTEMmustbeuppercase.XML-relatedattributenamessuchasversion,encoding,andstandalonemustbelowercase.

Document Body

Thedocumentbody,or instance, is thebulkof the informationcontentof thedocument.Whereas across multiple instances of a document of a given type (as identified bytheDOCTYPE)theXMLprologwillremainconstant,thedocumentbodychangeswitheachdocument instance (in general). This is because the prolog defines (either directly orindirectly) the overall structure while the body contains the real instance-specific data.Comparingthistodatastructuresincomputerlanguages,theDTDreferencedintheprologisanalogoustoastructintheClanguageoraclassdefinitioninJava,andthedocumentbodyisanalogoustoaruntimeinstanceofthestructorclass.Because the document type declaration specifies the root element, thismust be the firstelement the parser encounters. If any other element but the one identified bytheDOCTYPElineappearsfirst,thedocumentisimmediatelyinvalid.Listing3-1showsaverysimpleXHTML1.0document.TheDOCTYPEis"html"(not"xhtml"),sothedocumentbodybeginswith<html....>andendswith</html>.

Page 101: Unit -1 Views of Web Programming 1. Introduction to Server

Listing3-1SimpleXHTML1.0DocumentwithXMLPrologandDocumentBody

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html

PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<title>XHTML 1.0</title>

</head>

<body>

<h1>Simple XHTML 1.0 Example</h1>

<p>See the <a href=

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">DTD</a>.</p>

</body>

</html>

7.Prolog

TheXMLProlog

ThislineiscalledtheXMLprolog:

<?xmlversion="1.0"encoding="UTF-8"?>

Page 102: Unit -1 Views of Web Programming 1. Introduction to Server

TheXMLprologisoptional.Ifitexists,itmustcomefirstinthedocument.

XMLdocumentscancontaininternationalcharacters,likeNorwegianøæåorFrenchêèé.

Toavoiderrors,youshouldspecifytheencodingused,orsaveyourXMLfilesasUTF-8.

UTF-8isthedefaultcharacterencodingforXMLdocuments.

CharacterencodingcanbestudiedinourCharacterSetTutorial.

UTF-8isalsothedefaultencodingforHTML5,CSS,JavaScript,PHP,andSQL.

AllXMLElementsMustHaveaClosingTag

InHTML,someelementsmightworkwell,evenwithamissingclosingtag:

<p>Thisisaparagraph.<br>

InXML,itisillegaltoomittheclosingtag.Allelementsmusthaveaclosingtag:

<p>Thisisaparagraph.</p><br/>

TheXMLprologdoesnothaveaclosingtag.Thisisnotanerror.TheprologisnotapartoftheXMLdocument.

XMLTagsareCaseSensitive

XMLtagsarecasesensitive.Thetag<Letter>isdifferentfromthetag<letter>.

Openingandclosingtagsmustbewrittenwiththesamecase:

<Message>Thisisincorrect</message><message>Thisiscorrect</message>

"Openingandclosingtags"areoftenreferredtoas"Startandendtags".Usewhateveryouprefer.Itisexactlythesamething.

XMLElementsMustbeProperlyNested

InHTML,youmightseeimproperlynestedelements:

<b><i>Thistextisboldanditalic</b></i>

InXML,allelementsmustbeproperlynestedwithineachother:

<b><i>Thistextisboldanditalic</i></b>

Page 103: Unit -1 Views of Web Programming 1. Introduction to Server

Intheexampleabove,"Properlynested"simplymeansthatsincethe<i>elementisopenedinsidethe<b>element,itmustbeclosedinsidethe<b>element.

XMLAttributeValuesMustbeQuoted

XMLelementscanhaveattributesinname/valuepairsjustlikeinHTML.

InXML,theattributevaluesmustalwaysbequoted.

INCORRECT:

<notedate=12/11/2007><to>Tove</to><from>Jani</from></note>

CORRECT:

<notedate="12/11/2007"><to>Tove</to><from>Jani</from></note>

Theerrorinthefirstdocumentisthatthedateattributeinthenoteelementisnotquoted.

EntityReferences

SomecharactershaveaspecialmeaninginXML.

Ifyouplaceacharacterlike"<"insideanXMLelement,itwillgenerateanerrorbecausetheparserinterpretsitasthestartofanewelement.

ThiswillgenerateanXMLerror:

<message>salary<1000</message>

Toavoidthiserror,replacethe"<"characterwithanentityreference:

<message>salary&lt;1000</message>

Thereare5pre-definedentityreferencesinXML:

&lt; < lessthan

Page 104: Unit -1 Views of Web Programming 1. Introduction to Server

&gt; > greaterthan

&amp; & ampersand

&apos; ' apostrophe

&quot; " quotationmark

Only<and&arestrictlyillegalinXML,butitisagoodhabittoreplace>with&gt;aswell.

CommentsinXML

ThesyntaxforwritingcommentsinXMLissimilartothatofHTML.

<!--Thisisacomment-->

Twodashesinthemiddleofacommentarenotallowed.

Notallowed:

<!--Thisisa--comment-->

Strange,butallowed:

<!--Thisisa--comment-->

White-spaceisPreservedinXML

XMLdoesnottruncatemultiplewhite-spaces(HTMLtruncatesmultiplewhite-spacestoonesinglewhite-space):

XML: HelloTove

HTML: HelloTove

Page 105: Unit -1 Views of Web Programming 1. Introduction to Server

8.Epilog

9.XSL

WhatisXSL?

XSLisalanguageforexpressingstylesheets.AnXSLstylesheetis,likewithCSS,afilethatdescribeshowtodisplayanXMLdocumentofagiventype.XSLsharesthefunctionalityandiscompatiblewithCSS2(althoughitusesadifferentsyntax).Italsoadds:

• A transformation language forXMLdocuments:XSLT.Originally intended toperformcomplexstylingoperations, likethegenerationoftablesofcontentsandindexes,itisnowusedasageneralpurposeXMLprocessinglanguage.XSLTis thuswidely used for purposes other thanXSL, like generatingHTMLwebpagesfromXMLdata.

• Advancedstylingfeatures,expressedbyanXMLdocumenttypewhichdefinesasetofelementscalledFormattingObjects,andattributes(inpartborrowedfromCSS2propertiesandaddingmorecomplexones.

HowDoesItWork?

StylingrequiresasourceXMLdocuments,containingtheinformationthatthestylesheetwilldisplayandthestylesheetitselfwhichdescribeshowtodisplayadocumentofagiventype.

ThefollowingshowsasampleXMLfileandhowitcanbetransformedandrendered.

TheXMLfile

<scene><FX>GeneralRoadBuildingnoises.</FX><speechspeaker="Prosser">ComeoffitMrDent,youcan'twinyouknow.There'snopointinlyingdowninthepathofprogress.</speech><speechspeaker="Arthur">I'vegoneofftheideaofprogress.It'soverrated</speech></scene>

This XML file doesn't contain any presentation information, which is contained in thestylesheet. Separating the document's content and the document's styling informationallowsdisplayingthesamedocumentondifferentmedia(likescreen,paper,cellphone),and

Page 106: Unit -1 Views of Web Programming 1. Introduction to Server

italsoenablesuserstoviewthedocumentaccordingtotheirpreferencesandabilities,justbymodifyingthestylesheet.

TheStylesheet

Here are two templates from the stylesheet used to format the XML file. The fullstylesheet(whichincludesextrainformationonpaginationandmargins)isavailable.

...<xsl:templatematch="FX"><fo:blockfont-weight="bold"><xsl:apply-templates/></fo:block></xsl:template><xsl:templatematch="speech[@speaker='Arthur']"><fo:blockbackground-color="blue"><xsl:value-ofselect="@speaker"/>:<xsl:apply-templates/></fo:block></xsl:template>...

ThestylesheetcanbeusedtotransformanyinstanceoftheDTDitwasdesignedfor.Thefirstrule says thatanFXelementwillbe transformed intoablockwithabold font. <xsl:apply-templates/>isarecursivecalltothetemplaterulesforthecontentsofthecurrentelement.The second template applies to all speech elements that have the speaker attribute settoArthur,andformatsthemasblueblockswithinwhichthevaluespeakerattributeisaddedbeforethetext.

DocumentsType

11.Definition

WhatisaDTD?

ADTDisaDocumentTypeDefinition.

ADTDdefinesthestructureandthelegalelementsandattributesofanXMLdocument.

WhyUseaDTD?

WithaDTD,independentgroupsofpeoplecanagreeonastandardDTDforinterchangingdata.

AnapplicationcanuseaDTDtoverifythatXMLdataisvalid.

AnInternalDTDDeclaration

Page 107: Unit -1 Views of Web Programming 1. Introduction to Server

IftheDTDisdeclaredinsidetheXMLfile,itmustbewrappedinsidethe<!DOCTYPE>definition:

XML document with an internal DTD

<?xmlversion="1.0"?><!DOCTYPEnote[<!ELEMENTnote(to,from,heading,body)><!ELEMENTto(#PCDATA)><!ELEMENTfrom(#PCDATA)><!ELEMENTheading(#PCDATA)><!ELEMENTbody(#PCDATA)>]><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don'tforgetmethisweekend</body></note>

ViewXMLfile»

IntheXMLfile,select"viewsource"toviewtheDTD.

TheDTDaboveisinterpretedlikethis:

• !DOCTYPEnotedefinesthattherootelementofthisdocumentisnote• !ELEMENTnotedefinesthatthenoteelementmustcontainfourelements:

"to,from,heading,body"• !ELEMENTtodefinesthetoelementtobeoftype"#PCDATA"• !ELEMENTfromdefinesthefromelementtobeoftype"#PCDATA"• !ELEMENTheadingdefinestheheadingelementtobeoftype"#PCDATA"• !ELEMENTbodydefinesthebodyelementtobeoftype"#PCDATA"

AnExternalDTDDeclaration

IftheDTDisdeclaredinanexternalfile,the<!DOCTYPE>definitionmustcontainareferencetotheDTDfile:

XML document with a reference to an external DTD

<?xmlversion="1.0"?><!DOCTYPEnoteSYSTEM"note.dtd"><note><to>Tove</to><from>Jani</from>

Page 108: Unit -1 Views of Web Programming 1. Introduction to Server

<heading>Reminder</heading><body>Don'tforgetmethisweekend!</body></note>

View XML file »

12.Entities

Entities are used to define shortcuts to special characters within the XML documents.Entitiescanbeprimarilyoffourtypes:

• Built-inentities

• Characterentities

• Generalentities

• Parameterentities

EntityDeclarationSyntaxIngeneral,entitiescanbedeclaredinternallyorexternally.Letusunderstandeachoftheseandtheirsyntaxasfollows:

Internal Entity

IfanentityisdeclaredwithinaDTDitiscalledasinternalentity.

Syntax

Followingisthesyntaxforinternalentitydeclaration:

<!ENTITYentity_name"entity_value">

Intheabovesyntax:

• entity_nameisthenameofentityfollowedbyitsvaluewithinthedoublequotesorsinglequote.

• entity_valueholdsthevaluefortheentityname.

• The entity valueof the InternalEntity is de-referencedby addingprefix& to theentitynamei.e.&entity_name.

Page 109: Unit -1 Views of Web Programming 1. Introduction to Server

EXAMPLEFollowingisasimpleexampleforinternalentitydeclaration:

<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?>

<!DOCTYPEaddress[

<!ELEMENTaddress(#PCDATA)>

<!ENTITYname"Tanmaypatil">

<!ENTITYcompany"TutorialsPoint">

<!ENTITYphone_no"(011)123-4567">

]>

<address>

&name;

&company;

&phone_no;

</address>

In the above example, the respective entity names name, company and phone_no arereplaced by their values in the XML document. The entity values are de-referenced byaddingprefix&totheentityname.

Save this file assample.xml andopen it in anybrowser, youwill notice that the entityvaluesforname,company,phone_noarereplacedrespectively.

External Entity

If an entity is declaredoutside aDTD it is called as external entity. You can refer to anexternalEntitybyeitherusingsystemidentifiersorpublicidentifiers.

Syntax

FollowingisthesyntaxforExternalEntitydeclaration:

<!ENTITYnameSYSTEM"URI/URL">

Intheabovesyntax:

• nameisthenameofentity.

• SYSTEMisthekeyword.

Page 110: Unit -1 Views of Web Programming 1. Introduction to Server

• URI/URListheaddressoftheexternalsourceenclosedwithinthedoubleorsinglequotes.

Types

YoucanrefertoanexternalDTDbyeitherusing:

• SystemIdentifiers -Asystem identifierenablesyou tospecify the locationofanexternalfilecontainingDTDdeclarations.Syntaxisasfollows:

<!DOCTYPEnameSYSTEM"address.dtd"[...]>

As you can see it contains keywordSYSTEMandaURI referencepointing to thedocument'slocation.

• PublicIdentifiers-

PublicidentifiersprovideamechanismtolocateDTDresourcesandarewrittenasbelow:

<!DOCTYPEnamePUBLIC"-//BeginningXML//DTDAddressExample//EN">

Asyoucansee,itbeginswithkeywordPUBLIC,followedbyaspecializedidentifier.Public identifiers areused to identify anentry in a catalog.Public identifiers canfollow any format; however, a commonly used format is called Formal PublicIdentifiers,orFPIs.

Example

Letusunderstandtheexternalentitywiththefollowingexample:

<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?>

<!DOCTYPEaddressSYSTEM"address.dtd">

<address>

<name>TanmayPatil</name>

<company>TutorialsPoint</company>

<phone>(011)123-4567</phone>

</address>

BelowisthecontentoftheDTDfileaddress.dtd:

<!ELEMENTaddress(name,company,phone)>

Page 111: Unit -1 Views of Web Programming 1. Introduction to Server

<!ELEMENTname(#PCDATA)>

<!ELEMENTcompany(#PCDATA)>

<!ELEMENTphone(#PCDATA)>

Built-inentitiesAll XML parsers must support built-in entities. In general, you can use these entityreferencesanywhere.YoucanalsousenormaltextwithintheXMLdocument,suchasinelementcontentsandattributevalues.

Therearefivebuilt-inentitiesthatplaytheirroleinwell-formedXML,theyare:

• ampersand:&amp;

• Singlequote:&apos;

• Greaterthan:&gt;

• Lessthan:&lt;

• Doublequote:&quot;

Example

Followingexampledemonstratesthebuilt-inentitydeclaration:

<?xmlversion="1.0"?>

<note>

<description>I'matechnicalwriter&programmer</description>

<note>

As you can see here the &amp; character is replaced by & whenever the processorencountersthis.

CharacterentitiesCharacterEntitiesareusedtonamesomeoftheentitieswhicharesymbolicrepresentationofinformationi.echaractersthataredifficultorimpossibletotypecanbesubstitutedbyCharacterEntities.

Example

Followingexampledemonstratesthecharacterentitydeclaration:

Page 112: Unit -1 Views of Web Programming 1. Introduction to Server

<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?>

<!DOCTYPEauthor[

<!ELEMENTauthor(#PCDATA)>

<!ENTITYwriter"Tanmaypatil">

<!ENTITYcopyright"&#169;">

]>

<author>&writer;&copyright;</author>

Youwillnoticeherewehaveused&#169;asvalueforcopyrightcharacter.Savethisfileassample.xmlandopenitinyourbrowserandyouwillseethatcopyrightisreplacedbythecharacter©.

GeneralentitiesGeneralentitiesmustbedeclaredwithintheDTDbeforetheycanbeusedwithinanXMLdocument.Insteadofrepresentingonlyasinglecharacter,generalentitiescanrepresentcharacters,paragraphs,andevenentiredocuments.

Syntax

Todeclareageneralentity,useadeclarationofthisgeneralforminyourDTD:

<!ENTITYename"text">

Example

Followingexampledemonstratesthegeneralentitydeclaration:

<?xmlversion="1.0"?>

<!DOCTYPEnote[

<!ENTITYsource-text"tutorialspoint">

]>

<note>

&source-text;

</note>

WheneveranXMLparserencountersa reference to source-text entity, itwill supply thereplacementtexttotheapplicationatthepointofthereference.

Page 113: Unit -1 Views of Web Programming 1. Introduction to Server

ParameterentitiesThe purpose of a parameter entity is to enable you to create reusable sections ofreplacementtext.

Syntax

Followingisthesyntaxforparameterentitydeclaration:

<!ENTITY%ename"entity_value">

• entity_valueisanycharacterthatisnotan'&','%'or'"'.

Example

Following example demonstrates the parameter entity declaration. Suppose you haveelementdeclarationsasbelow:

<!ELEMENTresidence(name,street,pincode,city,phone)>

<!ELEMENTapartment(name,street,pincode,city,phone)>

<!ELEMENToffice(name,street,pincode,city,phone)>

<!ELEMENTshop(name,street,pincode,city,phone)>

Nowsupposeyouwanttoaddadditionaleleementcountry,thenthenyouneedtoaddittoall four declarations. Hence we can go for a parameter entity reference. Now usingparameterentityreferencetheaboveexamplewillbe:

<!ENTITY%area"name,street,pincode,city">

<!ENTITY%contact"phone">

Parameterentitiesaredereferencedinthesamewayasageneralentityreference,onlywithapercentsigninsteadofanampersand:

<!ELEMENTresidence(%area;,%contact;)>

<!ELEMENTapartment(%area;,%contact;)>

<!ELEMENToffice(%area;,%contact;)>

<!ELEMENTshop(%area;,%contact;)>

Whentheparserreadsthesedeclarations,itsubstitutestheentity'sreplacementtextfortheentityreference.

13.ScriptinginXML

Page 114: Unit -1 Views of Web Programming 1. Introduction to Server

WhatisXMLScriptingLanguage

1.TheXMLspecificationdefinesastandardwaytoaddmarkupstructure(formattingandadditionalinstructions)todocuments.XMLScriptallowsforthecreation,storageandmanipulationofvariablesanddataduringprocessing.XMLisamarkuplanguagefordocumentscontainingbothcontent(words,pictures,etc.)andsomeindicationofwhatrolethatcontentplays(forexample,whetheritisinasectionheadingorafootnote,etc.).

2.XMLScriptallowsforthecreation,storageandmanipulationofvariablesanddataduringprocessing.XMLisamarkuplanguagefordocumentscontainingbothcontent(words,pictures,etc.)andsomeindicationofwhatrolethatcontentplays(forexample,whetheritisinasectionheadingorafootnote,etc.).TheXMLspecificationdefinesastandardwaytoaddmarkupstructuretodocuments.

3.XMLScriptallowsforthecreation,storageandmanipulationofvariablesanddataduringprocessing.XMLisamarkuplanguagefordocumentscontainingbothcontent(words,pictures,etc.)andsomeindicationofwhatrolethatcontentplays(forexample,whetheritisinasectionheadingorafootnote,etc.).TheXMLspecificationdefinesastandardwaytoaddmarkupstructuretodocuments.

4.XMLScriptallowsforthecreation,storageandmanipulationofvariablesanddataduringprocessing.XMLisamarkuplanguagefordocumentscontainingbothcontent(words,pictures,etc.)andsomeindicationofwhatrolethatcontentplays(forexample,whetheritisinasectionheadingorafootnote,etc.).TheXMLspecificationdefinesastandardwaytoaddmarkupstructuretodocuments.

14.MixedData

MixedContent

XML1.0providedtheabilitytodeclareanelementthatcouldcontainparsedcharacterdata(#PCDATA)andunlimitedoccurrencesofelementsdrawnfromaprovidedlist.Schemasprovidethesamefunctionalityplustheabilitytocontrolthenumberandsequenceinwhichelementsappearwithincharacterdata.

AllowingMixedContent

ThemixedattributeofthecomplexTypeelementcontrolswhethercharacterdatamayappearwithinthebodyoftheelementwithwhichitisassociated.Toillustratethisconcept,Example16-9givesusanewschemathatwillbeusedtovalidateform-letterdocuments.

Example16-9.formletter.xsd

<xs:schemaxmlns:xs="http://www.w3.org/2001/XMLSchema">

Page 115: Unit -1 Views of Web Programming 1. Introduction to Server

<xs:elementname="letter"><xs:complexTypemixed="true"/></xs:element></xs:schema>

Thisschemaseemstodeclareasingleelementcalledbodythatmaycontaincharacterdataandnothingelse.Butattemptingtovalidatethefollowingdocumentproducesanerror,asshowninExample16-10.

Example16-10.formletterdoc.xml

<letterxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="formletter.xsd">Hello!</letter>

Thefollowingerrorisgenerated:

Thecontentofelementtype"letter"mustmatch"EMPTY".

Thisisbecausethere'snocomplexcontentfortheletterelement.Settingmixedtotrueisnotthesameasdeclaringanelementthatmaycontainastring.Thecharacterdatamayonlyappearinrelationtoothercomplexcontent,whichleadstothesubjectofrelativeelementpositioning.

Controlling Element Placement

Youhavealreadyseenthexs:sequenceelement,whichdictatesthattheelementsitcontainsmustappearinexactlythesameorderinwhichtheyappearwithinthesequenceelement.Inadditiontoxs:sequence,schemasalsoprovidethexs:choiceandxs:allelementstocontroltheorderinwhichelementsmayappear.Theseelementsmaybenestedtocreatesophisticatedelementstructures.

Expandingtheform-letterexample,asequenceaddssupportforvariouslettercomponentstotheformletter.xsdschema:

<xs:elementname="letter"><xs:complexTypemixed="true"><xs:sequence><xs:elementname="greeting"/><xs:elementname="body"/><xs:elementname="closing"/></xs:sequence></xs:complexType></xs:element>

Now,thankstothexs:sequenceelement,alettermustincludeagreetingelement,abodyelement,andaclosingelement,inthatorder.Butinsomecases,whatisdesiredisthat

Page 116: Unit -1 Views of Web Programming 1. Introduction to Server

oneandonlyoneelementappearfromacollectionofpossibilities.Thexs:choiceelementsupportsthis.Forexample,ifthegreetingelementneededtoberestrictedtocontainonlyonesalutationoutofapermissiblelist,itcouldbedeclaredtodosousingxs:choice:

<xs:elementname="greeting"><xs:complexTypemixed="true"><xs:choice><xs:elementname="hello"/><xs:elementname="hi"/><xs:elementname="dear"/></xs:choice></xs:complexType></xs:element>

Nowoneofthepermittedsalutationsmustappearinthegreetingelementforthelettertobeconsideredvalid.

Theremainingelement-orderenforcementconstructisthexs:allelement.Unlikethexs:sequenceandxs:choiceelements,thexs:allelementmustappearatthetopofthecontentmodelandcanonlycontainelementsthatareoptionalorappearonlyonce.Thexs:allconstructtellstheschemaprocessorthateachofthecontainedelementsmustappearonceinthetargetdocument,butcanappearinanyorder.Thiscouldbeappliedintheform-letterexample.Iftheformletterhadcertainelementsthathadtoappearinthebodyelement,butnotinanyparticularorder,xs:allcouldbeusedtocontroltheirappearance:

<xs:elementname="body"><xs:complexTypemixed="true"><xs:all><xs:elementname="item"/><xs:elementname="price"/><xs:elementname="arrivalDate"/></xs:all></xs:complexType></xs:element>

Thiswouldallowtheletterauthortomixtheseelementsintothenarrativewithoutbeingrestrictedastoanyparticularorder.Also,itwouldpreventtheauthorfrominsertingmultiplereferencestothesamevaluebyaccident.Avaliddocumentinstance,includingthenewbodycontent,mightlooklikeExample16-11.

Example16-11.formletterdoc.xml

<letterxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="formletter.xsd"><greeting><hello/>Bob!</greeting><body>

Page 117: Unit -1 Views of Web Programming 1. Introduction to Server

Thankyoufororderingthe<item/>($<price/>),itshouldarriveby<arrivalDate/>.</body><closing/></letter>TIP:Theelementorderconstructsarenotjustlimitedtocomplextypeswithmixedcontent.Ifthemixedattributeisnotpresent,thedeclaredsequenceofchildelementsisstillenforced,butnocharacterdataispermittedbetweenthem.