asp net using vb net

Upload: oseuka

Post on 04-Jun-2018

254 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/13/2019 ASP Net Using Vb Net

    1/566

    ASP.NET USING VB.NET

    Finding Your Best Starting PointMicrosoft ASP.NET Programming with Microsoft Visual Basic .NET 2 ! Ste" #$ Ste" isdesigned to "ro%ide a com"rehensi%e introduction and o%er%iew of de%elo"ing &e# a""licationswith ASP.NET. The goal of this #oo' is to hel" $ou #ecome com"etent at the #asic s'illsnecessar$ for creating and using ASP.NET a""lications. To hel" $ou get there as (uic'l$ andeasil$ as "ossi#le) this #oo' has #een di%ided into four "arts) each com"osed of one or morecha"ters related to a s"ecific to"ic. *%er the course of these "arts and cha"ters) $ou+ll learn a#outthe new Microsoft .NET de%elo"ment "latform and the "art that ASP.NET "la$s in it. You+ll alsolearn the s'ills necessar$ to ta'e ad%antage of ASP.NET &e# Forms) Ser%er ,ontrols) and-M /#ased &e# ser%ices.

    0e"ending on the s'ills and e1"erience $ou #ring to this #oo') $ou might want to start with a "articular "art of interest to $ou or s'i" o%er certain "arts entirel$. The following ta#le can hel"$ou decide where to start.

    If you are Follow these steps

    New

    To "rogramming . 3nstall the sam"le files as descri#ed in 43nstalling the Sam"leFiles5 on "age 1%ii.2. earn a#out the #ac'ground of the Microsoft .NET

    Framewor' and ASP.NET #$ reading ,ha"ters /6. Then either wor'through Part 333 if $ou want to 'now more a#out the technologiesunderl$ing ASP.NET or wor' through Part 3V if $ou want to getstraight into the coding.!. &or' through the rest of the "arts and cha"ters #ased on $ourinterest in the %arious to"ics.

    Switching

    From classic ASPor similartechnologies

    . 3nstall the sam"le files as descri#ed in 43nstalling the Sam"leFiles.52. 7ead or scan Parts 3 and 33 if $ou+re interested in the

    #ac'ground of .NET and ASP.NET.!. &or' through Part 333 for #asic &e# Forms s'ills as well asan introduction to using ASP.NET Ser%er ,ontrols and accessingdata with A0*.NET.8. &or' through Part 3V for additional ASP.NET a""lications'ills.

    Referencing

  • 8/13/2019 ASP Net Using Vb Net

    2/566

    If you are Follow these steps

    This #oo' afterwor'ing through thecha"ters

    . 9se the inde1 to locate information a#out s"ecific to"ics) anduse the ta#le of contents to locate information a#out general to"ics.2. 7ead the :uic' 7eference at the end of each cha"ter for a

    #rief re%iew of the ma;or tas's in each cha"ter.

    ,orrections) ,omments) and

  • 8/13/2019 ASP Net Using Vb Net

    3/566

    Part IGetting Started with ASP.NET

    ,ha"ter *"ening and 7unning an ASP.NET &e#A""lication3n this cha"ter) $ou will learn how to=

    Start Microsoft Visual Studio .NET.*"en and run an ASP.NET a""lication.

    &or' with tool windows.E1it Visual Studio .NET.

    Microsoft ASP.NET is not ;ust an u"grade not #$ a long shot. ASP.NET "ro%ides the mostad%anced &e# de%elo"ment "latform created to date. &hat+s more) ASP.NET has #een re#uiltfrom the ground u" to create an entirel$ new and more fle1i#le infrastructure for &e#de%elo"ment.

    &hat ma'es ASP.NET so re%olutionar$ is that it+s #ased on Microsoft+s new .NET "latform) ormore accuratel$ the Microsoft .NET Framewor'. To understand clearl$ where and when to use

    ASP.NET) let+s ta'e some time to go o%er the Microsoft .NET "latform) the "roducts that itcom"rises) and where ASP.NET fits within Microsoft .NET.

    9nderstanding Microsoft .NET

    Microsoft .NET is an um#rella term that descri#es a num#er of recentl$ released technologiesfrom Microsoft. Ta'en together) these technologies are the most su#stantial changes to theMicrosoft de%elo"ment "latform since the transition from 6/#it to !2/#it de%elo"ment.

    Microsoft .NET includes the following technolog$ areas=

    The .NET Framewor'

    .NET languages and language tools

    3n the ne1t section) $ou+ll learn a#out these technologies and how $ou can use them to s"eed u"$our de%elo"ment of ro#ust) high/"erformance &e#/ or Forms/#ased a""lications on theMicrosoft &indows "latform.

  • 8/13/2019 ASP Net Using Vb Net

    4/566

    The .NET Framewor'

    The .NET Framewor' is an essential technolog$ for ASP.NET de%elo"ment. 3t "ro%ides the #asic s$stem ser%ices that su""ort ASP.NET) as well as &indows Forms de%elo"ment) the newrich client de%elo"ment technolog$ "ro%ided #$ .NET. Much li'e the Microsoft &indows NT

    8. *"tion Pac') which was an add/on to &indows NT 8. that added 3nternet 3nformationSer%er 8. and Acti%e Ser%er Pages technologies to NT 8. ) the .NET Framewor' is an add/on toMicrosoft &indows -P) &indows 2 ) &indows NT 8. ) and &indows CD ME that adds the

    #asic su""orting s$stem ser%ices for .NET technologies. The framewor' will also #e #uilt intonewer releases of the &indows ser%er o"erating s$stem line) including the &indows Ser%er 2 !line.

    IMPORTANT&hile Visual Studio .NET is su""orted on the &indows CD) &indows NT) &indows 2 ) and&indows -P "latforms) the full .NET framewor' is not a%aila#le on all "latforms. Mostim"ortant) while other "latforms can #e used as ASP.NET clients) ASP.NET a""lications will

    run onl$ on &indows 2 and later.

    The .NET Framewor' consists of two main "arts=

    The common language runtimeThe .NET Framewor' class li#rar$

    The ,ommon anguage 7untime

    The common language runtime ?, 7 "ro%ides a run/time en%ironment for the e1ecution ofcode written in an$ .NET language. The , 7 manages the e1ecution of .NET code) includingmemor$ and o#;ect lifetime management. 3n addition to these management ser%ices) the , 7allows de%elo"ers to "erform de#ugging) e1ce"tion handling) and inheritance across multi"lelanguages. Performing these tas's re(uires that the language com"ilers follow the ,ommonanguage S"ecification ?, S ) which descri#es a su#set of the data t$"es su""orted #$ the , 7that are common to all of the languages used in .NET.

    The indi%idual language com"ilers com"ile the code written #$ de%elo"ers into an intermediatelanguage called Microsoft 3ntermediate anguage ?3 or MS3 . The 3 is then ust/3n/Time? 3T com"iled at first e1ecution. *"tionall$) 3 assem#lies ma$ #e com"iled to nati%e code #$the , 7 at install time using a utilit$ called ngen.e1e. This can im"ro%e startu" time) although atsome cost to "erformance) due to o"timiGations a%aila#le during 3T com"ilation. Note thatngen.e1e cannot #e used for assem#lies generated from ASP.NET "ages and code/#ehindclasses.

    ,ode that is com"iled to 3 and managed #$ the , 7 is referred to as managed code . 3t+s calledthis #ecause the , 7 ta'es res"onsi#ilit$ for managing the e1ecution of the code) including theinstantiation of o#;ects) allocation of memor$) and gar#age collection of o#;ects and memor$.

  • 8/13/2019 ASP Net Using Vb Net

    5/566

    ,om"onents written in managed code and e1ecuted #$ the , 7 are referred to as .NET managedassemblies ) or assemblies for short. Assem#lies are the #asic unit of de"lo$ment in the .NETworld and are (uite similar to ,*M com"onents. The difference is that whereas a ,*Mcom"onent has a t$"e li#rar$ to descri#e how clients should interact with it) an assem#l$contains a manifest ) which is the set of metadata that descri#es the contents of the assem#l$.

    Among other ad%antages) the self/descri#ing nature of .NET com"onents means that the$ don+tneed to #e registered on a com"uter in order to wor'H

    This metadata also descri#es the de"endencies and %ersion information associated with anassem#l$. Not onl$ does this ma'e it much easier to ensure that all necessar$ de"endencies of anassem#l$ are fulfilled) #ut it also means that multi"le %ersions of the same assem#l$ can #e runside #$ side on the same com"uter without conflict. This is a ma;or ste" in resol%ing 40 sam"les contains auseful ,lass Browser sam"le a""lication ?which can #e found athttp://localhost/#uickStart/aspplus/doc/classbrowser.asp$ once $ou ha%e installed the .NETFramewor' S0> sam"les that $ou can use to %iew the %arious classes of the .NET Framewor'class li#rar$.

  • 8/13/2019 ASP Net Using Vb Net

    6/566

    3nheritance

    "nheritance is a central conce"t in the .NET Framewor'. 3t "ro%ides a wa$ for de%elo"ers to usee1isting code in classes. A class can e1"ose #oth "ro"erties and methods that clients can use.,lasses that are inherited from a "articular #ase class are said to #e deri%ed from that class. B$

    inheriting from a class) a de%elo"er can reuse the functionalit$ that it e1"oses without ha%ing torewrite the code.

    3n addition ?and more im"ortant ) a de%elo"er creating a deri%ed class can o%erride one or moreof the methods e1"osed #$ the "arent class in order to "ro%ide a s"ecialiGed im"lementation ofthat functionalit$. This ca"a#ilit$ will come in hand$ when $ou learn a#out custom ser%ercontrols in ,ha"ter ..NET anguages and anguage Tools

    *ne of the #est things a#out the .NET "latform is that whereas classic ASP restricted de%elo"ersto using scri"ting languages ?with their inherent limitations ) ASP.NET lets $ou wor' with

    any .NET/com"liant language. This means that the code $ou write in ASP.NET is com"iled for #etter "erformance) and $ou can ta'e full ad%antage of ad%anced language features.

    For the .NET "latform) languages ?and the de%elo"ment tools with which $ou+ll use them are "ro#a#l$ one of the most im"ortant to"ics to discuss. et+s ta'e a high/le%el loo' at some of thelanguages and tools that will #e a%aila#le for de%elo"ing .NET a""lications.

    Note"ad and *ther Te1t Editors

    Belie%e it or not) man$ de%elo"ers) "articularl$ ASP de%elo"ers) still do much of theirde%elo"ment in Microsoft Note"ad ?which 3 used to lo%ingl$ refer to as 4Visual5 Note"ad orother free or ine1"ensi%e te1t editors. &hile Note"ad has the su#stantial ad%antage of #eingu#i(uitous) it+s not e1actl$ what $ou+d call a ro#ust de%elo"ment en%ironment. That said) if$ou+re wor'ing with the .NET Framewor' S0> ?rather than Visual Studio .NET ) there+s noreason $ou can+t use Note"ad ?or another fa%orite te1t editor to do all of $our .NETde%elo"ment. The .NET Framewor' S0> includes command/line com"ilers for MicrosoftVisual Basic .NET) Microsoft Visual ,J ?"ronounced 4, shar"5 ) and Microsoft Scri"t .NET.So) $ou can create $our classes) ASP.NET "ages) and so on in Note"ad) and then $ou can eithercom"ile them e1"licitl$ using the command/line com"ilers or) in the case of ASP.NET) allow theASP.NET runtime to d$namicall$ com"ile the "age when it+s re(uested for the first time.

    Visual Studio .NET

    For sim"ler and faster de%elo"ment) most de%elo"ers will "ro#a#l$ want to wor' in VisualStudio .NET) which "ro%ides a single integrated de%elo"ment en%ironment ?30E for all ofMicrosoft+s .NET languages ?with the e1ce"tion of Microsoft Visual Fo1Pro K. ) which does notuse the , 7 or the .NET Framewor' . This means that de%elo"ers of Visual Basic) MicrosoftVisual ,LL) and ,J all share the same 30E) including the ca"a#ilit$ to "erform de#ugging ande1ce"tion handling across languages) in the same en%ironment.

  • 8/13/2019 ASP Net Using Vb Net

    7/566

    Visual Studio .NET "ro%ides a su#stantial num#er of new features) including

    A single) unified "rogramming model for all .NET languages and for #oth &indows and&e# a""lications0rag/and/dro" de%elo"ment for the ser%er using the Ser%er E1"lorer

    0$namic

  • 8/13/2019 ASP Net Using Vb Net

    8/566

    0e%elo"ers familiar with ,) ,LL) and a%a will (uic'l$ #ecome "roducti%e using ,J. This #oo'will include some code e1am"les in ,J to gi%e $ou a taste of this e1citing new language.

    Additional .NET anguages

    Visual Studio .NET also shi"s with Scri"t .NET) Visual ,LL) and the managed e1tensions forVisual ,LL) which allow ,LL de%elo"ers to target their a""lications to the , 7.

    Visual Studio .NET also "ro%ides an e1tremel$ fle1i#le "lug/in architecture that allows otherlanguages written for or "orted to the .NET "latform to easil$ use the "ower of the Visual Studio30E. The current list of third/"art$ languages "lanned for Visual Studio .NET includes

    AP,*B*

    Eiffel

    F*7T7AN

  • 8/13/2019 ASP Net Using Vb Net

    9/566

    Getting Started with Visual Studi .NET

    Although this #oo' will focus on #uilding ASP.NET a""lications with Visual Basic .NET) thede%elo"ment en%ironment $ou+ll #e wor'ing in is Visual Studio .NET. Because Visual Studio.NET now su""orts all of the .NET languages in a single 30E) man$ of the tas's $ou+ll learn inthis #oo' are a""lica#le to ,J) Visual ,LL) and Scri"t .NET) as well as to Visual Basic .NET.

    Visual Studio .NET Basics

    You+ll #egin $our tour #$ starting the Visual Studio .NET 30E. Ne1t) $ou+ll learn a#out some ofthe features of the 30E designed to hel" $ou get started. You+ll finish this section #$ learninghow to o"en an ASP.NET &e# a""lication "ro;ect.

    IMPORTANTThe e1ercises in this cha"ter re(uire that $ou ha%e installed at minimum the Visual Basic .NETStandard Edition) as well as the "ractice files for the #oo') which $ou can download from the

    #oo'+s &e# site at http://www.microsoft.com/mspress/books/&'().asp ?under the com"anioncontent lin' . 3f $ou ha%e not installed #oth) "lease do so now and then return to this cha"ter.Start Visual Studio .NET

    . ,lic' the Start #utton ?shown #elow ) "oint to All Programs ?or Programs in &indows2 ) and then "oint to Microsoft Visual Studio .NET 2 !.

    The icons for Visual Studio .NET will #e dis"la$ed.

    2. ,lic' the icon for Microsoft Visual Studio .NET 2 !.

    The Visual Studio .NET 30E will start. The Start Page is dis"la$ed #$ default whene%er$ou start Visual Studio .NET) and "ro%ides lin's and tools to hel" $ou configure the 30E)o"en recent "ro;ects) create new "ro;ects) and man$ other tas's. B$ default) the 30E willdis"la$ the Pro;ects ta# of the Visual Studio .NET Start Page. This ta# allows $ou to(uic'l$ o"en a recent "ro;ect or to create a new "ro;ect. The *nline 7esources ta# allows$ou to find sam"le code) access online communit$ resources) find .NET downloads) andmore. You+ll see more of this ta# in a #it. The M$ Profile ta# of the Start Page) shown inthe following illustration) allows $ou to configure the la$out of the tool windows inVisual Studio .NET) as well as the 'e$#oard shortcuts used to accom"lish common tas's.

    http://www.microsoft.com/mspress/books/6725.asp%20http://www.microsoft.com/mspress/books/6725.asp%20
  • 8/13/2019 ASP Net Using Vb Net

    10/566

    !. Select the M$ Profile ta#) and then change the main Profile dro"/down list from VisualStudio 0e%elo"er to Visual Basic 0e%elo"er.

    This will configure the 30E windows and 'e$#oard configuration to match that of VisualBasic 6) as shown in the following illustration) so that e1"erienced Visual Basicde%elo"ers can more easil$ find their wa$ around.

  • 8/13/2019 ASP Net Using Vb Net

    11/566

    8. ,hange the Profile dro"/down list #ac' to Visual Studio 0e%elo"er to restore the originalsettings.

    Search for sam"le code

    . ,lic' the *nline 7esources ta#.

    B$ default) the @et Started section will #e selected ?if it+s not) clic' @et Started .

  • 8/13/2019 ASP Net Using Vb Net

    12/566

    2. T$"e ASP.NET in the te1t #o1) and then clic' @o.

    A list of matching sam"les will #e dis"la$ed) as shown in the following illustration.

    IMPORTANTSam"le a""lications and code can #e useful tools for learning how to de%elo" a""lications)including ASP.NET a""lications. But 'ee" in mind that sam"les are often designed to illustrate alimited set of s"ecific conce"ts) and might not alwa$s use #est "ractices for securit$ and design.Before using sam"le code in $our a""lications) #e sure that $ou understand the securit$ andarchitectural im"lications of doing so.*"en a &e# a""lication "ro;ect

    . Switch #ac' to the Pro;ects ta# and then clic' *"en Pro;ect.

    The *"en Pro;ect dialog #o1 will #e dis"la$ed) as shown in the following illustration.

    2. Browse to the location where $ou installed the "ractice files ?the default is ,= MS PressBoo's ASPNETSBS ) o"en the ,ha"terO folder) select the ,ha"terO .%#"ro; file) andthen clic' *"en. ?Alternati%el$) $ou can o"en all the "ro;ects installed with the "ractice

    files #$ selecting the as"nets#s.sln file located in the as"nets#s folder.

    The ,ha"terO "ro;ect will #e loaded. Note that if $ou o"en a "ro;ect originall$ createdwith Visual Studio .NET 2 2 in Visual Studio .NET 2 !) $ou will #e "rom"ted tocon%ert the "ro;ect file to the newer format. *nce this con%ersion is done) $ou will not #ea#le to o"en the "ro;ect in older %ersions of Visual Studio .NET.

  • 8/13/2019 ASP Net Using Vb Net

    13/566

    NOTEB$ default) &indows 2 and &indows -P hide file e1tensions for 'nown file t$"es. 3f thissetting is turned on) $ou will not see the .%#"ro; and or .sln e1tensions to the files mentionedearlier. You can modif$ this setting in the &indows E1"lorer Folder *"tions dialog #o1. Fromthe &indows E1"lorer Tools menu) select Folder *"tions and then clic' on the View ta#.9nchec' the nown File T$"es chec' #o1) and then clic' *> or A""l$.The file e1tensions will now a""ear in the *"en Pro;ect dialog #o1.Solutions and Pro;ects

    A""lications in Visual Studio .NET are organiGed into containers called pro*ects and solutions .Pro;ects are containers for the files associated with a single a""lication t$"e) such as a &e#a""lication or control li#rar$) while solutions are containers for one or more "ro;ects. The

    "ro;ects that ma'e u" the sam"le files for this #oo' are contained in a single solution namedas"nets#s.sln. Solutions are a useful tool for organiGing all of the "ro;ects associated with alarger a""lication) such as &e# a""lications) and the control "ro;ects or com"onent "ro;ectsassociated with them.

    7unning &e# a""lications is a little different than running &indows a""lications or consolea""lications. &ith &indows a""lications and console a""lications) running the a""lication in the30E is as sim"le as clic'ing the Start #utton) shown in the following illustration) on the VisualStudio .NET tool#ar. Although $ou can also run a &e# a""lication using this techni(ue) it+s morecommon to sim"l$ #rowse to the "age in the a""lication that $ou want to test. 3f $ou want to runa &e# a""lication using the Start #utton ?or #$ selecting Start from the 0e#ug menu ) $ou needto select a "age in $our a""lication that will #e the start "age) or the first "age loaded when thea""lication is run. You+ll learn a#out these techni(ues in ,ha"ter 8) which co%ers de#uggingASP.NET a""lications. For now) let+s ;ust test a "age #$ #rowsing it.

  • 8/13/2019 ASP Net Using Vb Net

    14/566

    Test a &e# Forms "age

    . oad the ,ha"terO "ro;ect. ?3f $ou+%e #een following along in the #oo') $ou mightha%e alread$ loaded the ,ha"terO "ro;ectI if so) s'i" to the ne1t ste". 3f not) return tothe "re%ious section) follow the ste"s to load the "ro;ect) and then return to this section.

    2. 3n the Solution E1"lorer window) right/clic' the &elcome.as"1 file) and then select View3n Browser.

    The &elcome.as"1 "age) shown in the following illustration) will #e loaded into a #rowser window that is integrated into the 30E. You can #rowse "ages in a Microsoft3nternet E1"lorer e1ternal #rowser window or with #rowsers other than 3nternet E1"lorer

    #$ right/clic'ing a "age) selecting Browse &ith) and then choosing $our desired #rowserand other o"tions.

  • 8/13/2019 ASP Net Using Vb Net

    15/566

  • 8/13/2019 ASP Net Using Vb Net

    16/566

    Ta##ed 0ocuments

    0esigned to sim"lif$ the management of multi"le files #eing edited simultaneousl$) theTa##ed 0ocuments interface allows $ou to see all of the files $ou+re editing at once. Thisma'es it much sim"ler to switch #ac' and forth #etween o"en editing windows. You canstill set u" Visual Studio .NET to use the old method used #$ Visual Studio 6) howe%er.ust clic' the Tools menu) select *"tions) then select the @eneral o"tion in theEn%ironment folder) switch from Ta##ed 0ocuments to M03 en%ironment) and then clic'

    *>. You+ll need to restart Visual Studio .NET for this change to ta'e effect.

    Auto

  • 8/13/2019 ASP Net Using Vb Net

    17/566

    2. Switch #etween o"en documents ?including the Start Page #$ clic'ing on the ta# for thedocument $ou want to switch to.

    3f there are more ta#s than will fit onscreen) $ou can scroll to %iew the hidden ta#s using

    the Scroll #uttons) as shown #elow) at the to" of the editor window. You can close thecurrentl$ selected document #$ clic'ing the ,lose #utton) as shown #elow) at the to" ofthe editor window.

    New Features

    3n addition to the 30E enhancements) a num#er of entirel$ new features ha%e #een added to theVisual Studio .NET 30E.

    -M editor

    This allows $ou to edit -M data ?.1ml and schema ?.1sd files in source) data) or schema%iews) de"ending on the t$"e of -M file $ou+re editing.

    0$namic

  • 8/13/2019 ASP Net Using Vb Net

    18/566

    NOTE&hile the 0$namic

  • 8/13/2019 ASP Net Using Vb Net

    19/566

    unified source/code editor that "ro%ides su""ort for -M )

  • 8/13/2019 ASP Net Using Vb Net

    20/566

    Ser%er E1"lorer

    The Ser%er E1"lorer) as shown in the following illustration) is a new feature of VisualStudio .NET that allows $ou to %iew resources on #oth $our local machine and remoteser%ers) including configured data connections) e%ent logs) message (ueues) and

    "erformance counters. The Ser%er E1"lorer also lets $ou drag and dro" resources onto&e# Forms "ages or .NET com"onents) allowing some of the most "roducti%e ser%er/sidede%elo"ment a%aila#le to date. 3n the Standard edition of Visual Basic .NET) the Ser%erE1"lorer is limited to connecting to and %iewing data#ase o#;ects.

    Pro"ertiesThe Pro"erties window should #e immediatel$ familiar to an$one who+s used an$ of theVisual Studio suites of de%elo"ment tools. 3t "ro%ides access to the "ro"erties of the o#;ectcurrentl$ selected in the 30E. The Pro"erties window allows $ou to colla"se or e1"andcategories of "ro"erties to #etter %iew the categories $ou+re interested in. You can also%iew the "ro"erties in al"ha#etical order #$ clic'ing the Al"ha#etic ?A #utton) as shownin the following illustration) ;ust #elow the o#;ect selection dro"/down menu.

  • 8/13/2019 ASP Net Using Vb Net

    21/566

    The Visual Studio .NET Tool#o1

    The Visual Studio .NET Tool#o1 is another element modeled closel$ on the Visual3nter0e% en%ironment. 3t "ro%ides access to a wide %ariet$ of controls) com"onents) and

  • 8/13/2019 ASP Net Using Vb Net

    22/566

    own items) ma'e sure the "ro"er categor$ ta# is selected) select the desired item in the0esigner ?or te1t in the code editor ) and then drag it to the Tool#o1. You can gi%e the newitem a descri"ti%e name #$ right/clic'ing it and selecting 7ename 3tem.

    Tas' ist

    An underrated and often underutiliGed tool from Visual 3nter0e%) the Tas' ist windowallows de%elo"ers to create) sort) and trac' tas's to #e com"leted for the current solution.The Tas' ist also can contain tas's automaticall$ generated #$ Visual Studio to hel"de%elo"ers locate and correct #uild errors. Tas's can #e categoriGed and "rioritiGedaccording to the de%elo"er+s needs. ,ategories include ,omment tas's ?indicated #$comment to'ens such as T+,+ ) !P- ,E0T+,+ ) and so on ) 9ser tas's) Build Errors)Shortcuts ?created #$ right/clic'ing a line of code in the editor and selecting Add Tas' istShortcut ) and 3ntelliSense tas's) which are dis"la$ed when 3ntelliSense detects an error in$our code. The following illustration shows a Tas' ist with a Shortcut tas') a 9ser tas')and a ,omment tas'.

    *ut"ut

    The *ut"ut window will #e familiar to de%elo"ers who+%e used Microsoft+s Visual ,LL orVisual LL tools. *ne of the "rimar$ "ur"oses of the *ut"ut window is to dis"la$messages related to "ro;ect #uilds. ?A build is the "rocess of com"iling all of the code filesthat ma'e u" a "ro;ect. Since $ou need to #uild $our ASP.NET &e# a""lication #efore

    code modifications will a""ear) $ou+ll #e seeing a lot of this window. The followingillustration shows the out"ut of a #uild of a sam"le "ro;ect. 3n this case the #uild wassuccessful) with no errors or warnings.

  • 8/13/2019 ASP Net Using Vb Net

    23/566

    Now that $ou+%e seen some of the main windows in the 30E) "ut $our 'nowledge to wor' #$following these "rocedures.

    Switch %iews in the Editor

    . *"en the &elcome.as"1 "age) if it+s not alread$ o"en) #$ dou#le/clic'ing the file in theSolution E1"lorer window. ?You can tell if the file is o"en #$ reading the ta# la#els alongthe to" of the editor.

    2. ,lic' the

  • 8/13/2019 ASP Net Using Vb Net

    24/566

    9se the Pro"erties window to modif$ "ro"erties. *"en the &elcome.as"1 file) if it isn+t alread$ o"en) #$ dou#le/clic'ing the file in the

    Solution E1"lorer window. Ma'e sure $ou+re in 0esign %iew if not) clic' the 0esign #utton to switch to 0esign %iew.

    2. ,lic' the te1t 4&elcome to ASP.NETH5 to select the control it re"resents.

    This is an ASP.NET a#el ser%er control. ?You+ll learn more a#out ASP.NET ser%ercontrols in later cha"ters. &hen $ou select the control) its "ro"erties are dis"la$ed in thePro"erties window) as shown in the following illustration.

  • 8/13/2019 ASP Net Using Vb Net

    25/566

    !. ,lic' the L s$m#ol ne1t to the 1ont "ro"ert$ to e1"ose its su#/"ro"erties.8. Select the 2old "ro"ert$) and then clic' its dro"/down list to change the "ro"ert$ %alue toTrue.

    Q. Select the Si3e "ro"ert$) and then clic' its dro"/down list to change the "ro"ert$ %alue toarge.

    Note how the te1t dis"la$ed is modified in the following illustration.

  • 8/13/2019 ASP Net Using Vb Net

    26/566

    6. ,enter the a#el control o%er the image #$ clic'ing and dragging the control in thedesigner window) and then sa%e the file #$ clic'ing the Sa%e #utton) as shown in thefollowing illustration) on the tool#ar.

    K. Browse the "age #$ right/clic'ing &elcome.as"1 in Solution E1"lorer and selectingView 3n Browser.

    The result should loo' similar to the following illustration.

    Tool#ars

    To accom"lish tas's in Visual Studio .NET) $ou+ll most li'el$ use a com#ination of the 30E+stool#ars and menus. This section will ta'e a loo' at the most commonl$ used tool#ars) and thene1t section will loo' at the most commonl$ used menus. You can %iew the full list of a%aila#letool#ars #$ right/clic'ing an$ tool#ar ?or em"t$ tool#ar area . 3n 'ee"ing with the customiGa#lenature of the Visual Studio .NET 30E) all tool#ars can #e customiGed #$ adding) remo%ing) orrearranging #uttons) mo%ing tool#ars) and showing or hiding tool#ars.

    NOTE@i%en the fle1i#ilit$ of the Visual Studio .NET tool#ars) it+s eas$ to end u" with $our tool#arsloo'ing nothing li'e the$ did when $ou installed Visual Studio. For some de%elo"ers this might

    #e a good thing) #ut if $ou want to restore $our tool#ars to their original configuration) clic' theTool#ar *"tions #utton ?which loo's li'e the arrow of a dro"/down list control found at theright end of each tool#ar) then clic' Add *r 7emo%e Buttons) then clic' the menu item for thetool#ar name) and then clic' 7eset Tool#ar.

  • 8/13/2019 ASP Net Using Vb Net

    27/566

    Standard

    The Standard tool#ar) shown in the following illustration) contains #uttons for commonfile and "ro;ect commands) including o"ening files and "ro;ects) creating new files and

    "ro;ects) and accessing %arious windows in the 30E.

    Formatting

    The Formatting tool#ar) shown in the following illustration) contains #uttons related to theformatting of te1t) including font and font siGe) te1t alignment o"tions) and #ac'groundand foreground colors. This tool#ar is ena#led onl$ when $ou+re entering or editing te1t in0esign %iew.

    Te1t Editor

    The Te1t Editor tool#ar) shown in the following illustration) contains #uttons related to theo"eration of the Te1t Editor) including access to 3ntelliSense features) indenting andcommenting of code) and #oo'mar's. ?You can use these to na%igate (uic'l$ to s"ecificsections of $our code.

    0e#ug

    The 0e#ug tool#ar) shown in the following illustration) contains #uttons related to0e#ugging commands) from Start) Sto") and Brea' commands to #uttons for accessing the%arious 0e#ug windows. 0e#ugging is co%ered in ,ha"ter 8.

    MenusA great man$ menus are a%aila#le in Visual Studio .NET) de"ending on the tas' $ou+re wor'ingon at an$ gi%en time. &hile we won+t go o%er all of them) the menus $ou+ll encounter mostfre(uentl$ in $our Visual Studio tra%els are listed here.

    File menu

  • 8/13/2019 ASP Net Using Vb Net

    28/566

    The File menu is used to create) o"en) and sa%e files and "ro;ects) as well as to "rint filesand to e1it the "rogram.

    Edit menu

    The Edit menu is used for wor'ing with te1t and o#;ects such as ,ut) ,o"$) and Paste) aswell as te1t/s"ecific commands such as Find and 7e"lace) and formatting commands suchas Ma'e 9""ercase or Ma'e owercase.

    View menu

    The View menu is used to access windows or %iews that are currentl$ hidden. 9se thismenu to switch from source code to design %iew or to o"en u" windows such as the Tas'ist) as well as to choose which tool#ars are dis"la$ed.

    Pro;ect menu

    The Pro;ect menu is used to add items to a "ro;ect) add references to assem#lies or &e#ser%ices) and set the start "age and start/u" "ro;ect used for de#ugging.

    Build menu

    The Build menu is used for #uilding and re#uilding a "ro;ect or "ro;ects) as well ascommands for de"lo$ing "ro;ects.

    0e#ug menu

    The 0e#ug menu is used to start) sto") and "ause ?#rea' de#ugging) and to set #rea'"ointsand access de#ugging windows.

    Ta#le menu

    The Ta#le menu is used for wor'ing with

  • 8/13/2019 ASP Net Using Vb Net

    29/566

    &indow menu

    The &indow menu is used to na%igate and manage the o"en document windows #eingused #$ the a""lication.

  • 8/13/2019 ASP Net Using Vb Net

    30/566

    and set the o"tions to $our "referred setting. 3n this wa$) $ou can determine how formatting isa""lied to $our code or) for some languages) $ou can turn off reformatting entirel$.

    NOTE*ne new o"tion that will a""eal to longtime BAS3, users is ha%ing the 30E dis"la$ line num#ers

    in the te1t editor. 9nli'e BAS3,) howe%er) the line num#ers are onl$ for referenceI the$+re notactuall$ a "art of the code. You can turn this o"tion on or off for indi%idual languages) or $oucan turn it on glo#all$ for all languages.E1iting Visual Studio .NET

    &hen $ou+re finished wor'ing with a gi%en "ro;ect) naturall$ $ou+ll want to e1it from VisualStudio .NET.

    E1it Visual Studio .NET

    . Sa%e an$ o"en files) using the Sa%e All #utton) as shown in the following illustration) onthe tool#ar or #$ selecting Sa%e All from the File menu.

    2. From the File menu) select E1it.

    Visual Studio .NET shuts down.

  • 8/13/2019 ASP Net Using Vb Net

    31/566

    !hat"s New in ASP.NET

    &hile there are "lent$ of familiar features in ASP.NET) some significant changes ha%e #eenmade to the ASP.NET architecture) including man$ im"ro%ements and new features. Thefollowing section will ta'e a high/le%el loo' at what+s new in ASP.NET.

    Familiar Features

    3t+s im"ortant to note that man$ things in ASP.NET will #e familiar to &e# de%elo"ers who+%eused classic ASP. The much/used e4uest and esponse o#;ects are still there) as are the

    pplication ) Session ) and Ser%er o#;ects) al#eit with some new "ro"erties and methods. You canstill use either R script runat56ser%er7 #loc's or the R 8 8 ASP scri"t delimiters to denoteser%er/side scri"t. 3n fact) for the most "art $ou can write an ASP.NET "age e1actl$ the samewa$ $ou would write a classic ASP "age. *nce $ou get used to the new "rogramming model ofASP.NET) though) $ou+ll ne%er go #ac' to coding $our ASP a""lications the wa$ $ou do toda$.

    Also) $ou don+t need to migrate all of $our e1isting ASP a""lications at once. ASP.NET isdesigned to run side #$ side with classic ASP. So while $ou+re wor'ing on $our first newASP.NET a""lication) $our current ASP a""lications can still #e running right alongside.

    !hat"s New

    There+s a lot of new stuff in ASP.NET) and it will ta'e time to learn all of it. But once $ou+%elearned it) $our "roducti%it$ will #e far greater than it was with classic ASP. et+s loo' at a list ofsome of the new features of ASP.NET.

    !e# $ r%s

    This is the new "rogramming model of ASP.NET. &e# Forms com#ines the #est of ASP withthe ease of de%elo"ment and "roducti%it$ of Visual Basic. You can drag controls onto a "age andthen write code to "ro%ide interacti%it$) call #usiness o#;ects) and more. You+ll learn a#out &e#Forms in ,ha"ter K.

    Ser&er c ntr ls

    A ma;or com"onent of the &e# Forms "rogramming model) the ASP.NET ser%er controls ma"a""ro1imatel$ to

  • 8/13/2019 ASP Net Using Vb Net

    32/566

    !e# Ser&ices

    This is a 'e$ "art of ASP.NET that allows de%elo"ers to ma'e "rogrammatic ser%ices a%aila#leto other de%elo"ers o%er the 3nternet ?or a local intranet . &e# Ser%ices are #ased on theemerging S*AP standard) so the$ will allow relati%el$ "ainless intero"eration across di%erse

    "latforms. You+ll learn more a#out &e# Ser%ices in ,ha"ter .

    'aching

    ASP.NET includes a "owerful new caching engine that will allow de%elo"ers to im"ro%e the "erformance of their a""lications #$ reducing the &e# ser%er and data#ase ser%er "rocessingloads. You+ll learn more a#out caching in ,ha"ter 2.

    ' nfigurati n i%(r &e%ents

    ASP.NET uses a new method of storing configuration information for &e# a""lications. 3nsteadof ha%ing 33S store this information in a hard/to/access data#ase) it+s stored in -M /#asedhuman/ and machine/reada#le configuration files) which also ma'e de"lo$ment easier. You+llloo' at how these configuration files wor' in ,ha"ter Q.

    State %anage%ent i%(r &e%ents

    3f $ou+%e had to #uild an ASP a""lication to run on a &e# farm) $ou 'now all too well that therewere ma;or limitations to state management in classic ASP. ASP.NET o%ercomes theselimitations) "ro%iding su""ort for distri#uting session state across &e# ser%ers) "ersisting stateinformation in a Microsoft S: Ser%er data#ase) and "ro%iding state management without theuse of coo'ies. You+ll learn how to ta'e ad%antage of these features in ,ha"ter 8.

    Securit)

    This is an e1tremel$ im"ortant function in toda$+s &e# a""lications. The securit$ model inASP.NET has #een su#stantiall$ im"ro%ed) including new and im"ro%ed authentication methods)code access securit$) and role/#ased authoriGation. You+ll loo' at the ASP.NET securit$ modeland how to im"lement securit$ in $our ASP.NET a""lications in ,ha"ter 6. New in %ersion .of ASP.NET is a feature called 7e(uest Validation. This feature) which chec's form in"ut forscri"ts or

  • 8/13/2019 ASP Net Using Vb Net

    33/566

    'ha(ter *'reating an ASP.NET !e# A((licati n3n this cha"ter) $ou will learn how to=

    ,reate a new &e# a""lication with Microsoft Visual Studio .NET.Add a &e# Forms "age to a &e# a""lication "ro;ect.

    Add Ser%er ,ontrols to a &e# Forms "age and modif$ their "ro"erties.

    &rite code in e%ent handlers.

    Build and test a &e# a""lication.

    Now that $ou+%e learned a#out some of the features of Visual Studio .NET) the ne1t ste" is tota'e ad%antage of them in $our own a""lications. ,on%enientl$ enough) that+s "recisel$ what$ou+re going to learn how to do in this cha"ter.

    You+ll #egin with an o%er%iew of the two ma;or "ro;ect t$"es used for ASP.NET a""lications.Then $ou+ll loo' at the file t$"es used in ASP.NET and the "ur"ose of each. Ne1t) $ou+ll learnhow to create a new &e# a""lication) add a new &e# Forms "age) and add controls to the "ageand mani"ulate their "ro"erties. Finall$) $ou+ll learn how to add e%ent/handler code to the "age)

    #uild the "ro;ect) and test the "age.

    ASP.NET Pr +ect T)(es

    There are three #asic t$"es of ASP.NET a""lications) each with a distinct "ur"ose. SP.NETeb pplications are for a &e# a""lication that will "ro%ide its own

  • 8/13/2019 ASP Net Using Vb Net

    34/566

    ASP.NET &e# A""lications

    ASP.NET a""lications) at their sim"lest) are much li'e classic ASP a""lications. The elements ofa sim"le ASP.NET a""lication are

    A %irtual director$ in 33S) configured as an a""lication root) to hold the files that ma'e u"the a""lication and to control access to the files.*ne or more .as"1 files.

    A @lo#al.asa1 file ?analogous to the @lo#al.asa file in classic ASP to deal with Sessionand A""lication startu" and clean/u" logic. This file is o"tional.

    A &e#.config file used to store configuration settings. This file is o"tional) and is new forASP.NET.

    For Visual Studio .NET users) the good news is that all of the "receding files are created for $ouwhen $ou create a new &e# a""lication "ro;ect.

    ASP.NET &e# Forms

    &e# Forms are an im"ortant "art of an$ ASP.NET &e# a""lication. Put sim"l$) the$ areASP.NET "ages that use SP.NET Ser%er ,ontrols. The &e# Forms "rogramming model ma'esit "ossi#le ?and relati%el$ eas$ to de%elo" &e#/#ased a""lications in much the same wa$ thattoda$+s Microsoft Visual Basic "rogrammers de%elo" Microsoft &indows #ased a""licationsthat ha%e a @93.

    &e# Forms in Visual Studio .NET allow $ou to create rich) interacti%e a""lications sim"l$ #$dragging and dro""ing controls onto a "age and then writing minimal code to handle userinteraction) e%ents) and so on. 3n addition) the Visual Studio .NET en%ironment lets $ou wor' on$our "ages either %isuall$ using the &e# Forms 0esigner or te1tuall$) using the "owerfulVisual Studio .NET source/code editor.

    You can write code in $our &e# Forms in one of two wa$s= inline in the .as"1 file ?as is t$"icalof a classic ASP "age ) or using a code/#ehind module. Although it+s "ossi#le to write $our

  • 8/13/2019 ASP Net Using Vb Net

    35/566

    a""lication with code in the actual .as"1 file and still ta'e ad%antage of com"iled code and theother im"ro%ements of .NET) 3 recommend that $ou get in the ha#it of using code/#ehindmodules. Visual Studio .NET defaults to using code/#ehind for 93/s"ecific "rogramming logic.

    ,ode/Behind

    ,ode/#ehind is a new feature in ASP.NET that allows de%elo"ers to trul$ se"arate the

  • 8/13/2019 ASP Net Using Vb Net

    36/566

    allows com"uters on %ar$ing "latforms) from &indows ser%ers to 9N3- wor'stations) to offerand consume "rogrammatic ser%ices o%er the

  • 8/13/2019 ASP Net Using Vb Net

    37/566

    ASP.NET $ile T)(es

    You+ll see a num#er of new file t$"es in $our ASP.NET a""lications. To a%oid an$ confusion)let+s ta'e a minute to go o%er the ones $ou+ll see most often and discuss how the$+re used.

    .as"1

    The e1tension $ou+ll see most often. Analogous to the .as" e1tension in classic ASP) .as"1is used for &e# Forms "ages.

    .asc1

    The e1tension used for &e# Forms user controls. 9ser controls "ro%ide one of the man$wa$s a%aila#le in ASP.NET to reuse code. Similar to include files in classic ASP) .asc1files can #e as sim"le as a few

  • 8/13/2019 ASP Net Using Vb Net

    38/566

  • 8/13/2019 ASP Net Using Vb Net

    39/566

    Visual Studi .NET

    3t+s certainl$ "ossi#le to create ASP.NET &e# a""lications in Note"ad or another te1t editor) #utif $ou+re doing serious ASP.NET or com"onent de%elo"ment) $ou+ll "ro#a#l$ want to wor'within the Visual Studio .NET en%ironment. The ad%antages of Visual Studio .NET o%er sim"lete1t editors include

    7o#ust management of "ro;ect files and multi"le "ro;ects3ntegration with the Microsoft Visual SourceSafe source/code control en%ironment

    Visual Tools for wor'ing with &e# ser%ices) &e# Forms ser%er controls) and data#asetools

    Pac'aging and de"lo$ment ser%ices for &e# a""lications

    Su""ort for multi"le languages within a single 30E) including cross/language inheritanceand de#ugging

    That+s ;ust a #rief list. There+s much more to the tool than can #e co%ered in a single cha"ter. Sowithout further ado) let+s loo' at how to create "ro;ects and "ages in the Visual Studio .NETen%ironment.

    ,reating A""lications

    *ne of the first things $ou+re going to want to do in order to wor' with ASP.NET in VisualStudio .NET is create a new "ro;ect) or in Visual Studio .NET "arlance) a &e# a""lication.

    ,reate an ASP.NET &e# a""lication

    . aunch Visual Studio .NET using the techni(ues $ou learned in ,ha"ter .2. *"en the New Pro;ect dialog #o1 using one of the following methods=

    ,lic' the ,reate A New Pro;ect lin' on the Visual Studio .NET Start Page?dis"la$ed #$ default when $ou first o"en Visual Studio .NET .

    ,lic' the New Pro;ect #utton ?shown in the following illustration ) located on theStandard tool#ar.

    From the File menu) select New) and then Pro;ect.

    !. 3n the New Pro;ect dialog #o1 ?see the following illustration ) under Pro;ect T$"es) selectthe Visual Basic Pro;ects folder) then select the a""ro"riate tem"late ?ASP.NET &e#A""lication . T$"e the location as htt(,--l calh st-'ha(ter /* ) and then clic' *>.

  • 8/13/2019 ASP Net Using Vb Net

    40/566

    Visual Studio .NET will create a new &e# a""lication along with "h$sical and %irtualdirectories for the "ro;ect.

    That+s itH You+%e created $our first ASP.NET &e# a""lication. Note that this a""lication isse"arate from the ,ha"terO 2 "ro;ect included with the "ractice file installation) which iscontained in the as"nets#s solution. Ne1t we+ll loo' at how to add new "ages.

    3n $our new &e# a""lication) $ou+ll notice that Visual Studio .NET has alread$ added a "agenamed &e#Form .as"1 to the "ro;ect for $ou and o"ened it in the editor. Your Visual Studio.NET screen should loo' similar to the following illustration.

  • 8/13/2019 ASP Net Using Vb Net

    41/566

    ,reate a new ASP.NET "age ?&e# Form

    . Add a new &e# Form to $our a""lication.

    As with creating a new "ro;ect) there are se%eral wa$s to add a new ASP.NET "age ?&e#Form to $our a""lication. The method $ou choose de"ends largel$ on how $ou li'e towor'.

  • 8/13/2019 ASP Net Using Vb Net

    42/566

    *n the Visual Studio .NET tool#ar) clic' the Add New 3tem #utton ?shown in thefollowing illustration and then select &e# Form from the Tem"lates list.From the Pro;ect menu) select Add &e# Form.

    An$ of these methods will o"en the Add New 3tem dialog #o1) shown in the followingillustration.

  • 8/13/2019 ASP Net Using Vb Net

    43/566

    2. 3n the Add New 3tem dialog #o1) %erif$ that the &e# Form tem"late is selected and namethe new "age

  • 8/13/2019 ASP Net Using Vb Net

    44/566

    Modif$ &e# Form "ro"erties

    . &ith the &e# Form o"en in the Visual Studio .NET designer) clic' the &e# Form "ageto ensure it is selected.

    &hen the "age is selected) the word ,+=!9ENT should a""ear in the dro"/down #o1 atthe to" of the Pro"erties window.

    2. Select the page

  • 8/13/2019 ASP Net Using Vb Net

    45/566

  • 8/13/2019 ASP Net Using Vb Net

    46/566

    Q. ,lic' the #ac'ground of the "age to "lace the cursor after the 0=lick .

    2. Add the following code to the 2utton>0=lick "rocedure=

    3. Label1.Text = "Hello, " & TextBox1.Text & "!"

    4. TextBox1.Visible = False

    Button1.Visible = False

    Q. Sa%e the code/#ehind module) which should now loo' li'e the following illustration.

  • 8/13/2019 ASP Net Using Vb Net

    47/566

    Building and Testing Your Page

    Because $ou modified the code/#ehind module for the &e# Form) $ou need to #uild $our "ro;ect #efore $ou can #rowse the "age. ?You+ll learn more a#out code/#ehind in later cha"ters. 2uilding is the "rocess of com"iling all of the code modules in the "ro;ect so the$+ll #e a%aila#leto the "ages and modules that call them. To #uild the "ro;ect) from the Build menu) select Build,ha"terO 2 ?or Build Solution) which will #uild all "ro;ects in the solution .

    *nce $ou+%e sa%ed the &e# Form "age and its code/#ehind module and #uilt the a""lication) $oucan test the "age.

    Test $our "age

    . 7ight/clic' the "age in Solution E1"lorer and select View 3n Browser.

    The result should loo' li'e the following illustration. ?You can close the *ut"ut windowif $ou want to see more of a "age.

  • 8/13/2019 ASP Net Using Vb Net

    48/566

    2. Enter $our name in the te1t #o1 and clic' Su#mit.

    The result should #e similar to the following illustration. ?Note that the &e# tool#arshows the address of the "age #eing #rowsed. You can enter this address in a #rowserwindow on $our machine to %iew the "age in a non/em#edded #rowser window.

  • 8/13/2019 ASP Net Using Vb Net

    49/566

    ,ha"ter !9nderstanding Programming Basics3n this cha"ter) $ou will learn how to=

    9se e1"ressions) %aria#les) and constants.9se "rocedures.

    9se flow control statements.

  • 8/13/2019 ASP Net Using Vb Net

    50/566

    Visual Basic .NET documentation is a container of code that is made a%aila#le to other classesand modules within the same names"ace. 9nless otherwise s"ecified) the term module in this

    #oo' has the former meaning rather than the latter.

    A class ) as $ou+ll see in 49sing ,lasses as ,ontainers for ,ode5 later in this cha"ter) is a s"ecial

    t$"e of code container that "ro%ides a num#er of useful features. ,lasses are contained withinmodules ?that is) files with the e1tension .cs or .%# .

    A namespace contains one or more classes) and can #e defined in one or more modules. Names"aces can #e used to "re%ent name collisions when two classes ha%e the same name.

    E0(ressi ns1 Varia#les1 and ' nstants

    E1"ressions) %aria#les) and constants are some of the most #asic #uilding #loc's of com"uter "rograms) and $ou+ll use them all e1tensi%el$ in $our ASP.NET a""lications.

    E1"ressions

    E1"ressions are central to %irtuall$ all com"uter "rograms. Among other ca"a#ilities)e1"ressions let $ou

    ,om"are %alues to one another Perform calculations

    Mani"ulate te1t %alues

    An e1"ression can #e as sim"le as the following=

    1 + 1

    An e1"ression li'e this isn+t %er$ useful #$ itself) howe%er. 9nli'e "eo"le) who can easil$recogniGe 4one "lus one5 and fill in the #lan' ?4e(uals two5 ) com"uters aren+t ca"a#le of that'ind of lea" of logic. 3n order for the e1"ression to #e useful) it needs to tell a com"uter not ;ustto add one and one) #ut to store the result somewhere so that we can ma'e use of it later ?either

    #$ dis"la$ing it to the user or using it in another e1"ression later . This is where %aria#les comein.

    Varia#les

    At some "oint during the e1ecution of most "rograms) $ou+ll need to store %alues of some sort)such as the results of com"arisons or mathematical o"erations ?as in the "receding e1am"le ) orte1t in"ut acce"ted from users. Sim"l$ "ut) %ariables are storage areas for data. This data can #enumeric) te1t) or an$ one of a num#er of s"ecial data t$"es.

  • 8/13/2019 ASP Net Using Vb Net

    51/566

    0ata T$"es

    The data type of a %aria#le defines the t$"e of data that can #e stored in it) as well as the formatin which that data is stored ?and the amount of memor$ that the s$stem needs to allocate for the%aria#le . Ta#le !/ lists the data t$"es su""orted #$ Visual Basic .NET and ,J) as well as the

    Microsoft .NET Framewor' S0> t$"es to which the$ ma". The data t$"es mar'ed with anasteris' ? don+t ha%e a nati%e re"resentation) #ut $ou can still access these data t$"es #$ usingthe a""ro"riate System ?or .NET Framewor' t$"e when declaring the %aria#le.

    The data t$"e of a %aria#le is determined at the time the %aria#le is declared. This will #ediscussed further in the section entitled 40eclaring Varia#les5 later in the cha"ter.

    Ta#le 234. ,ata Types

    C# DataType

    Visual Basic DataType

    .NET Data Type Size

    bool 2oolean System.2oolean 2 #$tes

    byte 2yte System.2yte #$te

    sbyte ? System.S2yte #$te

    char =har System.=har 2 #$tes

    ,ate System.,ateTime D #$tes

    decimal ,ecimal System.,ecimal 6 #$tes

    double ,ouble System.,ouble D #$tes

    int "nteger System."ntA( 8 #$tesuint ? System.!"ntA( 8 #$tes

    long & 2 #$tes

    ushort ? System.!"nt>& 2 #$tes

    float Single System.Single 8 #$tes

    string String System.String From to 2 #illion 9nicodecharacters

    struct !serC,efined Type System.DalueType ?inherited

    Sum of mem#er siGes

  • 8/13/2019 ASP Net Using Vb Net

    52/566

    IMPORTANTASP.NET contains #oth framewor'/s"ecific data t$"es and language/s"ecific data t$"es fors"ecific .NET languages) such as Visual Basic .NET and ,J. To ta'e ad%antage of some of themultilanguage features of the .NET en%ironment) $ou need to limit $our use of data t$"es tothose su""orted #$ the ,ommon anguage S"ecification ?, S ) a su#set of the data t$"es

    su""orted #$ the common language runtime ?, 7 . 3n the "receding ta#le) data t$"es mar'edwith W are not , S/com"liant. A%oid using them in classes that $ou want to ma'e a%aila#le foruse with other .NET languages. 0ata t$"es mar'ed with do not ha%e a language/s"ecificre"resentation) so if $ou want to use these t$"es $ou need to use the .NET Framewor' t$"e.Value T$"es %s. 7eference T$"es

    3n .NET de%elo"ment) there are two categories of data t$"es= %alue t$"es and reference t$"es.Although understanding the distinction #etween these t$"es isn+t a#solutel$ necessar$ if $ouwant to de%elo" ASP.NET a""lications) it can hel" $ou to #etter understand how these data t$"eso"erate and how to deal with error messages resulting from coding errors. ?Not that those e%erha""en) rightU

    Value t$"es are data t$"es that store their data directl$ as %alues in memor$. The$ include all thenumeric t$"es ? intA( ) short ) single ) and so on ) structures ?custom data t$"es #ased onSystem.DalueType ) and enumerations ?custom t$"es that re"resent a defined set of %alues ) aswell as boolean ) char ) and date t$"es. Value t$"es are accessed directl$) as in the followinge1am"le=

    'Visual Basic.N T ecla ation #o an int3$

    %i (nt as (nte)e

    ' x* ession to assi)n t e alue 1$3 i ectl to t e a iable

    (nt = 1$3TIPThe "receding code e1am"le uses comments to "ro%ide an additional e1"lanation of what thecode in the e1am"le is used for. ,omments are lines ?or "ortions of lines of code that use as"ecial character that tells the language com"iler to ignore them when com"iling the code. 3nVisual Basic .NET) the single (uote character ?+ is used to "recede a comment. &ith thee1ce"tion of a single (uote contained within dou#le (uotes ?which re"resents a literal string )e%er$thing following a single (uote on the same line is ignored #$ the com"iler. This means that$ou can "ut comments on the same line as the code the$ refer to or on their own line) as in the

    "receding e1am"le. For comments that s"an more than one line) each line must #e "receded withthe comment character.

    9sing comments is a good ha#it to get into #ecause comments ma'e $our code easier to read andunderstand. You should consider using comments e%en if $ou+re the onl$ one who+ll e%er see thecode since comments are %er$ useful when $ou ha%e to re%ise code that $ou wrote months or$ears #efore) when it might no longer #e clear wh$ $ou wrote the code the wa$ $ou did.

  • 8/13/2019 ASP Net Using Vb Net

    53/566

    7eference t$"es are data t$"es that store a reference to another memor$ location that contains thedata) which is usuall$ #ased on a class) such as the String class in the .NET Framewor'.7eference t$"es include +b*ect ?which acts as a re"lacement for Visual Basic+s Dariant t$"e) nolonger su""orted in .NET ) String ) and all rrays ) as well as instances of custom classes.7eference t$"es are accessed through mem#ers of the class that the t$"e holds a reference to) as

    in the following e1am"le=

    '%e#ine a class

    -lass a *le-lass

    /ublic (nt 0s (nte)e

    n -lass

    '- eate an instance o# t e class

    %i -lass(nstance 0s Ne a *le-lass2

    ' x* ession to assi)n t e alue 1$3 to -lass(nstance e be (nt

    -lass(nstance. (nt = 1$3

    0eclaring Varia#les

    Before $ou can use %aria#les in $our "rograms) $ou need to declare them. Dariable declaration is the "rocess of s"ecif$ing the characteristics of the %aria#le ?name) data t$"e) lifetime) sco"e)and accessi#ilit$ so that the run/time s$stem 'nows how much storage s"ace to allocate for the%aria#le) which actions to allow on the %aria#le) and who can ta'e those actions. A %aria#ledeclaration ta'es the following form in Visual Basic .NET=

    '%ecla es a a iable o# t *e (nte)e

    %i x 0s (nte)eTIPThe "receding e1am"le uses $ as the name of the %aria#le. &hile this is "erfectl$ acce"ta#le asfar as the language com"ilers are concerned) $ou should consider gi%ing $our %aria#les moremeaningful names) such as 1irstName ?for a string %aria#le holding a first name )

  • 8/13/2019 ASP Net Using Vb Net

    54/566

    #loc' in which the declaration a""eared. 3n addition to sim"le declarations li'e these) $ou canuse the "lacement of the declarations) as well as Visual Basic .NET 'e$words) to modif$ thelifetime) sco"e) and accessi#ilit$ of $our %aria#les.

    Varia#le ifetime

  • 8/13/2019 ASP Net Using Vb Net

    55/566

    n ub Naming ,on%entions and ,ase

    The Visual Basic .NET documentation recommends that $ou use whole words when naming$our %aria#les. You should use mi1ed case) with the first letter of each word ca"italiGed) as in

  • 8/13/2019 ASP Net Using Vb Net

    56/566

    Bloc' le%el

    Varia#les declared within statement #loc's such as "f G Then ) 1or G Ne$t ) or ,o G

  • 8/13/2019 ASP Net Using Vb Net

    57/566

    Static %aria#le that+s declared within a "rocedure is a good illustration of this distinction. 3n thate1am"le) the %aria#le 9y"nt will continue to e1ist e%en after the "rocedure in which it+s declaredhas com"leted) #ut #ecause it has "rocedure/le%el sco"e) it+s onl$ accessi#le within the

    "rocedure.

  • 8/13/2019 ASP Net Using Vb Net

    58/566

    Pri%ate has the same effect on the %aria#le+s accessi#ilit$) #ut Pri%ate ma'es $ourintentions more e1"licit. The Pri%ate 'e$word cannot #e used within a "rocedure.

    NOTE3n ,J) all %aria#les must #e declared #efore the$ can #e used. Failure to declare a %aria#le will

    result in a com"iler error. 3n Visual Basic .NET and some other languages) it+s "ossi#le ?#ut notad%isa#le to use %aria#les without first declaring them. 9sing %aria#les that ha%e not #eene1"licitl$ declared is a ma;or source of #ugs in Visual Basic "rograms and should #e a%oided.

    The Visual Basic +ption E$plicit statement ?"laced at the to" of a module or class re(uires thatall %aria#les in that module #e e1"licitl$ declared.

    'tu ns 9*tion x*licit on

    9*tion x*licit 9n

    'tu ns 9*tion x*licit o##

    9*tion x*licit 9##

    To further "rotect $our code from inad%ertent #ugs) $ou can also use the new +ption Strict statement. &hen +ption Strict is on) con%ersions #etween data t$"es that would result in dataloss ?also 'nown as narrowing con%ersions) such as con%erting a Single containing the %alue .2Qto an 3nteger) which would result in the 3nteger %aria#le ha%ing the %alue are disallowed) asare con%ersions #etween strings and numeric t$"es.

    'tu ns 9*tion t ict on

    9*tion t ict 9n

    'tu ns 9*tion t ict o##

    9*tion t ict 9##

    You can also set +ption E$plicit and +ption Strict in the "ro;ect "ro"erties for the "ro;ect) inwhich case the$ will a""l$ to all classes in the "ro;ect.

    Following these guidelines can hel" reduce the num#er of #ugs in $our code) and moreim"ortantl$) the time $ou s"end trac'ing them down.

    The *"tion Strict statement includes all of the restrictions of *"tion E1"licit) so it is notnecessar$ to use #oth.

    ,onstants

    ,onstants are similar to %aria#les) e1ce"t for one im"ortant detail= *nce a constant has #eendeclared and initialiGed) its %alue cannot #e modified. ,onstants are %er$ useful when $ou ha%e aliteral %alue that $ou want to refer to #$ name. For e1am"le) in a "rogram that calculates

  • 8/13/2019 ASP Net Using Vb Net

    59/566

    shi""ing weights in "ounds and ounces) $ou might want to create a constant to refer to thenum#er of ounces in a "ound=

    -onst 9unces(n0/oun 0s (nte)e = 1:

    An$where within $our "rogram ?su#;ect to the same sco"e) lifetime) and accessi#ilit$ rules as%aria#les $ou can use the constant name +unces"n Pound instead of the literal %alue >& .

    ,onstants are "articularl$ hand$ in "lace of literal %alues used as the arguments to methods ofcom"onents $ou might use. For e1am"le) in classic Microsoft Acti%e- 0ata *#;ects ?A0* ) thedata t$"es of stored "rocedure "arameters were re"resented #$ numeric %alues. Tr$ing toremem#er all of those %alues would #e unrealistic) so the de%elo"ers of A0* also made it

    "ossi#le to use constants ? ad"nteger ) adDar=har ) and so on in "lace of the literal %alues.

    3n other words) constants let $ou su#stitute eas$/to/remem#er names for difficult/to/remem#erliteral %alues. This can ma'e $our code easier to write and maintain) since $ou can u"date the

    %alue in a single location ?the constant initialiGation ) rather than ha%ing to search $our code fore%er$ instance of a literal %alue.

    Enumerations

    Man$ constants used with ASP.NET are actuall$ created using enumerations. 9singenumerations allows $ou to define a set of related constants and access them in a t$"e/safe wa$.For instance) if $ou ha%e a "rocedure that acce"ts numeric %alues) from to !) re"resenting acolor) it might loo' li'e this=

    ub et-olo 2B Val -olo 0s (nte)e

    (# -olo = 3 T en

    '-o e to a**l colo settin) 3.

    n (#

    n ub

    This method will) in fact) ha""il$ acce"t an$ integer %alue. To limit the "ossi#le %alues) $oucould declare an enumeration as follows=

    nu -olo T *e 0s (nte)e

    6e =1

    ; een

    Blue

    n nu

  • 8/13/2019 ASP Net Using Vb Net

    60/566

    B$ default the first element of an enumeration is e(ual to . 3n this e1am"le) since $ou want anenumeration that contains through !) $ou set the first %alue in the enumeration to ) and thenthe su#se(uent %alues are each incremented #$ one. So) -reen is 2 and 2lue is !. Now) ratherthan the "re%ious "rocedure declaration) $ou could use the following=

    ub et-olo 2B Val -olo 0s -olo T *e

    (# -olo = -olo T *e.Blue T en

    '-o e to a**l t e colo settin) blue.

    n (#

    n ub

    This "rocedure will re(uire an instance of the =olorType enumeration to #e "assed as the "arameter) ensuring that the %alue is a %alid mem#er of the enumeration) and thus that the %aluere"resents a %alid color. The following is an e1am"le of calling Set=olor with a =olorType enumeration mem#er=

    et-olo 2-olo T *e.Blue

    Pr ceduresProcedures are an im"ortant tool in ASP.NET de%elo"ment #ecause the$ allow $ou to determineat the time that $ou write the code the order in which sections of code will run at run time.Procedures also allow $ou to #etter organiGe $our code into discrete units #ased on thefunctionalit$ "ro%ided #$ each one. For e1am"le) if $ou write code that multi"lies two num#ersand returns the result) that code is much more useful if it+s wra""ed in a "rocedure. 9sing a

    "rocedure allows the code to #e called from more than one "lace in $our a""lication asnecessar$) which allows $ou to reuse the code rather than rewriting it each time $ou need tomulti"l$ two num#ers.

    3n Visual Basic .NET) $ou+ll use two main t$"es of "rocedures= Sub "rocedures and 1unction "rocedures. ?,J has functions onl$.

    Sub Procedures

    A Sub "rocedure e1ecutes code #ut doesn+t return a %alue. ,ode contained in a Sub "rocedure isdelimited #$ the Sub and End Sub statements) as follows=

    ' ub * oce u e t at ites out*ut to t e b o se

  • 8/13/2019 ASP Net Using Vb Net

    61/566

    ub iteHello2

    6es*onse. ite2"Hello o l !"

    n ub

    A Visual Basic .NET Sub "rocedure is e(ui%alent to a ,J function declared with the %oid modifier.

    7ecei%ing 3n"ut Parameters

    Note that in #oth the Visual Basic .NET Sub "rocedure and ,J 1unction "rocedure) the name ofthe "rocedure is followed #$ a set of em"t$ "arentheses. These "arentheses ha%e a "ur"ose otherthan sim"l$ ta'ing u" s"ace. You can "lace code #etween these "arentheses to define one ormore "arameters that users must "ass when the$ call the "rocedure. Parameters can #e "assedeither #$ %alue ?a co"$ of the %alue is "assed to the "rocedure or #$ reference ?a reference to thelocation of the %alue is "assed to the "rocedure) which allows the "rocedure to modif$ theoriginal %alue . You use the 'e$words 2yDal or 2y ef to s"ecif$ which wa$ the "arameters areto #e "assed. 3f no 'e$word is used) the "arameters will #e "assed #$ %alue. The following codeshows some e1am"les=

    'B Val exa *le

    ub 7o i# (nt2B Val (nt 0s (nte)e

    '0 4$ to (nt

    (nt = (nt + 4$

    'T e o i)inal alue o# (nt in t e callin)

    '* oce u e, as not been o i#ie .

    n ub

    'B 6e# exa *le

    ub 7o i# (nt2B 6e# (nt 0s (nte)e

    '0 4$ to (nt

    (nt = (nt + 4$

    'T e o i)inal alue o# (nt in t e callin)

    '* oce u e as no been o i#ie .

    n ub

  • 8/13/2019 ASP Net Using Vb Net

    62/566

    '( *licit B Val exa *le

    ub 7o i# (nt2 (nt 0s (nte)e

    '0 4$ to (nt

    (nt = (nt + 4$ 'T e o i)inal alue o# (nt in t e callin)

    '* oce u e as not been o i#ie .

    n ub

    Note that Visual Studio .NET will not allow the im"licit use of 2yDal . 3f $ou add the "recedingcode to a class in Visual Studio .NET) it will automaticall$ "refi1 arguments with 2yDal unless$ou e1"licitl$ "refi1 them with 2y ef . You can "ass more than one "arameter to a "roceduresim"l$ #$ se"arating each "arameter with a comma) as in the following e1am"le=

    ub iteHello2B Val Na e1 0s t in), B Val Na e$ 0s t in)

    6es*onse. ite2"Hello to bot " & Na e1 & " an " & Na e$

    n ub

    Note that $ou e1"licitl$ declare the data t$"e of each "arameter as String . 3f an$ data t$"e otherthan String is "assed to the "rocedure) an e1ce"tion will #e thrown. ?An e1ce"tion) which $ou+lllearn more a#out later in the cha"ter) is similar to an error.

    NOTE

    3n Visual Basic 6) the default for a "arameter definition without the 2yDal or 2y ef 'e$words isto "ass the "arameter #$ reference. Because this #eha%ior is the o""osite of that of the %astma;orit$ of languages) the Visual Basic de%elo"ment team has changed this #eha%ior in VisualBasic .NET. 3n Visual Basic .NET) "arameters defined without the 2yDal or 2y ef 'e$words are

    "assed #$ %alue.

    &hether $ou+re writing Visual Basic 6 code that might need to #e u"graded to Visual Basic .NETor writing nati%e Visual Basic .NET code) it+s a good "rogramming "ractice to alwa$s use 2yDal and 2y ef to e1"licitl$ declare how $our "arameters should #e "assed.

    You can ma'e one or more of the "arameters of $our "rocedure o"tional ?meaning the caller

    decides whether the "arameter will #e "assed or not #$ "receding them with the +ptional 'e$word.

    ub iteHello29*tional B Val Na e1 0s t in) = "Bob"

    6es*onse. ite2"Hello, " & Na e1 & "!"

    n ub

  • 8/13/2019 ASP Net Using Vb Net

    63/566

    &hen $ou use o"tional "arameters) $ou must su""l$ a default %alue for each one) as in the "receding e1am"le. Also) once $ou+%e declared an o"tional "arameter) all su#se(uent "arametersfor that "rocedure must also #e o"tional.

    Finall$) $ou can change the accessi#ilit$ of Sub "rocedures using the Public ) Pri%ate) 1riend )

    and Protected 'e$words. Sub "rocedures are "u#lic #$ default) which means the$ can #e calledfrom an$where within $our a""lication.

    1unction Procedures

    1unction "rocedures in Visual Basic .NET are ;ust li'e Sub "rocedures) e1ce"t for one im"ortantdetail the$ can return a %alue. &ith a 1unction "rocedure) $ou could

    7eturn a numeric %alue re"resenting an error or success code7eturn data in the form of an arra$ or an A0*.NET dataset

    7eturn True or False to indicate the results of some conditional test

    The following code e1am"le ta'es two string "arameters) concatenates them) and then returns theresult to the caller as a string=

    Function -oncat t in)s2B Val t in)1 0s t in), ou c ose 6e "

    6es*onse. ite2"? #ontA"

    -ase "; een"

    6es*onse. ite2"?#ont colo ='" & -olo t in) & "'A"

    6es*onse. ite2">ou c ose ; een"

    6es*onse. ite2"? #ontA"

    -ase "Blue"

    6es*onse. ite2"?#ont colo ='" & -olo t in) & "'A"

    6es*onse. ite2">ou c ose Blue"

    6es*onse. ite2"? #ontA"

    n elect

    You can also add a =ase Else statement to e1ecute s"ecific code when the tested e1"ressiondoesn+t match an$ of $our listed %alues) as the following code demonstrates=

    elect -ase -olo t in)

    -ase "6e "

    '...

    -ase "; een"

    '...

    -ase "Blue"

    6es*onse. ite2"?#ont colo ='" & -olo t in) & "'A"

    6es*onse. ite2">ou c ose Blue"

    6es*onse. ite2"? #ontA"

  • 8/13/2019 ASP Net Using Vb Net

    66/566

    -ase lse

    6es*onse. ite2"?#ont colo ='BlacC'A"

    6es*onse. ite2">ou i not c oose a colo "

    6es*onse. ite2"? #ontA"n elect

    3t+s good "rogramming "ractice to alwa$s ha%e a =ase Else statement) ;ust in case there areune1"ected %alues for the e1"ression $ou+re testing ?such as =olorString in this e1am"le .

    9se Select =ase in a &e# Forms "age

    . *"en Visual Studio .NET.2. Select New from the File menu) and then select Pro;ect.

    !. 3n the New Pro;ect dialog #o1) select Visual Basic Pro;ects from the Pro;ect T$"es listand ASP.NET &e# A""lication from the Tem"lates list.

    8. T$"e htt(,--l calh st-'ha(ter /2 in the location te1t #o1. ?The Name te1t #o1 willshow the new name as $ou t$"e it. ,lic' *>.

    The "ro;ect will #e created and loaded into the 30E) as shown in the followingillustration.

  • 8/13/2019 ASP Net Using Vb Net

    67/566

    Q. Mo%e the mouse "ointer o%er the Tool#o1 on the left side of the screen. The Tool#o1 willa""ear. Place a label ) a dropCdown list ) and another la#el on the form) as shown in thefollowing illustration.

  • 8/13/2019 ASP Net Using Vb Net

    68/566

    6. ,lic' the first

  • 8/13/2019 ASP Net Using Vb Net

    69/566

    C. 9se the Pro"erties window to change the ", "ro"ert$ of the second la#el to Message .. 0ou#le/clic' on the ,rop,own

  • 8/13/2019 ASP Net Using Vb Net

    70/566

    . Add the following code to the =olor0Selected"nde$=hanged handler=

    1$. 7essa)e.Text = "" 'initialiDe Text * o*e t

    13. elect -ase -olo . electe (te .Text

    14. -ase "6e "

    18. 7essa)e.Text &= "?#ont colo ='" & 0=lick e%ent handler will #e added.

    C. Add the following code to the handler=

    1 . %i a, b, c 0s (nte)e

    11. a = 1

    1$. b =

    13. c = a b

    7essa)e.Text = c.To t in)

    8. *n the File menu) clic' Sa%e All to sa%e the "age) and then select Build ,ha"terO ! fromthe Build menu to com"ile the "ro;ect.

    Q. Test the "age #$ right/clic'ing E1ce"tions.as"1 in Solution E1"lorer) and then selectingView 3n Browser. &hen $ou see the screen with the 0i%ide B$ ero #utton) clic' the #utton.You will see a screen similar to the following illustration) in which the *ut"ut window isclosed to allow $ou to see more of the "age.

  • 8/13/2019 ASP Net Using Vb Net

    82/566

    6. ,lose the em#edded #rowser window) locate the 2utton>0=lick handlerin E1ce"tions.as"1.%#) and then change the code in the handler to the following=

    1E. %i a, b, c 0s (nte)e

    1 . T ' ta t onito in) #o exce*tions

    1G. '-o e t at a cause an exce*tion

    $ . a = 1

    $1. b =

    $$. c = a b

    $3. -atc 9 0s 9 e #lo xce*tion

    $4. '-o e to an le exce*tion

    $8. 7essa)e.Text = "9 e #lo # o i i in) b De o."

    n T

    26. Select File) then Sa%e All to sa%e the "age) and then select Build ,ha"terO ! from theBuild menu to com"ile the "ro;ect.

    2K. Test the "age using the same "rocess as in ste" C. ,lic'ing the #utton should gi%e $ou aresult similar to the following illustration.

    Understanding O#+ect3Oriented Pr gra%%ing Basics

    *#;ect/oriented "rogramming will "ro#a#l$ #e new to man$ Visual Basic "rogrammers. Thissection will "ro%ide an o%er%iew of o#;ect/oriented "rogramming) "articularl$ as it relates to

  • 8/13/2019 ASP Net Using Vb Net

    83/566

    the .NET de%elo"ment "latform. *#;ect/oriented "rogramming is a su#stantial to"ic) so 3 highl$recommend that $ou do some additional reading to su""lement the material "ro%ided here. Agood "lace to start is the Visual Studio .NET documentation for Visual Basic) which contains anentire section on o#;ect/oriented "rogramming. There are also man$ #oo's on #oth o#;ect/oriented "rogramming and design patterns ) a related su#;ect.

    3n the sim"lest terms) an ob*ect is an instance of a class in o#;ect/oriented languages such as ,LL) ,J) and now Visual Basic .NET. ?,lasses are descri#ed in the section 49sing ,lasses as,ontainers for ,ode5 later in this cha"ter. *#;ects t$"icall$ mirror their real/world counter"arts=em"lo$ees) in%oices) and "urchase orders are all e1am"les of real/world entities that can #emodeled as o#;ects in $our "rograms. *#;ects t$"icall$ "ro%ide #oth properties ) which descri#esome attri#ute of the o#;ect ?for e1am"le) an Employee o#;ect might ha%e an Employee",

    "ro"ert$ ) and methods ) which allow actions to #e ta'en #$ the o#;ect ?for e1am"le) an Employeeo#;ect might e1"ose a Promote method . *#;ect/oriented "ro"erties and methods ma'e it easierfor "rogrammers to use a gi%en o#;ect in wa$s that relate to the real/world o#;ects that the

    "rogram is modeling.

    3n addition to "ro"erties and methods) o#;ect/oriented "rogramming offers three hel"ful features=inheritance) "ol$mor"hism) and enca"sulation.

    "nheritance is the a#ilit$ to create new classes that are deri%ed from e1isting classes. Aderi%ed class 4inherits5 all of the "ro"erties and methods of the class from which it isderi%ed ?referred to as the parent class . Programmers can then add additional "ro"ertiesand methods to the deri%ed class) or in some cases o%erride the im"lementation of ane1isting method inherited from the "arent class.

    Polymorphism lets "rogrammers ha%e identicall$ named methods on different classesderi%ed from the same "arent) and it allows the correct method to #e e1ecuted #ased on

    the conte1t of the call. For e1am"le) a "rogrammer could define an "n%oice class with a Process method. The "rogrammer could then define se"arate Time"n%oice and 9aterials"n%oice classes that are deri%ed from the "n%oice class) #ut define differentfunctionalit$ in their Process methods) hence o%eriding the functionalit$ e1"osed #$ the

    "arent class. &hen a "rocedure calls the Process method on one of these deri%ed o#;ects)the "ro"er "rocessing will #e e1ecuted. The calling "rocedure doesn+t ha%e to 'nowwhich 'ind of "n%oice it is dealing with.

    Encapsulation allows o#;ects to #e treated as 4#lac' #o1es5 in that onl$ the "ro"ertiesand methods defined #$ the "rogrammer as "u#licl$ a%aila#le are %isi#le outside of theo#;ect. The internal o#;ect state and the im"lementation of the "u#licl$ a%aila#le methodsare hidden #$ enca"sulation. This limited %isi#ilit$ lets de%elo"ers freel$ modif$ theinternal state and im"lementation of their o#;ects) as long as the$ don+t change the

    "u#licl$ defined interface used to access the o#;ect. For instance) an Employee

  • 8/13/2019 ASP Net Using Vb Net

    84/566

    9sing ,lasses as ,ontainers for ,ode

    =lasses are the #asic units of o#;ect/oriented a""lications. A class in Visual Basic .NET or ,Jt$"icall$ contains "ro"ert$ and method definitions) as well as e%ent handlers ?a s"ecial class ofmethods . ,lasses are often grou"ed into useful collections through the use of names"aces.

    Namespaces can contain classes and other names"aces. For e1am"le) the System. eb names"acedefined #$ the .NET Framewor' S0> contains not onl$ classes such as Kttp e4uest )

    Kttp esponse ) and KttpSer%er!tility ?which "ro%ide the e(ui%alent functionalit$ of the ASP e4uest ) esponse ) and Ser%er intrinsic o#;ects ) #ut also a num#er of names"aces) includingSystem. eb.!" ) System. eb.=aching ) and System. eb.SessionState ) each of which also containsclasses and or names"aces.

    B$ using classes as containers for code and names"aces) the .NET architecture ma'es it %er$eas$ to create a rich $et intuiti%e a""lication hierarch$ that can ma'e $our code easier to use)de#ug) and maintain.

    NOTE&hen $ou de%elo" a""lications in the Visual Studio .NET en%ironment) a root names"ace will

    #e created with the same name as $our "ro;ect. 3f $ou s"ecif$ additional names"aces within $ourcode modules) these will #ecome child names"aces of the root names"ace. You can change theroot names"ace) if desired) #$ right/clic'ing $our "ro;ect in the Solution E1"lorer window andselecting Pro"erties. The oot Namespace "ro"ert$ a""ears under ,ommon Pro"erties) @eneral.9sing 3nheritance

    Now that $ou 'now a #it a#out o#;ect/oriented "rogramming) let+s ta'e a loo' at a sim"lee1am"le of how to "ut it to use. First) let+s define a class #ased on a real/world entit$ ananimal. The following class retrie%es a reference to the current Kttp=onte$t in order to #e a#le towrite out"ut to the #rowser) and then defines Eat and Sleep methods) each of which writes amessage to the #rowser.

    /ublic -lass 0ni al

    %i -ontext 0s Htt*-ontext = Htt*-ontext.-u ent

    /ublic 9 e i able ub at2

    -ontext.6es*onse. ite2">u !?b A"

    n ub

    /ublic 9 e i able ub lee*2

    -ontext.6es*onse. ite2"KDDDD...?b A"

    n ub

    n -lass

  • 8/13/2019 ASP Net Using Vb Net

    85/566

    Ne1t) we+ll create a more s"ecific animal class) ,at) which deri%es from the Animal class. Notethe use of the 3nherits 'e$word on the second line. 3nheriting from another class is reall$ thatsim"le. This class will o%erride the #eha%ior of the Eat method #ut not the Slee" method) asfollows=

    /ublic -lass -at

    (n e its 0ni al

    %i -ontext 0s Htt*-ontext = Htt*-ontext.-u ent

    /ublic 9 e i es ub at2

    -ontext.6es*onse. ite2">u , >u ...7eo , 7eo !?b A"

    n ub

    n -lass

    You+ll also create a 0og class that deri%es from Animal and that o%errides the Slee" method #utnot the Eat method) as follows=

    /ublic -lass %o)

    (n e its 0ni al

    %i -ontext 0s Htt*-ontext = Htt*-ontext.-u ent

    /ublic 9 e i es ub lee*2

    -ontext.6es*onse. ite2"KDDDDD... oo# oo# oo# oo#...

    DDDDDD!?b A"

    n ub

    n -lass

    Finall$) we+ll use the =at and ,og classes in the following code. Note that $ou use the "mports statement to access the mem#ers of the nimals names"ace without ha%ing to full$ (ualif$names ?such as =at instead of nimal.=at . The sam"le code for this cha"ter shows theim"lementation of "mports .

    / i ate ub /a)e

  • 8/13/2019 ASP Net Using Vb Net

    86/566

    7 -at. lee*2

    7 %o). at2

    7 %o). lee*2

    n ub

    This code) when added to a &e# Form) "ro%ides the out"ut shown in the following illustration.

    E%en though $ou called the same two methods on #oth the =at and ,og classes) when $ouo%errode a method of the "arent nimal class) $ou got the #eha%ior that $ou s"ecified for the

    "articular animal. &hen $ou didn+t o%erride) the out"ut shows that $ou got the #eha%ior inheritedfrom the "arent nimal class. You can find the full source code for this e1am"le in the "racticefiles for this cha"ter.

    3nheriting from the .NET Base ,lasses

    The "receding e1am"le might not seem terri#l$ useful) and admittedl$) creating $our own =ats and ,ogs #$ inheriting from nimal won+t hel" $ou much in $our de%elo"ment efforts.Fortunatel$) the same "rinci"les demonstrated in that e1am"le a""l$ to the classes that ma'e u"the .NET Framewor'. You can use man$ of these classes to deri%e $our own s"ecialiGed classes.You+ll see s"ecific e1am"les of this in ,ha"ter .

    3nheriting Across anguages

    Another nift$ feature of the .NET Framewor' and the , 7 is that the$ allow $ou to inherit fromclasses written in other languages. &h$ is this im"ortantU Because it means that de%elo"mentteams can ma'e #etter use of the e1isting s'ill sets of their de%elo"ers) as well as their com"an$+se1isting code #ase. For e1am"le) a com"an$ with e1"erienced Visual Basic de%elo"ers ?ande1isting code in Visual Basic can ha%e those de%elo"ers continue to write in Visual Basic .NET.S'illed a%a de%elo"ers can easil$ ma'e the transition to ,J and use the e1isting class resourcescreated #$ the Visual Basic de%elo"ers through inheritance.

  • 8/13/2019 ASP Net Using Vb Net

    87/566

  • 8/13/2019 ASP Net Using Vb Net

    88/566

    Part IIASP.NET Infrastructure

    ,ha"ter 8Managing State3n this cha"ter) $ou will learn how to=

    Store and retrie%e a""lication state.Store and retrie%e session state.

    ,onfigure session state storage.

    9se client/side coo'ies for state storage.

    Most a""lications of an$ significance will use "ieces of data) or %aria#les) that need to #emaintained across a series of re(uests or shared #etween multi"le users of an a""lication. Thisdata is referred to as state . 3n a rich client a""lication) it+s relati%el$ sim"le to maintain indi%idualuser state sim"l$ #$ allocating s"ace in memor$ on the client machine. 3n &e# a""lications)managing user and a""lication state is more challenging. The "rimar$ reason for this is that the

  • 8/13/2019 ASP Net Using Vb Net

    89/566

    Using A((licati n State

    pplication state refers to an$ data that $ou want to share among multi"le users of $oura""lication. This can include connection string information for data#ases ?although thisinformation is often #etter to limit to the #usiness tier of an a""lication ) shared %aria#les) andcached datasets ?although these might #e #etter stored using the ASP.NET cache engine) whichis discussed in more detail in ,ha"ter 2 . 3n fact) one of the difficulties of managing a""licationstate is choosing from the man$ a%aila#le o"tions for storing such state.

    i'e classic ASP) ASP.NET "ro%ides a collection of 'e$/%alue "airs that de%elo"ers can use tostore %alues and o#;ect instances. This collection can #e accessed as shown in the following codee1am"le=

    0**lication2"7 0**licationVa " = "7 Value"

    7 LocalVa = 0**lication2"7 0**licationVa "

    A""lication state storage in ASP.NET is su""lied #$ the .NET Kttp pplicationState class ?whichresides in the System. eb names"ace ) an instance of which is e1"osed as the pplication

    "ro"ert$ of the Page class. Because e%er$ ASP.NET "age inherits from the Page class) $ou canaccess the pplication "ro"ert$ as if it were an inherent "ro"ert$ of the "age) as shown in the

    "receding code.

    For #ac'ward/com"ati#ilit$ with classic ASP) the ASP.NET pplication o#;ect e1"oses a=ontents "ro"ert$ that can #e used to access indi%idual %alues) using the a""ro"riate 'e$.

    0**lication.-ontents2"7 0**licationVa " = "7 Value"

    7 LocalVa = 0**lication.-ontents2"7 0**licationVa "

    New in ASP.NET is the a#ilit$ to add items to the Kttp pplicationState collection using the dd method e1"osed #$ the pplication o#;ect. You can use the emo%e method to remo%e itemsfrom the pplication collection. ?3n classic ASP) the dd and emo%e methods are e1"osed #$the pplication.=ontents collection.

    0**lication.0 2"7 0**licationVa ", "7 Value"

    0**lication.0 2"7 9t e 0**licationVa ", "7 9t e Value"

    0**lication.6e o e2"7 9t e 0**licationVa "

    You can also clear the contents of the pplication collection #$ using the =lear method e1"osed #$ the pplication o#;ect ?or the emo%e ll method) which is "ro%ided for #ac'ward/com"ati#ilit$ with classic ASP .

    ' it e line belo ill clea t e a**lication state

  • 8/13/2019 ASP Net Using Vb Net

    90/566

    0**lication.-lea 2

    0**lication.6e o e0ll2

    The pplication o#;ect e1"oses se%eral other wa$s to access and modif$ the %alues stored in the

    pplication collection) as shown in Ta#le 8/ .

    Ta#le 834. pplication +b*ect 9ethods and Properties

    Method or roperty

    !se

    llLeys "ro"ert$

    7eturns a collection of all of the 'e$s #$ which pplication collection %alues can #e accessed.

    =ount "ro"ert$ 7eturns the num#er of o#;ects stored in the pplication collection.

    -et method 7eturns an item from the pplication collection #$ 'e$ or #$ inde1.

    Set method 9"dates an item in the pplication collection #$ 'e$ or #$ inde1.

    -etLey method

    7eturns the 'e$ for an item #ased on a su""lied inde1.

    ToString method

    7eturns a string that re"resents an item in the pplication collection. 9seful whena string %alue is re(uired) rather than an o#;ect reference.

    3n addition to storing %alues in the pplication collection) $ou can instantiate and storereferences to .NET com"onents) such as 0ataSets) in a""lication state using the ob*ectrunat5Mser%erM; tag s$nta1 in the @lo#al.asa1 file ?or its associated code/#ehind file . These

    o#;ects then #ecome "art of the pplication o#;ect+sStatic+b*ects collection and can #ereferenced in $our ASP.NET &e# Form "ages #$ referring to the id attri#ute associated with theo#;ect.

    ' ;lobal.asax

    ?ob ect unat="se e " i ="7 -lass(nstance" class="7 -lassNa e"

    sco*e="0**lication"A

    ? ob ectA

    ' eb Fo s *a)e

    6es*onse. ite2"Value = " & 7 -lass(nstance.7 ValueNOTE@lo#al.asa1 ?or its associated code/#ehind file is the onl$ mechanism for creating o#;ectinstances with pplication sco"e.TIP&hen $ou+re using either the pplication or Session collections) it+s a good idea to initialiGe the%aria#les $ou+re using to a default %alue ?such as for a string or for a numeric in the

  • 8/13/2019 ASP Net Using Vb Net

    91/566

  • 8/13/2019 ASP Net Using Vb Net

    92/566

    8. From the View menu) select ,ode) or "ress FK to o"en the code editor.Q. ocate the Page0

  • 8/13/2019 ASP Net Using Vb Net

    93/566

  • 8/13/2019 ASP Net Using Vb Net

    94/566

    3nformation stored in a""lication state can #e easil$ shared among all users of an a""lication.This can ma'e it %er$ tem"ting to use a""lication state to store all manner of data) froma""lication settings such as data#ase connection strings to cached datasets containing fre(uentl$used data. 3n man$ cases) there are more efficient means of storing this data than a""licationstate. Ta#le 8/2 shows some e1am"les of when $ou might or might not want to store information

    in a""lication state) as well as alternati%es for storing such information.

    Ta#le 83*. pplication State ecommendations

    State I"for atio" Issues $lter"ati%e

    0ata#ase connectionstrings or othera""licationconfiguration settings

    T$"icall$) these settings areaccessed infre(uentl$. Storingthis information in a""licationstate is not %er$ efficient.

    9se the &e#.config configuration file tostore this information) and retrie%e withthe ppSettings "ro"ert$ of the=onfiguration Settings ,lass) asdiscussed in A""endi1 B.

    0atasets containingfre(uentl$ read data

    ,aching fre(uentl$ used data atthe a""lication le%el can #eefficient) #ut there+s littleautomatic control o%er when thedata is refreshed.

    9se the ASP.NET cache engine to cachee1"ensi%e or fre(uentl$ read data. TheASP.NET cache engine "ro%ides fine/grained control o%er how and when datais refreshed or "urged from the cache.?See ,ha"ter 2 for more information.

    Shared a""licationflags or counter%aria#les

    Shared %alues that can #eu"dated #$ multi"le users of ana""lication can "resent ma;orscala#ilit$ issues) as discussed in4State and Scala#ilit$5 later in

    this cha"ter.

    ,onsider storing shared a""lication flagsin a data#ase) which will "ro%ide finer/grained control o%er the reading andu"dating of indi%idual %alues.

    7eferences too#;ect instances

    Storing references to o#;ects withthe wrong threading model ?suchas legac$ ,*M com"onentscreated with Visual Basic canha%e a se%ere im"act on thescala#ilit$ of an a""lication.

    3f it+s a#solutel$ necessar$ to store areference to an o#;ect instance) ensurethat the class from which the o#;ect iscreated is thread safe.

    imitations of A""lication State

    A""lication state has se%eral limitations that $ou should consider when deciding how to manage

    $our state information.

    0ura#ilit$

    A""lication state lasts onl$ as long as the &e# a""lication is running. 3f the &e#a""lication or &e# ser%er is shut down or crashes) an$ state information stored at thea""lication le%el will #e destro$ed. An$ information that needs to "ersist #etweena""lication restarts should #e stored in a data#ase or other "ersistent storage.

  • 8/13/2019 ASP Net Using Vb Net

    95/566

    &e# farms

    A""lication state is not shared across multi"le ser%ers in a &e# farm ?nor across multi"le "rocessors in a &e# garden . 3f $ou need to store %alues that must #e a%aila#le to all usersin these scenarios) a""lication state is not an a""ro"riate choice.

    Memor$

    An$ gi%en ser%er has onl$ a limited amount of "h$sical memor$ a%aila#le. *%eruse ofa""lication state can result in information #eing swa""ed to %irtual memor$ ?a location ona hard dri%e used to "ro%ide su""lemental 4memor$5 storage . This can reduce

    "erformance significantl$.

    NOTE&e# farms are grou"s of identicall$ configured ser%ers that share the load of ser%ing userre(uests for a gi%en &e# a""lication. Each ser%er contains the same content and can fulfill an$

    re(uest. 7e(uests are routed to indi%idual ser%ers #$ a hardware/ or software/#ased load/ #alancing algorithm that either determines which ser%er is least loaded or assigns re(uests to agi%en ser%er randoml$.

    &e# gardens are a new conce"t in ASP.NET in which an a""lication can #e set to run ons"ecific "rocessors on a multi"rocessor ser%er.

    Using Sessi n State

    As challenging as it can #e to manage a""lication/state information) the statelessness of

  • 8/13/2019 ASP Net Using Vb Net

    96/566

    3n classic ASP) session state would #e destro$ed #$ a ser%er restart or crash. This made it a "oor choice for such uses as sho""ing carts) whose contents should sur%i%e such e%ents.

    ' 9ie reliance

    ,lassic ASP offered no inherent solution for su""orting session state with #rowsers thatcould not or would not acce"t coo'ies. Although aftermar'et solutions were a%aila#le) the$often in%ol%ed unacce"ta#le "erformance trade/offs.

    ASP.NET sol%es each of these limitations) "ro%iding "er/user state storage that+s scala#le)relia#le) and a%aila#le on #rowsers that don+t su""ort coo'ies ?or for users who choose not