Table of ContentsUnit I
Part I-IntroductionChapter 1 -Introductionto.NETChapter 2 -VB6andVB.NETDifferencesPart I I -The VB.NET Programming LanguageChapter 3 -Object-OrientedProgramming and VB.NETChapter 4 -HelloWorldChapter 5 -DataTypes, Variables and OperatorsChapter 6 -ArraysChapter 7 -ConditionalLogic
Unit IIChapter 8 -ProceduresChapter 9 -DialogBoxesChapter1 0 -FileIOandSystemObjectsChapter1 2 -ErrorHandlingChapter1 3 –NamespacesChapter 1 4 -ClassesandObjectsChapter1 5 -MultithreadingChapter1 6 -COMInteropandMSMQ
Unit IIIPart II I -VisualStudio.NET:TheIDEforVB.NETChapter1 7 -VisualBasic.NETIDEChapter1 8 -Compiling and DebuggingChapter1 9 -CustomizingPart I V -Data AccessChapter2 1 -Introduction to Data Accessin.NET Chapter2 2 -ADO.NETPart V -Windows FormsChapter2 5 -Introduction to System.Windows.FormsChapter2 6 -ControlsChapter2 7 -SpecificControlsChapter2 9 -IrregularForms
Unit IVPart V I - VB.NET and the WebChapter3 1 -Introduction to WebDevelopmentChapter3 2 -Introduction to ASP.NETChapter3 3 -Page FrameworkChapter3 4 -HTML Server ControlsChapter3 5 -WebControlsChapter3 6 -Validation ControlsChapter3 8 -EventsChapter3 9 -Cascading Style SheetsChapter4 0 -State ManagementChapter4 2 -TracingChapter4 3 -Security
Unit VPartVI I -WebServicesChapter4 4 -Introduction to WebServicesChapter4 5 -WebServices InfrastructureChapter4 6 -SOAPChapter4 7 -Building a WebServiceChapter4 8 -Deploying and Publishing WebServicesChapter4 9 -Finding WebServicesChapter5 0 -Consuming Web Services
PartI:Introduction
Chapter 1 :Introduction to .NETChapter 2 :VB6 and VB.NET Differences
Chapter1:Introduction to .NETWhat is.NETThe.NET FrameworkCommon Language RuntimeBase Class LibrariesVB.NET
.NET Defined
.NETisMicrosoft'splatformforbuildingXMLWebServices.
Moreimportant,however,iswhat.NETdoesforyou.Nomatterwhatyourdefinitionof.NETmightbe,orwhatyoureadaboutinmagazinesandontheWeb,theendgoalisto provideaplatformfordevelopinganddeployingWeb-basedservices,orWebServices, inasimple,secure,andconsistentmanner.Thisdoesnotmean,however,thatyouwill onlybewritingwebservicesforallofyournew.NETcoding.Therearegreat technologicalachievementsin.NETthatgofarbeyondtheabilitytocreateandconsumewebservices,andthroughoutthischapterandthroughoutthisbookthiswillbecomeveryclear.
EnterSOAP.TheSimpleObjectAccessProtocol,orSOAP,wasthefirsteffortin enablingacommonandconsistentmechanismformovingdataoverHTTPtoanytype ofcomputer.SOAPisasetofXMLspecificationsthatdescribeshowdatacanbesent andreceivedovertheInternet.ASOAPmessagecontainsinformationaboutitself. Thereare"parts"toaSOAPmessagethatdefinethemessagecontent,theintentofthe message,andhowtosenddatabacktothesenderoftheSOAPrequest.
InordertohaveaconsistentandcommonplatformforbuildingWebServices,there neededtobeaconsistentandcommonwayofcommunicatingovertheInternet.With SOAP,XMLcanbeusedtohandleanyrequest,andbecauseXMLisjustaself- describingtextfile,anytypeofoperatingsystemorbrowsercanconsumeSOAP-based WebServices.
ThesoftwareasaserviceparadigmcanbeaccomplishedbyusingSOAPasthe commonprotocol.AnyWebsitecanofferaservice,andtheserveronthebackendcan accepttherequestforthatservicethroughthestandardport80thatHTTPuses.Itcan thensendtheresultsbackdowntotheclientasXML,andtheclientcanmanipulatethe dataisitseesfit.
The.NETexperience
Figure1-1: The.NETexperience
WithVisualStudio.NET,youhavethetoolsyouneedtoleverageyourexisting knowledgetocreateapplicationsfor.NET.VisualBasichasalwaysbeenknownfor providingthedeveloperwiththemostefficientIDEfordevelopingWindows-based applications.WiththeintroductionofVisualInterDev,Microsofttriedtocreatethesame ease-of-useGUIforcreatingWeb-basedapplications.IfyouhaveeverusedInterDev, youknowthatitfellshortinbeingtheRapidApplicationDevelopment(RAD)toolforthe Internetitwaspromisedtobe.VisualStudio.NETistrulyRADfortheInternet.Withthe bestofallworlds,fromVisualBasictoInterDevtoFrontPagetoanyotherGUItoolyou haveeverused,VisualStudio.NETisacombinationofeverythinggreatMicrosofthas everproducedinadevelopmentenvironment.
Ifyouarelikeme,youdonothavetimetolearnbrandnewstuff.Youhaveenoughtodo atworkasitis,letalonelearnaboutSOAPandhowtomakeitworkwith.NET.With VisualStudio.NET,XMLis"baked"in;itiseverywhere,andyoudonothavetoknow whereorhow.Everythingtothedeveloperistransparent;allyouneedtoworryaboutis coding.TheplumbingthatgoesintomarshallingXMLfromclienttoserverisnotanissue.ImentionedRADfortheInternet,butVS.NETisalsoRADfortheserver.Itisaunifiedenvironmentfordevelopingclient-andserver-basedapplicationsandservices,in justaboutanylanguageyouchoosetouse,fasterandeasierthanever.Andbestofall,itisbasedonstandardsthatareinplacetoday,suchasXML,SOAP,HTTP,andHTML.
The .NET FrameworkThe.NETFrameworkistheplumbingof.NET.Theframeworkprovidestheservices necessarytodevelopanddeployapplicationsforthelooselycoupled,disconnected Internetenvironment.Figure 1 - 2showsthekeycomponentsoftheframework.
Figure1-2: The.NETFramework
ThetwomaincomponentsthatmakeuptheframeworkaretheCommonLanguage Runtime(CLR)andtheBaseClassLibraries(BCL).Everythinginthisbookrelatestothe BCL.Asadeveloper,youarecodingagainstclasslibraries,whichareallderivedfrom theBCL.Inthefuture,youmaybeusingthird-partyclasslibrariesthatarenotpartofthe baseclasses,buttheymuststillbebasedontheCLRspecifications.
Othercoreservicesincludecross-languageinteroperability,security,managed execution,andtheCommonTypeSystem(CTS).Together,theseservicesmakeupthe.NETFramework.
Common Language Runtime
TheCLRisthefoundationoftheframework.ThegoalsoftheCLRareasfollows: Secure and robust execution environment Simplified development process Multilanguage support Simplified management and simplified deployment
AsImentionedearlier,IalwaysthoughtWindowsDNAwastheend-alltoprogramming concepts.InmyworldofWindowsonly,Ineverranintoanyinteroperabilityissues,butin reality,thatwasamajordrawbackoftheCOMtechnology.COMprovidedagreatwayforapplicationstointegrate,buteachapplicationhadtosupplytheunderlyinginfrastructure,andtheobjectshadnodirectinteraction.Thisdoesnotmakeforavery globalconcept.Inorderforanyapplicationtoconsumeanytypeofservice,thereneeded tobeabetterwaytohandlecross-processandcross-platformcommunication.
SecureandrobustexecutionenvironmentTheCLRprovidestheenvironmentthatmanagescodewhenitisexecuted.Codethat runsinsidetheframeworkisknownasmanagedcode,whichrunsundercertainrules providedbytheCLR.ManagedcodesuppliestheMetadata(dataaboutdata)necessary fortheCLRtoprovideservicessuchasmemorymanagement,cross-language integration,codeaccesssecurity,andautomaticlifetimecontrolofobjects.Codebased onMicrosoftIntermediateLanguage(MSIL)executesasmanagedcode.Managedcode isthecoreconceptoftheframework.Withmanagedcode,CPU-specificcompilerscan bebuilttohandletheintermediatelanguage'srequest.Inthistypeofscenario,theCOM modelisoutdated.
TheMSIListheoutputproducedwhen.NETapplicationsarecompiled.Thisisasemi- newconceptforVBdevelopers.Inthepast,youcouldeithercompileto"native"code (whichwasn'treallynativeatall),oryoucouldcompiletoP-Code,whichwasinterpreted bytheVBruntimewhenyourapplicationexecuted.TheMSIListhelanguagethatallof the.NETlanguagescompiledownto.Aftertheyareinthisintermediatelanguage,a processcalledJust-In-Time(JIT)compilationoccurswhenresourcesareusedfromyour applicationatruntime.JITallows"parts"ofyourapplicationtoexecutewhentheyare needed,whichmeansthatifsomethingisneverneeded,itwillnevercompiledowntothePE(portableexecutable)filethatisthenativecode.ByusingJIT,theCLRcancache thecodethatisusedmorethanonceandreuseitforsubsequentcalls,withoutgoing throughthecompilationprocessagain.Figure 1 - 3 describestheJITprocess.
Figure1-3: JITcompilationprocess
TheJITprocessenablesasecureenvironmentbymakingcertainassumptions: Typereferencesarecompatiblewiththetypebeingreferenced. Operationsareinvokedonanobjectonlyiftheyarewithinthe
executionparametersforthatobject. Identitieswithintheapplicationareaccurate.
Byfollowingtheserules,themanagedexecutioncanguaranteethatcodebeing executedistypesafe;theexecutionwillonlytakeplaceinmemorythatitisallowedto access.ThisispossiblebytheverificationprocessthatoccurswhentheMSILis convertedintoCPU-specificcode.Duringthisverification,thecodeisexaminedto ensureitisnotcorrupt,itistypesafe,andthecodedoesnotinterferewithexisting securitypoliciesthatareinplaceonthesystem.
Exceptionhandling
TheframeworksupportsStructuredExceptionHandling(SEH)acrosslanguagesand processes.Whenyoucompileyouapplications,tablesarecreatedbasedonthe methodsintheclassesandtheerrorsthatcanoccuraremappedtohandlersinyour methodcalls.Inanunmanagedenvironment,errorswerepassedthroughHRESULTs andBooleanreturnvalues,andtherewasnocommonwaytohandleanerrorifitdid occur.In.NET,errorhandingisintegratedwiththeframework;itisnotanafterthought.
Garbagecollection
Objectlifetimeismanagedthroughaprocesscalledgarbagecollection(GC).Through GC,releasedobjectreferencesareautomaticallyreclaimedbytheoperatingsystem.In VB6,youhadtoexplicitlysetobjectsequaltonothingtoensurethatmemorywas regained,andinC++,overlookingthereleaseofobjectscausednastymemoryleaks.In.NET,memorymanagementisautomatic,andmemoryisreclaimedwhentheruntimedecidesthattheobjectreferencesarenolongerinuse.
SimplifieddevelopmentSimplifieddevelopmentcouldmeanalotofdifferentthingstoalotofdifferentpeople.In somecases,itcouldmeanthecomputerreadingyourmind,savingyoualotoftyping.In othercases,itcouldmeanwinningthelotteryandretiringtoabeachsomewhereinthe SouthPacific,ormaybeevena20-million-dollar(586,440,010.07Russianrubles)rideto Alpha,thatcoolspacestationcirclingtheearth.In.NET,simplifieddevelopmentmeans morethananyofthat.
Oneofthebiggestchangesintheframeworkistheeliminationoftheregistry.Theregistryistheenemyofalldevelopers.GUIDs,IDLfiles,HRESULTs,andallotherCOM- relatednightmaresgoawayin.NET.
ThegoodnewsisthatyoucanstilluseyourCOMcomponentsin.NET.
JustlikeaddingareferencetoaDLLinVB6,youcanaddareferencetoaCOMDLLin.NET,anditwillcreateawrapperfortheDLLthat.NETcanusetoaccessthemembers intheDLLinamanagedenvironment.Youcanalsocall.NETassembliesfroman unmanagedenvironment,suchasVB6.Bothofthesefeaturesrequirenoadditionalwork onyourpart,soyouhaveaveryflexibleenvironmenttouseyourexistingcodeina.NET application,ortouse.NETassembliesinaVB6environment.
Object-orientedfeatures
AnewconcepttoVBdevelopersisobject-orientedOOprogramming.OOsimplifiesthe reuseandinteroperabilitybetweencomponents.Theclassesintheframeworkareall100%object-oriented.ThenicethingabouttheBCLbeing100%OOisthatyoucan implementOOfeaturesacrosslanguages,suchasinheritanceandpolymorphism.This isakeyfactortosimplifieddevelopmentinlargeshopswheresomeprogrammersmight beusingVB.NET,whereasotherdeveloperscouldbeusingCOBOL.NETorC#.No matterwhatyourlanguagechoice,thesamefeaturesareavailabletoeveryone.
VisualStudio.NETTheVisualStudio.NETIDEisthebestpartofsimplifieddevelopment.Thetools availableinVS.NETallowyoutoquicklyandeasilydeveloplarge-scale,distributed applications.Chapter1 7 delvesintothefeaturesoftheVS.NETIDE,andIamsureyou willbeveryimpressedasyoustarttouseitintherealworldtodevelopapplications.
MultilanguagesupportAsoftoday,thereareroughly18languagesthattheframeworksupports.FromPascalto COBOLtoJScript,youhavecompletefreedomoverthetoolyouusetodevelopyour applications.AstheCLRgainsmoreacceptance,therearesuretobeadditional languagesaddedbyothercompaniesbesidesMicrosoft.
OutoftheVS.NETbox,MicrosoftshipswithcompilersforJScript.NET,VisualBasic.NET,C#,andManagedC++..AlloftheselanguagesarefullysupportedintheVS.NET IDE,andtherearecommand-linecompilersforeachoftheselanguages.Theother15or solanguagesarecomingfromthirdparties,andtheywilleitherhavetheirownIDEor theywillhookintotheVS.NETIDE.
Howisthispossible?The.NETFrameworkdefinesasubsetofrulesthatdefineshowa languagecanbeconsumedbytheCLR.ThesetofrulesiscalledtheCommon LanguageSpecification(CLS).TheCLSallowsanythirdpartytocreatealanguagethat cantargetthe.NETFramework,aslongasthespecificationslaidoutintheCLSare followed.
BecauseoftheCLS,languageinteroperabilityispossible.ComponentswritteninVB.NETcanbeconsumedfromC#orManagedC++,noextracoderequired.Passing stringsfromManagedC++toVB.NETdoesnotrequirestrangeconversionfunctionsthatwillallowVB.NETtousethedata.In.NET,astringisastring,thesameinall languages.ThisispossiblebytheCommonTypeSystememployedbytheframework, definedintheCLS.TheCTSdefineswhattypesareallowedtoruninsidetheframework.Atypecanbedefinedasavaluetypeorareferencetype.Valuetypesarestoredasarepresentation oftheirvalue,suchasdatatypes.Referencetypesarestoredasareferencetoatype, suchasanobject.Referencetypesin.NETarebasedontheSystem.Objecttype, andtheycanbefurtherbrokendownintoclassesthatderivefromtheSystem.Object type.Figure 1 - 4describestheCTSasimplementedinthe.NETFramework.
Figure1-4: CommonTypeSystem
Debugging,tracing,andprofilingareavailableacrosslanguagesandacrossmachines. Sincetheseprocessesarebasedonwhatoccursatruntime,asingledebuggercanbe usedacrossalllanguagesbecauseitisinteractingwiththeMSIL,notthespecificsofa particularlanguage.
Alllanguages,nomatterwhatdeveloper-specificfeaturesthelanguageoffers,stillhave tocompiledowntotheMSIL,andthengetinterpretedbytheCPU-specificexecution engine.Thismeansthatalllanguagesareonalevelplayingfield.Alllanguagessupport thefeaturesofthe.NETFramework,orelsetheywouldnotbeconsidereda.NET language.
Therearelanguage-specificfeaturesbasedonyourlanguagechoice,whichcouldincludebuilt-infunctions,keywords,orlanguagesemantics,butwhenthefileisbuilt,itis builttotheMSIL.Thelanguage-specificcompilerwillensurethatthecodeistypesafe andwillpasstheMSILverificationprocess.Thisisnottosaythatcertainrulescannotbe broken,soyoushouldinvestigatetheCLSandCTStomakesureyouareusingCLS- complianttypes.VB.NETisanexampleofalanguagethathasspecialfeaturesthatotherlanguagesdonot.Becausethereareroughly12millionVBdeveloperswhohave10,000timesthatin linesofcodewritten,Microsofthasincludedanupgradepathforexistingapplications. Thisupgradepathusesacompatibilitylibrarythatcontainsmanyofthesamekeywords andfunctionsyouareusedtousinginVB6.WhenyouarecodinginVB.NET,functions suchasMsgBoxarestillvalid,eventhoughtheBCLhasaMessageBoxclassthatis morerobustandshouldbeused.Essentially,theMsgboxfunctionhasacompatibility wrapperthatactuallycallsthenativeBCLMessageBoxclassmembers.
SimplifieddeploymentandmanagementThemainunitofdeploymentin.NETisanassembly.Althoughassembliescanhavea.dllextension(theycanalsohavethe.exeextension),theyarenottraditionalCOM DLLs.Assembliescontainamanifest,whichisMetadatathatis"emitted"tothecallersof theassembly.TheMetadatacontainsthenameoftheassembly,theversion,theculture,andoptionally thepublickeyfortheassembly.Otherinformationintheassemblyincludeswhattypes areexported,whattypesarereferenced,andthesecuritypermissionsforeachtype. Assembliescomeintwoflavors:privateorshared.
Privateassembliesaredeployedthrougha"zeroimpactinstall"process.Zeroimpact installmeansthatyounolongerhavetocrossyourfingerswhenyoudeployan application,becausetheapplicationinstallationisnotaffectingthestateofthemachine. Becausetheregistryisnotinvolved,yousimplycopythefilesthatyourapplicationneeds toexecutetothedirectoryinwhichitwillrun.ThisprocessiscalledXCopydeployment. That'sright,XCopyfromthe oldDOSdays.Youarejustcopyingfiles,anditalljust works.SharedassembliesarecopiedtotheGlobalAssemblyCache(GAC).TheGACis arepositoryforfilesthatcanbesharedacrossmultipleprocesses.Whenassembliesare installedtotheGAC,theyareboundbyversionandpoliciesdefinedbythepublisherof theassembly.
.NET.Onthesamemachine,inthesameexactprocess,DLLswiththesamenamebut differentversionscanbeexecutingatthesametime.
BaseClassLibraries
The.NETFrameworkprovidesasetofhierarchicalobjects,brokendownby functionality,calledtheBaseClassLibraries(BCL).Theclassesprovideasetof common,object-orientedinterfacesthatcanbeaccessedfromany.NETlanguage.
TheBCLisdividedintonamespaces,whichdefineanamingschemeforclasses,such aswebclasses,Dataclasses,WindowsForms,XMLclasses,Enterpriseservices,and Systemclasses.Byimplementinganamingscheme,itiseasytocategorizewhat functionalitytheclassesareactuallygoingtoprovide.Forexample,theDataclasses providethefollowingtop-levelnamespaces:
System.Data System.Data.Common System.Data.OLEDB System.Data.SQLClient System.Data.SQLTypes
Eachoneofthedatanamespacesisbrokendownfurtherintomoregranularclasses, whichdefinethemethods,fields,structures,enumerations,andinterfacesthatare providedbyeachtype.
TheSystemclassprovidesthebaseservicesthatalllanguageswouldinclude,suchasIO,arrays,collections,security,andglobalization.Becausetheclasssystemisunifiedforalllanguages,itisnotimportantwhatlanguageis attemptingtoaccessthebaseclasses,allofthefeaturesareavailabletoalllanguages, andthewayinwhichthecodeisimplementedisthesame.Thisactuallymakesitvery easytounderstandcodewritteninotherlanguages.Becausetheclasslibrariesinusearethesame,theonlydifferenceinthecodeisthesemanticsofeachspecificlanguage.
Visual Basic .NETLanguage innovations
VB.NETisfinallyafirst-classlanguage.Everyfeaturethatisprovidedbytheframework isavailableinVB.NET.VB.NETisafullyobject-orientedlanguage,providinginheritance,polymorphism,encapsulation,overloading,andoverriding.Withstructured exceptionhandling,thereisacleanandconsistentmethodofhandlingerrorsnotonly withinamethod,butalsoinacallingchainofmultiplemethods,andevenacross componentswritteninotherlanguages.
RADfeatures
TheVS.NETtoolprovidesthemostRADtooleverdevelopedtoassistyouinevery possiblewaywhilewritingcode.Withimproveddesigners,serverexplorers,data designers,andXMLdesigners,youhavealltheexternaltoolsatyourfingertipstowrite client-andserver-basedapplications.Allofthiswithouthavingtolearnanythingnew, becausetheVS.NETIDEwillbefamiliartoyouifyouhaveusedanyofthepreviousVB versions,orevenVisualInterDev.IDEfeaturessuchasautocompleteandauto-list membershavebeenimprovedtomakeiseasierthanevertoverifyyourcodeasyouare developing.
WebForms
WebFormsallowthedevelopmentofscalableWeb-basedapplicationsinafamiliarVB- likeIDE.FeaturessuchascodebehindminimizethespaghetticodeproducedbyVisual InterDev,andwithdown-levelbrowsersupport,nospecialcodeisneededtotarget specificbrowsertypesorversions.TheIDEisthesameforWindows-basedapplications, soallofthefeaturesavailabletodevelopingWindows-basedapplicationsareavailable whenbuildingWeb-basedapplications.
WebServicesByprefixingamethodwiththe<webmethod>identifier,whichisanexampleofattribute- basedprogramming,youhavejustcreatedaWebServicecallablemethod.The underlyingplumbingishandledbytheIDE,anddeploymentisaseasyascopyingafiletotheWebserver.CreatingaWebServiceisaseasyascreatinganyothertypeofapplication.
WindowsForms
WindowsFormsarearewrittenformsenginetargetedspecificallyforthe.NETplatform. ThesameclassesthatareusedinVB.NETaresharedacrossalllanguages,and WindowsFormscanevenrunasasemi-trustedorfullytrustedbrowsercomponent.
Chapter2:VB6andVB.NETDifferencesIn This Chapter
DatatypechangesArraychangesOperatorchangesVariablescopingandinitializationProceduresandpropertieschangesControlofflowFormschangesApplicationtypechanges
Data Type ChangesThe.NETFrameworkhasclassesthatdefinetheCommonTypeSystemthatallowfor datatypestobeconsistentacrossapplicationswrittenindifferent.NETlanguages. Becauseofthis,VisualBasicneededtochangethetypesofdataitsupportsandthe numericrangesofexistingdatatypes.Thefollowingsectioncoversthedifferences.
VariantnotsupportedInVB6,theVariantdatatypewasthedefaultuniversaldatatype;thiswasreplacedby theObjectdatatypeinVB.NET.ThedefaultvalueforObjectdatatypesisNothing, whereasthedefaultvalueforVariantdatatypeswasEmpty.
Dimvar1asVariant
Changesto:
Dimvar1asObject
IntegerandLongInVB6,theIntegerdatatypewasa16-bitnumber,ranginginvaluefrom–32,767to32,767.TheShortdatatypereplacesIntegerasa32-bitnumberinVB.NET,andthe Integerdatatypenowrangesfrom–2,147,483,648to2,147,483,647.TheLongdata typeisnowa64-bitnumber.UsingIntegerfor32-bitoperationsisthemostefficient datatype.
DimXasInteger
DimYasLong
Changesto:DimXasShort
DimYasInteger
CurrencynotsupportedTheCurrencydatatypeischangedtodecimalinVB.NET.Decimalismoreaccurate forroundingnumbers,sotheDecimaldatatypewascreatedtohandlecurrency operations.Currencywasa64-bitnumber,with4digitstotherightofthedecimal place.ThenewDecimaldatatypeisa96-bitsignedintegerandcanhaveupto28 digitstotherightofthedecimalplace.
DimXasCurrency
Changesto:
DimXasDecimal
DatechangesTheDatedatatypeisnowa64-bitinteger,whereasinVB6itwas64-bitdouble.To accommodatethecodeusedintheDatedatatype,youhavetheToOADateand
FromOADatefunctionstoconvertbetweenDoubleandDatedatatypes.
DimXasDouble
Changesto:
DimXasDouble,YasDate
Y=X.ToOADate
Strings
Fixed-lengthstringsarenolongersupported.SDKdocumentationstatesthatthis functionalitywillbeaddedinfutureversions.Thereisacompatibilitylayerthatallowsfor fixed-lengthstrings,buttheyarenotdirectlysupportedbytheCLR.
DefTypenotsupportedTheDefTypestatement,whichgivesadefaulttypeforallvariablesdeclaredwithouta type,isnolongersupported.DefInt,DefStr,DefBool,andDefLngarenolonger supported.
VarPtr,StrPtr,ObjPtrThesefunctions,whichreturntheintegeraddressesof variablesin APIcalls,areno longersupported.TheAddrOfPinnedHandlemethodoftheGCHandleclasscan providesimilarfunctionality.
ArraysOneofthebiggestissueswhenMicrosoftannouncedthelanguagechangesinVB.NET wasthelower-dimensionarrays.Fromthebeginning,VisualBasichasalwaysallowed thelowerboundofanarraytobeeither0or1.TheOptionBasestatement,whichis nolongersupported,dictatedwhetherallarraysshouldbetreatedas0-basedor1- based.Intheend,Microsoftdecidedthatallarrayswillhaveadefaultlowerboundof0, meaningthatexistingcodeusingtheOptionBase1statementwillneedtobe revisitedtoensurethatthereisnodatalossorcorruption,becausethesizeofthearray willbedifferent.
Arrayscannotbefixed
Arrayscannotbedeclaredasfixedsizesbyspecifyingthelowerandupperboundsat designtime.Younowdeclarejusttheupperboundtothearray,withzerobeingthe defaultlowerbound.
Dimx(0to5)asstring'6itemarray
Changesto:
Dimx(5)asstring'6itemarray
Or
DimXasString=newString(5)'6itemarray
OptionBasenotsupportedTheOptionBasestatementtospecifythelowerboundsforallarraysinamoduleor formisnolongersupported.Thedefaultlowerboundforallarraysiszero.
ReDimchangedTheReDimstatementcannotbeusedinthedeclarationofanarrayvariable.InVB.NET, youdeclareanarrayusingDim,andthenusetheReDimstatementtoaltertheboundsofthearray.
The Value of TrueInVB6,thevalueoftrueis–1.ThisisthesameinVB.NET,however,intheCommon LanguageRuntime;thevalueoftrueisequalto1.WhenpassingBooleanvariables betweenlanguagesinthe.NETFramework,–1willbetrueinVB,and1inallother languages.
OperatorsSomeofthemostexcitinglanguagechangesinVB.NEThavecomeinthecategoryof operators.Table2 - 1liststhenewassignmentoperators,whichwillmeanlesstypingfor youwhenyouareusingoperators.
Table2-1:NewAssignmentOperators
Operator Action
+= Additionand concatenation
-= Subtraction
*= Multiplication
/=and\= Division
=̂ Exponentiation
&= String concatenation
EQVTheEQVoperatorisreplacedwiththe"="assignmentoperator.
Short-circuitingTheAndAlsoandOrElseoperatorshavebeenaddedtohandleshort-circuiting.All otheroperatorswillremainthesame.Inshortcircuiting,ifthefirstpartofanexpression returnsfalse,thentheremainderoftheexpressionisignored,andfalseisreturned.
DimXasInteger=5
DimYasInteger=6
DimZasInteger=7ret=X>YAndAlsoZ>Y'ReturnFalse,5isnotgreaterthan6
Assignment
VB.NETofferssomecoolnewassignmentoperators. DimintXasInteger
intX=intX+1
Cannowbechangedto: DimintXasInteger
intX+=1
User Defined TypesUserdefinedtypesarenolongersupportedinVB.NET.Theyarereplacedwith structures,whichhavesimilarsyntaxbutmuchgreaterpowerandflexibility.
PublicTypeMyCust strNameasString
strEMailasstring
EndType
Changesto:
PublicStructMyCust
PrivatestrNameasString
PrivatestrEMailasString
EndStruct
Null ValuesNullpropagationisnotsupported.Valuetypesthatarenullarepassedtofunctionsas theDBNulldatatypes.Totestfornullvalues,theIsNullstatementisnolonger
supported.ItisreplacedwiththeDBNullstatement.
IfIsNull(field)then..
Changesto:
IfIsDBNull(field)then…TheIsEmptystatementisnotsupported.InVB6,thevaluesNULLandEmptycouldbe usedtocheckforavariablethathasnotbeeninitializedorforavariablethatcontainsno data.NULLandEmptyarenolongeravalidmeanstocheckforthisinformation,making IsEmptyobsolete.Thenothingkeywordshouldnowbeusedtocheckforthese conditions.
Variable ScopingVariablescanbedeclaredwithinstatementblocksandareonlyavailablewithinthat block.Inthisexample,thevariableintXisonlyavailablewithintheIf…EndIf statement,whereasthevariableintYisavailabletothewholeprocedure.
PrivateSubTest()
DimintYasIntegerIfintY>5then
DimintXasInteger
'DoSomething
Endif
IntX=5
'Causesanerror,intXcannotbeusedoutsideoftheIfblock. intY=10
'OK. intYisnotdecalredwithintheIfblock. EndSub
Variable InitializationVariablescannowbeinitializedto avalueonthesamelineinwhichtheyaredeclared. DimintXasinteger
intX=5
Canbechangedto: DimintXasInteger=5InstantiatingobjectscanalsobedonewiththeNewkeywordonthesamelineasthe objectdeclaration.ThisbehavesexactlyoppositeofVB6,whereitwasfrownedupon becauseofthewayinwhichCOMhadtoensurethatanobjectwascreatedbeforeit coulduseitspropertiesandmethods.
DimcnAsConnection
SetCn=NewConnection
Canbechangedto:
DimcnasSQLConnection=NewSQLConnection'moreefficient
Youcannowdeclaremultiplevariablesonthesameline,withasingletype.Consider thefollowingcode:
Dimstr1,str2,str3asStringInVB6,thevariablesstr1andstr2wouldbeVariantdatatypes,andstr3wouldbe aStringdatatype.InVB.NET,allofthevariableswillbeoftheStringdatatype.
ParmArray VariablesParmArrayvariablesarenotpassedByRefanymore.ParmArraysarepassedby value,andthereceivingfunctioncanmodifythevaluesoftheParmArrayasitwoulda regulararray.
IsMissingTheIsMissingfunctionisnolongersupportedandshouldbereplacedwiththeIsNothingstatement.
Date$andTime$TheDate$andTime$functionsinVB6toreturnastringrepresentationofthecurrent dateortimearereplacedbytheDateStringandTimeStringmethodsinVB.NET.
Atn,Sgn,andSqrTheAtn,Sgn,andSqrfunctionsarereplacedbytheSystem.MathmethodsAtan,Sign,andSqrt.
MsgBoxTheMsgBoxfunctionisreplacedwiththeShowmethod,theMessageBoxclass. MsgBox"VB6isGreat"
Changesto:
MessageBox.Show"VB.NETisGreater"AlthoughMsgBoxisstillsupportedthroughthecompatibilitylibrary,youshouldconsider usingthenewMessageBoxclassessincetheMsgBoxfunctionissimplyawrapper whichcallstheMessageBoxclasses.
ProceduresBecauseVB.NETfullysupportsobject-orientedfeatures,therehavebeencritical changesinprocedurescope,returningvalues,andthetypesofproceduresyoucanuse.
Callingprocedures
Callingprocedures,eithersubsorfunctions,nowrequireparenthesesfortheargument list,eveniftherearenoarguments.
SubTest()
'code EndSub CallTest
Changesto: CallTest()
StaticproceduresStaticproceduresarenolongersupported.Ifyouusestaticprocedures,youshould changethemtoregularsubproceduresanddefinethevariableswithinthestatic procedureasStatic.
StaticSubTest() DimXasinteger
EndSub
Changesto: SubTest()
StaticXasInteger
EndSub
ByVal,ByRef,andAsAnyThedefaultbehaviorofByValandByRefhaschanged.InVB6,thedefaultforpassing parameterswasByRef.InVB.NET,ByValisthedefaultmechanismforpassingvariablestoprocedures.TheAsAnystatementintheDeclarestatementforAPIcalls isnotsupported.
PropertiesThesyntaxfordeclaringpropertyprocedureshasbeenchangedtoaccommodatethe object-orientedfeaturesinVB.NET.Chapter1 4 hasreal-worldexamplesofusing propertiesanddefinesthespecificsyntaxthatyouwillneedtoimplement.
Let,Get,andSetTheLetkeywordisnolongersupported.WhenusingSetandGet,thescopeofthe propertymustbethesameinVB.NET.InVB6,theGetcouldhavebeenscopedas Private,whereastheSetcouldhavebeenscopedasPublic.Thisiseasilynoticed inthewaythatthepropertymustbedeclared.
FriendPropertystrName()AsString
Get
EndGet
Set(ByValValueAsString) EndSet
EndProperty
Defaultproperties
Defaultpropertiesforanyobjectarenolongersupported.InVB6,customclassescould havedefaultproperties,andvisualobjects,suchastextboxes,listboxes,andcombo boxescouldhavedefaultproperties.
strName=Text1'Text1isthenameofatextboxonaform
Me.Caption="HelloWorld"
Changesto:
strName=Text1.Text'mustusetheTextproperty
Me.Text="HelloWorld"Note Defaultpropertiescanstillbecreated.RefertoChapter1 4 for
informationonhowthiscanbeaccomplished.
Control FlowThechangesincontrolflowarenotthatdrastic.ThebiggestchangeistheGoSub keyword,butbecausemostdevelopershavenotusedthissinceVB2.0,itwillnotreally bemissedthatmuch.TheRetur n statementisthenewwaytoreturnvaluesfrom functionprocedures.
While…WendTheWhile…Wendconstructisnolongersupported.ItisreplacedwithWhile…EndWhile. WhileX<5
'CodeWend
Changesto: WhileX<5
'Code
EndWhile
GoSub…ReturnTheGoSubbranchingtoanothersubroutinewithinaprocedureisnolongersupported. Thefollowingcodewillnolongerbevalid.
SubTest
Return EndSub SubTest2
GoSubTest
EndSub
ReturnTheReturnstatementnowreturnscontrolbacktothecallerofthefunction.Ifthe functionisofacertaintype,itcanreturnthevaluebacktothecalleralso.
PrivateFunctionGetNames()asString
DimstrNameasstring strName="SevenOfNine"
GetNames=strName
EndFunction
Changesto:
PrivateFunctionGetNames()asString
DimstrNameasstring strName="SevenOfNine"
ReturnstrName
EndFunction
Forms-based Application ChangesWindowsFormsapplicationshaveacompletelydifferentsubsysteminwhichformsare drawnonthepage,makingitnecessarytoremovesomeofthefunctionalityyoumight beusedtoforpaintinginformationonaform.OneifthebestnewfeaturesinVB.NETis theIDEforaddingmenustoforms,andtheprintingcontrolsthatallowfullprintpreviewinWindowsFormsapplications.
PrintFormThePrintFormmethodisnolongersupported.The.NETFrameworkhasanew printingsubsystem,withfeaturessuchasPrintPreview,whichallowamorerobust handlingofscreenshotsandformsprinting.Circle,Cls,PSet,Line,andPoint
ThesemethodsarenolongersupportedinVB.NET.ThegraphicsmethodsofVB6are replacedwiththeSystem.Drawingnamespace,whichusesthenewGDI+classesfor drawing.
CaptionpropertyTheCaptionpropertyoflabelcontrolsandformsisnolongersupported.TheTextpropertyreplacestheCaptionproperty. Label1.Caption="VB.NET"
Form1.Caption="MyForm"
Changesto:
Label1.Text="VB.NET" Form1.Text="MyForm"
Twipsonforms
Thetwipsmeasurementinformsisreplacedbypixels.
Fonts
FontsinVB6formscouldbeanyfontsupportedbyWindows.WindowsFormssupport onlyTrueTypeorOpenTypefonts.
ControlarraysMultiplecontrolswiththesamename,butadifferentIndexpropertycouldsharethe sameeventproceduresinVB6.InVB.NET,controlscannotbegroupedinarrays,but thesameprocedurecanbeusedformultiplecontrolswiththeHandleskeyword.
Contextmenusandmainmenus
InVB6,amenuaddedtoaformcouldbeusedforboththemainmenuonthetopofa formandacontextmenuthatappearedwiththeright-clickaction.InVB.NET,youcan haveamenubeamainmenuoracontextmenu,butnotboth.
DDE
DDEisnolongersupported.Othermeansofcommunicationbetweenapplicationscanbe accomplishedusingOLE,WebServices,orin-processcomponents.
ClipboardobjectTheClipboardclassreplacestheClipboardobject.
Controlschanges
WhenyoucreateanewWindowsFormsapplication,youwillnoticesomenewand excitingcontrolsintheToolbox.Thecontrolslistedinthissectionarenolonger supported,andtheywillnotappearintheToolbox.
OLEcontrolTheOLEContainercontrolthatallowedtheaddingofOLEobjectstoformsisnolonger supported.
ImagecontrolTheImagecontrolisreplacedwiththePictureBoxcontrolinVB.NET.
LinecontrolTheLinecontrolhasbeenreplacedbyGDI+Drawmethods.
ShapecontrolTheShapecontrolhasbeenreplacedbyGDI+Drawmethods.
Application TypesManyofthetemplatesthatyoumighthavebeenusedtoinpreviousVBversionsno longerexist,andsomeapplicationtypesdonotevenhaveanupgradepath.
Webclasses
Webclassapplicationsarenolongersupported.WebFormsapplicationsshouldbeused towriteWeb-basedapplications.ThepowerandfunctionalityprovidedinusingWeb ServicesandASP.NETapplicationswillgiveyoumuchmoreflexibilitythanprogramming Webclassesapplicationseverdid
ActiveXdocuments
ActiveXdocumentapplicationsarenolongersupported.Youcan,however,write WindowsFormsapplicationsthatrunthroughthebrowserassafecodeandmimic ActiveXdocuments,yetyouwillhavethefullWindowsFormsobjectmodelandcontrols support.
DHTMLapplications
DHTMLapplicationsarenolongersupported.WebFormsapplicationsshouldbeusedto writeWeb-basedapplications.
Usercontrols
UsercontrolscreatedinVB6areusableinVB.NET,butthereisnodesigntimesupport foreditingormodifyingthecontrols.
Propertypages
Propertypagesarenolongersupportedandthereisnoupgradepath.Thisisnotavery bigdeal,sincepropertypageswereusedinActiveXcontrolapplications,andin.NET, youwillbecreatingusercontrolsinsteadofActiveXcontrols.
Data AccessADO.NETisthenewlibraryforaccessingdatafromanysource.Morethanjustan upgrade,itisanactualrewritefromthepreviousversionofADOthatyoumighthave used.Abigissueforupgradingapplicationsistheeliminationofdatabinding.When performinganupgradeusingtheUpgradeWizard,youwillbenotifiedofcodethat cannotbemigratedifyouareusingdatabindingofanysort.
DataBinding,RDO,andADO
DataBindingtoanRDOorADOdatasourceisnolongersupported.Thefollowingcode isobsolete.
Text1.DataField="Customer_Name"
SetText1.Datasource=rs
ThereareextremelypowerfulandmoreadvanceddatabindingcapabilitiesinVB.NET, andtheyarejustimplementeddifferently.
DAO
DataAccessObjectsisnotsupportedinVB.NET.BecauseyoucanaccessdatathroughADO.NET,thelossofDAOisnotearthshattering.Itwilljustmeanthatyouneed toconvertDAOcodetoADO.NETcode.
DebuggingVisualBasichasalwaysbeenattheforefrontinsupportfordebugging.The Debug.Printmethodhasbeenreplaced,butthisisminorcomparedtoallofthenew featuresthatmakedebuggingeasierthanever.
Debug.PrintDebug.PrintisreplacedbytheDebug.WriteortheDebug.Writelinemethods. TheDebugclassprovidesacompletesetofmethodsandpropertiesthathelpdebug yourcode.
Debug.PrintErr.number
Changesto:
Debug.WritelineErr.Number'includesLineFeed
Or
Debug.WriteErr.Number'doesNOTincludeLineFeed
Debug.AssertTheDebug.Assertmethodisnolongersupported.ItisreplacedwiththeAssertandFailmethodsoftheDebugclass.
PartII:TheVB.NETProgrammingLanguageChapter 3 :Object-OrientedProgrammingandVB.NET Chapter 4 :HelloWorldChapter 5 :DataTypes,Variables,andOperatorsChapter 6 :ArraysChapter 7 :ConditionalLogic
Chapter3:Object-OrientedProgrammingandVB.NETIn This Chapter
EncapsulationInheritancePolymorphism
EncapsulationEncapsulationExamplePublicClassContact
Private_FirstNameAsStringPrivate_LastNameAsStringPrivate_EmailAsString
PublicPropertyFirstName() Get
Return_FirstName
EndGetSet(ByValValue)
_FirstName=ValueEndSet
EndProperty
PublicPropertyEmail() GetReturn_Email
EndGetSet(ByValValue)
_Email=ValueEndSet
EndProperty
PublicPropertyLastName() Get
Return_LastNameEndGet
Set(ByValValue)_LastName=Value
EndSetEndProperty
PublicReadOnlyPropertyNameHi() Get
Return_FirstName.ToUpper&""&_LastName.ToUpper
EndGet
EndProperty
PublicReadOnlyPropertyNameLo() Get
Return_FirstName.ToLower&""&_LastName.ToLower
EndGet
EndProperty
PublicReadOnlyPropertyNameProper() Get
ReturnStrConv(_FirstName,VbStrConv.ProperCase)&""_
&StrConv(_LastName,VbStrConv.ProperCase) EndGet EndProperty
EndClass
InheritanceInheritanceistheabilitytocreatenewclassesbasedonanexistingclass.Thenewclass inheritsalltheproperties,methods,andeventsofthebaseclass,andcanbecustomized withadditionalpropertiesandmethods..Aderived classisaclassbasedonabaseclass.TheInheritskeywordusedinsideaclass derives,orinherits,thefunctionalityofthatclass.In.NET,allclassesareinheritablebydefaultunlesstheyaredefinedwiththeNotInheritablekeyword.IntheContactclassyoucreatedearlier,theclasswas definedas
PublicClassContact
Tomaketheclassnotinheritable,youwoulddefineitasfollows:
PublicNotInheritableClassContactBydefiningtheContactclassasNotInheritable,itdoesnotaffecttheclient-side declaration.Itdoes,however,affecthowtheclasscanbeusedinotherclasses.An instanceofContactcanbecreatedwiththeNewkeyword,butaclasscannotusethe InheritskeywordtoimplementtheContactclassfunctionality.
TheexactoppositeoftheNotInheritablekeywordistheMustInheritkeyword.IfyoudefineaclasswiththeMustInheritkeyword,itcannotbecreatedwiththeNew keyword.Thebaseclasscanonlybeinheritedfromotherclasses.IftheContactclass wasdefinedasMustInherit,asthefollowingcodedemonstrates:
PublicMustInheritClassContact
Thenthefollowingcodefromtheclientapplicationwouldbeinvalid:
DimcasNewCustomerThismeansthatinordertogettoanyofthemembersintheContactclass,youneedto createanotherclass,andusingtheInheritskeyword,inherittheContactclass.
PolymorphismPolymorphismisthecapabilitytohavemethodsandpropertiesinmultipleclassesthat havethesamenameandcanbeusedinterchangeably,eventhougheachclass implementsthesamepropertiesormethodsindifferentways.
Thefollowinglistgetsyouuptospeedonsomeofthesyntaxyoucanusewhen implementingpolymorphism:Overridable:Allowsapropertyormethodinaclasstobeoverriddenina derivedclass.Overrides:OverridesanOverridablepropertyormethoddefinedinthe baseclass.NotOverridable:Preventsapropertyormethodfrombeingoverriddenin
aninheritingclass.PublicmethodsareNotOverridablebydefault.MustOverride:Requiresthataderivedclassoverridethepropertyor
method.WhentheMustOverridekeywordisused,themethoddefinition consistsofjusttheSub,Function,orPropertystatement.Noother statementsareallowed,andspecificallythereisnoEndSuborEnd Functionstatement.MustOverridemethodsmustbedeclaredin MustInheritclasses.
Chapter4:HelloWorldIn This Chapter
AHelloWorldapplicationusingWindowsFormsAHelloWorldapplicationusingWebForms
Withthe.NETFramework,youcancreatethreetypesofapplications—Windows applications,Webapplications,andConsoleapplications.WindowsFormsprovideuserswithabasicsetofclassestocreateagraphicaluser interfaceforWin32desktopapplications.Theyusethesamedrag-and-droptechniqueto createarichuserinterface.Ontheotherhand,WebFormsprovideabrowser-based userinterface.WebFormsalsoallowyoutocreateauserinterfacebyusingthedrag- and-dropmethod.Inadditiontothegraphicaluserinterface(GUI)applications,the.NETFrameworkalso allowsdeveloperstocreatecharacteruserinterface(CUI)applications.CreatingCUI applicationsispossiblethroughConsoleapplications.
Creating a Windows Forms ApplicationWindowsForms,whicharebasedonthe.NETFramework,allowyoutodevelop Windowsapplications.YoucandevelopVisualBasic.NETWindowsapplicationsby usingtheWindowsFormsDesignerprovidedwithVisualStudio.NET.VisualStudio.NETprovidesacommonIntegratedDevelopmentEnvironment(IDE)fordevelopingapplicationsinall.NETprogramminglanguages.
CreatingaWindowsApplicationproject
ThefirststeptocreateaWindowsFormsapplicationistocreateaVisualBasicWindowsApplicationproject.Todoso,followthesesteps.
1. SelectFile New ProjecttoopentheNewProjectdialogbox.Tip Alternatively,youcanusehotkeystoaccessdifferentoptions.Inthe
precedingstep,pressAlt+FtoopentheFilemenu.Then,pressNto opentheNewsubmenu.Finally,toopentheNewProjectdialogbox, pressP.
YoucanalsoopentheNewProjectdialogboxbypressingCtrl+Shift+N.
2. FromtheProjectTypespane,selectVisualBasic.3. FromtheTemplatespane,selectWindowsApplicationtocreatea
VisualBasicWindowsApplicationproject.4. IntheNamebox,enterthenameoftheproject.IntheLocationbox,
specifythedirectorywhereyouwanttostoretheproject.Todoso, youcanusetheBrowsebutton.Inthiscase,specifythenameofthe projectasWinHelloWorldandthelocationasC:\VBProjects.Atthis stage,theNewProjectdialogboxappears,asshowninFigure4 - 1 .
Figure4-1: TheNewProjectdialogbox.AftertheVisualBasicWindowsApplicationprojectiscreated,VisualStudio.NETdisplaystheinterface,asshowninFigure 4 - 2 .
Figure4-2: AsampleWindowsApplicationproject.Asyoucanseeinthefigure,theSolutionExplorerwindowisdisplayedtotheextreme rightoftheVisualStudio.NETwindow.TheSolutionExplorerwindowcanconsistof multipleprojects,whichcouldbecreatedinmultiplelanguages.WhenaWindows Applicationprojectiscreated,theForm1.vbfileisselectedbydefault,andtheformis displayedinDesignmode.
UsingWindowscontrolsVisualStudio.NETprovidesaToolboxthatyoucanusetodesigntheuserinterfacefor yourapplications.YoucandisplaytheToolboxbyselectingToolboxfromtheView menu.Bydefault,theToolboxisplacedtotheextremeleftofthewindow.TheToolbox opensonlywhenyoumoveyourmouseoverit.Thisfeatureiscalledautohide.
TheToolboxcontainsdifferentcontrols,categorizedaccordingtotheirfunctionality.For example,thestandardWindowscontrols—suchasLabel,Button,andTextBox—are categorizedunderWindowscontrols.
Figure 4 - 3displaysthePropertieswindowwhenaLabelcontrolisselected.Asyoucanseeinthefigure,theDefaultpropertyoftheLabelcontrolishighlighted.
Figure4-3: ALabelcontrolisselectedinthePropertieswindow.
InthePropertieswindow,youcanviewthepropertiesofaselectedobjectina categorizedoranalphabeticalmanner.TocreateasimpleHelloWorldWindowsapplication,createaformthatcontainsaLabel andaButton.Specifytheproperties,asdescribedin Table4 - 1 .Table4-1:PropertiesofControlsintheSampleWindowsForm
Control Property Value
Label Text
Name
ForeColor
Font.Bold
TextAlign
Welcometo Windows Forms
MessageLabel
BlueTrue
TopCenter
Button Text
Name
Forecolor
Font.Bold
SayHello
HelloButton
Blue
TrueFigure 4 - 4 showsthesampleform.
Figure4-4: AsampleformfortheHelloWorldWindowsapplication.
UsingtheCodewindowAfteryoudesignaform,thenextstepiswritingthecodetoprovidethedesired functionalityforthecontrols.YouwritethecodeintheCodewindow,whichyoucan openbyselectingCodefromtheViewmenuorbypressingF7.YoucanalsoopentheCodewindowbydouble-clickingthebuttoncontrolorright-clickingtheformandselectingViewCode.TheCodewindowalreadycontainssomeVisualBasiccode,asshowninFigure 4 - 5 .
Figure4-5: TheCodewindowdisplayingtheVisualBasiccode.ThetopoftheCodewindowcontainstwodrop-downlists:ClassNameandMethod Name.TheClassNamelistcontainsthenamesofalltheclassesinthecurrentproject. Currently,theClassNamelistdisplaysForm1[WinHelloWorld].TheMethodNamelist containsthenamesofthemethodsoftheclassthatisselectedintheClassNamelist. Currently,theMethodNamelistdisplays[Declarations].
ThefirstlineoftheCodewindowdisplaysthefollowingcode: PublicClassForm1
InheritsSystem.Windows.Forms.FormTheprecedingcodeindicatesthatForm1isaclassthatisinheritedfromtheFormclass. TheFormclassisincludedintheSystemnamespaceofthe.NETFramework. System.Windows.Forms.FormindicatestheclasshierarchyintheSystemname- space.Namespacesareawaytogrouptherelatedclassestogether.Theyprovideproperorganizationofclasses,sothattheyareconvenienttouse.
Creating a Web Forms ApplicationWebFormsisafeatureofASP.NETthatcreatesrichWebapplications.ASP.NETisa programmingframeworkusedtodevelopWebapplications,andisapartofthe.NET Framework.WebFormsprovideRapidApplicationDevelopmenttechniquesthatenable youtocreatearichuserinterfaceforWebapplications.WebFormsconsistofapagethatisusedtodesigntheuserinterfaceandacodefile thatprovidesfunctionalitytotheuserinterface.Thepageconsistsofafilecontaininga markuplanguage,suchasHTMLorXML,andcontrols.Apagefilehas.aspxasits extension.
ThefunctionalitytorespondtouserinteractionswiththeWebFormspagesisimplementedbyusingprogramminglanguages,suchasVisualBasicandVisualC#.Youcanimplementthefunctionalityinthe.aspxfileorinaseparatefilewritteninVisualBasic.NETorC#.Thisseparatefile,calledtheCodeBehindclassfile,has.aspx.csor.aspx.vbasitsextension.Thus,aWebFormspageconsistsofapage(an.aspxfile)andacodebehindclassfile(an.aspx.vbfileoran.aspx.csfile).CreatingaWebApplicationproject
Note ThefirststeptocreateaVisualBasicWebFormsapplicationisto createaWebApplicationproject.Todoso,followthesesteps:
1. SelectFile New ProjecttoopentheNewProjectdialogbox.2. FromtheProjectTypespane,selectVisualBasic.3. FromtheTemplatespane,selectASP.NETWebApplicationtocreate
aVisualBasicWebApplicationproject.4. IntheNamebox,enterthenameoftheproject.IntheLocationbox,
specifythenameofaWebserverinwhichyouwanttostorethe project.Inthiscase,specifythenameoftheprojectas WebHelloWorldandthelocationashttp://<computername>/. Here,<computername>intheLocationboxrepresentsthenameof thecomputerthathoststheIISServer.
Note YoumusthaveanIISServerinstalledonthedevelopmentcomputer.Otherwise,youcannotcreateWebapplications.
AftertheVisualBasicWebApplicationprojectiscreated,VisualStudio.NETdisplays thenumberoffilesintheSolutionExplorerwindow.TheWebForm1.aspxisselected bydefaultandisdisplayedinthedesigner.
UsingtheWebFormsServercontrols
AfteryoucreateaWebApplicationproject,youcandesigntheuserinterfaceoftheWeb FormspagebyusingtheWebFormsdesignerprovidedbyVisualStudio.NET.The designerprovidesaToolboxthatcontainsvariousWebFormsServercontrolsthatcan beaddedonthepagetodesignarichuserinterface.TheseServercontrolsdifferfrom theusualWindowscontrols.UnliketheWindowscontrols,theWebFormsServercontrolsworkwithintheASP.NETFrameworkandareavailabletobeprogrammedatthe serverend.ThewaycontrolsareaddedtotheWebFormspagesissimilartothewayyouaddthem totheWindowsForms.Youcanaccessorassignthepropertiesofacontrolinthe PropertieswindowthesamewayasyoudowithWindowsForms.TocreateasimpleHelloWorldWebapplication,addaLabelandButtontothepage.Thensettheproperties,asshownin Table4 - 2 .Table4-2:PropertiesofControlsintheSampleWebForm
Control Property Value
Label TextID
ForeColor
Font.Bold
WelcometoWebForms
MessageLabel
Blue
True
Button TextID
Forecolor
Font.Bold
SayHello
HelloButton
Blue
True
TheformshouldappearasshowninFigure4 - 6 .
Figure4-6: AsampleWebFormspage.
UsingtheCodewindow
Afterthevisualcomponentisdesigned,youcanusetheCodeBehindfiletoimplement thedesiredfunctionalitywiththeuserinterface.YoucanviewtheCodeBehindfileby selectingCodefromtheViewmenuorbypressingF7.
Chapter5:DataTypes,Variables,andOperatorsIn This Chapter
DatatypesVariablesTypeconversionStructuresNumericparsingSystem.StringclassOperators
Data Types and VariablesAvariableisapointertoablockofmemorythatstoresinformation.Theinformationthat isstoredinavariableisofacertaindatatype.Inallprogramminglanguages,youdefine areal-worldobjectthatreferstosometypeofinformationthatyouneedtoworkwith. The.NETFrameworkusestheconceptofCommonLanguageSpecification(CLS)compliantdatatypes.Thismeansthatany.NETcompileryouareusingmustatleast allowforcertaindatatypes.Ifitdoesnot,thecompilerisnotCLScompliantand,inturn, thelanguagecannotbeconsideredaCLR-compliantlanguage.
VB.NETdatatypesInVB.NET,alldatatypesallowedareCLS-compliant.The.NETFramework,alldata typesarederivedfromtheSystemnamespace.Eachtypeisdefinedasastructure withintheSystemnamespace.Becauseallobjectsin.NETarederivedfromthebasetypeSystem.Object,thedatatypesyouareusingareactuallyclassesandstructures derivedfromtheSystem.Objecttype.Allclasseshavemembers,properties,and fields;thedatatypesdefinedintheSystemnamespacearenodifferent.Table5 - 1 lists thedatatypes,theCLStypeandtheallowablerangesforeachtypedefinedinthe Systemnamespace.
AnimportantthingtonoticeforVBdevelopersisthedifferencesbetween.NETdata typesandpre-.NETdatatypes.InVB6,theShortdatatypedidnotexist,andthe Integerdatatypehadarangeof–32,768to+32767.In.NET,theShortdatatypereplacestheIntegerdatatype,andtheIntegerdatatypereplacestheLongdata type.ThenewLongdatatypeisa64-bit,8-bytenumber,averylargenumber.Table 5 - 2summarizesthedatatypechangesinVB.NETfrompreviousVBversions.
Table5-1:VB.NETDataTypes
Type CLSType Bytes Value
Boolean System.Boolean 4 TrueorFalse
Byte System.Byte 1 0to255unsigned
Char System.Char 2 0to65,535unsigned
Date System.DateTime 8 January1,1toDecember31,9999
Decimal System.Decimal 12 +/–79,228,162,514,264,337,593,950,335withnodecimalpoint.
+/–7.9228162512264337593543950335with28placestotherightof thedecimalpoint.
Thesmallestnonzeronumber wouldbea1inthe28thposition totherightofthedecimalpoint.
Double System.Double 8 1.797693134862231E308to–4.94065645841247fornegative valuesto4.94065645841247to1.797693134862231E308for positivevalues
Integer System.Int32 4 –2,147,483,648to2,147,483,648
Long System.Int64 8 9,223,372,036,854,775,808to9,223,372,036,854,775,807
Short System.Int16 2 –32,768to32,767
Object System.Object 4 Anobjectcanholdanyvariable type
Single System.Single 4 3.402823E38to–1.401298E-45 fornegativevaluesto1.401298E-45to3.402823E38forpositive values
String System.String 10+ (2*Leng th)
0to2billionUnicodecharacters(approximately).
User Defined Type
(structure) System. ValueT ype
Sumofthesizeofitsmembers
Eachmemberofthestructure hasarangedeterminedbyits datatypeandindependentofthe rangesoftheothermembers
Table5-2:DataTypeChanges
DataType PreVB.NET
VB.NET
System.Int16 Integer Short
System.Int32 Long Integer
System.int64 Didnot exist
Long
Variant Variant Doesnotexist
Currency Currency Decimal
Date Date Long
VariabledefaultsWhenyoudeclareavariableofatypewithoutassigningavaluetoit,thevariablehasa defaultvaluebasedonthetypeofvariableyouhaveassignedasthetype.Thefollowing arethedefaultvaluesfordifferenttypes:
Numbers:0(zero) Boolean:False String:Nothing Object:Nothing Date:12:00:00AM
OptionExplicitstatementTheOptionExplicitstatementforcesyoutodeclarevariablesbeforeyoureference theminyourcode.ThisstatementworksthesamewayasitdidinpreviousVBversions. InVB.NET,youcansettheOptionExplicitstatementontheprojectlevel,inthe propertiesdialogbox,oryoucanusetheOptionExplicitstatementatthetopof yourclassfilesormodules.TheusagefortheOptionExplicitstatementisas follows:
OptionExplicit{On|Off}IfyouspecifyOptionExplicitOnandattempttoreferenceavariablethatisnot declared,theIDEnotifiesyouoftheerrorasyouarecoding.
ConstantsAconstantallowsyoutouseafriendlynameforavariablevaluethatdoesnotchange throughouttheexecutionofyourapplication.ConstantsinVisualBasic.NETactexactly astheydidinpreviousversions.Todeclareaconstant,youusetheConstkeyword withinaprocedureoratthedeclarationssectionofyourclassesormodules.Constants canbedeclaredwiththescopeofPrivate,Public,Friend,Protected,or ProtectedFriend.ThefollowingistheusageoftheConststatement.
[Public|Private|Friend|Protected|ProtectedFriend]
Constconstantname[Astype]=expressionWhenyoudeclareaconstant,youmustdeclareitasacertaintype.ConstantscanbedeclaredasBoolean,Byte,Char,DateTime,Decimal,Double,Integer,Long, Short,Single,orStringdatatypes.Inthefollowingcode,youaredeclaringseveral constantsandthenusingthemintheprocedurewithinthemodule.
ModuleModule1
PrivateConstBillsSalaryAsDouble=1000000000
PrivateConstMySalaryAsByte=100
PrivateConststrMsgAsString="TryAgainPlease"
PrivateFunctionTest_Salary()AsBoolean
IfMySalary>BillsSalaryThen
Console.WriteLine(strMsg) EndIf
EndFunction
EndModule
VariablescopeThescopeofavariablecanbedeclaredasPrivate,Public,Static,Shared, Protected,orFriend.Hereissomefamiliarlookingcode,declaringdifferentvariable typeswithdifferentscopes:
Publicv,basDouble
Statici,sasLongDimc,o,o,lasString
Privaten,e,a,t,oasInteger
PrivatevariablesPrivatevariablesareavailabletothemodule,class,orstructureinwhichtheyare declared.AswithpreviousVisualBasicversion,DimandPrivateactinthesame manner,withtheexceptionthatthePrivatekeywordcannotbeusedtodeclare variableswithinasubprocedureorfunction.HereisanexampleofhowyoucouldusePrivateandDimwithinaclass: PublicClassVar1
PrivateSharedintJasInteger
SharedSubMain()
DimintYasInteger=100
CallDoSomething
Console.Writeline(intJ)
'returns100
Console.Writeline(intY) EndSub
PrivateSharedSubDoSomething() IntJ=100
EndSub
EndClassInthisexample,intJissharedthroughoutallmembersoftheclass,sinceyouusedthe PrivateShareddeclaration.WhenyoudeclaredintYwithintheSubMain procedure,thescopeofthatvariableistheSubMainprocedureonly;anyattemptto useitoutsideofSubMainresultsinanerror.ThisbehaviorisidenticaltopreviousVB versions.Thefollowingcodeisinvalid:
SubEatDinner()asBoolean
PrivateintXasinteger=100
EndSub
Privateisnotallowedtodeclarelocalvariableswithinasubprocedure.
PublicvariablesPublicvariablesareavailabletoallproceduresinallclasses,modules,andstructuresin yourapplication.Itisimportanttonotethatinmostcases,methodandvariable declarationispublicbydefaultinVB.NET.InpreviousversionsofVisualBasic,the defaultwasprivate,soyoumaywanttoconsiderwhereyouneedtoaccessmethodsandvariablesbeforedeclaringeverythingaspublic.Thefollowingexampledemonstratestheuseofapublicvariableusedinmultipleclasses.NoticethatbothintXandintYare inthePublicscope,andareaccessibletotheclassesinthemodule.
ModuleModMain
'Thisisourpublicvariable,availabletoeverything
PublicintX,intYAsInteger
PublicClassDog
SubX()
intX=100
EndSub
SubY()
intY=300
EndSub
EndClass
PrivateClassAnimals
SubZ()
intX=500
EndSub
EndClass
EndModule
StaticvariablesStaticvariablesarespecialvariabletypesthatretaintheirvalueswithinthescopeofthe methodorclassinwhichtheyaredeclared.Astaticvariableretainsitsvalueuntilthe valueofthevariableisreset,oruntiltheapplicationends.
StaticintSAsInteger=100
SubTest()
intS=intS+1
IfintS=105Then intS=100
EndIf
EndSubInthisexample,eachtimethesubisexecuted,thevalueofintSisretaineduntilthe valuereaches105,thenthevalueofintXisresetto100,andthishappensforeveruntil theapplicationends.Staticvariablescanonlybedeclaredattheprocedurelevel.Ifyou attempttodeclareavariableattheclassormodulelevel,yougetacompilererror.
SharedvariablesSharedmembersareproperties,procedures,orfieldsthataresharedbyallinstancesof aclass.Thismakesiteasytodeclareanewinstanceofaclass,butmaintainashared, publicvariablethroughoutallinstancesoftheclass.Hereissomecodethatexplains this:
ModuleModMain
ClassAnimal
PublicSharedEyesAsBoolean
PrivatestrDescAsString
PropertyFriendly()AsString
Get
Friendly=strDesc
EndGet
Set(ByValValueAsString)
strDesc=Value
EndSet
EndProperty
EndClass
SubMain()
DimCatAsAnimal=NewAnimal()
DimRatAsAnimal=NewAnimal()
Cat.Friendly="Yes" Cat.Eyes=True
Rat.Friendly="No"
console.WriteLine(Rat.Eyes)
EndSub
EndModuleTheresultwrittentotheconsoleisTrue.BecauseyoudeclaredEyesasshared,you don'thavetosetitforeachinstanceoftheclasscreated.Thevariableisshared throughoutallinstancesoftheclass.Thiscouldalsocauseyouproblemsifyouareexpectingvariablestobeinitializedtoemptyornullwhenaclassisinstantiated,soyoushouldusecautionwhenimplementingsharedvariables.
ProtectedvariablesProtectedvariablesareonlyavailabletotheclassinwhichtheyaredeclared,orclasses thatderivefromthesameclass.Inthefollowingcode,thevariableXisavailableonlyto theclassinwhichitisdeclared.TheattempttoaccessitintheClassBresultsinan error.
ModuleModule1
ClassA
'Declareprotectedvariable
ProtectedXAsInteger
PrivateFunctionTestX()AsBoolean
'Setvalueofprotectedvariable
X=5
EndFunction
EndClass
ClassB
PrivateFunctionTestX()AsBoolean
X=5
EndFunction
EndClass
EndModule
FriendvariablesFriendvariablesareaccessiblefromanyclassormodulewithintheassemblythatthey aredeclaredin.Inthefollowingcode,afriendvariableisdeclaredatthemodulelevel, andthevariableisavailabletoallclasseswithinthismodule.
ModuleModule1
'DeclareFriendvariable
FriendXAsInteger
ClassA
PrivateFunctionTestX()AsBoolean
'Setvalueofprotectedvariable
X=5
EndFunction
EndClass
ClassB
PrivateFunctionTestX()AsBoolean
X=5
EndFunction
EndClass
EndModule
Type ConversionDatatypeconversioninVB.NETisverysimilartoearlierVBversions.Whenyouconvert types,youcanusebuilt-infunctionstoconvertfromonetypetoanother.Therearetwo typesofdataconversion:wideningandnarrowing.
Widening:Conversionisabletomaintaintheoriginaldatavalue,withoutdataloss.
Narrowing:Conversionattemptstoconvertdatafromalargertypetoa smallertype(inbytesorprecision)thatmaynotbeabletomaintainthe originalvalue.
Anexampleofnarrowingconversionwouldbethefollowing: DimXasSingle=123.45
DimYasInteger
Y=X
Table5-5:AllowableTypeConversionRanges
DataType Allowable Conversi onRange
Byte Byte, Short, Integer, Long, Decimal, Single, Double, Object
Short Short, Integer, Long, Decimal, Single, Double, Object
Integer Integer, Long, Decimal, Single, Double, Object
Long Long, Decimal, Single, Double, Object
Decimal Decimal, Single, Double, Object
Single Single, Double, Object
Double Double, Object
Char Char, String, Object
DerivedTypes Any base type from whichit is derived
Inthiscase,thedecimalplacesarelost;anintegervaluedoesnothaveprecision,soit cannotholdnumberstotherightofthedecimalplace.InVS.NET,ifyouturnOption StricttoONtheapplicationdoesn'tcompileunlessyouperformanexplicitconversion betweenthedatatypes.Thisisagoodthing;thecompilerinallearlierVBversionsdid notofferthiscatch,andbugswereeasilyintroducedduetoconversionerrors.Table5 - 5liststheallowablerangesforwideningwhenconvertingdatatypes.
Table5-5:AllowableTypeConversionRanges
DataType Allowable Conversi onRange
AnyType Any Interface theType implement s
Built-intypeconversionfunctions
Thefollowingbuilt-inconversionkeywordsarestillavailableinVB.NET:
CBool,CByte,CChar,CDate,CDbl,CDec,CInt,CLng,CObj,
CShort,CSng,CStrandCType.
StructuresInpreviousVBversions,theUserDefinedType(UDT)wasanextremelyusefulwayof definingyourowntypes.Iuseditallthetimetostoreglobaldata,andtostorerowsfrom adatabasethatweremostlystatic.AnexampleofaUDTinVB6wouldbe:
PublicCustomerasType strNameasstring
strAddressasstring strEmailasstring
EndType
PublicCCustomer()asCustomerThevariableCCustomerwasdeclaredasanarrayoftypeCustomer.InVB.NET, StructuresreplaceUDTs.Thisisnotatrivialnamechange.Structuresofferincreased functionalityandobject-orientedfeatures.MyexampleoftheCustomertypewouldbe convertedtoastructureinVB.NETlikethis:
StructureCustomer
PublicstrNameasstring
PublicstrAddressasstring
PrivatestrTaxIDNumberasstring
EndStructure
PublicCCustomerasCustomerBothexampleslooksimilar,andtheyare.It'swhathappensunderthehoodthatgivesus theadvantagesofstructuresinVB.NET.Youcandefineastructureasawaytogrouplikedata.Structuresaredeclaredwiththe Structure…EndStructurestatement.Betweenthedeclarations,youlistyour variableswiththePublic,Private,Protected,orSharedscope.Insideofa structure,variablesdeclaredwithDimarePublicbydefault;thisistheexactopposite behaviorinclassesandmodules.Whenyoudeclareavariabletobeaninstanceofa structure,allofthestructure'smembersareinitializedautomatically,whichmeansyou donotneedtoinitializeindividualmembersofastructure.Whenyoudecidethatyou needtousethestructure,youdeclareavariableasthetypeofthatstructure.Youcan declarethevariableinoneoftwoways:
DimvarnameasStructureName
Dim varnameasStructureName=NewStructureName
Note Structuresarevaluetypes,notreferencetypes.
Afteryoudefineastructure,anddeclareavariabletoreferencethestructure,youcan usethefollowingsyntaxtoreferencethemembersofthestructure:
CCusotmer.strAddress="1234MainStreet"
CCustomer.strName="BillGates"
Table5-9:ArithmeticOperators
Operator Action
+ Addition
- Subtraction
* Multiplication
/ and\ Division
% Modulo
^ Exponentiation
OperatorsTheoperatorscanfallintoone ofthesecategories:arithmetic,assignment,bitwise,comparison,concatenation,and logical.Thebasicpurposeofanoperatoristoassignorretrievevaluesbasedonexpressionsor statements.Inthefollowingexample,youareassigningthevalueofthevariableXequaltowhatever thevalueofYmightbe.Thisisanexampleofanassignmentoperator;youareassigning thevalueofoneexpressiontothevalueofanother.
X=YThefollowingisanotherexampleofanassignmentoperator,exceptthatinthiscase, youareevaluatingthereturnvalueoftheSquareItfunction,whichisastatement,and assigningthevaluefromthefunctioncalltothevariableintX.
X=SquareIt(5)
Inthenextexampleyouarecombiningtwostringswiththeconcatenationoperator, settingthevalueofthevariableonthelefttotheevaluationofthestatementontheright sideoftheequals(=)sign.
TheCarIWishIHad="Mercedes"&"Benz500SL"
Arithmeticoperators
AdditionoperatorThe+,oradditionoperator,sumsorconcatenatestwoexpressions.Concatenationis discussedalittlelaterinthischapter,aswellaswhatyouhavetolookoutforwhen usingthe+operator.Theusageforadditionoperatorisasfollows:
Result=Expression+Expression
Thefollowingexampleshowsthesimplestformoftheadditionoperatorpossible,adding twovaluestogether:
DimintXAsInteger intX=intX+5
Console.Writeline(intX.ToString)ThevariableintX,declaredasintegervalue,hastheinitialvalueofzero.Toadd5to thevalueintX,yousimplyusetheadditionoperator(+)andtheassignmentoperator (=)toderivethenewvalue.Thefollowingcodeaccomplishesthesamething:
Dim intX As Integer Dim intY As Integer
intY=intX+5
Console.Writeline(intY.ToString)TheonlydifferenceisthatyoucreateanewvariablecalledintYtoholdthevalueof intXplusthenumber5.Creatingvariablesjustfortheheckofitisnotefficient,soifthe valueofintXhasthesolepurposeofbeinganintegerwith5addedtoit,thenusethe firstexampleasaguide.NewtoVisualBasic.NETarespecialassignmentoperators thatperformanactiononavariable,suchasaddition.Theprecedingadditioncodecan alsoberepresentedas
DimintXAsInteger intX+=5
Console.Writeline(intX.ToString)Assignmentoperatorsarecoveredinmoredetailinthenextsection .Eventhoughthey looklikemathematicaloperators,theyareactuallynot;becauseyouareusingtheequals
sign(=),itindicatesanassignment.Inthepreviouscode,youdeclaredvariablesofthe typeInteger,whichthecompilerunderstood,andaddedthevaluestogether.Consider thisexample:
DimintXAsInteger=10
MessageBox.Show(intX+"9")Theresultinthisexampleis109.Additiondidnotoccur.Becausethevalueof"9"is enclosedindoublequotes,thecompilerunderstandsitasastringdatatype,sothe valuesareconcatenated,andnotadded.Ifyouarenotsureofthetypeofdatayouare dealingwith,andyouneedtomakesurethatadditionoccurs,usetheconversion functionsdiscussedearlierinthechapter.Thefollowingcodetakescareofthisproblem:
DimintXAsInteger=10
MessageBox.Show(intX+CInt("9"))
Understandingthedatayouaredealingwithisveryimportant;asyoucansee,the resultscanvarysignificantlyifyouarenotcareful.Thefollowingrulesapplywhenusing theadditionoperator:
Additionoccursifbothexpressionsareofthesamenumericdatatype. Concatenationoccursifoneorbothexpressionsarestrings. If OptionStrictisON,implicitconversionbetweentypesisnot
allowed,sothepreviousexampleusingCIntthrowsanexception, andneitherconcatenationnoradditionoccurs.
If OptionStrictisOFF,implicitconversionisallowed,andthe expressionsareaddedifimplicitconversionisused.Thisconversion canbetonumericorstringdatatypes,andtheresultvariesbasedon theconversionoftheexpression.
Narrowingorwideningconversionsoccurifthenumericdatatypesusedinexpressionsaredifferentthanthenumericdatatypeofthe result.
Thefollowingcoderoundsupanexampleofusingtheadditionoperand,andtheresults thatcanoccur,assumingthedefaultOptionStrictofOFF.Theinlinecommentsin thecodecanhelpyouunderstandwhatwe'retryingtoaccomplish.
DimdblXAsDouble=6.54
DimdblYAsDouble=9.32
DimstrXAsString= "6" DimstrYAsString= "5"
DimintXAsShort
intX=CShort(strX)+CShort(strY) MessageBox.Show(intX)
'ResultisShortDataTypewithavalueof11
MessageBox.Show(strX+strY)
'ResultisStringDataTypewithavalueof65 intX=dblX+dblY
MessageBox.Show(intX)
'Resultis16,Integerdatatypecannothaveadecimalplace,
'sothenarrowingconversiontakesplace strX=dblX+dblY
MessageBox.Show(strX)
'Resultis15.86,Doubledatatypesareadded,sincetheyare
'ofthesametype,andtheStringwillholdtheresultwithout
'anerror
strX=dblX.ToString+dblY.ToString
MessageBox.Show(strX)'Resultistheconcatenationof6.549.43,sincetheToString
'converttheDoublevaluestostrings,allvaluesarestrings,
'andconcatenationoccurs
SubtractionoperatorThesubtractionoperator(–),indicatingsubtractionornegations,returnsthedifference betweentwonumbersorexpressions,oritnegatesanumericvalue.Herearethetwo possibleuses:
result=number1—number2 variable=-number
Youhavebeendoingsubtractionsinceyouopenedyourfirstbankaccountandtheteller gaveyouthelittleaccountbalancebooklet.Therearenorealgotchasherewiththeway theoperatorworks.
DimintXasInteger
DimintYasInteger=500 intX=intY—100Inthisexample,youaresubtracting100fromthevalueofintY,whichis500,and assigningthisvaluetothevariableintX.Inthiscase,thenewvalueofintXis400.If intYislessthan100,thevaluereturnedtointXisnegative.Soifthecodewas modifiedto
DimintYasInteger=5
theresultwouldnowbe–95.
Tosimplynegateavalue,youcanassignittothenegativevalueofitselfortoanew variable.Youcouldrefertothe—operatorastheunarynegationoperatorinthiscase,as inthefollowingexample:
DimintXasInteger=100 intX=-intX
Whenusingsubtraction,makesurethatthedatatypesinusesupportthetypeof operationthatyouareattemptingtoaccomplish.Thisrulestandsforalloperators.For example,ifyouarebalancingyourcheckbook,andtheresultvariableisdeclaredasan integerdatatype,thenyouaredefinitelylosingmoney,becausethedecimalplacesare gettinglostintheprocess.
DimdblVal1AsDouble=100.54
DimdblVal2AsDouble=23.45
DimintYAsInteger
intY=dblVal1-dblVal2
MessageBox.Show(intY)'Returns77
MessageBox.Show(dblVal1 -dblVal2)'Returns77.09
MultiplicationoperatorThemultiplicationoperator(*)multipliestwonumbersandreturnsaresult. Theusageis
Result=Number1*Number2
5*5=25
Whenyouuseacalculator,thelogicalprocessistakingthetwonumbersyouwantto multiplyandthenpresstheequalssign.Whenyoucode,youdotheopposite—you declarethevariable,andsetthatvaluetotheresultingvalueoftheoperationyouare attemptingtoaccomplish.
DimintXasInteger=5
DimintYasInteger=5
DimintResultasInteger intResult=intX*intYInthisexample,youmultiplytwovariablesandassignthevalueofintResulttothe resultofyourmultiplication.Ifyoudidthistheoppositeway,asyouwouldtypeitintoa calculatororaddingmachine,thevalueofintResultwouldbezero.
intX*intY=intResultintResultisinitializedaszero,andbysettingthevalueofintX*intYtothevalue ofzero,youhavedonetheexactoppositeofwhatyouaretryingtoaccomplish.
DimintXasShort
intX=56000*998
DivisionoperatorTheregulardivision(/)andtheintegerdivision(\)operatorsdividetwonumbersand returnaresult.
Theusageis
RegularResult=Number1/Number2
IntegerResult=Number1\Number2Thedifferencebetweenthetwotypesofdivisionishowthenumbersontheright-hand sideoftheequalssignaretreatedbeforethedivisionoperationtakesplace.Ininteger division,integraldatatypesmustbeused.Thesearethedatatypesthatdonotallow decimalplaces,suchasInteger,Long,Bit,andShort.Theresultofaninteger divisionishowmanytimesonenumbercanevenlydivideintoanothernumber.
25\5=5
Thenumber5evenlydividesinto25fivetimes.
26\5<>5
Inthiscase,26dividedby5obviouslydoesnotequal5.Hereisthelongcaseexampleofseveralscenariosofchoosingthecorrectorincorrect typeofdivision:
DimintXAsInteger=100
DimintYAsInteger=50
MessageBox.Show(intX/intY)'Returns2
MessageBox.Show(intX\intY)'Returns2
intX=101'Modifyvariablesodivisionisnoteven
MessageBox.Show(intX/intY)'Returns2.02
MessageBox.Show(intX\intY)'Returns2
'Usefloatingpointvariables
DimdblXAsDouble=103.435
DimdblYAsDouble=50
MessageBox.Show(dblX/dblY)'Returns2.0687
MessageBox.Show(dblX\dblY)'Returns2
ModulooperatorThemodulooperator(%)dividestwonumbersandreturnstheremainder. Theusageis
Result=Number1MODNumber2
Ifeitherofthenumbersbeingdividedarefloating-pointnumbers,theresultisthefloating-pointremainder.Ifthebothofthenumbersbeingdividedareintegers,thereturn valueisanintegerdatatype.
Hereisasummaryofsamplesusingthemodoperand: DimintXAsInteger=100
DimintYAsInteger=50
MessageBox.Show(intYModintX)'Returns50
MessageBox.Show(intXModintY)'Returns0
intX=101'Modifyvariablesodivisionisnoteven
MessageBox.Show(intXModintY)'Returns1
'Usefloatingpointvariables
DimdblXAsDouble=103.435
DimdblYAsDouble=50.74
MessageBox.Show(dblXModdblY)'Returns1.955
MessageBox.Show(dblYModdblX)'Returns50.74
Asyoucansee,onceagain,usingthecorrectdatatypesandunderstandinghowyour divisionshouldtakeplacealterstheoutcomeofyourresults.
ExponentiationoperatorTheexponentiationoperator(^)returnstheexponentoftwonumbers. Theusageis
Result=Number1^Number2
Thefirstnumberisraisedtothepowerofthesecondnumber.Normallythedatatypeof theresultisdouble,unlessyouexplicitlydefinetheresultasanintegraldatatype.Here areafewsamplesoftheexponentialoperand:
DimintXAsInteger=50
DmintYAsInteger=5
DimintZAsInteger
Console.WriteLine(intY^intX)'Returns8.88178419700125E34
Console.WriteLine(intX^intY)'Returns312500000 intZ=intY^intX
Console.WriteLine(intZ)
'Overflowexceptionoccurs
'Theexponentofthe2floatingpoint
'numberscannotfitintoanintegerdatatype
DimdblXAsDouble=3
DimdblYAsDouble=3
Console.WriteLine(dblX ^dblY)'Returns27Intheprecedingexamples,Ithrewinanexampleofanexception,soyoucanseethat whendealingwithraisingnumberstothepowerofanothernumber,thereturndatatype shouldbeDouble,becausethenumbershaveatendencytobequitelarge.
Concatenationoperators
Concatenationoperators(&)combinestringvariableswithstringexpressions. Theusageis
Variable=expression&expression
DimXasInteger=3
DimintYasInteger=15
intX=intX&intY'Returns315
Or,youdonothavetoassignthevalueimmediately: Dimstr1asstring="NCC"
Dimstr2asstring="D"
str1=str1&"1701"&str2'ReturnsNCC1701DWhenyoucombinestringsinVisualBasic,youcanusethevariableontheleft-handside oftheequalssignasastringvariableintheexpressionontheright-handsideofthe equalssign.Sothestr1variableintheprecedingexamplecanbeusedinyour expressionaswellasintheresult.
Theadditionoperator(+)canalsobeusedforconcatenation,ifanyofthevaluesinthe expressionontheright-handsideoftheequalssignarestringdatatypes.Theprevious sectionsonarithmeticoperatorsshowedseveralexamplesofthisbehavior.
Assignmentoperators
Assignmentoperatorsarealmostascommonasarithmeticoperators.Theequals(=) signisusedwheneveryouneedtosetthevalueofavariable.Whenyoudeclare variables,youcanuseassignmenttosetthevalueofthevariableinthesamelinethat youaredeclaringit.
DimXasInteger=3
Table5-10:AssignmentOperators
Operator Action
= Equalsassignment
+= Addition/concatenation assignment
-= Subtraction assignment
*= Multiplication assignment
/=and\= Divisionassignment
=̂ Exponentiation assignment
&= StringConcatenation assignment
EqualsoperatorTheequalsoperator(=)isprobablythemostwidelyusedoperatorinanydevelopment language.Youarealwaysassigningavariableorobjecttotheresultofarithmetic,ora functioncallreturnvalue,oranyvaluethatyouneedtoassign.The=operatorisalso usedtocompareoneexpressionofvariabletoanother,returningaBooleanvalue.
Theusageis
Variable=Expression
Theexpressionontheright-handsideofthe=isevaluated,andassignedtothevariable ontheleft-handsideoftheoperator.
DimstrFirstNameasString="BillionDollar"
DimstrLastNameasString="Bill"
DimstrFullNameasstring
strFullName=strFirstName&strLastName'ReturnsBillionDollarBillIntheprecedingexample,youaretakingtwostringvariablesandassigningthemtothe variablestrFullName.
DimlngResultasLong lngResult=DoTheMath()
Inthisexample,thereturnvaluefromtheDoTheMathfunctionisassignedtothe variablelngResult.
Inalloftheexamplessofar,youhavebeenevaluatinganexpressionontheright-hand sideoftheoperatorandassigningavaluetotheleft-handside.Youcanalsocompare variableswiththeassignmentoperator:
IfbNotEmpty=TrueThen
Messagebox.Show("Please fillinavalueforname") Endif
IfstrName="SMITH"then
Messagebox.show("YournameisnotGates") EndifInthefirstexample,iftheBooleanvariablebNotEmptyhasavalueofTrue,thenyounotifytheuserthattheymustfillinavalueintoatextboxorwhatevercontrolyoumight beusing.Inthesecondexample,youcheckthevalueofthestrNamevariable,andifit equalsSMITH,youraiseamessagetotheuser.Bothoftheseexamplesusethe= operatortocheckforthevalueofanoperator,andnotnecessarilyassignavaluetoan operator.
Addition/concatenationassignmentoperatorTheaddition/concatenationassignmentoperator(+=)addsthevalueofanexpressionto thevalueofavariableandassignstheresulttothatsamevariable.Thetypeofoperation thatoccursisbasedonthetypeofdatathatisbeingevaluated.
Theusageis
Variable+=Expression
Iftheexpressionisnumeric,thenadditionoccurs;iftheexpressionisastring,then concatenationoccurs.
DimstrFNameasstring="Romeo"
DimstrLNameasstring="MustDie"HereyouhavethestrFNamevariablethatholdsavalueof"Romeo".Youthenusethat samevariableastherecipientoftheexpression+=strLName.Thisevaluationtakes thecontentsofstrFName,andconcatenatesstrLNametoit.Seethe"&="operatorlaterinthissectiontoaccomplishthesamethinginacleanerfashion.Youshouldalwaysavoidusingtheaddition(+)operatorforstringconcatenation.
strFName+=strLName'ReturnsRomeoMustDie
DimintXasInteger=100
intX+=1'Returns101HereyouareincrementingthevalueofintX.TheoriginalvalueofintXwas100,and usingtheassignmentconcatenationoperator,youcanincrementthevalueandassignit backtointX.Youcanaccomplishthesamethingwiththislineofcode:
intX=intX+1
DoWhileintX<100
intX+=1'Incrementintegervalueby1
Loop
MessageBox.Show(intX)'Displays100Whendiscussingtheadditionoperatorinthebeginningofthesection,yousawsomeof theerrorsthatcouldariseifyouareattemptingadditionandthedatatypeisnotnumeric.
DimVal1asInteger=100
DimVal2asInteger=50
Val1+=Val2' Returns150
DimVal1asString=100
DimVal2asstring=50
Val1+=Val2'Returns10050
Hereyoucanseethatbasedonthedatatype,eitheradditionorconcatenationmay occur.Youhaveobviouslydeclaredyourownvariableshere,butasImentionedbefore, youmightnotalwaysknowthedatatypeofthevariablesyouaredealingwith,souse cautionandmakesureyoucandeterminetheactualdatatypesbeforeperformingany operationsthatincludearithmetic.
SubtractionassignmentoperatorThesubtractionassignmentoperator(–=)subtractsthevalueofanexpressionfromthe valueofavariableandassignstheresulttothatsamevariable.
Theusageis
Variable-=Expression
Thesamerulesapplyforthesubtractionassignmentoperatorasforthesubtraction arithmeticoperator.
DimintXasinteger=100 intX-=25'Returns75
or
intX-=100+34'Returns-34Bothstatementsarefairlystraightforward.ThevariableintXisinitializedwithavalueof100,andtheexpressionontheright-handsideoftheoperandisevaluated,subtracted fromthevariableontheleft,andthenassignedtothevariableontheleft.
MultiplicationassignmentoperatorThemultiplicationassignmentoperator(*=)multipliesthevalueofanexpressionbythe
valueofavariableandassignstheresulttothatsamevariable.
Theusageis
Variable*=Expression
Thesamerulesapplyforthemultiplicationassignmentoperatorasforthemultiplication arithmeticoperator.
DimintXasinteger=3 intX*=3'Returns9
intX*=15'Returns45
DimintYasInteger=7
intX*=intY'Returns21
Youaredoingsimplemultiplicationhere,takingthevalueontheright,multiplyingitby thevariableontheleft,andassigningtheresulttothevariableontheleft.
DimintXasinteger=10IntX*=DoTheMath()Inthisexample,youareevaluatingtheexpressionDoTheMath,afunctioncall, multiplyingitbyintX,andassigningtointX.IfthefunctionDoTheMathreturned10, yourresultwouldbe100;ifitreturned3,yourresultwouldbe30,or3*10.
DimintXasinteger=27000 intX*=129093482^45
Division assignmentoperatorThefloating-pointdivision(/=)andintegerdivision(\=)assignmentoperatorsdividethe valueofanexpressionbythevalueofavariableandassigntheresulttothatsame variable.
Theusageis
FloatingPointVariable/=Expression integralVariabe\
=Expression
Thesamerulesthatyoulearnedearlierinthechapterregardingfloating-pointand integraldivisionapply.Here isasummaryofexamplesusingthedivisionassignment operators:
DimintXasinteger=5
DimintYasinteger=25 intY/=intX 'Returns5
DimdblXasDouble=234.6
DimdblYasDouble=23.928
dblX/=dblY'Returns9.80441323971916
DimintXasInteger=200
DimdblYasDouble=5.34 intX\=dblY'Returns40
ExponentiationassignmentoperatorTheexponentiationoperator(^=)raisesthevalueofavariabletothepowerofan expressionandassignsittothatvariable.
Theusageis
Variable^=Expression
Thevariableontheleft-handsideoftheoperatorisraisedtothepoweroftheexpression ontheright-handsideoftheoperator.
DimintXasInteger=3
DimintYasInteger=5 intX^=intY'Returns243
DimintX=10
DimintY=3
IntX^=intY'Returns1000Thisexampleisthesameas10*10*10.Ifyouweretomakethatsomewhatgeneric, youcouldcodelikethis:
DimintVar1asInteger
ForintVar1=0tointY—1 intX=intX*intX
Next
Obviouslyusingthecorrectoperatorsimplifiesyourcode,anddoesnotleaveroomfor anyerrors.
ConcatenationassignmentoperatorTheconcatenationoperator(&=)concatenatesastringexpressiontoastringvariable andassignsittothestringvariable.
Theusageis
Variable&=Expression
Thevariableontheleft-handsideoftheoperatorisconcatenatedtotheexpressionon theright-handsideoftheoperator.
DimstrNameasstring="Dr." DimstrVarasstring="Evil"
strName&=strVar'ReturnsDr.Evil
DimintXasInteger=3
DimintYasinteger=5 intX&=intY'Returns35
Theinclusionoftheintegerexampleintheprecedingcodeistodemonstratethatthe&= operatoralwaystreatsthevariablesandexpressionsasstrings,sonoadditionoccursas withthe+=operatorifthevariableandexpressionareactualnumbers.
Comparisonoperators
Comparisonoperatorsevaluateanexpressionontheright-handsideoftheequalssign andreturnaBooleanTrueorFalsebasedonthecomparisonoftheexpressions.
Theusageis
result=expression1comparisonoperatorexpression2 result=object1Isobject2
result=stringLikepattern
DimintXAsInteger=3
DimintYAsInteger=5
Console.WriteLine(intX<intY)
ThisexamplereturnsTrue,becausetheintegervalue3islessthantheintegervalue5. DimintXAsString="A"
DimintYAsString="a" Console.WriteLine(intX>intY)'ReturnsFalse
Console.WriteLine(Asc("A")) 'Returns65
Console.WriteLine(Asc("a")) 'Returns97
Thiscomparisonisbasedonstrings,whichisalittledifferentthannumericcomparison. Youhavecompared"A"and"a",whichthecompilerconvertstotheirrespectiveASCII equivalenttodothecomparisonbasedonthesortorderoftheASCIIvalue.TheASCII valuefor"A"is65,andtheASCIIvaluefor"a"is97,whichiswhyFalseisreturned fromthecomparison;65isnotgreaterthan97.Whencomparisonoperatorsareused withstrings,theASCIIequivalentofthestringvaluesiscomparedtoevaluatethe expressions.Table5 - 1 1 liststhecomparisonoperatorsandtheactionstheyperform.Table5-11:ComparisonOperators
Operator Action
Is Object compari son
Like String pattern compari son
< Less than
<= Less thanor equalto
> Greater than
>= Greater thanor equalto
= Equalto
IsoperatorTheIsoperatorcomparestwoobjecttypesandtestswhethertheyarethesame, alwaysreturningaBooleanvalue.
Theusageis
Result =objectXIsobjectYTheonlywaytogetaTruevaluebackfromthecomparisonisiftheobjectsrefertothe sameobject.Iftherearetwoobjectsthatareofthesametypebutdonotreferbackto thesameobject,thatis,theobjectwasnotcreatedfromthatobject,theresultisalways False.HereisasummaryofexamplesusingtheIsoperator:
DimxAsSystem.String DimyAsNewObject()
DimvAsObject
v=y
Console.Write(vIsy)'ReturnsTrue
Console.Write(xIsy)'ReturnsFalse
LikeoperatorTheLikeoperatorreturnsaBooleanvaluebasedontheevaluationofastringanda pattern.Ifthepatternmatchesthestring,Trueisreturned;otherwiseFalseisreturned.
Theusageis
Table5-13:ComparisonOperators
Operator Usage True Exam ple
False Exam ple
< Expr1< Expr2
27<45
45<27
<= Expr1<= Expr2
45<=45
16<=6
> Expr1> Expr2
98>97
98>98
>= Expr1>= Expr2
98>=98
97>=98
= Expr1= Expr2
98=98
98=100
<> Expr1<>Exp2
98<>97
98<>98
Result=StringLikePatternTheresultscanalsovarybasedontheOptionComparestatement.IfOption Compareis settoTEXT,thenacaseinsensitive,textsortisusedtodeterminetheresult. If OptionCompareBINARY(default)isset,thepatternmatchingisbasedonthebinaryrepresentationofthecharacters,basedonlocale,andnotthetextual representationofthecharacters.Table5 - 1 2 liststhepatternmatchingsyntaxforcharacter,numeric,andwildcard charactermatching.Table5-12:PatternMatchingSyntax
Character Meaning? Matches anysingle character.
* Matches zeroor more characters.
# Matches anysingle digit(0–9).[…] Character list surrounde dby brackets canmatch any character inthelist. For
example:[bilgates].
[!…] Character list surroundedby bracketsprefixedby exclamationpoint matchany single character notinthe list.
X—X Characters separated bya hyphen specifya rangeof Unicode characters
Console.Writeline("DOG" Like"D*")'ReturnsTrue
Console.Writeline("a"LIKE"A")'ReturnsFalse
Console.Writeline("XYZ"LIKE"X[ACY]?")ReturnsTrue
Theprecedingexamplesgiveasummaryofthepatternmatchingsyntax.
ComparingstringsandnumbersTheremainingcomparisonoperatorsarecoveredasagroupratherthanoneatatime becausetheyallfollowthesamerules,andtheyallactexactlyasyouwouldexpect.The onlythingthatyouneedtoworryaboutisthedatatypethatyouarecomparing:stringsornumbers.Eitherway,youarereturningaBooleanvalue.Table 5 - 1 3 liststheremainingnumericcomparisonoperatorsandthepossiblevaluestheevaluated expressionscanreturn.
Logical/bitwiseoperators
TheoperatorsusedforeitherthelogicalevaluationoftheBooleanexpressionsorbitwise
evaluationofthenumericexpressionsarecalledlogical/bitwiseoperators.Thesyntaxfor usingthelogical/bitwiseoperatoris
Var_result=Expr1OperatorExpr2
where Var_resultisanyBooleanornumericvariable. Expr1andExpr2areBooleanornumericexpressions. Operatorisanylogical/bitwiseoperator,suchasAnd,Or,Not,orXOR.
Table5-14:LogicalOperation
Operation Description
And Usedto perform logical joiningon twoBooleanexpressions.Itreturns Trueifboth theBoolean expressions areTrue.
Or Usedto perform logical disjoiningon twoBoolean expressions. Itreturns Trueifanyof theBoolean expressions isTrue.
Not Usedto perform logical negationon aBooleanexpressions. Itreturns Falseifthe Boolean expressionisTrueandvice-versa.
Xor Usedto perform logical exclusionon twoBoolean expressions. Itreturns Trueonlyif oneofthe Boolean expressionisTrue.
AndAlso Usedto perform logical joiningoftwoBooleanexpressions inashort-circuit manner.It returnsTrue ifboththe expressions areTrue. However,if thefirst expression
Tounderstandthelogicaloperationoftheseoperators,considerthefollowingexample:
'DeclarethreeIntegervariables
DimintVar1AsInteger=16
DimintVar2AsInteger=14
DimintVar3AsInteger=12
'DeclareaBooleanvariable
DimbResultAsBoolean
'UseAndOperator
bResult=intVar1>intVar2AndintVar2>intVar3 'ReturnsTrue
bResult=intVar1>intVar2AndintVar3>intVar2 'ReturnsFalse
'UseOrOperatorbResult=intVar1>intVar2OrintVar2>intVar3 'ReturnsTrue
bResult=intVar1>intVar2OrintVar3>intVar2 'ReturnsTrue
bResult=intVar2>intVar1OrintVar3>intVar2 'ReturnsFalse
'UseNotOperator
bResult=Not(intVar1>intVar2) 'ReturnsFalse
bResult=Not(intVar1<intVar2) 'ReturnsTrue
'UseXorOperator
bResult=intVar1>intVar2XorintVar2>intVar3 'ReturnsFalse
bResult=intVar1>intVar2XorintVar3>intVar2 'ReturnsTrue
bResult=intVar2>intVar1XorintVar3>intVar2 'ReturnsFalse
'UseAndAlsoOperator
bResult=intVar1>intVar2AndAlsointVar2>intVar3
'ReturnsTrue
bResult=intVar2>intVar1AndAlsointVar2>intVar3
'ReturnsFalse—SecondConditionisnotevaluated
'UseOrElseOperator
bResult=intVar1>intVar2OrElseintVar2>intVar3
'ReturnsTrue
bResult=intVar1>intVar2OrElseintVar3>intVar2
'ReturnsTrue—SecondConditionisnotevaluated
Operatorprecedence
Inalloftheexamples,youhaveseenfairlysimpleexpressions.Thisisnotalwaysthe casewhenyouarewritingyourapplications,andyoumayhaveseveraldifferent operatorsbeingusedtoevaluateasingleexpressionorseriesofexpressions.
DimdblRetasInteger
dblRet=5*4/6^4+9—100
Console.Writeline(dblRet) 'Returns-90.9845679012346Inthisstatement,fiveoperatorsarebeingusedtoretrievethevalueofintRet.The precedenceinwhichtheoperatorsareevaluatedaffectstheoutcome.
DimdblRetAsDouble
dblRet=((5*4)/6)^4+9-100
Console.WriteLine(dblRet) 'Returns32.4567901234568Youcanseethedifferenceinthetwoexamples.Althoughtheybothareusingthesame numbers,theresultsaredifferentbasedontheusageofparenthesesonthecode.So twothingsareactuallyaffectingtheoutcome:
1. Thelocationoftheparenthesesintheexpression.2. Theorderoftheoperatorsintheexpression.
Table5 -1 6liststheprecedenceofoperatorswhenevaluatingexpressions.Table5-16:OperatorPrecedence
Arithmetic Comparison Logical
^ = Not
-(Negation) <> And
*,/ < Or
\ > XOR
Mod <=
+,- >=
BitwiseOperators Like,Is, TypeOf..Is
&
Whenparenthesesareusedinexpressions,theyarealwaysevaluatedfirst.Sointhe previousexample,therearetwodifferentresultsforthesamenumbersbecausethe parentheseshaveoverriddentheprecedenceoftheoperators,causingaportionor portionsoftheexpressiontobeevaluatedbyothers.
Hereisasummaryoftherules: Operatorevaluationbeginsfromthelefttotheright.
Arithmeticoperatorsarealwaysevaluatedfirst,thencomparison operators,followedbylogicaloperators.
Comparisonoperatorsallhaveequalprecedence. Operationsenclosedwithparenthesesareevaluatedbeforeexpressions outsideoftheparentheses. Concatenation(&)operatorprecedesallcomparisonoperatorsand
followsmathematicaloperators.
Theserulesareveryeasytounderstand;theyfollowthelogicalorderinwhichyouwould processtheseexpressionsonpaperorusingacalculator.Youalwaysfigureoutyour grouping,processthoseinstructionsandthenmoveontothemath,andfinallyyou comparetheresultsoftheexpressionsandcomeupwiththeanswer.
Chapter6:ArraysIn This Chapter
IntroducingarraysMultidimensionalarraysDynamicarraysTheArrayClassmembersArraysofarrays
Arrayshelpyoustoredatainacontiguousmemoryarea..
Introducing ArraysAnarrayisamemorylocationthatisusedtostore multiplevalues.Allthevaluesinanarrayareofsametype,suchasIntegerorStringandarereferencedbytheirindexorsubscriptnumber,whichistheorderinwhichthesevalues arestoredinthearray.Thesevaluesarecalledtheelementsofanarray.Thenumberof elementsthatanarraycontainsiscalledthelengthofthearray.InVB.NET,allthearraysareinheritedfromtheSystem.Arrayclass.TheArrayclassisamemberoftheSystemnamespace.TheArrayclassprovidesmethodsforcreating,searching,sorting, andmodifyingarrays.SomeofthecommonlyusedmethodsoftheArrayclassare GetUpperBound,GetLowerBound,andGetLength.Arrayscanbesingle-ormultidimensional.
DimArray_Name(Num_Elements)[AsElement_Type]
whereArray_Namereferstothenameofthearray.Num_Elementsreferstothenumberofelementsthearraycancontain.
Element_Typereferstothedatatypeofelements.Thisparameteris optional.IfyoudonotspecifytheElement_Type,thearrayisoftype Object.
Forexample,
DimEmp_Name(100)asStringThisstatementdeclaresanarraynamedEmp_NameoftypeString,anditcanstore101valuesoftypeString.Thisisbecausethestartingindexofanarrayiszero.
Youcanalsorewritetheprecedingstatementasfollows:
DimEmp_Name()AsString=NewString(100){}
Afterdeclaringanarray,youneedtoassignvaluestoit.Considerthefollowingexample, whichillustratesassigningvaluestoanarray:
Emp_Name(0)="Jack" Emp_Name(1)="Peter"
Emp_Name(2)="John"
…
…
Emp_Name(100)="Michelle"Inthisexample,Jackisstoredattheindex0ofthearrayEmp_Name.Similarly,Peter,
John,andMichellearestoredatindices1,2,and100,respectively.Thisimpliesthatthe arraycanstore101elements.Here,0isthestartingindexorthelowerboundofthe array.Thelowerboundisfixedforallthearrays.Here,100istheupperboundofthe arrayanditcandifferfromarraytoarraydependingonthesizespecified.
Thelowerboundofanarrayisalwayszero.Theupperboundofanarrayisoneless thanthenumberofelementsinthearray.
Multidimensional ArraysDimarr(10,2)asStringTheprecedingstatementdeclaresatwo-dimensionalarray,arr,oftypeString.Atwo- dimensionalarrayhastwoindices,whichhelpsyoutospecifythepositionofelementsin thearray.
Dimarr1(10,10,10)asIntegerTheprecedingstatementdeclaresathree-dimensionalarray,arr1,oftypeInteger. Thenumberofdimensionsinanarrayiscalledtherankofanarray.Sothearray mentionedintheprecedingstatementhasarankof3.Eachdimensioninanarraycan haveadifferentlength.
Considerthefollowingexample,whichdescribestheprocessofcreatingatwo- dimensionalarrayandstoringthedatainit.
DimEmp_Details(10,6)AsStringTheprecedingstatementcreatesanarray,Emp_Details,oftypeString.Now, considerthefollowingstatementstoinitializevaluesinthisarray:Emp_Details(0,0)="John"TheprecedingstatementstoresthevalueJohnattheindexposition(0,0).
Emp_Details(0,1)="$10000"Theprecedingstatementstoresthevalue$10000attheindexposition(0,1).
MessageBox.Show(Emp_Details(0,1))Theprecedingstatementdisplaysthevaluestoredattheindexposition(0,1)ofthe arrayEmp_Details.
Dynamic ArraysYoucreateadynamicarraybynotspecifyingthesizeofthearrayatthetimeofthearray declaration.Tounderstanditbetter,considerthefollowingexample:
DimCand_Name()asStringIntheprecedingexample,Cand_NameisadynamicarrayoftypeString.Notethatthe numberofelementsinthearrayisnotspecified.YouusetheReDimstatementtospecify thesizeofthisarray.
TheReDimstatementYouusetheReDimstatementtospecifyorchangethesizeofoneormoredimensionsofanarraythathasalreadybeendeclared.However,theReDimstatementcannotchangethenumberofdimensionsinanarray.WhentheReDimstatementisexecuted,theexistingcontentsofthearrayarelost.ThisisbecausetheReDimstatementreleasesthearrayresourcesandcreatesanewarray.SomeofthefeaturesoftheReDimstatementare
TheReDimstatementdoesnotchangethedatatypeofthearrayor initializenewvaluesforthearrayelements.Theelementsofthenew arrayareinitializedwiththedefaultvaluesoftheirdatatype.
TheReDimstatementcanbeusedattheprocedurelevelonlyandnotattheclassormodulelevel.
ThefollowingstatementillustratestheuseoftheReDimstatement: DimCand_Name()asString
ReDimCand_Name(10)Intheprecedingexample,Cand_NameisadynamicarrayoftypeString.TheReDim statementresizesthearrayCand_Nameto10.Youcannowstore11stringsinthe array.TheReDimstatementcanalsobeusedforresizingmultidimensionalarrays.However,youcannotchangethenumberofdimensionsinanarray.Tounderstandthisbetter, considerthefollowingexample:
'Declaresamultidimensionalarray
DimArry(10,20)AsString
'Resizingthearray
ReDimArry(15,25)
Intheprecedingexample,Arryisamultidimensionalarray.Thesizeofthefirst dimensionischangedfrom10to15andtheseconddimensionischangedfrom20to25 byusingtheReDimstatement.
The Array Class MembersTheArrayclassprovidesvariousmethodsthathelpyouinmanipulatingthearrays. Someofthecommonlyusedfunctionsarementionedinthefollowingsections.
TheGetUpperBoundfunctionTheGetUpperBoundfunctionreturnstheupperboundofthespecifieddimensionofan array.Ittakesthedimensionforwhichtheupperboundistobefoundasaparameter. Thesyntaxis
Array_name.GetUpperBound(Dimension)
Intheprecedingsyntax Array_namereferstothenameofthearrayforwhichtheupperbound istobefound. Dimensionreferstothedimensionnumberforwhichtheupperboundis
tobefound.Youuse0forthefirstdimension,1forthesecond dimension,andsoon.Considerthefollowingexample,whichusestheGetUpperBoundfunction:
Dimvar1(10,20,30)asStringDimResultasInteger
Result=var1.GetUpperBound(0) 'Returns10
Result=var1.GetUpperBound(1) 'Returns20
Result=var1.GetUpperBound(2) 'Returns30
TheGetLowerBoundfunctionYouusetheGetLowerBoundfunctiontofindthelowerboundofthespecified dimensionofanarray.However,becausethelowerboundofanarrayisalways0,this functionwillalwaysreturn0.Italsotakesthedimensionforwhichthelowerboundisto befoundasaparameter.Thesyntaxis
Array_name.GetLowerBound(Dimension)
Intheprecedingsyntax Array_namereferstothenameofthearrayforwhichthelowerboundis tobefound. Dimensionreferstothedimensionnumberforwhichthelowerboundis
tobefound.Youuse0forthefirstdimension,1fortheseconddimension,andsoon.
TheGetLengthfunctionYouusetheGetLengthfunctiontofindthenumberofelementsinthespecified dimensionofanarray.Thesyntaxis
Array_name.GetLength(Dimension)
Intheprecedingsyntax Array_namereferstothenameofthearraywhoselengthistobe found. Dimensionreferstothedimensionnumberforwhichthelengthistobe
found.Youuse0forthefirstdimension,1fortheseconddimension,and soon.
TheSetValuefunctionYouusetheSetValuefunctiontosetavalueforaspecificarrayelement.Youcanuse thisfunctiontosetvaluesinsingle-ormultidimensionalarrays.ThesyntaxoftheSetValuefunctionforstoringvaluesinasingle-dimensionalarrayis
Array_name.SetValue(Value, Pos)Intheprecedingsyntax:
Array_namereferstothenameofasingle-dimensionalarrayforwhich thevalueoftheelementistobeset. Valueisthevaluetobestoredorsetatthespecifiedposition. Posistheindexnumberatwhichthevalueistobestored.
ThesyntaxoftheSetValuefunctionforstoringvaluesinatwo-dimensionalarrayis
Array_name.SetValue(Value, Pos1,Pos2)
Intheprecedingsyntax: Array_namereferstothenameofatwo-dimensionalarrayforwhichthe valueoftheelementistobeset. Valueisthevaluetobestoredorsetatthespecifiedposition.
Pos1andPos2aretheindexnumbersspecifyingtherowandthe columnatwhichthevalueistobestored.
ThesyntaxoftheSetValuefunctionforstoringvaluesinathree-dimensionalarrayis
Array_name.SetValue(Value, Pos1,Pos2,Pos3)
Intheprecedingsyntax: Array_namereferstothenameofathree-dimensionalarrayforwhich thevalueoftheelementistobeset. Valueisthevaluetobestoredorsetatthespecifiedposition. Pos1,Pos2,andPos3arethefirst-,second-,andthird-dimensionindex numbersofthearray.
ThesyntaxoftheSetValuefunctionforstoringvaluesinamultidimensionalarrayis
Array_name.SetValue(Value, Pos())
Intheprecedingsyntax: Array_namereferstothenameofamultidimensionalarrayforwhich thevalueoftheelementistobeset. Valueisthevaluetobestoredorsetatthespecifiedposition. Pos()isaone-dimensionalarraythatcontainstheindexnumbersat whichthevaluesaretobestored.
Arrays of ArraysVB.NETallowsyoutocreateanarraycontainingsub-arrays.
Forexample,
'Declarethebasearray
DimmyArray()()AsInteger=NewInteger(2)(){}
'Assignfirstsubarrayattheindexposition0 myArray(0)=NewInteger(5)
{1,3,5,7,9,10}
'Assignsecondsubarrayattheindexposition1 myArray(1)=NewInteger(4)
{2,4,6,8,20}Inthisexample,myArrayisanIntegerarray.ThisarraycontainstwoIntegersub- arrays.
Considerthefollowingstatement,whichexplainshowtoaccesstheelementsofthese arrays:
MessageBox.Show(myArray(1)(4))
Chapter7:ConditionalLogicIn This Chapter
If…Then…ElseSelect…CaseDo…LoopWhile…EndWhileFor…NextForEach…Next
VB.NEThasstatements,suchasIf…Then…ElseandSelect…Case,whichhelpyoutoconditionallyexecuteyourprogram.VB.NETalsoprovidesyouwithvariouslooping statements,suchasDo…Loop,While…EndWhile,andFor…Next,whichhelpyour programtorepeatasetofstatements,conditionally.Inthischapter,youlearnaboutthe syntaxandimplementationofthesestatements.
The If…Then…Else StatementThesyntaxofthesingle-lineIf…Then…Elsestatementis
If conditionThenstatement[Elsestatement]Intheprecedingsyntax,condition,whichisaBooleanexpression,isevaluated.Ifthe conditionistrue,thestatementfollowingThenisexecuted.Iftheconditionisfalse,the statementfollowingElseisexecuted.However,theElsepartisoptional.
Thefollowingexampleillustratestheuseofsingle-lineIf…Then…Elsestatement:
IfQtyOrdered>10ThenDiscount=20ElseDiscount=10
Inthisexample,thevalueofthevariableQtyOrderedisevaluated.Ifitisgreaterthan10,thevalueofDiscountissetto20;otherwise,itissetto10.
Youcanhavemultiplestatementsinthesingle-lineformoftheIf…Then…Else statement.However,allthestatementsneedtobeonthesamelineandshouldbe separatedbyacolon.Thesyntaxis
If conditionThenstatement:[statement]:[statement]Thefollowingexampleillustratestheuseofmultiplestatementsinasingle-lineIf…Then…Elsestatement:
IfQtyOrdered>10ThenDiscount=20:MsgBox("Discountis"
&iDiscount)
Inthisexample,thevalueofthevariableQtyOrderedisevaluated.Ifitisgreaterthan10,thevalueofDiscountissetto20andamessageboxisdisplayed.However, multiplestatementsinasinglelinemightaffectthereadabilityofthecode.Insucha situation,youcanbreakasingle-lineIf…Then…Elsestatementtomultiplelines.The syntaxforamultiple-lineIf…Then…Elsestatementisasfollows:
If conditionThen statement(s)
[Else
[statement(s)]] EndIfInamultiple-lineIf…Then…Elsestatement,theEndIfstatementisusedtomarkthe endofanIf…Then…Elsestatement.
Thefollowingexampleillustratesthepoint: IfQtyOrdered>10Then
Discount=20
Else
Discount=10
EndIf
The Select…Case StatementYouusetheSelect…Casestatementtoexecutedifferentsetsofstatementsbasedon thevalueofanexpression.TheSelect…Casestatementissimilartothe If…Then…Elsestatement.TheonlydifferencebetweenthetwoisthatIfandElseIf canevaluatedifferentexpressionsineachstatement,whereastheSelectstatement canevaluateonlyoneexpression.TheSelectstatementthenusestheresultofthis expressiontoexecutedifferentsetsofstatements.However,theSelect…Case statementispreferredoverIfandElseIfstatementwhenyouneedtousemultiple conditionsbecauseitmakesthecodeeasytoreadandunderstand.Thesyntaxforthe Select…Casestatementis
SelectCaseexpression
Caseexpressionlist statement(s)
[CaseElse
[statement(s)]] EndSelectIntheprecedingsyntax,expressionlistreferstotheconstantsorexpressionsthatarecomparedwiththeresultoftheexpressionmentionedwiththeSelect…Casestatement.WhentheSelect…Casestatementisexecuted,theexpressionisevaluatedandtheresultiscomparedwitheachconstantspecifiedwiththe Casestatement.IftheresultoftheexpressionisequaltoanyoftheCaseconstants, statementsfollowingthatCasestatementareexecuted.However,ifnomatchisfound fortheexpressionresult,statementsfollowingtheCaseElsestatement(ifitispresent) areexecuted.TheEndSelectstatementmarkstheendoftheSelect…Case statement.
Forexample:
SelectCaseMonth
Case1
Msgbox("January") Case2
MsgBox("February")
…
…
Case12MsgBox("December") CaseElse
MsgBox("Incorrectnumber")
EndSelect
Do…Loop StatementTheDo…Loopstatementsareusedtoexecuteasetofstatementsrepeatedly.ThesyntaxoftheDo…Loopstatementis
DoWhile|Untilcondition
[statements] [ExitDo] [statements]
Loop
or
Do [statements] [ExitDo] [statements]
LoopWhile|Untilcondition
IntheprecedingsyntaxWhile|Untilarethekeywordsthatareusedtorepeattheloop.Youcan
useonlyoneofthematatime.UseWhiletorepeattheloopuntilthe conditionbecomesfalseanduseUntiltorepeattheloopuntilthe conditionbecomestrue.
TheExitDostatementisusedtoexittheDoloop.Asaresult,thestatementfollowingtheLoopstatementisexecuted.IfyouplacetheWhileorUntilaftertheLoopstatement,theloopwillbeexecutedatleastonce. Forexample:
DimCtrasInteger=1
DoWhileCtr<=10
MsgBox("Thevalueofcounteris"&Ctr) Ctr=Ctr+1
LoopInthisexample,thesetofstatementswithintheDo…Loopstatementisrepeated10 times.
While…End While StatementYouusetheWhile…EndWhilestatementstorepeatasetofstatementsaslongasthe conditionistrue.ThesyntaxfortheWhile…EndWhilestatementis
Whilecondition
statements
EndWhileIntheprecedingsyntax,iftheconditionistrue,thestatementsareexecuted.TheEndWhilestatementmarkstheendoftheWhilestatement.
Forexample:
DimCtrasInteger=1
WhileCtr<=10
MsgBox("Thevalueofcounteris"&Ctr) Ctr=Ctr+1
EndWhileInthisexample,thesetofstatementswithinWhile…EndWhilestatementisrepeated10times.
For…Next StatementTheFor…Nextstatementsareusedtorepeatasetofstatementsaspecifiednumberof times.ThesyntaxfortheFor…Nextstatementis
ForCounter=<StartValue>To<EndValue>[StepValue] [Statement(s)]
[ExitFor]Next[Counter]
IntheprecedingsyntaxCounterisanynumericvariable.StartValueistheinitialvalueofthecounter.EndValueisthefinalvalueof thecounter.StepValueisthevaluebywhichthecounterisincremented.Itcanbe
positiveornegativeandisoptional.Ifyouomitthestepvalue,thedefaultis setto1.Statementsreferstothecodethatisexecutedthegivennumberoftimes.
TheExitForstatementisusedtoexittheForloop.Asaresult,the statementfollowingtheNextstatementisexecuted.
TheNextstatementmarkstheendoftheForstatement.AssoonastheprogramencounterstheNextstatement,thestepvalueisaddedtothe counterandthenextiterationofthelooptakesplace.Itisgood programmingpracticetospecifythenameofthecounterintheNext statement.
For Each…Next StatementTheForEach…Nextstatementisusedtorepeatasetofstatementsforeachelement inanarrayorcollection.TheForEach…Nextstatementisexecutedifthereisatleast oneelementinanarrayorcollection.Thelooprepeatsforeachelement.Thesyntaxof theForEach…Nextstatementis
ForEachComponentInSet
[Statement(s)] [ExitFor]
Next[Counter]
IntheprecedingsyntaxComponentisthevariableusedtorefertotheelementsofanarrayora collection.Setreferstoanarrayoranobjectcollection.
Forexample:
DimArr()asString={"Mon","Tues","Wed","Thurs","Fri","Sat"}
DimArrelementasString
ForEachArrelementinArr
MsgBox(Arrelement) NextInthisexample,ArrisanarrayoftypeStringthatstoresweekdays.Arrelementisa string.Here,theForEach…Nextstatementisusedtodisplayalltheelementsofthe arrayArr.
Unit IIChapter 8 :ProceduresChapter 9 :DialogBoxesChapter10:FileIOandSystemObjectsChapter11:DictionaryObjectChapt er12 :ErrorHandlingChapter13:NamespacesChapter14:ClassesandObjects
Chapter15:MultithreadingChapter16:COMInteropandMSMQ
Chapter8:Procedures
In This ChapterIntroductiontoproceduresFunctionstatementSubstatementBuilt-infunctionsinVB.NET
Procedures OverviewProcedurescontainalloftheexecutablecodeinyourapplication.ProcedureaccessmodifiersAprocedureiscreatedwithinaclassoramodule.Youcanalwayscallaprocedurefrom thesameclassormoduleinwhichitiscreated.However,youcancalltheprocedure fromdifferentclassesandmodulesdependingontheaccessmodifierusedwhilecreatingtheprocedure.Theaccessmodifiersdeterminethescopewithinwhichaprocedurecanbecalled.ThefollowingliststhevalidaccessmodifiersforallSubandFunctionprocedures:
Public:Proceduresthatcancalledfromanyclassormoduleinthe application.
Private:Proceduresthatcanbecalledonlyfromtheclassormodule wheretheyaredeclared. Shared:Proceduresthatarenotassociatedwithaninstanceofaclass. Protected:Proceduresthatcanbecalledfromtheclassormodule
wheretheyaredeclaredorfromthederivedclasses. Friend:Proceduresthatcanbecalledfromanyclassormoduleinthe
applicationthatcontainsitsdeclaration. ProtectedFriend:ProceduresthathavebothProtectedandFriend access.
Advantagesofprocedures
Asmentionedearlier,proceduresallowlogicalgroupingofcodeintotasks.Whena complexapplicationisdividedintoprocedures,thecodeismoreflexibleandeasierto maintainanddebug.Creatingprocedurestoperformasingletaskhasthefollowing benefits:
Thecodeinaprocedureisreusable.Afteraprocedureiscreatedandtested,itcanbecalledfromdifferentplacesinanapplication.
Theapplicationiseasiertodebugandmaintain,becauseyoucaneasily tracethesourceof anerrorina procedureinsteadof checkingtheentire applicationforerrors.
Types of ProceduresThetwotypesofprocedurescoveredinthischapterareSubproceduresandFunctionprocedures.
Subproceduresperformspecifictasks,suchasgeneratinganOrderIDor connectingtoadatabase.However,theseproceduresdonotreturnavalue tothecallingstatement.
last:Functionproceduresperformspecifictasksandreturnavaluetothecallingstatement.
SubproceduresYoucancreateaSubprocedureinmodulesandclasses.Thedefaultaccessmodifierfor SubproceduresisPublic,indicatingthatSubprocedurescanbecalledfromanywhere inanapplication.ThisistheexactoppositeofpreviousversionsofVisualBasic,where thedefaultaccessmodifierwasPrivate.ThesyntaxforcreatingaSubprocedureis
[<attrlist>][{Overloads|Overrides|Overridable| NotOverridable|MustOverride|
Shadows|Shared}]
[{Public|Protected|Friend|ProtectedFriend|Private
}]
Subname[(arglist)] [statements]
[ExitSub]
[statements] EndSub
Intheprecedingsyntax Overloadsindicatesthatthereareotherproceduresintheclasswith
thesamename,butwithdifferentarguments. Overridesindicatesthattheprocedurecan"override"anidentically
namedprocedureinthebaseclass. Overridableindicatesthattheprocedurecanbeoverriddenbyan
identicallynamedprocedureinaderivedclass. NotOverridableindicatesthatthisprocedurecannotbeoverriddenin
aderivedclass. MustOverrideindicatesthattheprocedureisnotimplementedinthe
classandmustbeimplementedinaderivedclassfortheclasstobe creatable.
[Public|Protected|Friend|ProtectedFriend| Private]representstheaccessmodifierfortheSubprocedure.Ifyou donotspecifyanyaccessmodifier,Publicisusedbydefault.
SubindicatesthattheprocedureisaSubprocedure. <ProcedureName>representsthenameoftheprocedure. ([Argumentlist])representsthelistofargumentstobepassedto theprocedure. EndSubindicatestheendoftheSubprocedure.
PublicSubCalculateDiscount(dblQuantity AsDouble,_
dblPriceAsDouble)
DimdblAmountAsDouble
DimdblDiscountAsDouble
dblAmount=dblQuantity*dblPrice
IfdblAmount>=150AnddblAmount<250Then dblDiscount=0.1
ElseIfdblAmount>=250Then dblDiscount=0.15
EndIf
TheSubMainprocedureTheSubprocedurethatisexecutedfirstwhenaVisualBasicprogramisrunistheMainprocedure.Thesyntaxofthisprocedureis
SubMain()
'Codehere
EndSubTheSubMainprocedureisthestartingpointofeveryapplication.EveryVisualBasic.NETapplicationmustcontainaSubMainprocedure.Youcanincludeanyinitialization codethatyoumighthaveintheSubMainprocedure,suchasconnectiontoadatabase orauthenticatingauser.
FunctionproceduresLikeSubprocedures,Functionprocedures(orfunctions),performaspecifictaskand arecreatedinclassesandmodules.However,unlikeSubprocedures,Function procedurescanreturnavalue.BecauseFunctionproceduresreturnavalue,youneed todefinethedatatypeforthereturnvaluewhilecreatingaFunctionprocedure.The syntaxforcreatingaFunctionprocedureis
[<attrlist>][{Overloads|Overrides|Overridable| NotOverridable|MustOverride|
Shadows|Shared}]
[{Public|Protected|Friend|ProtectedFriend|Private
}]Functionname[(arglist)][Astype][statements]
[ExitFunction] [statements]
EndFunction
Intheprecedingsyntax Overloadsindicatesthatthereareotherproceduresintheclasswith
thesamename,butwithdifferentarguments. Overridesindicatesthattheprocedurecan"override"anidentically
namedprocedureinthebaseclass. Overridableindicatesthattheprocedurecanbeoverriddenbyan
identicallynamedprocedureinaderivedclass. NotOverridableindicatesthatthisprocedurecannotbeoverriddenin aderivedclass. MustOverrideindicatesthattheprocedureisnotimplementedinthe
classandmustbeimplementedinaderivedclassfortheclasstobe creatable.
[Public|Protected|Friend|ProtectedFriend| Private]representstheaccessmodifierfortheSubprocedure.Ifyou donotspecifyanyaccessmodifier,Publicisusedbydefault.
FunctionindicatesthattheprocedureisaFunctionprocedure. <FunctionName>representsthenameoftheFunctionprocedure. ([Argumentslist])representsthelistofargumentstobepassedto
theFunctionprocedure.Theargumentscanbepassedbyvalueorby reference. [As<type>]representsthedatatypeofthereturnvalueofthe
Functionprocedure. ExitFunctionexplicitlyexitsafunction.Therecanbemorethanone
ExitFunctionstatementinafunction. EndFunctionindicatestheendoftheFunctionprocedure.
Built-in FunctionsVisualBasichasmanybuilt-infunctionsthatareveryusefulineasingyourdevelopment.
Inthissection,youlearnaboutthefunctionsandpropertiesinthefollowingnamespaces:Microsoft.VisualBasic.ConversionMicrosoft.VisualBasic.DateAndTimeMicrosoft.VisualBasic.Strings
Microsoft.VisualBasic.Conversion
TheMicrosoft.VisualBasic.Conversion namespacehandlesbasicconversionfunctions forstringsandnumbers.Forabroaderrangeofconversionfunctionality,includingtypes notallowedinVB.NET,referthetoSystem.ConvertnamespaceinthePlatformSDK.
ErrorToStringTheErrorToStringfunctionreturnsahuman-readablestringrepresentingthe numericerrornumberpassedtoit.WhenusingUnstructuredExceptionHandling,this willbethelastnumberreportedbynumberpropertyoftheerrobject.Inprevious versionsofVisualBasic,thesamefunctionalitywasprovidedbytheErrorfunction.
MessageBox.Show(ErrorToString(13))
'Returns"TypeMismatch"
FixandIntTheFixandIntfunctionsremovethefractionalpartofanumber.Forpositivenumbers,bothfunctionsbehavethesame;thefractionisremoved.Thereisnorounding ofnumbers.Thedifferenceiswhendealingwithnegativenumbers.TheIntfunction returnsthefirstnegativeintegerlessthanorequaltothenumber,whereastheFix functionreturnsthefirstnegativeintegergreaterthanorequaltothenumber.Dimx,yassingle
Y=-99.4
X=-99.4
Messagebox.showcstr(fix(y))'Returns-99
Messagebox.showcstr(int(x))'Returns-100Ifthenumberpassedtothefunctionswereapositive99.4,bothMessageboxfunctions wouldreturn99.
HexTheHexfunctionreturnsthestringrepresentationofthehexadecimalvalueofanumber. ThevaluepassedtotheHexfunctioncanbetheShort,Byte,Integer,Long,or Objectdatatype.
MessageBox.Show(Hex(10)) 'ReturnsA
MessageBox.Show(Hex(16)) 'Returns10
MessageBox.Show(Hex("T"))'Error-CannotpassaStringvalue
OctTheOctfunctionreturnsthestringrepresentationoftheoctalvalueofanumber.The valuepassedtotheOctfunctioncanbetheShort,Byte,Integer,Long,orObject datatype.
MessageBox.Show(Oct(10)) 'Returns12
MessageBox.Show(Oct(16)) 'Returns20
MessageBox.Show(Oct("T"))'Error-CannotpassaStringvalue
StrTheStrfunctionreturnsthestringrepresentationofanumber.Aleadingspaceis returnedtorepresentthesign.
MessageBox.Show(Str(10)) 'Returns"10" MessageBox.Show(Str(-10))'Returns"-10"
MessageBox.Show(Str("T"))'Error-CannotpassaStringvalue
ValTheValfunctionreturnsthenumberscontainedinastringasanumericvalueofthe typeIntegerorDouble,dependingonwhetherthereisadecimalplaceinthestring value.TheValfunctionevaluatesastringandstopsatthefirstcharacterthatcannotbe representedasanumberorspace.
MessageBox.Show(Val("123"))
'Returns123
MessageBox.Show(Val("123 4"))
'Returns"1234" MessageBox.Show(Val("123.4"))
'Returns"123.4"
MessageBox.Show(Val("123 4MainStreetSuite194"))
'Returns"1234"
Microsoft.VisualBasic.DateAndTime
TheMicrosoft.VisualBasic.DataAndTime namespacecoverseverythingyoucouldever needtoaccomplishwhenmanipulatingdatesandtimes.Thisnamespaceisvery comprehensiveindateandtimefunctionality.
DateAddTheDateAddfunctionreturnsadatevaluetowhichatimeintervalhasbeenadded.TheDateAddfunctioncontainsthreeparts:
Interval:TheDateIntervalenumerationvalueorstring equivalentrepresentingthetypeofintervalyouareadding.
Number:PositiveornegativeDoubledatatyperepresentingthenumberofintervalsyouareadding.
DateValue:Thedateexpressionrepresentingthedateandtimeto whichtheintervalisadded.
Table8-2:DateIntervalEnumeration
Value String IntervalAdded
DateInterval.Day D Day(integer)
DateInterval.DayOfYear Y Day(integer)
DateInterval.Hour H Hour rounded
DateInterval.Minute N Minute rounded to nearest millisecond
DateInterval.Month M Month(integer)
DateInterval.Quarter Q Quarter(integer)
DateInterval.Second S Second rounded to nearest millisecond
DateInterval.Weekday W Day(integer)
DateInterval.WeekOfYear www Week(integer)
DateInterval.Year yyyy Year(integer)
DimretAsDate
ret=DateAdd(DateInterval.Day, 5,#1/1/2001#)
'Returns1/6/200112:00:00AM
ret=DateAdd(DateInterval.Quarter, 2,#1/1/2001#)
'Returns7/1/200112:00:00AM
ret=DateAdd(DateInterval.Year, 25,#1/1/2001#)
'Returns1/1/202612:00:00AM
DateDiffTheDateDifffunctionreturnsalongvaluerepresentingthenumberoftimeintervals specifiedbetweentwodatevalues.TheDateDifffunctionhasthefollowingfour arguments:
Interval:DateIntervalenumerationvalueorstringexpression representingtheunitoftimebetweenthedate1anddate2values. Table8 - 2liststhevaluesoftheDateIntervalenumeration.
Date1,Date2:Thedateandtimevaluesusedinthecalculation.This firstdatevalueissubtractedfromtheseconddatevalue.
DayOfWeek:AnoptionalvaluefromtheFirstDayOfWeek enumerationthatspecifieswhatdaytouseasthefirstdayofthe week.ThedefaultvalueisSunday.Table 8 - 3 liststhevaluesofthe FirstDayOfWeekenumeration.
WeekOfYear:AnoptionalvaluefromtheFirstWeekOfYearenumerationthatspecifiesthefirstweekoftheyear.Thedefaultvalue isJan1.Table8 - 4liststhevaluesoftheWeekOfYearenumeration.
Table8-3:FirstDayOfWeekEnumeration
Enumeration Value Description
FirstDayOfWeek.System 0 Firstdayof theweekas specifiedin thesystem settingsin thecontrol panel.
FirstDayOfWeek.Sunday 1 Sunday
FirstDayOfWeek.Monday 2 Monday
FirstDayOfWeek.Tuesday 3 Tuesday
FirstDayOfWeek.Wednesday 4 Wednesday
FirstDayOfWeek.Thursday 5 Thursday
FirstDayOfWeek.Friday 6 Friday
FirstDayOfWeek.Saturday 7 Saturday
Table8-4:WeekOfYearEnumeration
EnumerationValue Value Description
FirstWeekOfYear.System 0 Firstweek oftheyear asspecified inthe system settingsin thecontrol panel.
FirstWeekOfYear.Jan1 1 Theweekin which January1st occurs.
FirstWeekOfYear.FirstFourDays 2 Thefirst weekthat hasatleast fourdaysin thenew year.
FirstWeekOfYear.FirstFullWeek 3 Thefirstfullweekofthe year.
DimretAsLong
ret=DateDiff(DateInterval.Day, #1/1/1970#,Now)
'Returns11575
ret=DateDiff(DateInterval.Year, #1/1/1970#,Now)
'Returns31
ret=DateDiff(DateInterval.Second, #1/1/1970#,Now)
'Returns1000108077
ret=DateDiff(DateInterval.Day, #1/1/1970#,Now,_ FirstDayOfWeek.Monday,_
FirstWeekOfYear.FirstFourDays)
'Returns11575
DatePartTheDatePartfunctionreturnsanintegervaluerepresentingtherequestedpartofa date.TheDatePartfunctiontakesfourarguments:
Interval:DateIntervalenumerationvalueorstringexpression representingtheunitoftimeyouarerequesting.Table8 - 2 liststhe valuesoftheDateIntervalenumeration.
DateValue:Thedateandtimevalueusedinthecalculation. DayOfWeek:AnoptionalvaluefromtheFirstDayOfWeek
enumerationthatspecifieswhatdaytouseasthefirstdayofthe week.ThedefaultvalueisSunday.Table 8 - 3 liststhevaluesofthe FirstDayOfWeekenumeration.
WeekOfYear:AnoptionalvaluefromtheFirstWeekOfYearenumerationthatspecifiesthefirstweekoftheyear.Thedefaultvalue isJan1.Table8 - 4liststhevaluesoftheWeekOfYearenumeration.
DimretAsInteger
ret=DatePart(DateInterval.Day, #1/1/1970#)
'Returns1
ret=DatePart(DateInterval.Year, #1/1/1970#)
'Returns1970
DateSerialTheDateSerialfunctionreturnsadatevaluerepresentingtheyear,month,andday. Thetimevalueissetto00:00.TheDateSerialfunctionhasthreerequiredarguments:
Year:Integervaluerangingfrom1to9999.InWindows98and greater,thetwo-digitvalues00through29areconsideredtheyear2000throughtheyear2029,andthetwo-digitvalues30through99 areconsidered1930through1999.Forallotheryearvalues,youshouldalwaysusethefour-digityearvalue.Tobesafe,youshould alwaysusethefour-digityearvalue.
Month:Integervaluerangingfrom1to12.Ifthemonthvalueis outsideofthisrange,themonthvalueisoffsetby1andappliedto Januaryofthecalculatedyear,whichisrecalculatedifnecessary.
Day:Integervaluerangingfrom1to31.Ifthedayvalueisoutsideofthisrange,thedayvalueisoffsetby1andappliedtothefirstdayof thecalculatedmonth,whichisrecalculatedifnecessary.
DateStringTheDateStringpropertyreturnsorsetsastringvaluerepresentingthecurrentdateon yoursystem.
Console.WriteLine(DateString())
'Returns09-07-2001
DayTheDayfunctionreturnsanintegervaluerangingfrom1to31representingthedayof
themonthofthedatepassed.TheDayfunctionhasonerequiredargument: DateValue:Datevaluefromwhichyouwanttoextracttheday.
DimintDayAsInteger intDay=Day("1/15/01") 'Returns15 intDay=Day("Jan152001")
'Returns15
HourTheHourfunctionreturnsanintegervaluerangingfrom0to23representingthehourof theday.TheHourfunctionhasonerequiredargument:
TimeValue:Thedatevaluefromwhichyouwanttoextractthehour.
DimdAsDate DimintHourAsInteger d=#1/15/20011:45:00PM# intHour=Hour(d)
'Returns13
Microsoft.VisualBasic.Strings
TheMicrosoft.VisualBasic.Stringsnamespacehandlesstringmanipulationand formatting.Fromsimpleupper-to-lowercaseconversiontomorecomplexjoiningand splittingofstrings,thenamespaceisextremelycomprehensive.
ASCTheASCfunctionreturnstheintegercharactercodevalueofthefirstletterinastring. Messagebox.ShowASC("A")
'Returns97
Messagebox.ShowASC("a")
'Returns65
ChrTheChrfunctiontakesanANSIvalueandconvertstoastringcontainingthecharacter code.
Messagebox.ShowChr(65)
'ReturnsA
Messagebox.ShowASC(97)
'Returnsa
FilterTheFilterfunctionreturnsazero-basedarraycontainingasubsetofastringarray basedonspecifiedfiltercriteria.TheFilterfunctionhasfourarguments:
Source:Arequiredone-dimensionalarrayofstringstobesearched. Match:Arequiredstringtosearchfor. Include:AnoptionalBooleanvalueindicatingwhethertoreturn
substringsthatincludeorexcludeMatch. Compare:Anoptionalnumericvalueindicatingthekindofstring
comparisontouse.TheCompareMethod.Binaryor CompareMethod.Textconstantscanbepassedtoindicateatextor binarymatchonthematchstring.
DimintXAsInteger DimstrArr(2)AsString
strArr(0)="We" strArr(1)="were"
strArr(2)="Relaxing"
GetCharTheGetCharfunctionreturnsacharvaluerepresentingthecharacterfromthespecified indexinthesuppliedstring.TheGetCharfunctionhastwoarguments:
Str:Arequiredstringexpression. Index:Arequiredintegerexpression.The(1-based)indexofthe characterinStrtobereturned.
DimstrInAsString="Mr.Spock"
Console.Writeline(GetChar(strIn,6))
'Return"p"
InStrTheInStrfunctionreturnsanintegerspecifyingthestartpositionofthefirstoccurrence ofonestringwithinanother.TheInStrfunctionhasfourarguments:
Start:Anoptionalnumericexpressionthatsetsthestartingpositionforeachsearch.Ifomitted,searchbeginsatthefirstcharacter position.Thestartindexis1-based.
String1:Thestringexpressionbeingsearched. String2:Thestringexpressionsought. Compare:Anoptionalsettingindicatingwhethertodoatextual-or binary-basedsearch.
DimstrSearch,strCharAsString
'Stringtosearchin.
strSearch="AaAaBbBbCcDdEe"
'Stringtoseachfor strChar="a"
'Atextualcomparisonstartingatposition1
Console.WriteLine(InStr(1, strSearch,strChar, CompareMethod.Text))
'Returns1
'Abinarycomparisonstartingatposition1
Console.WriteLine(InStr(1, strSearch,strChar,
CompareMethod.Binary))
'Returns2ThereturnvaluefromtheInStrfunctionreturnsazeroif
String1iszerolength String2isnotfound StartisgreaterthanString2
JoinTheJoinfunctionreturnsastringcreatedbyjoininganumberofsubstringscontainedin anarray.Joinhastwoarguments:
SourceArray():Arequiredone-dimensionalarraycontaining substringstobejoined. Delimiter:Anoptionalstringusedtoseparatethesubstringsinthe
returnedstring.Ifomitted,thespacecharacterisused.IfDelimiter isazero-lengthstring,theitemsinthelistareconcatenatedwithno delimiters.
DimstrArr(7),strOutAsStringstrArr(0)="You" strArr(1)="are"
strArr(2)="the" strArr(3)="finest"
strArr(4)="crew" strArr(5)="inthe"
strArr(6)="fleet"
strOut=Join(strArr,"~") Console.WriteLine(strOut)
'ReturnsYou~are~the~finest~crew~in the~fleet~
LCaseTheLCasefunctionconvertsastringtolowercase.
Console.Writeline(LCase("THIS ISCOOL"))
'Returns"thisiscool"
LeftTheLeftfunctionreturnsastringcontainingaspecifiednumberofcharactersfromthe leftsideofastring.TheLeftfunctionhastwoarguments:
Str:Arequiredstringexpressionfromwhichtheleftmostcharacters arereturned. Length:Arequiredintegerexpressionindicatinghowmany characterstoreturn.If0,azero-
lengthstringisreturned.Ifgreater thanorequaltothenumberofcharactersinStr,theentirestringis returned.
DimstrIn,strOutAsString
strIn="C:\MyDocuments\Document1.Doc" strOut=
Microsoft.VisualBasic.Left(strIn, 5) Console.WriteLine(strOut)
'Returns"C:\My"
Len
TheLenfunctionreturnsanintegercontainingeitherthenumberofcharactersinastring orthenumberofbytesrequiredtostoreavariable.
DimstrIn,strOutAsString
strIn="C:\MyDocuments\Document1.Doc" strOut=Len(strIn)
Console.WriteLine(strOut)
'Returns29
LSet,RSetTheLSetandRSetfunctionspadeithertheleftorrightsideofastring. DimstrInAsString="Left"
Console.WriteLine("~"&LSet(strIn,10)&"~")
'Returns~Left ~strIn="Right"
Console.WriteLine("~"&RSet(strIn,10)&"~")
'Returns~ Right~
LTrim,Trim,RTrimThesefunctionsreturnastringcontainingacopyofaspecifiedstringwithnoleading spaces(LTrim),notrailingspaces(RTrim),ornoleadingortrailingspaces(Trim).
DimstrInasString=" ThisisThat "
Console.Writeline(Trim(strIn))
'Returns"ThisisThat"
Console.Writeline(LTrim(strIn))
'Returns"ThisisThat "
Console.Writeline(RTrim(strIn))
'Returns" ThisisThat"
MidTheMidfunctionreturnsastringcontainingaspecifiednumberofcharactersfroma string.TheMidfunctionhasthreearguments:
Str:Thestringexpressionfromwhichcharactersarereturned. Start:A1-basedintegerrepresentingthepositioninStratwhich
theparttobetakenstarts.IfStartisgreaterthanthenumberof charactersinStr,theMidfunctionreturnsazero-lengthstring.
Length:Anoptionalintegerexpressionindicatingthenumberof characterstoreturn.IfomittedoriftherearefewerthanLength charactersinthetext(includingthecharacteratpositionStart),all charactersfromthestartpositiontotheendofthestringarereturned.
Console.WriteLine(Mid("USS Voyager",5))
'Returns"Voyager"
StrCompTheStrCompfunctionreturns–1,0,or1(see Table 8 - 7 ),basedontheresultofastring comparison.Thestringsarecomparedbyalphanumericsortvaluesbeginningwiththe firstcharacter.TheStrCompfunctionhasthreearguments:
String1:Anyvalidstringexpression. String2:Anyvalidstringexpression. Compare:Anoptionalnumericvalueindicatingwhethertousea textualorbinarycompare.
Dimstr1AsString="THEYARETHESAME"
Dimstr2AsString="theyarethesame"
Console.WriteLine(StrComp(str1, str2,CompareMethod.Text))
'Returns0
Console.WriteLine(StrComp(str1, str2,CompareMethod.Binary))
'Returns-1
UCaseTheUCasefunctionconvertsastringtouppercase. Messagebox.show
UCase("enterprise nx-01")
'ReturnsENTERPRISENX-01
Chapter9:DialogBoxesIn This Chapter
IntroductiontodialogboxesTheMessageBoxclassTheMsgBoxfunctionTheInputBoxfunctionTheCommonDialogclass
Introduction to Dialog BoxesAdialogboxaddsinteractivitytoyourapplication.Youcanuseadialogboxtoaccept somevaluefromauser,displaysomeerrormessagetoauser,orperformsome input/outputoperation,suchasopening,saving,orprintingafile.Adialogboxissimplya formwithitsownsetofcontrols,suchaslabels,textboxes,andbuttons.However,unlikeformsyoucannotresizeadialogbox.Youcancreateyourowndialogboxesorusethestandarddialogboxes.Dialogboxesareoftwotypes,modalandmodeless.
Amodaldialogboxmustbeclosedbeforeyoucancontinueyourworkwith thesameapplicationorswitchtoanotherapplication.Amodaldialogbox canbefurtherclassifiedintotwotypes,applicationmodaland systemmodal.
o Anapplicationmodaldialogboxdoesnotallowtheuserto continueworkinginthesameapplicationbeforeclosingthe dialogbox.However,theusercanswitchtoother applications.
o Asystemmodaldialogboxdoesnotallowtheusertowork inanyapplicationbeforeclosingthedialogbox.
Amodelessdialogboxallowsuserstoswitchbetweenapplicationsor continuetoworkwiththerestoftheapplicationwithoutclosingthedialog box.
.NETprovidestheCommonDialogclasstodisplaythestandarddialogboxes,suchastheOpen,Save,andPrintdialogboxes.ItalsoprovidestheMessageBoxclasstodisplayamessagetotheuser.Inaddition,VB.NETprovidestheMsgBoxfunctiontodisplayamessagebox.
The MessageBox ClassYouhaveseenanumberofmessageboxesinanapplication.Thesemessageboxes areusedtodisplayanerrormessageortheresultofacalculation,orprovidetipsand warnings.Theycanalsobeusedforconfirmingoperations,suchasconfirmingthe deletionofafile.Tocarryouttheseoperationsefficiently,themessageboxprovidesthe userwithdifferentbuttons,suchasOK,Cancel,Yes,andNo.YoutoocandisplaymessageboxesinyourapplicationsbyusingtheMessageBoxclass.Thismessagecancontaintext,buttons,andicons.
TheShowmethodYouusetheShowmethodoftheMessageBoxclasstodisplayamessagebox.This methodexistsintwelvedifferentforms.Theseformsdifferfromeachotheronthebasis oftheparameterspassedineachform.Lookatalltheseforms:
MessageBox.Show(Text) MessageBox.Show(Owner, Text) MessageBox.Show(Text, Caption) MessageBox.Show(Owner, Text,Caption)
MessageBox.Show(Text, Caption,Buttons) MessageBox.Show(Owner, Text,Caption,Buttons) MessageBox.Show(Text, Caption,Buttons,Icon) MessageBox.Show(Owner, Text,Caption,Buttons,Icon) MessageBox.Show(Text, Caption,Buttons,Icon,
DefaultButton) MessageBox.Show(Owner, Text,Caption,Buttons,Icon,
DefaultButton) MessageBox.Show(Text, Caption,Buttons,Icon,DefaultButton,
Options) MessageBox.Show(Owner, Text,Caption,Buttons,Icon,
DefaultButton,Options)
InalltheprecedingvariationsoftheMessageBox.Showmethod: Ownerspecifiesthewindowinfrontofwhichthemessageboxwillbe displayed. Textisthemessagetobedisplayedinthemessagebox. Captionisthetexttobedisplayedinthetitlebarofthemessagebox. Buttonsspecifiesthebuttonstobedisplayedinthemessagebox.You
usetheMessageBoxButtonsenumerationtospecifythebuttons.An enumerationisalistofconstants. Iconspecifiestheiconstobedisplayedinthemessagebox.Youuse
theMessageBoxIconenumerationtospecifytheicon. DefaultButtonspecifiesthedefaultbuttonforthemessagebox.You
usetheMessageBoxDefaultButtonenumerationtospecifythe defaultbutton.
Optionsspecifiesthedisplayandassociationoptionsforthemessage box.YouusetheMessageBoxOptionsenumerationtospecifythe options.
ThefollowingstatementdisplaystheuseoftheShowmethod:
MessageBox.Show("Hello World","Sample")ThisstatementdisplaysamessageboxwiththemessageHelloWorld.Sampleis displayedinthetitlebarofthemessagebox.
TheMessageBoxButtonsenumerationTheMessageBoxButtonsenumerationcontainsconstantsthatareusedtospecifythe buttonsforthemessagebox.SomeofthecommonlyusedconstantsareOK,OKCancel, YesNo,andYesNoCancel.Considerthefollowingstatementtounderstandtheusageof theMessageBoxButtonsenumeration:
MessageBox.Show("HelloWorld","Sample",
MessageBoxButtons.OKCancel)
Table9-1:MessageBoxButtons EnumerationConstants
Constant UsedTo
OK Display onlytheOKbutton.
OKCancel Display theOK and Cancel button s.
AbortRetryIgnore Display the Abort, Retry, and Ignore buttons.
YesNoCancel Display theYes,No, and Cancel buttons.
YesNo Display theYesandNo buttons.
RetryCancel Displaythe Retry and Cancel buttons
TheMsgBoxfunctionTheMsgBoxfunctionisasharedmemberofthe Microsoft.VisualBasic._Interactionclass.TheInteractionclasscontains proceduresandmethodsthatareusedtointeractwithobjects,applications,andsystems.Becauseitisasharedmember,youcanusetheMsgBoxfunctiondirectlylikeasystemfunction,aswasusedinpreviousversionsofVisualBasic,orbyspecifyingthe completeclasshierarchy.Thefollowingcodewillhelpyouunderstandthisbetter.
Microsoft.VisualBasic.Interaction.MsgBox("HelloWorld")
issimilarto, MsgBox("HelloWorld")TheMsgBoxfunctiontakesthreeparameters:themessagetobedisplayed,aconstant representingthebuttonsandiconstobedisplayed,andthetitleofthemessagebox. TheMsgBoxfunctionreturnsanintegervalue,whichcorrespondstothebuttonclicked bytheuser.Thesyntaxis
DimretValueasInteger
retValue=MsgBox(sMessage,[nConst],[sTitle])
Intheprecedingsyntax sMessageisthemessagetobedisplayed.Itcancontainupto1,024 characters. nConstisanumericornamedconstantusedtospecifythenumberand
typeofbuttons,icontobedisplayed,defaultbutton,andmodalityofthe messagebox.Todoso,youusetheMsgBoxStyleenumeration. Actually,allthepreviouslymentioneditems,suchasbuttonsandicons, arerepresentedbyanumberandthisparametercontainsthesumofall thesenumbers.Youcanalsousenamedconstantstospecifythis.This parameterisoptional.Ifyouskipit,onlytheOKbuttonisdisplayedinthe messagebox.
sTitleisthestringusedasatitleforthemessagebox.Thisparameter is alsooptional.If youskipthisparameter,thenameof theapplicationis displayedinthetitlebarofthemessagebox.
retValueisanintegerthatcontainsthevalueofthebuttonclickedby theuser.Youcanusethistotrapthebuttonclickedbytheuser.Youcan usetheMsgBoxResultenumerationtotrapthesevalues.
TheInputBoxFunctionTheInputBoxfunctionisasharedmemberofthe Microsoft.VisualBasic._Interactionclass.LiketheMsgBoxfunction,the InputBoxfunctioncanalsobeuseddirectlylikeasystemfunctioninsteadofspecifying thecompleteclasshierarchy.
Microsoft.VisualBasic.Interaction.InputBox("Enteryourname")
Theprecedingstatementissimilartothefollowingstatement: InputBox("Enteryourname")YouusetheInputBoxfunctiontoacceptavaluefromtheuser.Itreturnsthevalue enteredbytheuser.Thesyntaxis
InputBox(sPrompt,[sTitle],[sDefaultValue],[nX],[nY])
Intheprecedingsyntax sPromptistheprompttobedisplayedtotheuser.Itcanholda maximumof1,024characters. sTitleisthetexttobedisplayedinthetitlebaroftheinputbox.Itis
optional.Ifyouskipit,thenameoftheapplicationisdisplayedinthetitle bar. sDefaultValueisthevaluedisplayedinthetextbox(containedinthe
inputbox)asthedefaultvalue.It is optionalandif youomitit, anempty textboxisdisplayed. nXisthehorizontaldistancebetweentheleftedgeoftheinputboxand
theleftofthescreen.Itisoptional.Ifyouomitthisparameter,theinput boxisdisplayedinthehorizontalcenterofthescreen.
nYistheverticaldistancebetweenthetopedgeofthedialogboxandthetopofthescreen.Itisoptional.Ifyouskipthisparameter,theinput
boxisdisplayedatapositionapproximatelyone-thirdofthewaydown thescreen.TounderstandtheusageoftheInputBoxfunction,considerthefollowingexample: DimsVar,sResultAsString
sVar="Entertheusername"
sResult=InputBox(sVar,"Logon","User",50,50) YoucanseetheoutputofthiscodeinFigure 9 - 3 .
Figure9-3: ThesampleoutputIntheprecedingexample,theapplicationpromptstheuserfortheusername.Theinput boxcontainsLogoninitstitlebarandthevalueUserisdisplayedinthetextbox,by default.
Ifyoudonotspecifyanyoftheoptionalparameters,youneedtoretainthe correspondingdelimiter(thatis,comma).Forexample:
DimsVarAsString
sVar=InputBox("Entertheusername","Logon",,50,50)Intheprecedingexample,thedefaultvalueisnotspecifiedintheInputBoxfunction. However,thecorrespondingdelimiter(,)isspecified.Youcanseetheoutputofthis exampleinFigure9 - 4 .
Figure9-4: Thesampleoutput
The CommonDialog ClassFileDialog
ColorDialogFontDialogPageSetupDialog
PrintDialog
Thedetailsoftheseclassesarediscussedinthefollowingsections.
TheFileDialogclassTheFileDialogclassisusedtohandlefileoperations,suchasopeningandsavinga file.Thisclassdisplaysadialogboxfromwhichtheusercanselectafile.Thedialogbox shownbytheFileDialogclassisamodaldialogbox.TheFileDialogclassfurtherconsistsoftheOpenFileDialogclassandthe SaveFileDialogclassesthathelpyoutodisplayOpenandSavedialogboxes, respectively.
TheOpenFileDialogclassTheOpenFileDialogclassprovidesyouthestandardOpendialogboxprovidedby Windows.Youusethisdialogboxtoprovideuserswiththefileselectioncapability.The OpenFileDialogclassprovidesvariouspropertiesandmethodstomanipulatethe Opendialogbox.Table9 - 4describessomeofthepropertiesandmethodsofthe OpenFileDialogclass.
Table9-4:OpenFileDialogClassPropertiesandMethods
PropertyOrMethod Description
Table9-6:ColorDialogclassPropertiesandMethods
PropertyOrMethod
Description
ShowDialog Displaysthe dialogbox.
Color Determines thecolor selectedby theuser.
AllowFullOpen Determines whetherthe usercan addcustom colorstothe dialogbox.
SolidColorOnly Determines whether the usercan usedithered colors.
ShowDialog Displaysthe dialogbox.
Multiselect Determines whetherthe dialogbox allows selecting multiple files.
Table9-4:OpenFileDialogClassPropertiesandMethods
PropertyOrMethod Description
ShowReadOnly Determines whetherthe dialogbox displaysa read-only checkbox.
ReadOnlyChecked Determines whetherthe read-only checkboxis checked.
Filter Determines the typesof files that will appearinthe"FilesofType"boxin thedialog box.
FilterIndex Determines theindexof thefilter selectedin thedialog box.
TheSaveFileDialogclassTheSaveFileDialogclassoffersyouthestandardSavedialogboxprovidedby Windows.Youusethisdialogboxtoprovideuserswithfile-savingcapability.The SaveFileDialogclassprovidesyouwithmethodstomanipulatethisdialog.Table9 -5describessomeofthepropertiesandmethodsoftheSaveFileDialogclass.Table9-5:SaveFileDialogClassPropertiesandMethods
PropertyOrMethod Description
ShowDialog Displaysthe message box.
CheckFileExists Determines whetherthe filespecified bytheuser exists.
FileName Determines thefilenameselectedby theuserin thedialog box.
Filter Determines the typesof files that will appearinthe "Saveas fileType"boxinthe dialogbox.
FilterIndex Determines theindexof thefilter selectedin thedialog box.
Figure9-6: AsampleSaveAsdialogboxTheColorDialogclassTheColorDialogclassprovidesadialogboxthatallowstheusertoselectacolorfrom thepaletteandtoaddcolorstothatpalette.Table 9 - 6 describessomeoftheproperties andmethodsoftheColorDialogclass.
Table9-7:FontDialogClassPropertiesandMethods
PropertyOrMethod Description
ShowDialog Displaysthe dialogbox.
Color Determines fontcolor selectedby theuser.
Font Determines thefont, style,size, script,and effects.
Figure9-7: AsampleColordialogbox
TheFontDialogclassTheFontDialogclassprovidesadialogboxthatallowsyoutoalterthefont,fontstyle, andsize.Thisdialogboxdisplaysthecurrentlyinstalledfontsonyoursystem.Table9 - 7describessomeofthepropertiesoftheFontDialogclass.
Figure9-8: AsampleFontdialogbox
ThePageSetupDialogclassThePageSetupDialogclassdisplaysadialogboxthatyoucanusetomanipulatepagesettings,suchasmarginsandorientationsandtheprintersettingsofadocument.ThepagesettingsofasinglepagearerepresentedbythePageSettingsclass.The informationforprintingadocumentisrepresentedbythePrinterSettingsclass.The PrinterSettingsclasscanalsomanipulatethesettingsoftheprinterusedforprintingthedocument.Table9 - 8 describessomeofthepropertiesandmethodsofthePageSetupDialogclass.
Table9-8:PageSetupDialogClassPropertiesandMethods
PropertyOrMethod Description
ShowDialog Displaysthe dialogbox.
AllowMargins Determines whetherthe margins sectionof thedialog boxis enabled.
AllowOrientations Determines whetherthe orientation sectionof thedialog boxis enabled.
AllowPaper Determines whetherthe paper sectionofthedialog boxis enabled.
Document Determines the documentto getpage settings from.The PrintDocumentclass definesanobjectthatisusedtosendoutput toaprinter.
Figure9-9: AsamplePageSetupdialogbox
Chapter12:ErrorHandlingIn This Chapter
IntroductiontoerrorhandlingTypesoferrorsTry…Catch…FinallyOnErrorGoto
Errors in ProgrammingWhenwritingcode,thereareseveraltypesoferrors,orexceptions,thatcanoccur. DependingonhowyourVisualStudio.NETenvironmentissetup,theseerrorsmayor maynotgetcaught.Table1 2 - 1liststhetypesoferrorsthatcanoccur.Table12-1:TypesofErrors
Type Reason
SyntaxErrors Misspelled keywords or variables. TheVB.NET compiler will normally catch these
Table12-1:TypesofErrors
Type Reasonerrors whileyou are coding, butyou have control overhow much checking youwanttheIDEto do.
LogicErrors Code doesnot actas expected because ofaflaw inthe logicyou have applied.
RuntimeErrors Occur onceyour applicatio nisinproduction.The resultof not handling anunexpectederror.
Figure12-1: ErrornotificationusingOptionExplicitOptionStrictisanotherproject-levelsettingthatcanhelpyouavoiderrors.With OptionStrictsettoON,theIDEwillnotifyyouifthedataconversionyouare attemptingisillegal.Forexample,ifyouaremultiplyingnumbersandthosenumbersare greaterthantheamountallowedforthevariableyouhavedeclared,thecompilerwilllet youknow.Figure12 - 2showstheerrorthatwilloccurifyouattempttosetthevalueofan arithmeticoperationusingashortdatatypetoholdanon-integralnumber.
Figure12-2: OptionStricterrornotificationStructured Exception HandlingNowthatyouhaveagraspofthetypesoferrorsthatcanoccur,youneedtoknowhow totraperrorsthattheIDEdoesnotcatch.Afterall,itcannotdoeverythingforyou.A typicalscenarioforcatchingerrorsmightbecodethataskstheusertoopenafile.Your programwillpopupabox,andtheuserwillhavetotypeinafilename.Ifthefiledoes notexist,orpossiblyitwasmisspelled,yourapplicationwillhavetoreacttothat somehow.Ifyouarenottrappingforexceptions,aruntimeerrorwilloccur,andyour applicationwillcrash.TrappingerrorsinVisualBasicwasalwaysdonewiththeOn ErrorGotostatement.Youwillseethatlaterinthechapter,butnowyouneedtolook atanewandbetterwaytohandleerrors.UsingtheTry…EndTryblocksofStructured ExceptionHandling,youhaveamoreobject-orientedapproachtohandleerrors.The followingcodedemonstratesourFile
Openscenario:
PrivateSubButton1_Click(ByValsenderAsSystem.Object,_
ByValeAsSystem.EventArgs)HandlesButton1.Click
GetFileName(Textbox1.Text) EndSub
PrivateFunctionGetFileName(ByValstrNameAsString)As
String
Try
IfstrName<>""Then
Table12-2:ExceptionClassProperties
Property Description
HelpLink Getsorsets thelocation ofthehelp file associated withthe exception.
HResult Getsorsets HRESULT, acoded numerical valuethatis assignedto aspecific exception.
Return"EverythingisOK" EndIf
Catch
Return"Pleaseenteravalidfilename" Finally
'Dosomecleanupcode
EndTry
EndFunctionYouwillnoticeseveralnewthingshere;theTry…EndTryblock,theCatchstatement, andtheFinallystatement.ThisisthebackboneofStructuredExceptionHandling.
Exceptions.NETruntimehandlesexceptionsandthewaypreviousVBversionshandlederrorsareasfollows:
Exceptionscancrossprocessboundariesandmachineboundaries. Exceptionsarehandledthesamewayregardlessofwhatlanguagethe
applicationwaswritteninorwhatlanguagetheexceptionwillbehandled in. ExceptionsarebasedontheSystem.Exceptionclass. Exceptionscanbetracedtotheoffendingprocedureandlineofcodein
thecallingchainusingtheStackTraceproperty.
Table12-2:ExceptionClassProperties
Property Description
InnerException Getsa referenceto theinner exception.
Message Getsthe string representationofthe error message associated withthe exception.
Source Getsorsets thenameof the application orobjectthatcausedthe exception.
StackTrace Getsthe stacktrace identifying thelocation inthecode wherethe exception occurred.
TargetSite Getsthe methodthat threwthe exception.
Try…Catch…FinallyKnowingthatexceptionswillhappenisonething,butknowingwhattodowhenthey appearisanother.InStructuredExceptionHandling,youusetheTry…Catch…Finally blocktohandleexceptions.Whenreadingtheonlinehelp,theTry…Catch…Finally blockwillappearunder"HandlingProgramFlow,"orsomethingsimilar.Thisistrue becauseyouareactuallycontrollingtheflowofyourprocedureswhileimplementing exceptionhandling.Herearetherulesforhandlingexceptionswith Try…Catch…Finally:
CodethatcancauseanexceptionshouldbeplacedinaTry…EndTryblock.
WithintheTry…EndTryblock,youwriteoneormoreCatchblocksthatrespondtoexceptionsthatmayoccurintheTryblock,attemptingto handletheexception.
Ifyouwantcodetoalwaysexecute,regardlessofanexception,youwritecodeinaFinallyblock.
Chapter13:NamespacesIn This Chapter
NamespacesWritingnamespacesCommonnamespaces
Introduction to NamespacesNamespacesallowclassestobecategorizedinaconsistent,hierarchicalmanner.The.NETFrameworkiscomprisedofhundredsofnamespacesthatallderivefromthebase classSystem.Anamespaceisessentiallyaphonebookforfunctionalityinthe frameworkandiscomprisedoftypesthatyouuseinyourapplications.Thetypescanbe classes,enumerations,structures,delegates,orinterfaces.
Theconventionfornamingnamespacesisasfollows:Thefirstpartofthenamespace,uptotheright-mostdot,isthenameofthe namespace.Thelastpartofthenamespacenameisthetypename.
Ifyouneedtoperformdataaccess,youwouldlooktotheSystem.Datanamespace.To accessSQLServer-specificfunctionality,youwouldreferencethe System.Data.SQLClientnamespace.Touseanamespaceinyourapplication,youusetheImportsstatementattheverytopofyourclassfile.EachImportsstatementdefinesthenamespacesforthatspecificfile; ifyouneedtouseSystem.Datainmorethatonclassfile,youmustspecifyitineach classfile.Anamespacecancontainclasses,structures,enumerations,delegates,interfaces,and othernamespaces.Namespacescanalsobenested,meaningthatanamespacecalled BcanbeinsideanamespacecalledA,andeachnamespacecanhaveanynumberof members.ThefollowingcouldrepresenttheSystemnamespace.NoticehowtheIO namespaceisnestedwithinSystem.
NamespaceSystem
NamespaceIO
PublicClassFileStream
'Functionsthat
'implementstreamIO EndClass
EndNamespace
EndNamespace
Intheclientcode,youwouldreferencethisnamespacelikethis: ImportsSystem.IO
ClassClass1
SubNew()
DimfsasnewFileStream
EndSub
EndClass
Creating NamespacesTocreateanamespace,youusetheNamespace…EndNamespaceblock.Withinthe namespaceblock,youcreateclasses,enumerations,structures,delegates,interfaces, orothernamespaces.Youdonothavetoincludeallofyourcodeinasingle,physical file.Anamespacecanspanmultiplefiles,andevenmultipleassemblies.Thismakesit easyformanydeveloperstobuildasingleapplicationusingthesamenamespace.Forexample,ifyouarewritingabook,andthebookhaslotsofsourcecode,youmaydecide togivethenamespacethesamenameasyourbook.Thenamespaceyouwillbuildhere willbecalledVBBible.Itwilllooklikethis:
NamespaceVBBible
EndNamespace
Namespace ReferenceComponentmodelSystem.ComponentModel—Licensinganddesigntimeimplementationofcomponents.
DataSystem.Data—Dataaccess
System.Data.SQLClient—SQL Serverdataaccess System.Data.OLEDB—OLE DBdataaccess System.Data.XML—XMLProcessing System.XML.Serialization—BidirectionalobjecttoXMLmapping
ServicesSystem.Diagnostics—Provides debuggingandtracingservices System.DirectoryServices—ActiveDirectoryprovider System.Messaging—Microsoft MessageQueuemanagement System.ServiceProcess—Servicestoinstallandrunservice-basedapplications
NetworkingSystem.Net—Programmable accesstonetworkprotocolsSystem.Net.Sockets—Managed accesstoWindowsSockets
GUISystem.Drawing—Access toGDI+functionsSystem.Windows.Forms—Classes thatcreateWindowsFormsbased–applications
SecuritySystem.Security—Access to.NETFrameworksecuritymechanisms System.Security.Cryptography—Cryptographyservices,suchasencoding, decoding,hashing,authenticationanddigitalsignatures
WebServicesSystem.Web—ASP.NETandWebFormssupportSystem.Web.Mail—SMTPmailsendfunctionalitySystem.Web.Caching—Caching frequentlyusedresourcesontheWebserverSystem.Web.Services—Build andmaintainWebServices
Generalapplication System.Collections—Collection support System.IO—FileIOsupportSystem.Text—StringmanipulationandcharacterencodingSystem.Threading—Multithreading support
GlobalizationSystem.Globalization—Internationalizationclasses
Chapter14:Classes and ObjectsIn This Chapter
ClassesModulesOverloadingOverridingConstructorsDestructorsGarbagecollection
Chapter16:COM Interop and MSMQIn This Chapter
IntrotoCOMinteropCallingCOMfrom.NETHandlingerrorsinCOMinteropIntrotoMSMQCreatingqueuesCreatingqueuemessagesReadingqueuemessagesDeletingqueuemessages
Consuming COM from .NETTheCLRexposesCOMobjectstocallersthroughtheRuntimeCallableWrapper(RCW) proxy.TheRCWexposesmetadatatotheCLR,whichallowstheCLRtosuccessfully marshalcallsbetweenmanaged.NETcodeandCOMcomponents.WhenyoudecideyouneedtouseaCOMcomponentinyour.NETapplication,youaddareferencetoyourprojectjustasyoudidinVB6.Whenthecomponentisadded, metadataiscreatedfromthetypelibraryofthecomponentthatisbeingreferenced. Whentheobjectisinstantiatedinyour.NETapplication,itistreatedasanyother.NET classlibrary.Yourcodeactsandlooksthesame.Underthehood,theCLRiscreatingtheRCWfortheCOMobjectandtheCOMobjectitselfismarshalingcallsbackandforth betweenthemanagedandunmanagedprocesses.Figure16 - 1representsanoutside lookattheprocessofinteroperabilitybetweenunmanagedandmanagedcode.
Figure16-1: CominteroperabilitypathGettingthisprocessrollingisquitesimple.Tostart,createaVB6ActiveXDLLproject calledMath,andrenametheClass1toSquare.IntheSquareclass,addapublic functioncalledSquareIt.IfyouhavetakentheMicrosoftVBcourses,youhavedone thisexamplemanytimes.TheSquareItfunctionshouldlooklikethefollowing:
PublicFunctionSquareIt(intXAsInteger,intYAsInteger)AsLong
SquareIt=intX*intY EndFunctionWhenthatisallsquaredaway,goaheadandcompiletheDLL.ThiswillregisteritandmakeitavailabletoourVB.NETapplication.Ifyouareusinganothermachineto compiletheDLL,youwillneedtoregisteritusingREGSVR32.EXEonthe.NET machine.ToregisteracomponentusingtheREGSVR32.EXEutility,simplyopenthe commandpromptandpassthepathargumenttotheutility.IfyoucopiedtheDLLtothe C:\Winnt\System32directory,thentoregistertheDLL,typethefollowing:
C:\Winnt\System32\Regsvr32.exe C:\Winnt\System32\Math.Dll
YouwillbenotifiedwithamessageboxthattheDLLwassuccessfullyregistered.Next,createaVB.NETWindowsFormsapplication.OnthedefaultForm1,addtwotext boxes,alabel,andabutton.TheformshouldlooklikeFigure 1 6 - 2 .
Figure16-2: TheSquareItform
NowyouneedtoaddareferencetotheMathDLLthatyoucompiledearlier.Youcando thisinoneoftwoways:1. FromtheProjectmenu,selectAddReference.2. Right-clicktheProjectnameandselectAddReference.
OncetheAddReferencedialogisopen,clicktheCOMtab,findyourMath.DLLinthe list,highlightitwithyourmouse,clicktheSelectbutton,andthenclickOK.Youwill receiveamessageboxsimilartoFigure16 - 3 .
Figure16-3: Wrappergenerationnotification
ThisistheprocessofcreatingtheRCWforthiscomponent.ClickYesonthedialogbox, andlettheIDEgeneratetheRCWforthisCOMobject.YouwillnowseeyourMath objectinthereferenceslist.Allthatisleftistoconsumetheobject,whichisnodifferentthanconsuminganyother.NETcomponent,thankstotheRCW.Intheclickeventforthebuttononyourform, addthefollowingcode:
DimxAsNewMath.Square()
Label1.Text=x.SquareIt(TextBox1.Text, TextBox2.Text)
Runyourapplication,enteravalueineachofthetextboxes,andclickthebutton.The labelwilldisplayyournewlysquarednumber.Itdoesnotgetmucheasierthanthat.
Microsoft Message QueueMSMQisprobablyoneofthegreatest(andleastused)servers,makingitpossibleto writetrulydisconnectedandscalableapplications.Inthenextpartofthischapter,you learnthemajorcomponentsofwritingapplicationsthatuseMSMQandhowto manipulateMSMQobjects.
WhatisMessageQueue?MSMQisessentiallyanapplicationthatguaranteessendingandreceivingmessages reliably.MessagescanbeanythingfromXMLfilestoADORecordsetstoMicrosoftWord documents.ItdoesnotmatterwhatyousendtoMSMQ,youjustknowthatoncethe messageisinaqueue,itsdeliveryisguaranteed.
WhyMSMQ?
TheneedforMSMQneedstobebuiltintothedesignphaseofyourapplications.Itis notsomethingthatshouldbeanafterthoughtbecauseitisthebackboneofa disconnected,robustapplication.Thefollowingareafewfactorsthatwillmakeyou
choosetoimplementMSMQintoyourdesign: Directcallsbetweenclientsandserversoverconnectionscanfail.
MSMQgivesyoumechanisminwhichthiswillneverbeanissue. Messagescanbesenttoqueueswhenresourcesarenotavailable,such
asotherqueues,andretrievedwhentheresourcebecomesavailable. Messagescanbeprioritized,socertainmessagessuchasfoodorders
willbedeliveredbeforelogfilesorsomethingofanoncriticalnature. MSMQis100%transactional,soitcanbepartofaCOM+transaction,
givingyoutheguaranteeofanallornothingdeliverymechanism. MSMQaccessisbasedonWindowsSecurity,soyouareguaranteedto
beworkingwithinasecureenvironment.
GettingstartedwithMSMQ
BeforeyoudecidetoimplementMSMQ,youneedtomakesurethatitisinstalledonthe serverthatyouintendtosendthemessagesto.Unlessyoudidacustomsetupwhen youinstalledWindows,MSMQwillnotbeinstalled.Therearetwowaystocheckthat MSMQisinstalled:
1. Right-clickMyComputerandselectComputerManagement.Inthe treeviewunderServicesandApplications,youwillseeMessage Queue.Ifyoucandrillintothatnodewithoutreceivinganerrorthat MSMQisnotinstalled,youareallset.
2. FromtheServerExplorerinVisualStudio.NET,drillintotheServersnode.YouwillseeMessageQueuesin thelist.If youcandrillintothe MessageQueuesnode,and you see PublicQueues,PrivateQueues, andJournalQueues,thenMSMQisproperlyinstalled.
Table16-1:User-CreatedQueues
Name Description
PublicQueue Queuesthatarereplicatedthroughoutthenetwork andcanbeaccessedbyotherconnectedsites.
PrivateQueue Queuesthatareavailableonlyonthelocal computer.
AdministrationQueue
Containsacknowledgmentreceiptsofmessages sentinthenetwork.
ResponseQueue Containsresponsemessagesthatarereturnedto thesendingapplicationwhenthemessageis receivedbythedestinationapplication.
Table16-2:System-CreatedQueues
Name Description
JournalQueue Optionallystorescopiesofmessagesthataresent andcopiesofmessagesthatareremovedfroma queue.
Dead-LetterQueue Storescopiesofundeliverableorexpired messages.
ReportQueue Storestherouteamessagehastaken.
PrivateSystemQueue
Storesadministrativeandnotificationmessages thatthesystemneedstoprocess.
Programming MSMQImplementingmessagingintoyourapplicationisquiteeasy.Usingthe System.Messagingnamespace,youhaveallofthemembersthatincorporate messaging.UsingSystem.Messaging,youaregoingtodooneofthefollowingtasks:
CreateanewqueueFindanexistingqueueSendmessagestoaqueueReadmessagesfromaqueue
Table16-3:EnumerationMembers
Member Description
GetMessageQueueEnumerator Createsan enumerator objectfora dynamic listingof public queueson thenetwork.
GetPrivateQueuesByMachineName Retrieves private queuesona machine.
GetPublicQueues Retrieves public queueson thenetwork.
GetPublicQueuesByLabel Retrieves public queueson thenetwork thatmatcha specific label.
GetPublicQueuesByMachine Retrieves public queuesfora specified
Retrieveinformationaboutmessagesinaqueuewithoutactuallyreadingthe message
CreatingqueuesTheCreateconstructorofSystem.Messaginghandlesthecreationofnewqueues.If youareattemptingtosimplysendmessagestoaqueue,youwillnotusetheCreate method,butyouwillusetheSendmethod.Inmostenvironments,Tocreateanewqueue,usethefollowingcode:
IftxtQueueName.Text.Length >0Then
DimqAsNewMessageQueue()
DimstrQAsString=".\Private$\"&txtQueueName.Text q.UseJournalQueue=True
q.Create(strQ,True)q.Close() EndIf
AccessingqueuesIfyoucreatequeuesthroughtheCreatemethod,orifyoumanuallycreatethem throughComputerManagement,youwillneedawaytoreferencequeuesinyourcode. ThereareseveralenumerationmembersintheSystem.Messagingnamespace, dependingonwhattypeofqueuesyouarelookingfor.Table1 6 - 3 showscommon membersoftheSystem.Messaging.MessageQueue classusedforqueueenumeration.
DeletingqueuesTodeleteaqueue,youusetheDeletemethodafteryouhavegottenareferencetoa MessageQueueobject.TheparameteroftheDeletemethodwilltakeeitherafully qualifiedprivateorfullyqualifiedpublicqueuename,somakesureyoureferencethe machinenameandthequeuename.Thefollowingcodewilldeleteaprivateandpublic queuenamed"MyQ".
DimqAsMessageQueue
'DeletesPrivateQueue q.Delete("Server1\Private$\MyQ")
'DeletesPublicQueue
q.Delete("Server1\MyQ")SendingmessagestoqueuesYousendmessagestoaqueueusingtheSendmethod.TheSendconstructoris overloaded,havingparameterssuchasBody,Label,andTransaction.Tosenda message,youwillneedtocreateaninstanceofaqueue,andsetthePathproperty,so theSendwillknowwheretogo.Thefollowingcodewillaccomplishthisfeat.
DimqAsNewMessageQueue()
q.Path="jb650\Private$\MyQ" Ifq.Exists(q.Path)Then
q.Send("Thisisthemessage","TestLabel")
q.Close() Else
MsgBox("TheQueueyouarewritingtodoesnotexist")
EndIf
ReadingqueuemessagesToreadmessagesfromaqueue,youwilleitherPeekintoaqueueorReceivefroma queue.ThePeekmethodreadsthefirstmessageinthequeue,allthetime.Youwould peekintoaqueuetotestfortheexistenceofmessagesandcheckmessageproperties. Peekingintoaqueuedoesnotremovethemessage.Ifyoupeekintothesamequeue multipletimes,thesamemessagewillalwaysbereadunlessanewmessagehasbeen addedwithahigherprioritythanthemessagethatwaslookedatpreviously.The Receivemethodwillreadamessagefromaqueueandremoveitfromthequeue.So onceamessageisreceived,itwillnolongerexistinthequeue.
PeekingintoaqueueThefollowingcodeshowsthePeekmethodinaction. DimstrQAsString=".\Private$\
MyQ"
DimqAsNewMessageQueue()
q.Path()=strQ
Ifq.Exists(q.Path)Then
DimmsgAsMessage
DimformatterAsXmlMessageFormatter=_
CType(q.Formatter,XmlMessageFormatter)
formatter.TargetTypeNames =NewString()_
{"System.String,mscorlib"} msg=q.Peek
Console.Writeline(msg.Label)
Console.Writeline(msg.Body)
EndIfInthisexample,youusedthePeekmethodandassignedtheresulttoanobject declaredasamessage.Becausemessagesarewhatliveinaqueue,youareretrieving propertiesofthemessageitself,notthequeuethatthemessagelivesin.
ReceivingmessagesfromaqueueReceivingmessagesworksalmostlikethePeekmethod,exceptyouusetheReceive methodandyouspecifyatimeoutperiodfortheReceivemethodtofailifnothingisin thequeue.Thefollowingcodewillattempttoreceiveamessagefromthequeuefor threeseconds.
Ifq.Exists(q.Path)Then
DimformatterAsXmlMessageFormatter=_
CType(q.Formatter,XmlMessageFormatter)
formatter.TargetTypeNames=NewString()_
{"System.String,mscorlib"}
DimmsgAsMessage=q.Receive(NewTimeSpan(0,0,3)) Console.Writeline(msg.Label)
Console.Writeline(msg.Body)
EndIfTheReceivemethodwilltakedays,hours,minutes,seconds,andmillisecondsinthe constructor.Ifatimeoutoccurs,anexceptionwillberaisedthatnotifiesyouofthe timeout.ThefollowingCatchstatementwilltrapthetimeouterrorandallowyouto handleitgracefully.
PartIII:VisualStudio.NET:TheIDEforVB.NETChapter17:VisualBasic.NETIDEChapter18:CompilingandDebugging Chapter19:CustomizingChapter20:SourceControl
Chapter17:VisualBasic.NETIDEIn This Chapter
VisualStudio.NETIDECreatingaWindowsFormsapplicationWindowsmanagementbasicsProjectstructureDesigners
The Start Page
Figure17-1: VS.NETStartpage
MyProfile
Basedonthetypeofdevelopmentthatyouwillbedoing,youcancustomizetheIDEto specifickeyboardschemes,windowlayouts,andhelpfilters.IfyouareapreviousVB developer,youmightwanttoselecttheVisualBasicDeveloperprofilesothattheIDEis familiar.ThefollowingarethesettingsthatIchosebasedonmydevelopmentneeds:
Profile:(Custom) KeyboardScheme:VisualBasic6 WindowLayout:VisualStudioDefault HelpFilter:VisualBasicDocumentation ShowHelp:OutsidetheIDE AtStartupShow:VisualStudioHomePage
Thecoolthingisthatifyoufeelthepreferencesyouhaveselecteddonotdoyoujustice, youcanchangethemlateratanytime.Ithinkthatoneofthemostimportantoptionsis theHelpFilter.ThereissomuchinformationintheMSDNLibrarythatitmakeslifealot easierwhenthehelpisfilteredtojusttheVisualBasicinformationthatyouneed.
GetStarted
Themostrecentapplicationlistisoffered.Asingleclickwiththemouseonarecent projectwillopenyourdevelopmentsoyoucanbeginusingtheselectedproject.Youcan alsoselectOpenExistingProjectifanapplicationthatyouhaveworkedonisnotinthe list.CreateNewProjectwillstartanewproject,andReportaVisualStudio.NETIssue willtakeyoutotheWebtoreportaproblemortosubmitabugreport.
What'sNew
ThispageofferslinkstothelatestservicepackupdatesforVisualStudio.NET,linksto partnerresourcesontheWeb,andproductinformationonVisualStudio.NETproducts.
OnlineCommunity
Foryears,thebestresourceforVisualBasicdevelopershasbeentheonlineofferings. FromtheMSDNWebsitetonewsgroups,ifyoueverrunintoaseriousissue,expert helpisalwaysonlinesomewhere.ThenewIDEnowintegratesimportantWebsitesand newsgroupsforyou,soexperthelpisjustasingleclickaway.
Headlines
TheMSDNOnlinehomepageisintegratedintotheIDE,soallofthelatesttechnical articles,news,andtraininginformationareatyourdoorstep.
SearchOnline
TheMSDNOnlineLibraryinavailableforquickaccesswhentheanswersmightnotbein thehelpfilesinstalledonyourmachine.
Downloads
Thelatestdownloadsandadd-onsavailablefor VisualStudioandrelatedproductsare availablehere.Thisfeatureis greatbecauseyouonlyneedto lookata singleareafor anythingnewthatisavailable.
WebHosting
LinkstoISPsthatoffer.NEThostingareofferedinthisoption.Averystrongwordof caution:Yougetwhatyoupayfor,sobewaryof"free"hostingandverylow-priced hosting.Theservicemaynotbewhatyouareusedto(Iamspeakingfrompersonal experienceusingthisfeature).
Your First Visual Basic .NET SolutionNowthatwehaveexploredtheVisualStudio.NEThomepage,let'sgothroughtheIDE anddiscussitsfeatures.Thebestwaytoaccomplishthisistocreateanewsolution,and thendrillintothefeaturesVisualStudiooffers.
Tocreateanewsolution:1. FromtheFilemenu,clickNew Project(seeFigure17 - 2 ).TheNew
Projectdialogboxwillappear.TheNewProjectdialogboxisbrokenup intotwopanes,ProjectTypesandTemplates.Forourpurposes,wewill concentrateontheVisualBasicProjectsfolderintheProjectTypes pane.
Figure17-2: CreatinganewprojectThefollowingtemplatesareavailablethroughtheTemplatespane:
WindowsApplication:CreateaWindowsForms-based application ClassLibrary:CreateaClassLibrarytouseinanother
application
Table17-2:FileExtensions
File Extensi on
Description
XML XMLDocument.
XSD XMLSchemaFilewithoutgeneratedclasses.
TDL TemplateDescriptionLanguageFile.
VB WindowsForm,Control,Class,orCodefile.
RPT CrystalReportsDesignerfile.
HTML HTMLsourcefile.
XSLT XMLfilecontainingtransformationinstructionsforXMLandXSDdocuments.
CSS CascadingStyleSheetusedforHTMLpagestoapplystyles.
VBS VBScriptsourcefile.
WSF WindowsScriptingsourcefile.
JS Jscript.NETsourcefile.
CS C#sourcefile.
ASPX WebApplicationform.
ASP ActiveServerPagesourcefile.
ASMX WebServicesourcefile.
DISCO DynamicDiscoveryDocument,sourcefilethatenumeratesWebServicesandSchemasinaWebproject.
ASCX ASP.NETusercontrol.
CONFIG Applicationspecificconfigurationfile.
WindowsControlLibrary:CreateWindowsForms- basedcontrols WebApplication:CreateaWebServer–based ASP.NET-
basedapplicationcomprisedofstaticor dynamicHTMLpages WebService:CreateaWeb-basedServicetobe
consumedbyanyapplicationthatcancommunicateover theHTTPprotocol WebControlLibrary:CreateWeb-basedcontrols ConsoleApplication:Createacommand-line application WindowsService:CreateaWindowsService EmptyProject:EmptyWindowsApplicationproject EmptyWebProject:EmptyWebserver-based application ImportFolderWizard:Createanewprojectbasedon anexistingapplication
2. SelecttheWindowsApplicationtemplate.3. TypeaNameforyourapplication.Forourpurposes,typeHelloWorld, thedefactostandardforallfirst-
timeprojects.4. FortheLocation,youcanacceptthedefault,whichisyourMy
Documentsfolder.Ifyouwanttostoreyourprojectfileselsewhere, simplyclicktheBrowse…buttonandselectanewlocation.
5. ClickAddtoSolutionorCloseSolution.Thisoptionallowsyoutoeitheraddyournewprojecttotheexistingsolution,orclosetheexisting solutionandstartanewone.AnexamplewouldbeaddinganewWeb ServiceapplicationtoyourexistingVB.NETsolution.
6. Ifyouareaddingtoanexistingsolution,youcanspecifyanalternate directoryandsolutionnameforyournewprojectbyenteringavaluein theNewSolutionNametextbox.
7. ClickOK.
FileextensionsAllofthefileextensionsforVisualBasic.NEThavebeenchangedfromprevious versionsofVisualBasic.Itisimportanttounderstandwhattheextensionsareandwhat theymean.Table1 7 - 2describeseachfileextension.
Table17-2:FileExtensions
File Extensi on
Description
XML XMLDocument.
XSD XMLSchemaFilewithoutgeneratedclasses.
TDL TemplateDescriptionLanguageFile.
VB WindowsForm,Control,Class,orCodefile.
RPT CrystalReportsDesignerfile.
HTML HTMLsourcefile.
XSLT XMLfilecontainingtransformationinstructionsforXMLandXSDdocuments.
CSS CascadingStyleSheetusedforHTMLpagestoapplystyles.
VBS VBScriptsourcefile.
WSF WindowsScriptingsourcefile.
JS Jscript.NETsourcefile.
CS C#sourcefile.
ASPX WebApplicationform.
ASP ActiveServerPagesourcefile.
ASMX WebServicesourcefile.
DISCO DynamicDiscoveryDocument,sourcefilethatenumeratesWebServicesandSchemasinaWebproject.
ASCX ASP.NETusercontrol.
CONFIG Applicationspecificconfigurationfile.
Back to the IDENowthatyouunderstandthesolutionandprojectstructure,andthefilesthatarepartof aproject,let'sgobacktotheIDEandgointodetailswhileexploringourHelloWorld application.
AutoHideThenewAutoHidefeatureallowsyouto"hide"windowsfromthemainIDEwhileyouaredevelopingapplications.EverywindowthatappearsintheIDEhastheAutoHidefeature.TotoggleAutoHideonandoff,clickthepushpinbutton(seeFigure17 - 3)onthetoolbarforeachwindowyouwanttohide.Whenawindowishidden,atabreplacesthelocationofthewindow,whichallowsyoutoclickthetabtoviewthewindow.
Figure17-3: AutoHidepushpin
TabbeddocumentsInthepast,youhadtheWindowpull-downmenutoswitchbetweenopenwindowsinthe IDE.WithVisualStudio.NET,thereisthetabbeddocumentthemethataddsatabtothe topofthemainwindowforeachdocumentorfilethatyouhaveopen(seeFigure 1 7 - 4 ). ThisincludestheMSDNHelptopicsthatwepreviouslylookedat,theobjectbrowser,the Startpage,CodeFile,forms,oranypreviouslyopenedwindow.Toswitchbetweenopen documents,simplyclickonthetabthatrepresentsthedocumentyouwanttoopen.To closeadocument,ortonavigateforwardandbackwardwithinopendocuments,usethe buttonsontheupperright-handcornerofthemainwindow,whichgivefurthernavigation control.TheCtrl+Tabkeycombinationwillnavigateopenwindowsinthemainworkspace.ThistechniqueisidenticaltotheAlt+Tabkeycombinationthatweusetonavigateopenwindowsintheoperatingsystem.
Figure17-4: Tabbeddocumentfeature
DockablewindowsAllwindowswithintheIDEaredockabletoanyedgeoftheIDE.Simplydraganywindow towhateverlocationyouwantittoreside,anditwilllockintoplace.Ifyouhavepreviouslymadethewindowauto-hide,itwillnowauto-hideinitsnewlocation.ThecombinationofAutoHidewithdockablewindowsallowscompletecustomizationofyourIDEworkspace.
FavoritesSimilartoFavoritesinyourWebbrowser,anydocumentinyourIDEcanbeaddedto yourFavorites,aswellasanyWeb-baseddocument.
Multiplemonitor supportThiscoolnewfeatureallowsmultiplemonitorsupportwiththeIDE.Youcannowhave windowsspreadacrossmultiplescreens,furtherenhancingyourproductivity.Thisis,of course,basedonthetypeofvideocardthatyouareusing.Youcannotrunacrossover cablebetweentwocomputersandlikemagichavemultiplemonitors;youwillneedto investinafancyvideocardwithmultiplevideooutputs.
Windows,dialogs,andmorewindowsWenowdrillintothewindowsthatmakeuptheIDE,thetoolbars,thedrop-downmenus, andallthecoolthingsthatmakeupournewenvironment.Becausewehavethe HelloWorldapplicationopen,everythingthatyouareabouttoreadaboutshouldbe visible.Ifanyofthefollowingwindowsthatwedrillintoarenotvisible,youcangetto
thembyselectingtheViewmenu,asFigure17 - 5 demonstrates.
Figure17-5: ViewMenuwithotherwindowsIfyourefertoFigure1 7 - 4 ,youcanseeallofthepossiblewindowsthatyoucanopenin theIDE.Let'sgothrougheachoneandgivesomebackgroundanddetails.
SolutionExplorerSimilartotheProjectExplorerinVB6,theSolutionExplorer(seeFigure17 - 6 )containsa listofallofthefilesassociatedwithyourcurrentsolution.ThroughtheSolutionExplorer, youhavetotalmanagementofyourprojectanditscorrespondingfiles.Solutionsmay containseveralprojects,writteninseverallanguages,usingseveraldifferent technologies.Itistrulyaglobalviewofyoursolution.AsinVisualStudio6,allproject optionsareavailablebyright-clickingwithintheSolutionExplorerandbringingupthe contextmenu.Becauseeachpartofasolutionisdifferent,theoptionsavailabletoyouwillbedifferentdependingonwhatyouselect
Figure17-6: SolutionExplorer
andright-click.Ifyouright-clickonaProjectname,thenProjectoptionssuchasBuild, AddReference,andSaveAswillappear.Ifyouright-clickonaFormoraCodemodule, optionssuchasOpen,ViewCode,orViewDesignerwillbeavailabletoyou.Itisagood ideatoexploreeachoftheoptionswhenyoufirststartusingthisnewIDEtobecome moreproficientinSolutionManagement.
ClassViewTheClassViewwindowisahigh-levelviewofalltheclassesandobjectsinyour solution.FromtheClassView,youcanretrievedefinitionsofeachobject,itsproperties, andmethodswithasimpledouble-click.Iftheclasshasmethodsthatexistinyour application,double-clickingontheobjectwillbringitscodewindowupinthemain workspace.ThereisahandytoolbarontheClassViewwindowthatallowsdifferentsort optionsforfastaccesstoobjects.
ServerExplorerTheServerExplorer(seeFigure17 - 7 )isacentrallocationtomanageallserversand server-basedservicesfromwithintheVisualStudio.NETIDE.Becausethewholeidea ofthe.NETplatformissharedservicesamongmanydifferentservers,thereneedstobe aplacetolocateandmanagetheseservers.TheServerExplorerallowsacentralviewofallserverresources,anydataconnectionsthatyouhaveforyourcurrentsolution,e-mailconfiguration—particularly Exchange2000configuration—andWebService management.
Figure17-7: ServerExplorer
Thefollowingisalistofthetop-levelnodesintheServerExplorerandthepurposeof eachnode: CrystalServices:InstalledCrystalReportoptions. EventLogs:Application,Security,andSystemEventlogsforthe attachedserver. LoadedModules:ListoftheprocessesandloadedDLLsonthe
selectedserver.Theverycoolthinghereisthatthroughthe System.Diagnostics.Process classlibrary,youareexposedtothe propertiesoftheprocesses.Soifyoufeelitnecessary,youcanmodify anyoftheexposedread/writepropertiesthroughPropertieswindows.
ManagementData:ListofinterfacesavailablethroughWindowsManagementInstrumentation.Again,aninsighttoservicesand read/writepropertiesoftheconnectedserver.Forexample,Idrilled intoWin32_Server,LogicalDiskManager,allthewayintomy ComputerName,andmodifiedtheSystemStartupDelayproperty to10.NowwhenIreboot,theOSChoicesmenuisat10seconds insteadof30.
MessageQueues:Listofavailablequeuesandtheircorresponding messages.MessageQueuemustbeinstalledforthistowork.This wouldbethesameviewthatyoucanretrievefromComputer Managementsnap-in.
PerformanceCounters:ListofallavailablePerformanceCountersfortheselectedserver.Thelistishugecomparedtowhatweareused to.Therearehundredsofnewcountersfor.NETalone.Forexample, wenowhaveacountertotrack.NETCLRLOCKSandILBytes JITted/sec.
Processes:Listofrunningprocessesontheselectedserver. Services:Listofrunningservicesontheselectedserver. SQLServerDatabases:Listofdatabasesontheselectedserver.
LiketheDataViewwindowofpastVisualStudioversions,youare openeduptoallofthefunctionalityoftheSQLServerEnterprise Manager.ThisisaveryrobustCOMinterfacethatalleviatestheneed
to haveEnterpriseManageropen.Fromthisview,youcanadd,edit, anddeletetables,views,storedprocedures,databasediagrams,and functions.
WebServices:ListofWebServicesbyProjectandFilewithwhichtheywerepublishedon the selectedserver.Fromthis view,youcan immediatelyaddareferencetoaWebServicetoyourprojectwitha right-clickorbysimplyusingdraganddropintoyourcodewindow.
DataConnections:SimilartotheSQLServerDatabasesnode,youcanaddconnectionstoanydatabaseorserverproviderthathasan installedOLEDBprovideronyoursystem.Thisallowsyoutoconnect toserverssuchasOracle,DB2,Exchange,andActiveDirectory.
PropertieswindowThePropertieswindowallowsyoutomodifyatdesigntimethepropertiesofanyobject thatiscurrentlyselectedinthemainworkspace.IfyouareaVB6developer,youwillbe familiarwithworkingwiththePropertieswindow.Itisthesinglemostimportantwindow intheIDEforcustomizingyourapplicationatdesigntime.Thedefaultviewforthe PropertieswindowistodisplaypropertiesbyCategory;thiscanbechangedtoanalphabeticalviewofpropertiesbyclickingthealphabetictoolbarbuttonontheProperties window.Youcanalsoviewthepropertiesofanycontrolonthecurrentformbyselecting itfromthedrop-downlistjustabovethetoolbar.AsaVBdeveloper,regardlessof whetheryouaredevelopingaWindowsForms–basedapplicationoraWebForms–basedapplication,youarealwaysmodifyingpropertiesofobjectstomaintainthedesiredlookandfeelofyourapplication.UsingthePropertieswindowissomethingthatyoudo about10,000timesaday.GetyourselffamiliarwiththePropertieswindowandeach object'sproperties,especiallyifyouareanexperiencedVBdeveloper,becausethe changestopropertiesofallobjectsinVisualStudio.NETwillsurpriseyou.
ToolboxTheToolbox(seeFigure1 7 - 8 )containstheobjectsandcontrolsthatcanbeaddedto WindowsFormsapplicationsandWebFormsapplications.TheToolboxhasavertical tabbedthemethatallowsquicknavigationbetweenthedifferenttypesofobjectsor controlsthatyouwanttoaddtoyourforms.Bydefault,theToolboxdisplaystheData, Components,WindowsForms,ClipboardRing,andGeneraltabs.Aright-clickonthe ToolboxwilldisplayoptionsfortheToolbox.ShowAllTabswilldisplaytheremainderof thetabsthatarenotdisplayed.Ifyouselectthisoption,youwillseethatthereareabout20differenttabs,rangingfromXSDSchemastoUMLShapes.ToplaceaToolboxitem ontoaform,simplydragtheselectedcontroltothelocationoftheformwhereyouwant thecontroltoreside.Youcanalsodouble-clickonacontroltoplaceitatthelastcursor positionontheform.Oncethecontrolisontheform,youcanthenmoveittoany locationontheformbyclickingonthecontrolanddraggingitwithyourmouse.
Figure17-8: TheToolbox
Ifyouhavecodesnippetsthatyouuseacrossmanyprojects,orthereiscodethatyou don'twanttotypeeverytimeyouneedit,youcanaddthatcodetotheToolbox.Mygoal inlifeistowriteaslittlecodeaspossible,soIhavetonsofcodesnippetsstoredinthe Toolbox.
ToaddcodesnippetstotheToolbox:1.IntheCodewindow,highlightthecodeyouwanttoaddtothe
Toolbox.2.DragtheselectedcodetotheGeneraltab.3.Right-clickontheToolboxandselectRename,andgivethenewly
addedcodesnippetameaningfulname.
YoucandoallToolboxcustomizationwitharight-click,sogoaheadandlookatthe menuoptionsavailablewhenyouright-clickontheToolbox.
MacroExplorerWiththeMacroExplorer,youcanwritemacrosthatcustomizeyourIDEorautomate tasks.TheVisualStudio.NETIDEhasitsownobjectmodel,whichisverycomplete,so youcanautomateprocesseswithintheIDEusingtheMacroIDE.TogettotheMacro IDE,youcandouble-clickonanyofthemacrosthatalreadyexistintheMacroExplorer, oryoucanselectAdd,Edit,orDeletefromtheright-clickcontextmenuwithintheMacro Explorer.Figure17 - 9 displaystheMacroIDE.
Figure17-9: MacroIDE
ObjectBrowserTheObjectBrowser(seeFigure1 7 - 1 0 )isoneofthemostpowerfulwindowsinthe VisualStudioIDE.TheObjectBrowserallowsyoutovieweveryobjectinthecurrent solutionandtheirpropertiesandmethods.Brokenupintotwopanes,theleftpane,or ObjectsPane,displaysahierarchicallistofallobjectsinyoursolution(classes, interfaces,structures,types,namespaces,andsoon).Therightpane,orMembers Pane,displaystheproperties,methods,classes,enumerateditems,variables,and constants.Whenyouselectamemberintherightpane,theDescriptionPaneatthe bottomoftheObjectBrowserdescribesthememberandgivesyouanexampleofthe syntaxthatyouwilluseifyouplanonusingthemember.Thisincludesany dependencies,variables,andadditionalhelpdescriptionthatmayhavebeencompiled withtheobject.TheBrowsedrop-downonthetopoftheObjectBrowserenablesquick navigationtotheloadedobjectsinyourproject,soyoucanlimitthelistofobjectsinthe leftpanetoaspecificobjectinyourproject.TheCustomizebuttonenablesyoutoadd additionalcomponentstotheObjectBrowserortoremovecomponentsthatcurrently existintheproject.IfyouchoosetoaddnewcomponentstotheObjectBrowser,allof the.NETFrameworkandCOMcomponentswillbeofferedtoyouinanalphabeticallist. TheFindbuttonontheObjectBrowsertoolbargivesyouaquicksearchfunctionalityto siftthroughthehundredsofobjectsthatmaybeinyourproject.
Figure17-10: ObjectBrowser
TasklistThetasklistisafamiliarsiteforVisualInterDevdevelopers.Itisacentralizedareathat helpsyoutomanagetaskswithinyoursolution,giveyouerrordetailswhenyoucompile yourcodeorasyouentercode,andithelpsyouself-documentyourprojects.Thereare severalpredefinedtokensthathelpyouself-documentyourcode.TheyareTODO, UPGRADE_TODO,andUPGRADE_WARNING.Byenteringthesetokensafterthecomment symbol(thesinglequote),tasksareautomaticallyaddedtothetasklistforyou.When youneedtogobacktoatokenthatyouadded,justdouble-clicktheiteminthetasklist andtheappropriatesectionofcodeisbroughtupinthemainworkspace.Forerrors,the behavioristhesame.Ifthereareerrorslisted,simplydouble-clickthetasklistitemandyouaretakentotheoffendingline.YoucanaddcustomtokensbyselectingToolsOptionsanddrillingintotheTasksoptionsasFigure1 7 - 1 1 shows.
Figure17-11: Tasklistoptions
CommandwindowTheCommandwindowisusedforexecutingcommandsdirectlyintheVisualStudio.NETenvironment,bypassingthemenusystem,orforexecutingcommandsthatdonot appearonanymenu.
OutputwindowTheOutputwindowdisplayscompiler-specificinformationwhenyoubuildyourprojector solution.TheOutputwindowwilldisplaybuilderrors,librariesthatareloaded,andother detailsofthebuildprocess.
DebuggingwindowsIfyouarelikeme,youconsistentlyamazeyourselfbywritingerror-freecode.Iftheslight chancearisesthatyouneedtouseanyofthepowerfuldebuggingfeaturesinVisual Studio.NET,therearefivewindowsthatassistyouwiththisatruntime.Figure1 7 - 12displaystheavailablewindowsfordebugging:theBreakpoints,Autos,Locals,Watch, andCallStackwindows.Chapter1 8 talksaboutdebuggingindetail,sowewillnot duplicatethatefforthere.
Figure17-12: Debuggingwindows
TheCodeEditorThecodeeditor(seeFigure17 - 1 3 )iswhereyouspendmostofyourtimewritingVB.NETfunctionsandprocedures.Thecodeeditorisprobablythemostimpressivefeature
ofVisualStudio.Withfeaturessuchasspellchecking,Auto-complete,wordand statementcompletion,andAuto-listmembers,thecodeeditorassistsyouineveryfacet ofyourcoding.
Figure17-13: Thecodeeditor
Youcanopenthecodeeditorinseveralways,basedonyourpreference: Youcandouble-clickonanobjectonaformintheWindowsForms
designer,whichwillbringupthecodeeditor. Youcanclickthe"viewcode"buttonontheSolutionExplorertoolbar,
whichisthefirstbuttononthattoolbar. Youcanright-clickanywhereintheformsdesignerandselectViewCode fromthecontextmenu.
BecausetheIDEhasthetabbeddocumentsfeature,youcanhaveasmanycodeeditorwindowsopenasyoulike.Whenafileisopen,suchasaclassfile,form,orXML document,theyarelistedintabsacrossthetopoftheeditorwindow.Figure1 7 - 4 earlier inthechaptershowedthetabbeddocumentfeature.
WiththeinventionofAuto-complete,Auto-listmembers,andspellcheckinginthecode editor,youdonotevenhavetoknoweven70%ofthelanguagetogetapplications written.
AutoList Membersand AutoCompleteAutoListMembersandAutoCompletearefeaturesthathelpyoudiscoverobject membersandfinishoffobjectreferenceswhilecoding.Thisfeatureworksinconjunction withtheImportsstatementsatthetopofyourclassfiles,andwiththebuilt-in namespacesthatarepartofeachclassfile.Byimportinganamespaceintoyourclass, theeditorbecomesawareofitsexistenceandmakesitsproperties,methods,andeventsavailableintheformofdrop-downlistsasyoureferencethoseobjects.Oncealistofmembersforanobjectappears,youcanscrollthroughthelist,orstarttypingthe memberyouarelookingfor,andonceitishighlighted,pressingthespacebarorthe Enterkeywillcompletethestatementforyou.Figure17 - 1 4 isanexampleofAuto Completeinaction.
Figure17-14: AutoCompleteinaction
WithAutoComplete,itisnearlyimpossibletomakeincorrectobjectreferences, declarations,ortypingmistakes.
SpellcheckingSpellcheckinginMicrosoftWordisthemainreasonmostofuslooksosmartwhenwe typeletters(orwritebooks).Withoutthisfeature,Iwouldpersonallyneedtohireatypo editortoredoallofmywork.Inthecodeeditor,youhavethesamesortofspell-checking featurethatWordoffers.Whenyoudeclarevariablesinthecodeeditor,theyarecheckedagainstreferencestothosevariablenamesasyouarecoding.Ifyou accidentallymisspellavariablereference,theeditorwillinformyouofthismistakewitha squigglylineundertheoffendingcode.Figure17 - 1 5 givesanexampleofthespell checkerinaction.
Figure17-15: Thespellcheckerinaction
Designers
Thereareseveraldesignersthatmakeupthe"visual"partofworkingintheIDE. DesignersgiveyouasurfacetocreatethegraphicalfrontendofASP.NETapplications andWindowsFormsapplications.Therearealsodesignersthataidindatabase creation,querygeneration,andXMLediting.
WindowsFormsdesignerTheWindowsFormsdesignerisusedtocreateforms-basedapplications.Byaddinga newformtoyourproject,youcandraganddropcontrolssuchastextboxesorlistboxes ontotheformtovisuallycreateyourGUI.WhenworkingontheFormsdesigner,selectingobjectsontheform,ortheformitself,changesthePropertieswindowsto displaythepropertiesforthatobject.
WebFormsdesignerTheWebFormsdesignerbehavesexactlyliketheWindowsFormsdesigner.The differenceisthetypeofapplicationyouaredeveloping.Ifyouaredevelopingan ASP.NETapplication,youwillbeusingtheWebFormsdesignertomodifythelookand feelofyourASPXfiles,whichmakeuptheuserinterfaceofanASP.NETapplication.
XML designerTheXMLdesignerisusedtoeditandcreateXMLandXSDfiles.TheXMLdesignerhas threeviews:SchemaView,XMLSourceView,andDataView.
SchemaView
TheSchemaViewallowsyoutovisuallydesignandeditXMLschemas.Youcancreate schemasbydragginganddroppingtablesfromdatabaseconnectionsintheServer Explorer,oryoucanaddnewattributesandelementsintheeditor.TheSchemaView alsoallowsthecreationofADO.NETdatasets.
XMLSourceView
TheXMLSourceViewistheeditorforviewingandcreatingXMLfiles.Theeditoralso sharesthesamefeaturesofthecodeeditor,suchasauto-completeandauto-list members.
DataView
TheDataViewissimilartotheTableViewofadatabasetoolsuchasMicrosoftAccess orSQLServer.UsingtheDataView,youcanviewandeditXMLdatainafamiliartable- likefashion.YoucanalsogenerateandviewschemadefinitionsbasedonXMLdata beingdisplayedoreditedinthedataviewwindow.
DatabasedesignerTheDatabasedesignerisafull-fledgeddatabasecreationtool.WiththeDatabase designer,youcanadd,edit,anddeletetables,indexes,views,storedprocedures,and tablerelationshipsinaSQLServer,Oracle,oranydatabaseforwhichyouhavethe correctOLEDBproviders.
QuerydesignerTheQuerydesignerallowsthecreationofcomplexqueriesbydragginganddropping tablesfromadatabaseconnectionontothedesignersurface.Thelookandfeelisthe sameastheviewdesignerinSQLServerEnterpriseManagerandtheQuerydesignerin previousversionsofVisualStudio.
ComponentdesignerTheComponentdesignerallowsforthecreationofnon-graphicalmiddle-tier components.DraggingobjectsfromtheComponentstaboftheToolboxontothe designersurfaceallowsrapiddevelopmentofserver-basedobjectsbysettingproperties onobjectsthroughthedesigner,avoidingsomeofthecodingthatwouldnormallybe neededformiddle-tierandservercomponents.
UserControlDesignerTheUserControldesignerallowsforthevisualcreationofcontrolsthatcanbereused throughoutyourASP.NETapplications.LikeincludefilesinASP,ausercontrolcanbe placedontoanASPXpageanditsfunctionalityiscompletelyencapsulatedwithinthe controlitself.Thedifferencebetweenincludefilesandusercontrolsisthatauser controlcanbevisuallycreatedusingthedesigner,andhasitsowncode-behindpages.
Chapter18:CompilingandDebuggingbyRobTeixeira
In This ChapterCompilingyourcodeConditionalcompilationDebuggingDebuggingtoolsDebugandTraceobjects
Compiling Your CodeTwo scenarios exist for running your code. One is running your code from the development environment so that you can test what you are writing (runninginDebug mode), and the other is producing the binary files that will be placed into production or release. In either case, the source code files must be compiled. This process is called building.
Builds are controlled by build configurations. There are two levels of build configurations. One is the solution level, which affects abuild of all the projects in the solution, and the other is project level, which affects build settings for the individual projects in the solution.
Solution build configurations
There is always one active build configuration for the open solution. This is shown in a drop-down list on the Standard toolbar, which also allows you to select the active build configuration. You can also select the active build configuration, as well as define new configurations, by selecting the Configuration Manager command in the Build menu. This same command is a vailable from the context menu (opened by a secondary click) of the Solution item in the Solution Explorer. This command displays the Configuration Manager dialog box(seeFigure1 8 - 1 ).
Figure18-1: ConfigurationManagerdialogbox
Projectconfigurations
Eachprojectinthesolutionhastwosetsofproperties,onesetthatiscommonandone setthatisdefinedforeachconfiguration.Initially,allVB.NETprojectsstartoutwithonly DebugandReleaseprojectconfigurations.AsageneralruleinVisualStudio.NET,there isoneprojectpropertysetforeachcombinationofConfigurationandPlatform.Toaccessthepropertiesforaproject,selectaprojectandclickthePropertiescommandintheProjectmenu.Alternately,youcanusethePropertiescommandinthecontext menuofanyprojectitemintheSolutionExplorer.ThisopenstheProjectProperties dialogboxasshowninFigure18 - 3.Thecaptionofthedialogboxisintheformof ProjectNamePropertyPages.
Figure18-3: ProjectPropertiesdialogbox
DebuggingoptionsUsetheStartActiontotelltheenvironmentwhattodowhenrunningaprojectfrom withinthedesignenvironment.StartProjectsimplyrunstheproject.StartExternal Programisusefulforlibrarytypeprojects,andstartsanotherprogramthatusesthis libraryproject,allowingyoutodebugthelibrarywiththeotherprogramastheclient. StartURLopensthebrowserandnavigatestothegivenURL.ThegivenpageorASP scriptthenactsastheclienttothelibraryproject.
BuildThispropertypageallowsyoutospecifygeneralbuildoptionsfortheproject.Selectthe BuildnodeunderConfigurationPropertiestodisplaythispage.Thesebuildoptionsare dependentontheprojectconfiguration,incontrastwiththeBuildoptionsontheCommon Propertiesfolder.
Specifythedirectoryyouwanttheresultingcompiledfiletobeplacedinbytypingitin theOutputPath.
CheckGenerateDebuggingInformationifyouwantthecompilertoadddebug informationtoyourcompile.ThisgeneratesaPDBfile(programdatabase)andinserts informationthatallowsyoutostepthroughcode,addbreakpoints,synchronizethe executionwiththesourcecodefiles,andsoon.
DebuggingBreakpointsMostofthetime,steppingthroughtheprograminitsentiretyisveryimpracticalbecause oftheprogram'ssize.Settingabreakpointsomewhereinthecodeallowstheprogramto runnormallyuntilthebreakpointisreached.Theprogramtemporarilyhaltswhenthe executioncomestothelineofcodewiththebreakpoint.Whenthishappens,theprogramisinwhat'scalledBreakmode.Thisallowsyoutoexaminethedata,checkthe logic,andsoon,andtheneithercontinueexecutionbypressingF5(orStart)again,or stepthroughthecode(F10orF11).Toinsertabreakpoint,placethecursorontheline ofcodewhereyouwanttobreaktheexecutionandpressF9.Youcanalsoclickonthe margintotheleftofyourcode.Abreakpointsymbolthendisplaysonthatlineasshown inFigure18 - 5 .
Figure18-5: Noticetheredcircularbreakpointsymbolontheleftmargin.
PartIV:DataAccessChapter21:IntroductiontoDataAccessin.NET Chapter22:ADO.NETChapter23:DataAccessinVisualStudio.NET Chapter24:IntroductiontoXMLin.NET
Chapter21:Introduction to Data Access in .NETVisualBasic3.0
Manyofthedeveloperswhowerefortunateenoughtobeusingversion2.0ofVisual BasictodevelopapplicationswouldagreethattheadoptionofVisualBasicbycorporate developersreallybeganin1993withthereleaseofVisualBasic3.0.Itwaswiththis releasethatMicrosoftfirstprovidedVisualBasicdeveloperswithamethodtoeasily connecttoavarietyofdatasourcesandbuildmuchmorerobust,data-driven applications.Withthisnewcapability,corporationscouldtakeadvantageofVisual Basic'sinherentrapidapplicationdevelopmentstrengthstoquicklybuildsolutionsthat utilizednewandexistingdatabasesthroughouttheirorganizations.WithVB3.0,thetwo primarytechnologiesthatmadethispossibleweretheJetdatabaseengineanda revolutionarynewobjectmodelcalledDataAccessObjects.
Jet databaseengineTheJetdatabaseenginewasinitiallydevelopedasthecoredatabaseenginebuiltinto theMicrosoftAccessdatabase,andalldevelopmentfromwithinAccessusedtheJet enginetointeractwiththeunderlyingdatabaseobjects.UntilthereleaseofVB3.0,this enginewasspecifictoAccess,anditsfeaturescouldnotbeusedfromanyother product.
DAOOneofthekeyreasonswhyVB3.0andthisearlyversionoftheJetEngine,version1.1, gainedsuchwidespreadacceptancewastheinclusionofanabstractobjectmodelfor interactingwiththeJetengine.Thisobjectmodel,calledDataAccessObjects(DAO), providedasimpleandflexiblemethodforconnectingtoandmanipulatingdatainany datasourcecompatiblewiththeJetengine.AlthoughtheuseofDAOswasstillsubject tothearchitecturallimitationsimposedbytheJetengine,thesimplicityofdataaccess throughtheDAOstructurealloweddeveloperstoquicklydeveloprobustandpowerful databaseapplicationsinVB.
VBSQLVisualBasic4.0includedsupportforaSQLServer-specificAPI,calledVBSQL,which providedVBdeveloperswithalow-levelAPIforconnectingdirectlytoaSQLServer database.ThisAPI,builtaroundtheC-BasedDB-Library,servedasalightweightand high-speedinterfacethatwasrelativelyeasytocodewhenusingVB.AlthoughVBSQL providedagreatsolutioninspecificsituations,thefactthatitcouldbeusedonlyto connecttoaSQLServerdatabase,whichdidn'thaveasignificantmarketshareinthe early'90s,severelyhindereditsacceptancebythedevelopmentcommunity.Also,as moreobject-orientedanddatabase-neutralmethodsfordatabaseaccessbecame available,developersbecamelesslikelytocodedirectlyinadatabase-specificAPI.
RDOAlsoincludedinVB4.0wasanewobjectmodelfordataaccesscalledRemoteData Objects,orRDO.TheinclusionofRDOwasanattempttoaddressanumberofdesign andscalabilityissuesthatdeveloperswerecurrentlyfacingwhendevelopinglarge distributedclient/serverapplicationswithDAOandJet.AlthoughtheuseofDAOandJet requiredaheavyamountofprocessingandmemorytobeutilizedontheclient,RDO providedamuchsmallerandfasterclient-sideobjectmodelwhileallowingtheRDMS systemtobearthebruntofalltheprocessing.Thistypeofarchitecturewasnotintended toreplacetheDAO/Jetdataaccessmethod,whichwasstillsuitableforAccessandotherISAMdatabases;insteadit,alloweddeveloperstotakeadvantageofthefeatures providedbymorepowerfulandfull-featureddatabasessuchasSQLServerandOracle.
OLEDB
DuetothewidespreadadoptionofMicrosoft'sActiveXDataObjects,orADO,the associatedincreaseinavailableOLEDBdrivershasgrownsignificantly.Thefollowingis ajustsmalllistofsomeofthemanydatasourcesthatcanbeaccessedthrougha providedOLEDBprovidertoday:
MicrosoftSQLServerdatabases Oracledatabases Jetdatabases MicrosoftOLAPservers ActiveDirectory MicrosoftExchangeWebFolders MicrosoftIndexServer Sybasedatabases Btrievedatabases AS/400(throughHostIntegrationServer2000) Textfiles SharepointPortalServerDocumentStorage(WSS)
VisualBasic6.0
BystandardizingonOLEDBprovidersasthecoretechnologyforinteractingwithany typeofrelationalornonrelationaldatastores,Microsoft'snextstepwastoprovide developerswiththenecessarydataconsumertobeusedbyamultitudeofclient applications.ThisnewconsumerwouldhavetobuildonthestandardOLEDBprovider conceptbyprovidingapowerfulyetsimpleobject-orientedinterfacetoanyOLEDB- exposeddatasource.
RecordsetsTheentiredevelopmentparadigmpresentedbyADO(andOLEDB)centersaroundthe Recordsetobject.TheRecordsetobjectservesasadeveloper'sprimaryinterface
whenusingADOtointeractwithadatabase,effectivelyservingasadeveloper'swindowintothedatastore.AllmanipulationoftheunderlyingdatausingADOoccursthroughthis window,andtheADOsubsystemitselfhandlesthedetailsofmakingsureallchangesaremadebacktothedatabase.Inessence,theRecordsetobjectallowsyouto programmaticallymanipulateasubsetofdatafromadatabasebyusingavarietyof differentobjects,techniques,andcursormodels.EachRecordsetexposesasetof rowsandcolumnsthatyoucantraversetogetorsettheinformationyouneed.Because ADOservestoexposethefunctionalityoftheunderlyingOLEDBproviders,the Recordsetobjectprovidesaconsistentandfamiliarinterfaceregardlessoftheoriginof aparticularsetofdata.OneofthekeydrawbacksintheimplementationoftheADORecordsetobjecthas beenthelackofasimplewaytoexposetheextendedtypesandfeaturesprovidedby anyindividualdatabaseorproductinastandardfashionfordeveloperstoworkwith. Becausemultipledatabasescanhavedifferentunderlyingdatastructuresforcommon datatypessuchasstringsanddates,theRecordsetobjectsimplymanipulatesall actualdatavaluesasVariantdatatypes.Thisallowsagreatamountofflexibilityand neutralitytotheRecordsetobjectwhendealingwithdiversedatasources,butithas alsoprovidedADOwithitssinglebiggestperformancehit.Byforcingeveryvalueof everyfieldinanADORecordsettobeaccessedasalateboundVariantdatatype,asignificantperformancelossisincurred.ThisisakeyfeaturethathasbeenaddressedintheimplementationofADO.NET.
Overview of ADO.NETWiththereleaseofADO.NETinthe.NETFramework,Microsofthasprovidednotonly anobjectmodelandinfrastructuretofacilitatedataaccess,butalsoacompletenew mindsetfordataaccessthatdiffersfromanythingpreviouslyavailable.Beforeyoubegin examiningthedetailsofusingtheADO.NETFrameworkinthenextchapte r ,itis importanttohaveanoverviewofthemajorpiecesofthe.NETdata-accessFramework tohelpprovideabigpictureofthearchitecturebehindthistechnology.
XML=data,data=XML
ThebasicprinciplebehindtheADO.NETimplementationliesinthefactthatalldatais representedinanXML-basedformat.Thisallowsvendorswishingtoprovideintegration withrelationaldatabasesornonrelationalstructurestosimplyimplementanewtypeof providerthatmanipulatestheirrespectivedatastoresintoXML,andhandlesmanipulatingthereturnedXMLbackintoaformatunderstandablebythedatastore.ThiscapabilitytoconsumeXMLasdataalsoallowsADO.NETunderstanddatafromanyXML-compliantapplicationorplatform.
ADO.NETstructureThebasicstructureoftheADO.NETobjectmodelrevolvesaroundtwoseparategroups ofobjects:DataSetsanddataproviders.DataSetsandtheirrelatedgroupsofobjects provideadatabase-neutralviewofanydatathatcanbeexposedasanXMLdocument. Thisstructureallowsdeveloperstomanipulateadisconnectedandhierarchicalviewof datainamannerthatshouldbeveryfamiliartoADOdevelopers.Appropriately,data providersserveasthelow-levelintegrationandmappingbetweenXMLdocuments,such asthosemanipulatedbyDataSets,andtheunderlyingdatabases.Dataproviders essentiallyserveasthe"bridge"betweenDataSetsanddatasources,whichallow DataSetstoessentiallyremainisolatedfromanyspecificdataimplementationorsource.Beyondthis"bridge"functionalitybetweendatabasesandDataSets,dataprovidersalsoservetoprovidealladditionaldatasource-specificfunctionalitysuchas datatypesandcommands.
DataSetsTheDataSetprovidesanobjectmodeltomanipulate oneormoretablesofdata.TheDataSetalsoprovidesthemeanstotrackandmaintain relationshipsbetweentables,andenforcesuchconstraintssuchasuniquevaluesand calculatedfields.
DataSetobjectmodelTherootoftheDataSetobjectmodelistheDataSetobjectitself,whichhandlesallthe baseservicesfortheentireunderlyingstructure,suchasserializingtoandfromXML.ItisthroughtheDataSetobjectthatdevelopersgainaccesstothemanyobjectsthat
worktogethertomakeuptheentireDataSetobjectmodel.Thefollowinglistgivesan overviewofeachofthekeyobjectsthatmakeuptheDataSetobjectmodel:
DataTable:ThisobjectrepresentsasingletableofdatawithinaDataSet.ADataSetmaycontainmultipleDataTableobjects, eachrepresentingalogicaltableofdata.
DataRow:EachDataTableobjectinaDataSetcontainsacollection ofzeroormoreDataRowobjectsrepresentingthedatawithinthat table.EachDataRowobjectservesasanarrayoffieldsthatare definedbytheDataColumncollectiondiscussedasfollows.
DataColumn:TheDataColumncollectionofaDataTablespecifiesinformationabouttheindividualcolumnsofdataineachtable.This schemainformationconsistsofalargenumberofpropertiesbeyond thestandardnameanddatatypeofaspecificcolumn.
DataRelation:TheDataRelationcollectionexistsdirectlyoffthe rootDataSetobject,andspecifiesinformationregardingthespecific tableandcolumnrelationshipsthatneedtobemaintainedbetween twoDataTableobjectsinasingleDataSet.
DataConstraint:ADataConstraintobjectprovidesameansfordeveloperstospecifyconstraintsthatmustbeenforcedona particularcolumninaDataTable.
Chapter22:ADO.NET
In This ChapterAccessingADO.NETfeaturesandnamespacesUsingADO.NETDataprovidersDataSets
Accessing ADO.NET Features and NamespacesBeforeyoucanstarttotakeadvantageofthefeaturesprovidedbyADO.NET,youmust knowhowtomakethesefeaturesavailablefromyourVB.NETapplications.BecausetheADO.NETobjectsareprovidedaspartofthebaseclassesofthe.NET Framework,theycanbemadeavailabletoaVisualBasic.NETprogrambyadding referencetotheSystem.Data.dllfromwithinyourapplication.Addingareferencetoanapplicationcanbedoneinavarietyofways,buttheeasiestisprobablytoright-clicktheResourcesfolderofyourprojectundertheSolutionExplorer window.Afterdoingthis,acontextmenuappears,inwhichyoumayselectAdd Reference.Fromthefollowingdialogbox,youmayaddthereferencetothe System.Data.dllbyselectingitfromthelistof.NETcomponents.
Table22-1:ADO.NETNamespaces
Namespace Description
System.Data Thisnamespacecontainsallmajorcomponents oftheDataSetobjectmodel.
System.Data.SqlTypes AcollectionofMicrosoftSQLServer-specific datatypes.
System.Data.SqlClient AMicrosoftSQLServer-specificdataprovider.
System.Data.OleDb AmanageddataprovideroptimizedforOleDBproviders.
System.Data.ODBC AmanageddataprovideroptimizedforODBCdrivers.
Using ADO.NET
Table22-2:ProviderInterfacesandObjects
Object BaseInterface
SQLServerProvider
OLEDBProvider
Connection IDBConnection SQLConnection OleDBConnection
Command IDBCommand SQLCommand OleDBCommand
DataReader IDataReader SQLDataReader OleDBDataReader
DataAdapter IDataAdapter SQLDataAdapter OleDBDataAdapter
Transaction IDBTransaction SQLTransaction OleDBTransaction
UnderstandingdataprovidersBeforeyougetintohowtomanipulateandchangedatathroughaDataSetobject,you shouldfocusontheobjectsthatmakeupadataprovider.Themajorityofthesamples providedinthischaptermakeuseoftheSQLServerprovider (System.Data.SqlClient). Althoughsomeoftheexamplesdemonstrateusingother providers,itisimportanttorealizethatalltheprovidersimplementthesamefunctionality andbasesetofobjects.Becauseeachdataprovidertargetsadifferenttypeofdataconnection,eachimplementsitsownsetofobjectsthatexposeastandardinterface.Also,itisimportanttonotethat eachproviderprovidesaseparatesetofobjects,eachhavingauniquename.Whatthis meansisthattheSQLproviderimplementsasetofobjectswithnamesprecededbya SQLprefix,andtheOleDBproviderimplementsasimilarsetofobjectsexposingthesameinterfaces,butwithnamesprecededbyanOleDBprefix.Thesesetsofobjectsarealsolocatedwithinuniquenamespaces.Thus,whenyouwishtotargetaSQLserver database,youcanusetheSQLproviderlocatedintheSystem.Data.SqlClient namespaceandcontainingobjectssuchasSqlCommandandSqlConnection.WhentargetingadatabasetowhichthereisonlyanexistingOleDBconnection,youcanuse theOleDBproviderthatislocatedintheSystem.Data.OleDBnamespace.Thesame objectsintheOleDBnamespacewouldbecalledOleDBCommandand OleDBConnection.
Table2 2 - 2 presentseachofthebaseADO.NETdataproviderinterfacesandtheir associatedimplementationforthetwomajorproviders:
ConnectionsWhendealingwithADO.NETdataproviders,theobviousstartingpointistheConnection object,whichprovidesthebasisforwhichalltheotherADO.NETdataproviderobjects acquireandmaintaintheirconnectionswiththeirassociateddatastores.Ifyouare familiarwithADOConnectionobjects,youshouldbeinstantlyfamiliarwiththe ConnectionobjectsimplementedinADO.NET.
'CreateaConnectionobjectsettingit'slocationinthe_
constructor
DimoConnectionAsNewSqlClient.SqlConnection("Data _
Source=(local);InitialCatalog=Northwind;Userid=sa")
'CreateanemptyConnectionobject
DimoConnection2AsNewSqlClient.SqlConnection()
'Setit'slocation
Connection2.ConnectionString ="DataSource=(local);Initial_
Catalog=Northwind;Userid=sa"
NoticethattheoConnectionandtheoConnection2objectsareidentical,butyou simplifytheconfigurationofthefirstonebyspecifyingtheconnectionstringwhenyou
instantiateyourinstanceoftheobject.Thistypeofoverrideisacommonoccurrencein the.NETFramework,andtakingadvantageofitcangreatlysimplifyyourcode.
CommandsNowthatyouhaveseenthesimplicityofconnectingtoadatasourcethroughthe Connectionobject,thechapterdiscussesCommandobjects.ADO.NETdataproviders useaCommandobjectwheneverdatasource-specificcommandsneedtobeexecuted againstaspecificdatasource.Themostcommontypesofcommandstobeexecuted againstadatasourceareSQLcommands,butthedataprovidermodelallowsfora separateCommandobjecttobeimplementedwheneverthisisn'tpossible.Inthefollowingexample,youcreateasimpleCommandobjecttoexecuteasingleSelectstatementagainstaserverbyusingtheSqlCommandimplementationprovided intheSystem.Data.SqlClientprovidernamespace.
'CreateanewcommandobjecttobeusedtoselectallCustomers
DimoCommandAsNew_
SqlClient.SqlCommand("Select *FromCustomers",oConnection)
DataReaderobjectsNowthatyouhavebecomefamiliarwithbothConnectionandCommandobjects,you takealookatthefirstoftwomajormethodsforviewingtheresultsofyourCommand queries.Thesetwomethods,DataSetsandDataReaders,providesolutionstotwo verydifferentproblemsforthedeveloper.Itisimportanttorealizethateachofthese objectsisthebestchoiceforcertainsituations,andneitherprovidesacatchallsolution (aswasthecasewiththeADORecordset).TheDataReaderobject,thefirstofthetwoyouexamine,isprovidedaspartofaspecificdataprovider.ThismeansthataSQLServer-specificimplementationofthe DataReader(SQLDataReader)exists,aswellasanOLEDB-specificimplementation (OleDBDataReader).Anyvendorimplementingasetofdataproviderobjectsofthe ADO.NETFrameworkfordataaccessprovidesanapplication-specificimplementationof theDataReaderinterface.
DataAdapterobjectsThenextandmostcomplexmajorcomponentofadataprovideristheDataAdapter object.DataAdapterobjectsprovidethemeansforadisconnectedDataSetobject, tointeractwithadatabase. DataAdapterobjectsprovidetheentiremappingfromthedatabaseintotheXMLformatunderstoodbytheDataSet;theyalsomaptheXMLreturnedbyaDataSetinto theappropriateInsert,Update,andDeleteCommandobjects,andsetallparameters accordingly.Thisallowsanydatabase-specificimplementationandSQLdetailstobe preconfiguredatdesigntimebythedeveloper,andabstractedintoaDataAdapter.
TableMappingsOneadditionalfeatureprovidedbytheDataAdapteristheabilitytoprovideasetof tableandcolumnmappingsthroughwhichitassociatesalltablenamesandcolumnnamesprovidedbytheDataSetagainstthoseactuallyusedbythedatastore.This allowsDataAdapterdeveloperstheabilitytoprovideaseparatesetofnamesfor tablesandcolumnstothefront-enddevelopersandusersoftheDataSetwhile maintainingallmappingsinaconsistentplace.
CreatingDataTablesThecoreoftheDataSetarchitectureiscenteredontheDataTableobject.Asingle DataSetcancontainmanyDataTableobjects,andaDataSetprovidesthecapability toenforcerelationshipsbetweenanytwoDataTables.TheTablescollectionofa DataSetcontainseachoftheDataTableswithintheDataSet.UsingtheTables collection,youcanaccessaspecificDataTablebyeitherusinganindexorthenameof thetable.ThestructureofeachDataTableisdefinedbyacollectionofDataColumnobjects.ThiscollectioncanbeaccesseddirectlyfromaDataTableobjectusingtheColumns property.EachDataColumnobjectexposesalargeamountofinformationdefiningthe structureofthatparticularcolumn.BymanipulatingaDataColumnobject,youcan configureexactlyhowacolumnofdatabehavesinaparticularDataTable.Thebasic
columnfeatures,suchasname,datatype,length,andinitialvalueareeasilyavailable, aswellasahostofmoreadvancedproperties.PropertiessuchasAutoNumber, ReadOnly,Caption,andUniqueprovideahostofpowerfulfeaturesthatyoucanuse tomakeaDataTablebehavemorelikeaclient-sidedatabase.Anotherhandyproperty of theDataColumnobjectistheColumnMappingproperty,whichallowsyoutocontrol howaspecificcolumnisaddedtotheunderlyingXML.TheavailableColumnMapping typesareElement,Attribute,Hidden,andSimpleContent.Thesesettingsaffect howaDataColumniswrittenoutwhenusingWriteXMLmethodofaDataSettowrite itscontentsoutasXML.
Chapter23:DataAccessinVisualStudio.NETIn This Chapter
AhistoryofMicrosoftdataaccesstechnologiesAnoverviewofADO.NET
Visual Studio .NET Database ToolsThefirstsetofVisualStudio.NETfeaturesprovidesyouwiththetoolstoeasily administerdatasources.Thesefeaturesallowyoutocreateandmanipulatedatabase objectssuchastables,views,andstoredprocedures.Also,developerscanusethese toolstoviewandeditthedatawithindatasourcestosimplifydebuggingandmonitoring ofdatabaseapplicationswithouthavingtouseaseparatetoolsuchasSQLServer EnterpriseManager.AlthoughthemajortoolsprovidedbyVisualStudio.NETareonly
brieflydiscussedinregardstodatabaseadministration,eachofthetoolsdiscussed providesagreatdealofpowertoyouwhenyoudevelopdatabaseapplicationsfrom VisualStudio.NET.
UsingServerExplorerTheVisualStudio.NETServerExplorerwindowservesasadeveloper'swindowintonot onlydatabaseobjects,butalsoamyriadofotherservicesthatcanbeaccessedon remotemachines.TheServerExplorerwindow,likesomanyothertoolsinVisualStudio.NET,canbedockedandmadeeasilyavailableduringregulardevelopment(seeFigure23 - 1 ).
Figure23-1: YouusetheVisualStudio.NETServerExplorertomanipulateDatabaseObjectsandremoterServersdirectlyfromtheVisualStudio.NETIDE.
ThenodesintheServerExplorerwindowarepresentedintwoseparatesections:DataConnectionsandServers:
TheDataConnectionssectionletsyouaddconnectionstoregularlyused dataconnections.Afterthesedataconnectionsareestablished,the ServerExplorerwindowenablesyoutomanipulatetheunderlying databaseobjects.
TheServerssectionallowsyoutoconnecttoremoteservers,andprogramagainstavarietyofservicesthatmaybeavailable,suchasWeb services.
AddingconnectionsToaddaconnectiontotheServerExplorer,right-clickthenodeandselectAdd Connectionfromthepop-upmenu.AfterclickingAddConnection,theDataLink Propertiesdialogbox,whichprovidesalltheoptionsavailableforaddingavaliddata connectionusingavarietyofavailabledriversanddatasources,opens.Asyouseelater inthechapter,byhavingthisconnectionavailableintheServerExplorer,youcaneasily dragtheconnectionsontoformsorcomponents;VisualStudio.NETandtheIDE automaticallyaddtheappropriatecodetoconfiguretheconnectionwithinthatitemofa
project.Figure2 3 - 2 illustratessomeoftheoptionsavailablewhenconfiguringanew dataconnection:
Figure23-2: YouusetheDataLinkPropertiesdialogboxtoaddconnectionstotheServerExplorer.
ToproperlyconfigureadatabaseconnectioninVisualStudio.NETbyusingtheData LinkPropertiesdialogbox,youmustselecttheappropriateproviderandconnection information,suchasservername,databasename,andlogincredentials.Afterthese settingshavebeenproperlyconfigured,youcanaccessthisconnectioninformation,and manipulatedatabaseobjectsunderneaththisconnectionifthedatasourcesupportsthis, regardlessoftheVisualStudio.NETsolutionthatiscurrentlyopen.Thisfeatureallows youtoaddconnectionstoyourmostcommonlyuseddatabasesand,ifrequired,easily sharethemacrosssolutionswithouthavingtoreconnectorconfigure.
AdministeringdatasourcesthroughtheServerExplorer
OneofthebesttimesavingfeaturesavailablefromwithinVisualStudio.NETisthe capabilitytocompletelyadministermostdatasourceswithoutleavingtheIDE.This administration,similartothatprovidedbySQLServerEnterpriseManager,allowsyouto addandconfiguredatabasediagrams,tables,views,andstoredprocedures.
ManipulatingdatabasetablesinVisualStudio.NETByusingtheServerExplorerwindowtoexpandaspecificdatabaseconnection,youcan navigatetotheTablesnodetogainaccesstoalistofallexistingusertablesinthe database.Byright-clickingtheTablesnode,youcanselecttheNewTableoptionfrom theresultingpop-upmenutoaddanewtabletothedatabase.Also,byright-clickingan existingtableandselectingtheDesignTableoption,youcanmodifythestructureof existingdatatables.Figure23 - 3displaysthetabledesignerusedbyVisualStudio.NET tomanipulatedatabasetablestructures.
Figure23-3: TheVisualStudio.NETdatabasetabledesignerallowsyoutomanipulatethe structureofdatabasetablesfromdirectlywithintheIDE.
ThetabledesignerprovidedbyVisualStudio.NETallowsyoutomodifythestructureof tablesbyprovidingcompletecontroloveratable'scolumninformation.Asshownin Figure23 - 3,thecolumninformationforatablecanbeeasilyeditedinthegridprovided bythetabledesigner.Otherfeaturesavailablefromwithinthetabledesignerthatcanbe accessedfromtheVisualStudio.NETtoolbarwhenthetabledesignerisopeninclude theabilitytomodifycolumnindexesandforeignkeyrelationships.
Beyondtheabilitytodesigntables,theServerExplorerwindowprovidesyouwiththe abilitytoviewthedatainatable,exportallthedatatoafile,generatetheappropriate SQLscripttore-createthetableonanotherdatabase,andaddatriggertothe database—allfromwithinthestandarddevelopmentenvironment.Eachofthese functionsisavailablebyright-clickingtheappropriatetablenodeintheServerExplorer window.
ManipulatingdatabaseviewsinVisualStudio.NETWhenworkingwithdatabaseviews,VisualStudio.NETutilizesafull-featured,built-in queryanalyzer.ThisqueryanalyzerallowsyoutoconstructoreditSQLstatementsina mannerverysimilartousingthequeryanalyzerinSQLServerEnterpriseManager.You spendmoretimeonthequeryanalyzerinthefollowingsectionthatdiscussesstored procedures.Inadditiontothequeryanalyzer,VisualStudio.NETprovidesyouwitha powerfulquerybuilderforgraphicallydesigningandconstructingSQLstatementsand views.TheVisualStudio.NETquerybuildergivesyoutheoptionofbuildingthequeries graphicallyorbymanuallykeyingtherequiredSQLstatements.Also,byutilizingthe querybuilder,youcanverifythevalidityoftheSQLstatementsagainsttheappropriate datastore,andevenexecutethestatementandpreviewtheresults,asshowninFigure23 - 4 .
Figure23-4: TheVisualStudio.NETquerybuilderprovidesyouwithanumberoftoolsto graphicallyconstructSQLqueriesandviews.
Thequerybuilderitselfisbrokenintofourverticallypositionedpanes(asshowninFigure23 - 4 ).Thefollowinglistprovidesabriefdescriptionofeach ofthesepanesfromtopto bottom:
DiagramPane—Providesagraphicalrepresentationofthetables includedinaSQLstatementandthejoinsbetweenthem.Byaddingor removingtablesfromthispane,thequerybuilderautomaticallymakes theappropriateadjustmentstotheSQLpane(describedbelow).Also, bycheckingtheboxnexttoanycolumninanytable,youcanchoosetoincludethatparticularcolumnintheresultingquery.
GridPane—Providesyouwiththeabilitytoseeallthecolumns selectedtobereturnedasaresultofexecutingthecurrentquery.This panealsoprovidesyouwiththeabilitytoentercriteriaandfiltersbasedonaspecificcolumn,andtospecifyacolumnaliasandsorting information.
SQLPane—ThispaneinthequerybuilderdisplaysthecurrentSQL statementasdefinedbyyourmodificationstotheDiagramandGrid panes.YoualsohavetheabilitytomakechangesdirectlytotheSQL paneandseethemreflectedintheabovetwopanes.
ResultsPane—Itisinthispanethatyoucanviewtheresultsofa queryexecutedafterclickingtheRunbuttononthetoolbar.
Asyoucansee,thequerybuilderprovidesanumberoffeaturestogreatlysimplifythe generationofSQLstatements.Andasdiscussedinthenextsectio n onmanipulating storedprocedures,thequerybuilderintegratestightlywiththequeryanalyzerinVisual Studio.NETtoallowyoutoquicklybuildverycomplexstoredproceduresmadeupofa numberoflogical"blocks"ofSQLstatements.
PartV:WindowsFormsChapter25:IntroductiontoSystem.Windows.FormsChapter26:ControlsChapter27:SpecificControls Chapter28:"Visual"Inheritance Chapter29:IrregularFormsChapter30:OtherNamespacesandObjectsintheCatalog
Chapter25:IntroductiontoSystem. Windows.FormsWhatconstitutesawindow?
Awindow,initscrudestform,isanenclosed,rectangularareaofthescreen.Itis typicallydefinedbyaboundingrectangle(visibleornot)andoftencontainsdataorother windows.Bythisdefinition,notonlyareformswindows,butcontrolsarewindowsas well.
IntheWindowsoperatingsystem,ahandleidentifiesawindow.Thisisanalogoustoan onlinehandle,oraCBhandle.Inthecaseofwindowsprogramming,thehandleis uniqueamongstallwindowscurrentlyloaded.Furthermore,awindowhandleremains constantuntilthewindowisunloaded.
VisualBasic4introducedatypeofcontrolcalledlightweightorwindowless.Thesewerecontrols(forexample,theLineandShapecontrols)thatdidnothaveabounding rectangleorahandle.Theyessentiallyconstitutedasetofinstructionsforthecontainer controltopaint.Theintroductionofthesecontrolsledtomanyinconsistenciesforthedeveloperbecause windowedandwindowlesscontrolshadtobehandleddifferently.Furthermore,these controlshadsignificantlyreducedfunctionalityduetotheirlackofahandle.
In.NET,everycontrolis"windowed,"whichhasadvantagesanddisadvantages.The goodsideisthatyounowhaveathoroughlyconsistentframeworkuponwhichto develop.Allcontrolshaveahandleandcanreceiveanyrelevantornecessarymessage. Thedownsideisthatsomecontrolsthatmaynotneedtoreceivemessagesorbe identifiedbyWindowsnowhavetheoverheadofawindow.Inshort,thismeansthatcontrolssuchastheLineandShapecontrols,whicharenolongerpresentwithin.NET,canbeaccomplishedonlybyexplicitlycomposingthe paintingcode.Which,inmyopinion,isexactlythewaytheyneedtobe.
Whatcanawindowdo?
Awindowistheprimarymethodofinteractionbetweenyoursoftwareandtheenduser. Thus,ithandlesalltheinput(keyboard,mouse,andsoon)fromtheuser,andprocesses itaccordingtoyourinstructions.Furthermore,itdisplaysanyinformationyouinstructitto withanyformattingyoudesire.
Thefactthatthe.NETFrameworkhasnowmadeitemssuchasformsandcontrolsfully inheritableclassesalmostremovesallneedtoprogramagainsttheWin32API.Asa developer,youcannowgettheentirewindowprocessingpowerforfreeinwhateveryou wishtoaccomplish.ItisstillpossibletodealwiththeWin32APIdirectly,though.Methodsincludecalling P/InvokeoroverridingtheWndProcfunction.Thisabilityiscrucialforaccomplishing certaintasksthathavenotyetbeenimplementedintheframework.However,youwill findthatyourusageofthesemethodswillbeminimal.
Basics of the Windows FormTheWindowsForm(seeFigure25 - 1 )isessentially,themostimportantcontrolinyour repertoireasaGUI(GraphicalUserInterface)developer.TheFormisthecanvasupon whichyoupaintthecontrolsrequiredfortheenduserstoaccomplishtheirgoalsofdata entry,systemadministration,softwaredevelopment,oranynumberofinfinitetasks.
Figure25-1: Theever-importanttabularasa.
TheFormisacontrollikeanyotherinthetoolbox,yetitissomuchmore.Youlearnwhy throughoutthesechapters.
WheredoestheWindowsFormcomefrom?ThehierarchyofobjectsfromwhichtheWindowsFormisderivedisshowninFigure 25 - 2.
Figure25-2: TheWindowsFormclassancestry.Top 10 Reasons Why a Windows Form Is Better than a VisualBasic 6 FormThefollowinglistdelineates10itemsthatwerepreviouslyunavailableorunacceptablein VisualBasic6thathavebeenrectifiedinVisualBasic.NET.Opinionsdifferonthe"best" changesthathaveoccurred.Hopefully,though,thislistaddressesthemajorityofthe opinions.
10.AWindowsFormhastwiceasmanypropertiesandmethodsasanoldform.TheWindowsFormexposessignificantlymoreproperties, methods,andeventsthantheVisualBasic6 form.Thismeansmore functionalityisavailableforyoutoplaywith.Plus,thereisareduced levelofdependencyontheWin32API.Overall,theadditionofproperties,methodsandeventsfurtherenhancestherapiddevelopment experiencebyexposingsignificantlymorebehavior.9. AWindowsFormcaneasilycontainadockabletoolbar.The
WindowsFormsframeworkintroduceshandyconceptssuchasdocking, whichareeasilygraspedandimplementedbythenovicedeveloper. DockablewindowsinVisualBasic6werevirtuallyimpossibletoimplement.ThishandyfeaturecanbeeasilyleveragedtocreatericherGUIsthaneverbefore.
8. WindowsFormsareopaqueuntilthey'renot.TheWindowsForms frameworkintroducesapropertycalledopacity.Thisisnotaparticularly newconceptbecauseVisualBasicformshavealwaysbeenopaque. However,ratherthanusetheSetLayeredWindowsAttributesAPI onalayeredwindowtocreatevaryinglevelsoftranslucency,this propertyallowsyoutocreateatranslucentwindowbysettingaproperty. (CheckouttheSearchWindowinTextPadforagooduseofthis concept.)Thisconceptcanbeparticularlyusefulinthedevelopmentof moregraphicallyorientedapplications.
7.
Youcancapturethemousewheelwiththegreatestofease.Itmaybealittlething,butdarnit,you'llbehappyaboutit.InVisualBasic.NET, whenacontrolhasthefocusandtheuserscrollsthemousewheel,you canrespond,ifnecessary.ThiswasanothertaskfortheAPIinVisual Basic6.InMicrosoftExcel,holdingdowntheCTRLkeyandscrollingthe mousewheelresultsintheZoomFactorchanging.Thistypeof functionalitycanbeveryeasilyimplementedwiththeinclusionofa mousewheelevent.6. Thereisnowanobject-orientedapproachforgraphics. EverywindowinVisualBasic.NEThasanassociatedGraphicsObject.Every forminVisualBasic6hasaDeviceContext.InVisualBasic6,you neededtheDeviceContexttopasstotheAPIcallsnecessarytodrawa polygon.InWindowsForms,youcancalltheDrawPolygonmethodof theGraphicsObject.5. Allborderstylesareavailabletoyouatanytimeviathe
FormBorderStyleproperty.InVisualBasic6,youwereprevented fromeasilychangingtheborderofaformtocertainvalues.Youwere requiredtodestroytheformandthenredisplayit.VisualBasic.NETnow handlesallofthisforyou.Youmayrunintoproblemsregardingchanging handles,asoutlinedinthepitfallssectionofthischapter,buthowoftendoyouneedthehandleinWindowsForms?
4. AutoscrollisnotjustGermanparchment.AWindowsFormnow supportsautoscrolling.Autoscrollingsimplymeansthatthescrollbars appearonaformifanyofthecontrolsresideoutsidethevisibleareaof theform.Thisisaveryhandyfeaturefordealingwithsignificant variationsinresolution.InVisualBasic6,youhadtodevelopforthe lowestcommondenominator,600x480.
3.
AWindowsFormcananchorlikeasailor.Manyimportantpartsofthegraphicaluserinterfacedesigninvolvethelittlethings—thedetailsthat maketheenduser'sexperienceworthwhile.Onetheselittlethingsis resizeablewindows.VisualBasic6alwayshadresizeablewindows,but howdoyoumovethecontrolsinaccordancewiththeform?Theonly waytohandlethisinthepastwaswithafairamountofcodethat analyzedpositionsandratios,andmovedthecontrolstotheappropriate place.WindowsFormsintroducesaconceptcalledanchoring,which groundsthecontrolsintheirrespectivepositionsinrelationtotheir container.Nothingcouldbeeasier.2.
Youdon'tneednostinkingtwips.FewthingsweremorecumbersomeinVisualBasic6thanunitsofmeasurement.Okay,somethingswere morecumbersome,butthisonereallybuggedme.InWindowsForms, everythingismeasuredinpixels.Thismakesforveryconsistentinterface development.1.
IntheWindowsFormsframework,aformisjustaclass.ThemysticalVisualBasic6formisgone;ithasbeenreplacedbyafully extensibleandinheritableclasswithvisualcapabilities.Oneofthemost valuableresultsofthisisVisualInheritance.Thisfeatureisfully addressedin Chapter28 .
Chapter26:Controls
System.Windows.Forms.Control
Table26-1:PublicSharedPropertiesoftheControl
PropertyName DescriptionDefaultBackColor Read-only.Returnswhatthebackgroundcolorof
thecontrolwouldbeifthebackgroundcolorwere notexplicitlyset.
DefaultFont Read-only.Returnswhatthefontofthecontrol wouldbeifthefontwerenotexplicitlyset.
DefaultForeColor Read-only.Returnswhatthe foregroundcolorof thecontrolwouldbeif theforegroundcolorwere notexplicitlyset.
ModifierKeys Read-only.Returnsabitwisecombinationof valuesgivingthecurrentstateoftheCtrl,Alt,and Shiftkeys.
MouseButtons Read-only.Returnsabitwisecombinationof valuesgivingthecurrentstateoftheleft,middle, andrightmousebuttons.
MousePosition** Read-only.Returnsapointgivingthecurrent positionofthemouserelevanttotheupper-left cornerofthewindow.
PublicinstancepropertiesApublicinstancepropertyrequiresthattheclassbeinstantiated.Thepropertyvalues arenotsharedwithanyotherinstances.Thus,iftwoinstancesofanobjectarecreated, thevalueofonepropertyofthefirstinstanceisnotguaranteedtobethesameasthe valueofthesamepropertyofthesecondinstance.Table26-2:PublicInstancePropertiesoftheControl
PropertyName DescriptionAccessibilityObject SpecifiestheAccessibleObject
assignedtothecontrol.An AccessibleObjectisusedbyan accessabilityapplicationthataccomodates foruserswithdisabilities.
Table26-2:PublicInstancePropertiesoftheControl
PropertyName DescriptionAccessibleDefaultActionDescription Specifiesthedescriptionofthedefault
actionofthecontrolwhenaccessedbyan accessiblityapplication.
AccessibleDescription Specifiesthedescriptionofthecontrol whenusedinthecontextofanaccessibity application.
AccessibleName Specifiesthenameofthecontrolinthe contextofanaccessibilityapplication.
AccessibleRole Specifiestheroleofthecontrolinthe contextofanaccessibilityapplication.The resultisavalueintheAccessibleRole enumeration;forexample,scrollbarand pushbutton.
AllowDrop Specifieswhetherthecontrolacceptsdata thatisdraggedanddroppedintoitbythe user.
Anchor Specifieswhichedgesofthecontrolare boundtotheedgesofitscontainer.
BackColor Specifiesthebackgroundcolorofthe control.
BackGroundImage Specifiesthebackgroundimageofthe control.
BindingContext Specifiesthebindingcontextofthecontrol. ThismanagestheBindingManagerBase Collectionforthecontrol.Each BindingManagerBasecontrolsbindingto onedatasource.So,ifyouhavethreetext boxes,eachboundtoadifferentcolumnin thesametable,theBindingManagerBaseguaranteessynchronization.
Bottom Read-only.Returnsthey-coordinateofthe bottomedgeofthecontrolrelativetothe control'scontainerclientarea.
Bounds Specifiestheboundingrectangleforthe control.
CanFocus Read-only.Returnswhetherthecontrolcan receivethefocus.
CanSelect Read-only.Returnswhetherthecontrolcan beselected.
Capture Specifieswhetherthecontrolhascaptured themouse.Capture=Truemeansthat thecontrolreceivesallthemouse messages,regardlessofthepointerbeing intheclientareaofthecontrol.
CausesValidation** Specifieswhetherall controlsrequiring validationreceivesit whenthiscontrol receivesthefocus.
Table26-2:PublicInstancePropertiesoftheControl
PropertyName DescriptionClientRectangle Read-only.Returnstheclientareaofthe
control.Controlswithnon-clientregions, suchasthetitlebaronaform,donot includetheseregionsinthisrectangle.
ClientSize Read-only.Returnstheheightandwidthof theclientareaofthecontrol.
CompanyName Read-only.Returnsthecompanynameof theapplicationcontainingthecontrol.
ContainsFocus Read-only.Returnswhetherthecontrolor oneofitschildcontrolscurrentlyhasthe inputfocus.
ContextMenu Specifiesthecontextmenuobject(a.k.a. right-clickmenu)associatedwiththis control.
Controls Specifiesthecollectionofcontrolscurrently containedwithinthecontrol.*
Created Read-only.Returnswhetherthecontrolhas beencreated.Nottobeconfusedwith IsHandleCreated.
Cursor Specifiesthecursorthatisdisplayedwhen themousepointermovesoverthecontrol. Forexample,Cursors.WaitCursor changesthecursortoanhourglass.
DataBindings Read-only.Returnsthecollectionofsimple bindingobjectsforthecontrol.
DisplayRectangle Read-only.Alsoreturnstheclientrectangle ofthecontrol.However,inheritedcontrols maywishtomodifythis.
Disposing Read-only.Returnswhetherthecontrolis currentlyintheprocessofbeingdisposed. Note:Whenacontrolisdisposed,itisno longeraccessibleasavalidinstance. However,itmayremaininmemoryuntilthe garbagecollectorreclaimsit.
Dock Specifiestowhichedgeofthecontainerthe controlisdocked.Whenspecified,the resizingofthecontrolishandled automatically.Controlsthatare"dockable" requirecodeanalyzingwindowmovements coupledwiththesettingofthisproperty.
Enabled Specifieswhetherthecontrolis enabled. Thisalsocoversitemssuchas receiving focus.
Focused Readonly.Returnswhetherthecontrol currentlyhastheinputfocus.
Font Specifiesthecurrentfontforthecontrol.ForeColor Specifiestheforegroundcolorofthe
Table26-2:PublicInstancePropertiesoftheControl
PropertyName Descriptioncontrol.
Handle Read-only.ReturnstheWindowhandlefor thecontrol.
HasChildren Read-only.Returnswhetherthecontrol containschildren.*
Height Specifiesthefullheightofthecontrol.IMEMode SpecifiestheInputMethodEditormode
supportedbythiscontrol.TheIMEisused forallowinguserstoentercharacters neededforAsianlanguages.
InvokeRequired Readonly.ReturnswhetherInvokemust beusedwhenmakingmethodcallsonthis control.Typically,trueonlywhenthehandle ofthecontrolisonadifferentthreadthanthemethodcall.
IsAccessible Specifieswhetherthecontrolisvisibleto accessiblityapplications.
IsDisposed Read-only.Returnswhetherthecontrolhas beendisposed.Iftrue,thecontrolisno longeraccessibleasavalidreference.
IsHandleCreated Read-only.Returnswhetherawindow handlehasbeenassociatedwiththis control.
Left Specifiesthex-coordinateoftheleftedge ofthecontrol'swindow.
Location Specifiesthecoordinatesoftheupper-left cornerofthecontrolrelativetotheupper- leftcornerofthecontrol'scontainer.
Name Specifiesthenameofthecontrol.Thisvalueistypicallyusedtorefertothecontrol incode.
Parent Specifiestheparentcontainerofthe control.
ProductName Read-only.Returnstheproductnameofthe applicationcontainingthecontrol.
ProductVersion Read-only.Returnstheversionnumberof theapplicationcontainingthecontrol.
RecreatingHandle Read-only.Returnswhetherthehandleof thecontroliscurrentlybeingre-created. Thecomboboxsampleintheprevious chapte r demonstratedhowthiscanoccur.Region Specifiestheellipticalorpolygonalarea withinthewindowassociatedwiththis control.Youseemanyexamplesofthis propertyinthechapteronirregularforms.
Right Read-only.Returnsthex-coordinateforthe
Table26-2:PublicInstancePropertiesoftheControl
PropertyName Descriptionrightedgeofthecontrolrelativetothe containercontrol'sclientarea.
RightToLeft Specifieswhetherthealignmentofthe control'selementsisright-to-left.This propertyisusedtosupportlocaleswith right-to-leftfonts.
Size Specifiestheheightandwidthofthefull control.
TabIndex Specifiesthiscontrol'splaceinthetab orderofallcontrolswithinthesame container.
TabStop Specifieswhetherthecontrolcanreceive focusviatheTabkey.
Tag Specifiesextraneousdataforthecontrol. Forexample,ifacontrolneedsareference toaspecificobjectforittosuitthe programmer'sneeds,thispropertycould housethatobject.
Text Specifiesthe text associatedwiththis control.Thisis typically,althoughnot always,thetextdisplayed.
Top Specifiesthey-coordinateofthetopedge ofthecontrolrelativetothecontrol's containerclientarea.
TopLevelControl Read-only.Returnsthetop-levelcontrol thatcontainsthecurrentcontrol.Inthe instanceofaformcontainingmany containercontrolsthatinturncontainmay othercontrols,theformisreturnedforall controls.
Visible Specifieswhetherthecontrolisvisible.Width Specifiesthefullwidthofthecontrol.*Thesepropertiesmakereferencetocontainmentbythiscontrol;basedonthe hierarchy,onewouldconcludethatthisfunctionalityisincorrect.Table26 - 4coversthisinmoredetail.
EventsTheControlisalsotheprimarysourceofmanyoftheeventsavailabletoyouviaother controls.Table26 - 1 0 givesanorganizedsynopsiswithenhanceddescriptionsofthe eventsthatcomefromtheControlobject.Notethatmanyoftheeventsareveryself- explanatory.Specificexamplesforeventsinthefollowingtablearenotprovided.Other samplesthroughoutthischapteruseeventsextensively,andshouldgiveanindicationas towhattheydo.Table26-10:PublicInstanceEventsoftheControl
EventName DescriptionBackColorChanged Occurswhenthe BackColor propertyofthe controlchanges.
BackgroundImageChanged Occurswhenthe BackgroundIma geofthecontrol changes.
BindingContextChanged Occurswhenthe BindingContex tpropertyofthe controlchanges.
CausesValidationChanged Occurswhenthe CausesValidat ionproperty changes.
ChangeUICues Occurswhen Focusor Keyboardcues change.
Click Occurswhen the control has been clicked.ContextMenuChanged Occurswhenthe ContextMenu propertyofthe controlchanges.
ControlAdded Occurswhena controlhasbeen addedtothis control.
ControlRemoved Occurswhena controlhasbeen removedfromthis control.
CursorChanged Occurswhenthe Cursorproperty ofthiscontrol changes.
Disposed(InheritedfromComponent)
Representsthe methodthat handlesthe Disposedevent ofacomponent. Occurswhenthecomponent's resourcesare freed.
Table26-10:PublicInstanceEventsoftheControl
EventName Description
DockChanged Occurswhenthe Dockpropertyof thecontrol changes.
DoubleClick Occurswhen the controlhas been double-clicked.
DragDrop Occurswhena drag-and-drop operationhas beencompleted.DragEnter Occurswhenan objecthasbeen draggedtobe withinthe control'sbounds.
DragLeave Occurswhenan objecthasbeen draggedoutofthe control'sbounds.
DragOver Occurswhenan objecthasbeen draggedovera control'sbounds. Thiseventcovers theDragEnter andDragLeave events.
EnabledChanged Occurswhenthe Enabledproperty ofthiscontrol changes.
Enter Occurswhenthe controlisentered.
FontChanged Occurswhenthe Fontpropertyof thiscontrol changes.
ForeColorChanged Occurswhenthe ForeColor propertyofthe controlchanges.
GiveFeedback Occursduringa dragoperation. Thisistheevent thatallowsthe applicationto changethemousecursorand soon.
Table26-10:PublicInstanceEventsoftheControl
EventName Description
GotFocus Occurswhenthe controlreceives thefocus.
HandleCreated Occurswhenthe handleforthe windowis created.
HandleDestroyed Occurswhenthe handleforthe windowis destroyed.HelpRequested Occurswhenhelp isrequestedfora control.For example,by pressingF1.
IMEModeChanged Occurswhenthe IMEModeproperty changes.Invalidated Occurswhenthe control'sdisplayis updated.The rectanglethatis
invalidisavailableviathisevent.KeyDown Occurswhen a keyis pressed down while the controlhas the focus.
KeyPress Occurswhena keyispressed whilethecontrol hasthefocus.KeyUp Occurswhena keyisreleased whilethecontrol hasthefocus.
Layout Occurswhena controllaysoutits childcontrols.
Leave Occurswhenthe controlisleft.
LocationChanged Occurswhenthe Location propertyofa controlchanges.
Table26-10:PublicInstanceEventsoftheControl
EventName DescriptionLostFocus Occurswhenthe controlloses focus.
MouseDown Occurswhena mousebuttonis pressedwhilethe pointerisovera control.
MouseEnter Occurswhenthe mousepointer entersthecontrol.MouseHover Occurswhenthe mousepointer hoversovera control.
MouseLeave Occurswhenthe mousepointer leavesthecontrol.
MouseMove Occurswhenthe mousepointer moveswithinthe control.MouseUp Occurswhena mousebuttonis releasedwhilethe mousepointeris
overacontrol.MouseWheel Occurswhenthe mousewheel moveswhenthe controlhasthe focus.
Move Occurswhenthe controlismoved.
Paint Occurswhenthe controlisdrawn orredrawn.
ParentChanged Occurswhenthe valueofthe Parentproperty ofacontrolhas changed.
QueryAccessibilityHelp
Occurswhenthe Accessible objectofthe controlis providinghelpto accessibility applications.
Table27-1:Non-InheritedMembersofButtonBase
MemberName(scopeandtype) DescriptionFlatStyle(PublicInstanceProperty) Specfiesthe FlatStyle of the control.Can
beoneof fourvalues: Flat, PopUp, Standard, orSystem.
Image(PublicInstanceProperty) Specifesthe imagethat isdisplayed onthe Button control.
ImageAlign(PublicInstanceProperty) Specifies the alignmentof theimage displayedontheButton control.
ImageIndex(PublicInstanceProperty) SpecifiestheIndex valueofthe imageinthe imagelist displayedon theButton control.See ImageList
Table27-2:Non-InheritedMembersofListControl
MemberName(scopeandtype) DescriptionDataSource(PublicInstanceProperty) Specifiesthe DataSource ofalistcontrol. Thisistypically
acollectionor array.DisplayMember(PublicInstanceProperty) Ifthelist control contains objectsthat support
properties,this indicateswhich
Chapter27:SpecificControlsThereareafewcontrolsthatarebeyondthescopeofthis chaptersuchastheCrystalReportViewerandtheActiveXHostcontrols.
ButtonBaseThepurposeoftheButtonBasecontrolistoprovideallthebasicfunctionalitythatany buttonstylecontrolrequires.Thisclassinheritsdirectlyfromcontrol.Table2 7 - 1 listsand describestheproperties,methods,andeventsthatButtonBasebringstothetable.
ListControlThepurposeoftheListControlistoprovideallofthebasicfunctionalitythatanylist stylecontrolrequires.ThisclassinheritsdirectlyfromControl.Table2 7 - 2 listsand describestheproperties,methods,andeventsthattheListControlbringstothe table.
Table27-2:Non-InheritedMembersofListControl
MemberName(scopeandtype) Descriptionpropertyofthe objectto display.If unspecified,theresultoftheToString methodis used.SelectedIndex(PublicInstanceProperty) Specifiesthe indexofthe selecteditemin the ListControl.
SelectedValue(PublicInstanceProperty) Specifiesthe objectselected inthe ListControl.
ValueMember(PublicInstanceProperty) Analogousto DisplayMemb er.This indicateswhich propertyofthe objecttoreturn.
GetItemText(PublicInstanceMethod) Similartoa ToString Method.This method, however,takes anobjectasa parameterand returnsthetext ofthatobject.
DataSourceChanged(PublicInstanceEvent) Occurswhen the DataSource property changes.
DisplayMemberChanged(PublicInstanceEvent) Occurswhen the DisplayMemb erproperty changes.
SelectedValueChanged(PublicInstanceEvent) Occurswhen the SelectedVal uechanges.
Table27-3:Non-InheritedMembersofScrollableControl
MemberName(scopeandtype) DescriptionAutoScroll(PublicInstanceProperty) Specifieswhether ornotthe containerallows
theusertoscroll toanyitems beyondthevisible boundaries. Settingthisto trueessentially createsavirtual spacegreater thanthevisible space.
AutoScrollMargin(PublicInstanceProperty) Specifiesthe distancefromthe edgeofthe containerthata controlmustbe forthescrollbars toappear.
ValueMemberChanged(PublicInstanceEvent) Occurswhen the ValueMember property changes.
DataManager(ProtectedInstanceProperty) Handles managementof theBindingCont extofthe ListControl
ScrollableControlThepurposeoftheScrollableControlistoprovideallthebasicfunctionalitythat anyscrollingcontrolrequires,specificallyAutoScroll.Thisclassinheritsdirectlyfrom Control.Table27 - 3listsanddescribestheproperties,methods,andeventsthatthe ScrollableControlbringstothetable.
MenuThepurposeoftheMenuclassistoprovideallofthebasicfunctionalityformenus.This classinheritsdirectlyfromComponent. Table2 7 - 4 listsanddescribestheproperties, methods,andeventsthattheMenubringstothetable.
Table27-4:Non-InheritedMembersoftheMenuClass
MemberName(scopeandtype) DescriptionHandle(PublicInstanceProperty) ReadOnly. Returnsthe handlethat represents thewindow ofthis
object.
IsParent(PublicInstanceProperty) ReadOnly. Returnsa value indicating whetheror notthis menucontainsany menuitems.
MDIListItem(PublicInstanceProperty) ReadOnly. Returnsa value indicating themenu itemthatis usedtodisplayalistofMDIchild forms.
MenuItems(PublicInstanceProperty) ReadOnly. Returnsa collectionof menuitems associated withthis menu.
GetContextMenu(PublicInstanceMethod)
Returnsthe ContextMenuobject thatcontainsthismenu.
GetMainMenu(PublicInstanceMethod) Returnsthe MainMenu objectthat containsthis menu.
MergeMenu(PublicInstanceMethod) Mergesthe menuitem collections oftwo menus.
CloneMenu(ProtectedInstanceMethod) Performsa deep-copy of the current
ScrollBarThepurposeoftheScrollBarclassistoprovideallthebasicfunctionalitythatany scrollbarcontrolrequires.ThisclassinheritsdirectlyfromControl.Table2 7 - 5 listsand describestheproperties,methods,andeventsthattheScrollBarclassbringstothe table.Table27-5:Non-InheritedMembersoftheScrollBarClass
MemberName(scopeandtype) DescriptionLargeChange(PublicInstanceProperty) Specifiesthe valuetoaddor subtractfrom thevalue
propertywhen thescrollboxis movedagreat distance.
Maximum(PublicInstanceProperty) Specifies the upperlimit of the scrollbar value.
Minimum(PublicInstanceProperty) Specifies the lowerlimit of the scrollbar value.
SmallChange(PublicInstanceProperty) Specifiesthe valuetoaddor subtractfrom thevalue propertywhen thescrollboxis movedasmall distance.
Value(PublicInstanceProperty) Specifiesa numericvalue thatrepresents thecurrent positionofthe scrollboxonthescrollbar.
Scroll(PublicInstanceEvent) Occurswhen thescrollbox hasbeen movedbya mouseor keyboard action.
ValueChanged(PublicInstanceEvent) Occurswhen thevalue propertyhaschanged (typicallyviaa scrollevent,or programmatically).
Chapter29:IrregularFormsShapesTherearereallyonlyahandfulofshapesinthetoolkitofirregularformscreation. Thankfully,though,youonlyneedafew.Nearlyeveryshapecanbecreatedfroman ellipseorapolygon.Shapessuchascirclesandtrianglesarereallyonlyspecialcasesorcombinationsofthesetwofigures.Otheritemsthatcanbedrawnincludearcs,Beziers, curves,andlines.Thischapterprimarilydealswithclosedshapes.
GraphicsDrawinganirregularform,likedrawinganything,requiresfourthings:asurface,astylus, acolor,andsomethingtodraw.ThissectiondetailswhatobjectsintheFramework equatetotheserequireditems.Specialcareisgiventothoseobjectsthatarecomplexor usedfrequently.
SurfaceThesurfaceuponwhichyoudrawisequivalenttotwodifferentobjectswithinthe Framework:theGraphicsobjectandtheRegionobject.TheGraphicsobject providesthemethodsfordrawingtothedevicecontext.Adevicecontextisanalogousto acoordinatesystemlaidontopoftheform.Usefulitemssuchaspositioncanbe extrapolatedfromthisobject.Thisessentiallymeansthatthedrawingsurfaceoftheform,asrepresentedbytheGraphicsobject,canbedirectlyusedbyyourapplication.
PartVI:VB .NET and the Web Chapter31:IntroductiontoWebDevelopment Chapter32:IntroductiontoASP.NET
Chapter33:PageFrameworkChapter34:HTMLServerControlsChapter35:WebControls Chapter36:ValidationControlsChapter38:EventsChapter39:CascadingStyleSheetsChapter40:StateManagement
Chapter42:TracingChapter43:Security
Chapter31:Introduction to Web DevelopmentLanguages and Technologies of the WebThenumberofWebpagesontheInternetisenormous,andthelanguagesthatbuilt thesepagesarenumerousaswell.EventheuntrainedobservercanseeitintheURL extensionsthatareoutthere.Someoftheextensionsincludehtml,asp,jsp,cgi, perl,js,php,andmanymore.Thisisduetotheplethoraoflanguagesouttherethata programmercanusetobuildaWebpage.
HTMLHypertextMarkupLanguage(HTML)isalanguageusedtopresentinformationtothe browserfordisplay.HTMLisnotatrueprogramminglanguage—itwon'tallowyouto applyanylogic.Itisbasicallyacollectionoftagsthatbrowsersinterprettoapplystylesto text.HTMLcanalsoprovidelinkstootherpages,showimages,andpresentbasicforms.ThetagsinHTMLareenclosedwithinanopeningless-thansign(<)andaclosing greater-thansign(>).ItisimportanttonotethatdifferentbrowsersinterpretHTML differently,andnotallthetagsareequallyidentifiedineachofthevariousbrowsers.
CascadingStyleSheets(CSS)CascadingStyleSheets(CSS)isanoutstandingadditiontoHTMLthatallowsyouto applyacertainstyletoaparticularHTMLtag.Forinstance,ifyouwanteach<h1>tagin yourpagetobebold,beinArialfont,andhaveafontsizeof15,youcanapplyHTML<font>tagsaroundeachinstance.Thiscansometimesbeverytime-consuming,andcanmakeforsomemessycode.Byapplyingastylesheettothepage,youcanspecify howevery<h1>tagisformatted,whichsavestimeandallowsforcleanercode.
<html>
<head>
<title>MyHomepage</title>
<styletype="text/css">
body{
font-family:Arial,Helvetica,sans-serif;
font-size:smaller;
color:Red;
font-weight:bold;
}
</style>
</head>
<body>
HelloWorld!
</body>
</html>
JavaScript
Table31-1:T-SQLCommands
T-SQL
Description
Select Selectsspecifieddatafromthechosentable.The programmercanthenusethisdatainanumberof differentways.
Insert Insertsarowofdataintothedatabase.Itbasically createsanewrowoftabledata.
Update Updatesachosennumberofrowsofdata.Byupdating tabledata,dataischangedpermanantlywithinafield.
Delete Deletesaspecifiednumberofrows.Itispossibleto deletefromonerowofdatatoeveryrowinthe database.
JavaScriptisanoutstandingprogramminglanguagethatallowsyoutoprogramboth client-andserver-sideactions.MostdevelopersuseJavaScripttoperformactionsonthe client-side,whichallowsthemtoprogramforcertaineventstheusermakesonthepage. Forinstance,youmayhavenoticedthatifyouhoveryourcursoroveranimage(usuallyabutton),itchangestoadifferentimage.Thisiscalledarollover,andthisfunctionalityisusuallydoneinJavaScript.Itisbasedonanevent(thehoveringofthecursoroverthe image).Youcanusuallyprogramforanumberofdifferenteventsonthesamepage, suchasbuttonclicks,mouseovers,pageloads,andmore.
<html>
<head>
<title>MyHomepage</title>
</head><body>
<scriptlanguage="JavaScript"type="text/javascript">
<!--
document.write("Youareusing"+navigator.appName+""+navigator.appVersion);
//-->
</script>
</body>
</html>
Transact-SQLYes,thereisanSQLServerprogramtobuilddatabases,butthereisalsoaprogramminglanguagethatallowsyoutoprogramtransactionsagainstthisdatabase.ItiscalledTransact-SQL(orT-SQL).ToprogramagainstanOracledatabase,youwouldusePL-SQL,whichissimilartoT-SQL,butwithslightlydifferentsyntax(it'smorelikeC).
UsingT-SQL,youcansendawidevarietyofcommandstothedatabase.Hereisashort listofsomeexamples: Toselecttheentiretableofdatafromthedatabase,useSelect*
fromCustomers. Toselectonlyaselectedrowofdata,useSelect*from
Customerswherecustomerid=11. Toselectonlycertaininformationandthenreorderthedatabasedupon
selectedparameters,useSelectfirstname,lastnamefrom Customersorderbylastname.
Thelastexampleselectsthefirstnameandthelastnameofeachpersoninthe Customerstable.T-SQLthenrearrangesthisdatabasedonthecustomers'lastnames. WithT-SQL,itisalsopossibletousevariousothercommandstoperformtheactions neededinthedatabase.Table3 1 - 1liststhemaincommandstouseinT-SQL statements.
ADO2.6andADO.NET
Microsoft'sADO.NET,thelatestversionafterADO2.6,isacollectionofobjectsthat programmersusetomanagedata.ADOstandsforActiveXDataObjects.ThislatestversioniscalledADO.NET
ASP.NET
Initssimplestform,ASP.NETisanewtechnologyavailablewiththe.NETFramework thatallowsyoutobuildWebFormsandWebServices.ASP.NETcontainsacollectionof controlsthatyoucanprogram.Althoughitcontainsacollectionofbuilt-incontrols,it enablesyoutodevelopyourowncontrols.ASP.NETallowsyoutodevelopWeb-based applicationsinthesamemannerasaVisualBasic.NETWindowsForm.Thisnew technologyalsohassomeoutstandingnewfeaturesthatwerenotavailableinclassic ASPsuchaswaystomanagestateaswellasnumerousoptionsthatareavailableinthe configurationofyourapplications.
Chapter32:IntroductiontoASP.NETWithASP.NET,MicrosoftsetasideVBScript,andalloweddeveloperstousericher languagestodevelopserver-sidecode.DeveloperscannowuseVB.NET,C#,orJScript.NETtocodetheirWebpages.ThischapterwillfocusonusingVB.NETforWeb development.
Why ASP.NET?ASP.NETisanintegratedWebdevelopmentplatformthatallowsyoutousevarioustoolstobuildrichWebapplications.Thisnewtechnologyoffersgreatnewadvancesinstatemanagement,scalability,caching,deployment,security,performanceandsupportforaWebservicesinfrastructure.ASP.NETalsocontainsacollectionofcontrolstouseandbuildonwithinthecontextofaWebpage.ASP.NETisnotreplacingASP3.0.ASP.NETwasdevelopedbyMicrosoftasActiveServerPagesPlus(ASP+),andlater gotanamechangetoASP.NETandbecamepartofthe.NETfamily.
ASP.NETcontrols
ASP.NETincludesanumberofcontrolstoprogram.ThesecontrolsareusedwithinaWebFormtoproduceformswiththeexactfunctionalitythatyourequire.ForusewithintheWebFormareanumberofnewavailablecontrolssuchasHTML controls,Webcontrols,Validationcontrols,andUsercontrols.Itispossibleforyouto programthesecontrolsusingVB.NETtoprovidespecificfunctionality.
Now,ASP.NEThasasetofValidationcontrolsthatallowyoutospecifyclient-side validationrules.ASP.NETwilltakecareoftheJavaScript,andwillcodetheJavaScript basedonthebrowsertheuserisviewingthepagewith.
ASP.NETcomparedtoASP3.0
ASP.NETprovidesanumberofnewandexcitingfeatures.Bymakingsomebasic comparisonsofASP.NETtoASP3.0,youwillseewhyASP.NETprovidesabetterway tobuildWebpages.ASP.NETintheendwillmakeforeasierandfasterdevelopment, andtheapplicationsbuiltonthiswillbebetterandfaster.
PageextensionsThefirstnoticeabledifferenceisthatpagesbuiltusingASP.NETusetheaspxextension insteadoftheaspextensionthatisusedinASP3.0.WithtraditionalASP,wheneverthe servercametoanasppage,itsentthepagetobeprocessedbytheasp.dll,whereas theaspxpagesofASP.NETaresenttothexspisapi.dll.
Asstatedearlier,traditionalASPpagescanrunside-by-sidewithASP.NETpages.
Basedontheextensions,theywillbesenttotheappropriateDLLforprocessing.
Itisnotpossibletojustchangetheextensionnameofthefiletomagicallycreatean ASP.NETpage.YouwouldcreateanASP.NETpageonlybyextension,andyouwillget apagefulloferrorsifyoutry.
LanguageneutralityAmajorityoftraditionalASPdevelopersusedVBScriptasthescriptinglanguageto programtheirASPpages.WithASP.NET,VBScriptisnomore.ASP.NETdoesnotlimit itselftowhichlanguageitneeds.ASP.NETallowsyoutouseanyofthe.NETlanguages tousewhenprogrammingyourASP.NETpages(forexample,VB.NETandC#). ASP.NETisasetofcontrolsthatyoucanplaceonapagetoprovidespecific functionality,andyouuseotherlanguagestoprogramarichersetoffunctionalitiesand attributechanges.Nomatterwhich.NETlanguageyouusewhenyoubuildanASP.NET application,youhaveaccesstothesamecontrolsandfeaturesthateveryoneelsehas accessto.Youcanevenplugpiecesintoyourapplicationandnotbeconcernedabout which.NETlanguagetheywereprogrammedin—becauseitwon'tmakeanydifference. Alltheselanguagesworktogetherunderthesamesetofrules.
CodeseparationASP.NETincludesagreatnewfeaturecalledCodeBehind.WhendevelopingASP pages,thedeveloperwouldtraditionallyintermingleanumberoflanguageswithinone page(IrecentlydevelopedapagethatcontainedHTML,ASP,DHTML,JavaScript,and someCSS).Thepage,whencalledbyabrowser,wouldbeprocessedthroughthe asp.dllinalinearfashion,onelineatatime—startingatthetopofthepage.Withthis numberoflanguagesonasinglepage,thedevelopercouldhaveareallycomplicated pagetomaintainandupdate.Somedeveloperscallthisspaghetticode,andwithgood reason!
Therewerealsomanysituationsinwhichyoucouldhavemultipledevelopersworkingon oneASPpage.YoucouldhaveanHTMLdeveloperandanASPdeveloperworkingon distinctsectionsofthepage.Then,theJavaScriptwizardofthegroupwouldjumpinand startprogrammingsomeclient-sidecode.Witheveryonecodinghisownsections,the codewouldsometimesgetrathermessy.However,ASP.NETprovidesthemeansforprovidingthepage'slogic,theVB.NETcode,withinaseparatefile:theCodeBehindfile(seeFigure3 2 - 1 ).Thisallowspeopletoworkintheirownsettings,andnotbumpintooneanotherasthepagedevelops.Thisis alsothepartofthepageinwhichthedevelopercanprogramevent-drivenroutines.The authorswillbedoingalltheCodeBehindfilesinVB.NET,evenifitisalsopossibleto codetheminC#.
Figure32-1: AnexampleofaCodeBehindpage.NoticethatthepageiswrittenasWebForm3.aspx.vbonthetab.
EachcontrolthatisinthepresentationlayercanbecontrolledintheCodeBehindpage. EveneventsthathavenothingtodowiththeWebcontrolscanbeplacedinthe CodeBehindpage,suchaseventsforwhenthepageinitializesorisposted.
StatemanagementTraditionalASPcoulddealwithsessionsasameansofstatemanagement,althoughthis gotratherdifficultwhendealingwithaWebForm.IfauserrequestsanASPpagefrom
Table32-1:ASP.NETSessionObjects
SessionType Description
In-processmode Asession thatrunsin- process. Thisisthe default settingand isthesame astheASP 3.0session.
Out-of-processmode This session managementrunsout-of-process, andstores thesession information onthesame serveroran entirely different server.
SQLServermode Allowsfor thestoring ofsessions ina backend database.
Cookielessstate Forclients whochose nottotake advantage of the ASP.NET session state.
ServerA,atthesametimecreatingasession,andthenrequestsanASPpageserved fromServerB,thesessionwasimpossibletopassbetweentheservers.ASP.NETprovidesacompleteandrobustmeansofprovidingstatemanagement,however.Table3 2-1describesvariousASP.NETsessionobjects.
WebFormsWebFormsconsistofthetraditionalformsyoucanbuildinanyHTMLpage.WebForms areusedwheneverthereissomeinteractionwiththeuseronthepage.Someexamplesincludeanyoftheformelements,suchastextboxes,radiobuttons,andcheckboxes. Theseelementsdemandinteraction,andthereforeneedtobeencapsulatedwithina WebForm.WithWebForms,youcanreallygetdowntodetailandmakeeachaspectof theformfunctionasyouseefit.Youwillbebuildingalargenumberofformsinthe chaptersthatfollow.
DevelopingWebFormsisfairlystraightforward,andcanbedoneinacoupleofdifferent ways.ThefirstwayisthemethodthatmostASPprogrammersuse:codingeachofthe elementsstraightintothecodewindowofthepage(HTMLmode).Thesecondwayis morefamiliartotraditionalVisualBasic6.0developers:usingVisualStudio.NETto simplydraganddroptheitemsontothepage,therebybuildingtheform(Designmode).
Web ServicesAlthoughthispartofthebookdescribeseverythingyouneedtoknowtogetstarted buildingVB.NETWebFormsusingASP.NET,itisalsopossibletobuildASP.NETWeb Services.WebServicesareusedtoremotelycallaspecificfunctionalityacrosstheInternetusing XMLtotransportthedata.Wewon'tbediscussingWebServiceswithinthissectionof thebook.
XMLEveryoneistalkingaboutXMLtoday.Eveniftheydon'tknowwhatitisorwhatitdoes, peopledoknowthatitisimportant.Youhaveprobablyheardbusinessmanagersasking theirITcolleagues,"Yeah,butdoesitsupportXML?"(Ironically,theyhadproblems openingtheirbrowsersandpullingupthecompany'sWebsitethedaybefore.)
WithinASP.NET,XMLhasstrongersupportthanitdidwithASP3.0.Thegreatthingis thatwithASP.NET,youcannowread,write,oreditXMLasyouseefit.XMLis becomingmoreandmorepopularwiththeevolutionoftheInternet.Itisagreattoolto useforhandlingdata.
SecurityASP.NEToffersatremendouslybettersecurityfeatureset.Withtheweb.configfile, youcannowmodifysecuritysettingsinonespotinyoursystem,andthosechangeswill takeeffectimmediatelywithoutstoppingandstartingIIS.WithASP.NET,youcanusea widevarietyofauthenticationandauthorizationmodels,suchasWindows,Forms,and Passportauthentication.
CreatingyourfirstWebapplication
PullupVS.NET.DependingonhowyouhavetheIDEconfigured,youshouldseetheStartPage,aswellastheSolutionExplorerandtheemptyPropertiesBox.TheStartPagelistsanyapplicationsthatyoumayhavealreadystarted.Tobuildyour newapplication,clickNewProjectwithintheStartPage.TheNewProjectdialogbox displays(seeFigure 3 3 - 3 ).
Figure33-3: TheNewProjectdialogbox
Forthepurposesofthisbook,selecttheVisualBasicProjectsfolder.Youseea selectionoftemplatesintherightwindowofthedialogbox.Thelistofdialogboxes includethefollowing:
WindowsApplication ClassLibrary WindowsControlLibrary ASP.NETWebApplication ASP.NETWebService WebControlLibrary ConsoleApplication WindowsService EmptyProject EmptyWebProject Newprojectinexistingfolder
YoushouldselectASP.NETWebApplication,whichisaprojectforcreatingan applicationwithaWebuserinterface.Nametheapplicationwhateveryouwant,andthe locationwheretheapplicationwillresideshouldbehttp://localhost/.Afteryou configurethisdialogbox,clickOpen.VS.NETthencreatesanapplicationfolderwithinyourwwwrootfolder.Withinthefolder, itplacesanumberoffilesthatareimportantforyourapplication.Youcanviewallthese filesthatarecreatedwithintheSolution
ExplorerboxinVS.NET (seeFigure 3 3 - 4 ).
Figure33-4: TheSolutionExplorerallowsyoutoviewallthefileswithinyoursolution.
VS.NETwillhavecreatedthefollowingfilesforyourapplication: References:Thisisafolderthatcontainsapplicationreferencesto
.NETFrameworknamespaces.IfyouopenthefolderwithintheSolution Explorerwindow(clickonceontheplussignnexttothefolder),youwill noticewhatnamespacesarethereatthatmoment.Atthispointyour applicationisreferencingonlySystem,System.Data, System.Drawing,System.Web,System.Web.Services,and System.XML.
AssemblyInfo.vb:ThisVB.NETfilecontainsalltheinformationforyourassembly,suchasversioninganddependencies.
Global.asax:SimilartotheGlobal.asafilefromASP3.0.Thisisthe ASP.NETapplicationfileinwhichyoucanplacecodetorespondto application-levelevents.
Styles.css:ACascadingStyleSheetfilethatappliesstylestoyourdocuments.
Web.Config:Theconfigurationfilethatcontainstheapplication settings.ThisisanXML-basedfilethatiseasytounderstand.
WebApplication1.vsdisco: ThisisanXMLfilethatcontains informationallinksaboutanASP.NETWebService.
WebForm1.aspx:ThisisthefirstWebFormASP.NETpageforyour application.Ifyouwant,right-clickthefileandrenameitdefault.aspx.
WorkingwithyourfirstWebFormNowthatyouhaveyourfirstWebFormopen,noticethatyouseeapagethatcontainsa lotofdotsthroughoutthepage.ThismeansthatyouareworkingwithintheGridLayout mode.TochangetotheFlowLayoutmode,clickanywherewithinthedesignarea. NoticethatalonglistofpropertiesnowappearswithinthePropertiesbox(seeFigure33 - 5 ).ScrolldownuntilyoufindthepageLayoutproperty,andchangeitthere. FlowLayoutmeansthatallthecontrolswillbelaidoutinaleft-rightandup-down manner.GridLayoutlaysoutthecontrolsbaseduponXYpositioning,similartothe wayitwasinVisualBasic6.0.ASPdeveloperswillbemorefamiliarwiththe FlowLayoutmo
de,andVisualBasic6.0developerswillbemorefamiliarwiththe GridLayoutmode.
WorkinginDesignmode
IfyouworkinDesignmode,youseetheToolboxontheleftsideoftheVS.NET application.ClickingtheWebFormstabwithintheToolboxdisplaysalltheWebcontrols andValidationcontrols.TheHTMLtabshowsyoualargelistofHTMLelementsthatcan beconvertedtoHTMLServercontrols.TobuildaformwithinDesignmode,justdrag-and-dropyourselectedcontrolsontothepage.ToapplyanyVB.NETcodetothecontrol,justdouble-clickthecontrol.Youwill seetheCodeBehindpage,whichisaseparatecontainerforallyourserver-sidecode.It alreadycreatedaPage_Loadroutineforyouaswellasaroutineforthecontrolthatyou justclicked.
Usingthetabsatthetop,youcanswitchbetweenyourCodeBehindpageandthe Presentationpagewithease.Double-clickinganycontrolreturnsyoutotheCodeBehind page.
Afteryoufinishbuildingyourapplication,right-clickthefilewithintheServerExplorer box,andchooseBuildandBrowse.Thissavesthefileandrunsthefilethrougha browser,butallwithinVS.NET.Ifthereareerrorsonthepage,VS.NETwillinformyou ofthoseerrors.
Workingwithcontrols
Youcanalsoworkwiththecontrol'spropertiesorattributeswithintheDesignmodeofVS.NET.Clickonceonthecontrolthatyouwanttoworkwith,andnoticethatallthecontrol'spropertiesappearinthePropertiesbox.Changinganyofthepropertiesherewillbereflectedbacktothecontrol.Afterchangingthepropertiessothatthecontrolisas youwantit,clickHTMLmodeandseehowVS.NETalteredthecodetoreflectthe changesyoumadeinDesignmode.
AddingmorefilesItisquiterarewhenanInternetapplicationcontainsonlyonepage.Youusuallyneeda numberofpages.TocreateanotherpagewithinVS.NET,right-clickyourapplication withintheServerExplorerboxandselectAdd.ScrolldownandchooseAddNewItem. YouwillbepresentedwiththeAddNewItemdialogbox(seeFigure 33 - 6 ).
Figure33-6: AccesstheAddNewItemdialogboxtocreateanotheritem.
Youseethefollowingitems,allofwhichcanbeaddedtoyourapplication: WebForm:CreatesaWebForm.aspxfileinyourapplication.Thisisthe formforWebapplications. WebService:CreatesaService1.asmxfileinyourapplication.Thisis
avisuallydesignedclassforcreatingaWebService. Class:CreatesaClass1.vbfileinyourapplication.Thisisanempty classdeclaration. Module:CreatesaModule1.vbfileinyourapplication.Thisisafilefor storinggroupsoffunctions. ComponentClass:CreatesaComponent1.vbfileinyourapplication.
Thisisaclassforcreatingcomponentsusingthevisualdesigner. DataFormWizard:CreatesaDataWebForm1.aspxfileinyour
application.ThisisadataformforWebapplications. DataSet:CreatesaDataset1.xsdfileinyourapplication.Thisisafile
forcreatinganXMLschemawithDataSetclasses. WebUserControl:CreatesaWebUserControl1.ascxfileinyour
application.ThisisanASP.NETservercontrolcreatedusingthevisual designer. HTMLPage:CreatesanHTMLPage1.htmfileinyourapplication.Thisis
anHTMLpagethatcanincludeclient-sidecode. Frameset:CreatesaFrameset1.htmfileinyourapplication.Thisisan
HTMLfilethathostsmultipleHTMLpages. StyleSheet:CreatesaStyleSheet1.cssfileinyourapplication.This
isacascadingstylesheetusedforrichHTML-styledefinitions. XMLFile:CreatesanXMLFile1.xmlfileinyourapplication.Thisis basicallyablankXMLfile. XMLSchema:CreatesanXMLSchema1.xsdfileinyourapplication.
ThisisafileforcreatingaschemaforXMLdocuments. XSLTFile:CreatesanXSLTFile1.xsltfileinyourapplication.Thisis
afileusedtotransformXMLdocuments. WebCustomControl:CreatesaWebCustomControl1.vbfileinyour
application.ThisisaclassforcreatinganASP.NETservercontrol.
CodeFile:CreatesaCodeFile1.vbfileinyourapplication.Thisis basicallyablankcodefile. DynamicDiscoveryFile:CreatesaDisco1.vsdiscofileinyour
application.ThisisafileusedtopublishinformationaboutaWebService.
StaticDiscoveryFile:CreatesaDisco1.discofileinyour application.ThisisafileusedtopublishinformationaboutaWeb Service.
GlobalApplicationClass:CreatesaclassforhandlingWebapplicationevents.
WebConfigurationFile:CreatesafileusedtoconfigureWeb applicationsettings. TextFile:CreatesaTextFile1.txtfileinyourapplication.Thisisa blanktextfile. InstallerClass:CreatesanInstaller1.vbfileinyourapplication.
Thisisaclasstobeinvokedatsetuptime. CrystalReport:CreatesaCrystalReport1.rptfileinyour
application.ThisisaCrystalReportfilethatpublishesdatatoaWindows orWebForm. BitmapFile:CreatesaBitmap1.bmpfileinyourapplication.Thisisa
Win32bitmapfile. CursorFile:CreatesaCursor1.curfileinyourapplication.Thisisa
Win32cursorfile. IconFile:CreatesanIcon1.icofileinyourapplication.Thisisa
Win32iconfile. AssemblyResourceFile:CreatesaResource1.resxfileinyour
application.Thisisa.NETresourcefile. AssemblyInformationFile:CreatesanAssemblyInfo1.vbfilein
yourapplication.Thisisafilecontaininggeneralassemblyinformation. JScript:CreatesaJScript1.jsfileinyourapplication.Thisisascript filecontainingJScriptcode. VBScript:CreatesaVBScript1.vbsfileinyourapplication.Thisisa scriptfilecontainingVBScriptcode. WindowsHostScript:CreatesaWindowsScript1.wsffileinyour
application.ThisisafilecontainingscriptthatisrunasaWindows program.
Chapter34:HTMLServerControlsXHTML-Compliant CodeWhenwritingHTMLServercontrolstoprogram,itisveryimportanttowritethecontrols sothattheyareXHTML-compliant.
Therulesarefew andfairlystraightforward.Thefirstruletofollowisthattagsarenested properly.Tonesttagsproperly,youneedtoopenandclosetheminaspecificorder.The ruleis to closethetagsin thereverseorderin whichyouopenthem.Forinstance,ifyou openTagAandthenyouopenTagB,youcannotcloseTagAuntilyoucloseTagB.
INCORRECT:
<ahref="somepage.aspx"><b>Hello World!</a></b>Asyoucanseefromthefollowingexample,youopenthe<a>tagandthenopenthe<b>tagtomakethelinkbold,butyouclosedthe<a>tagbeforeyouclosedthe<b>tag. ThisisnotXHTML-compliantcode.Thiscodeshouldinsteadbewrittenasfollows:
CORRECT:
<ahref="somepage.aspx"><b>Hello World!</b></a>
Itisalsoimportanttonotethatforeveryopeningtag,theremustbeaclosingtagforall tagsthathaveclosingtags.So makesurethatwheneveryouopenanyof theseHTML tags,youalsoclosethetagintheproperplacewithinthedocument.Fortagsthataresingularelements,younowneedtoendthetagwitha/>toclosethetaginordertobeXHTML-compliant.Forinstance,the<hr>tagdoesnothaveopeningandclosingtags,instead,itisasingularelement.WithXHTML,youwouldnowdisplay the<hr>tagas<hr/>whenyouareprogrammingit.
Common Tag AttributesInorderfortraditionalHTMLelementstoworkasHTMLServercontrols,youhavetoadd somecommonattributestoworkagainstinordertochangetheelement'sfunctionality. ThefirstattributethateveryHTMLServercontrolmustcontainisarunat=server
withinthetagitself.Theattributerunat=servertellstheprocessingserverthatthetag isprocessedontheserver,andisnottobeconsideredasatraditionalHTMLelement. Also,thetagmustcontainanIDattributeinorderfortheservertoidentifyitandforyoutoprogramit.ThefollowingexampleisaHTMLServercontrol.
<aid="FirstLink"runat="server">ClickMe!</a>This<a>taghasbeenturnedintoanHTMLServercontrolbyitsinclusionoftheIDand therunat=serverattributes.
Overview of HTML Server ControlsASP.NETServercontrolsaregroupofnewcontrolsprovidedby.NET.HTMLServer controlsareonetypeofcontrolnowavailable.OthertypesincludeWebServercontrols andValidationcontrols.Figure34 - 1 showsthehierarchyofHTMLservercontrolsintheSystem.Web.UI.HtmlControlsnamespace.
Figure34-1: HierarchyofHTMLServercontrolsHTMLServercontrolsmapdirectlytotheircorrespondingHTMLelements.When convertingASP3.0pagestoASP.NETpages,usingHTMLServercontrolsisaless- painfulsolutionthanusingASP.NET'sWebcontrols(discussedinthenextchapte r ). Table3 4 - 1describesthesecontrolsinmoredetail.
Table34-1:HTMLServerControlsQuicklist
Control RelatedHTMLTagHTMLAnchor Allowsaccesstoprogramagainstthe<a>
tag.HTMLButton Allowsaccesstoprogramagainstthe
<button>tag.HTMLForm Allowsaccesstoprogramagainstthe
<form>tag.HTMLGeneric ThiscontrolallowsaccesstoHTMLtagsthat
arenotrepresentedbyanyHTMLServer controlspecifically;forexample,the<span>,<div>,and<font>tags.
HTMLImage Allowsaccesstoprogramagainstthe<img>tag.
HTMLInputButton Allowsaccesstoprogramagainstthe<inputtype=button>,<input type=submit>,and<input type=reset>tags.
HTMLInputCheckbox Allowsaccesstoprogramagainstthe<inputtype=checkbox>tag.
HTMLInputFile Allowsaccesstoprogramagainstthe<inputtype=file>tag.
HTMLInputHidden Allowsaccesstoprogramagainstthe<inputtype=hidden>tag.
HTMLInputImage Allowsaccesstoprogramagainstthe<inputtype=image>tag.
HTMLInputRadioButton Allowsaccesstoprogramagainstthe<inputtype=radio>tag.
HTMLInputText Allowsaccesstoprogramagainstthe<inputtype=text>and<input type=password>tags.
HTMLSelect Allowsaccesstoprogramagainstthe<select>tag.
HTMLTable Allowsaccesstoprogramagainstthe<table>tag.
HTMLTableCell Allowsaccesstoprogramagainstthe<td>and<th>tags.
HTMLTableRow Allowsaccesstoprogramagainstthe<tr>tag.
HTMLTextArea Allowsaccesstoprogramagainstthe<textarea>tag.
Chapter35:WebControlsWithinASP.NETServercontrols,Webcontrolsareonetypeofcontrolthatisnow available.OthertypesincludeHTMLServercontrolsandValidationcontrols.
BetweenWebcontrolsandHTMLServercontrols,Webcontrolsarethemore sophisticatedcontroltype.Theyallowahigherleveloffunctionalitythatisnotfoundin HTMLServercontrols.
UnlikeHTMLServercontrols,whichmapdirectlytotheircorrespondingHTMLelements, WebcontrolsgenerateHTMLcodebaseduponfunctionalityandthevisitingclient's browsertype.WithWebcontrols,youmightsaythatyouwantatextboxinyourWeb Form.Youcanchangethestyleofthetextboxbyjustchangingthepropertiesofthetext boxcontrolitself.Bychangingtheseproperties,youcanspecifywhetherthecontrol shouldoutputaregulartextbox,apasswordtextboxoratextarea.Whensomeonehits thatparticularpage,ASP.NETsendstotheclientthecodethatisappropriateforthat
browser.EachbrowsermayseedifferentHTMLcode,dependingonwhattheirbrowser supports.ASP.NETtakescareofallthebrowserdetectionandtheworkthatgoeswith thisforyou.
HTMLServerControlsversusWebControlsAWebcontrollookslikethis:
<asp:Label[attributes]>HelloWorld!</asp:Label>
OneimportantdifferencebetweenHTMLServercontrolsandWebcontrolsisthatthe attributesinHTMLServercontrolsarespecifictothatHTMLelement,buttheattributes withinWebcontrolsarespecificforthecontrolitself,notfortheHTMLthatisgenerated baseduponthecontrol.Whendecidingwhattypeofcontroltouse,youshouldbaseyourchoiceonwhatcontrol offersthespecificfunctionalitythatyourequire.Table3 5 - 1 summarizeswhentouse HTMLServercontrolsandwhentouseWebcontrols.Table35-1:HTMLServerControlsversusWebControls
ControlType
WhentoUseThisControl
Webcontrol Whenyourequirearichersetoffunctionalitytoperform complicatedpagerequirements.
WhenyouaredevelopingWebpagesthatwillbeviewed byamutitudeofbrowsertypesthatwouldrequiredifferent codebaseduponthesetypes.
WhenyoupreferamoreVisualBasic-typeprogramming modelthatisbasedontheuseofcontrols.
HTML Server control
WhenconvertingtraditionalASP3.0Webpagesto ASP.NETWebpages,andspeedisaconcern.You'llfind thatitisaloteasiertochangeyourHTMLelementstoHTMLServercontrolsratherthenchangingthemtoWeb controls. WhenyoupreferamoreHTML-typeprogrammingmodel.
Web Controls and How to Program for Them
Webcontrolscanbeassimpleandascomplexasyouwantthemtobe,butingeneral, theyareveryeasytousewithinyourpages.Figure35 - 1showsthehierarchyofWebcontrolsintheSystem.Web.UI.WebControlsnamespace.
Figure35-1: HierarchyofWebcontrolsYouneedtocodeWebcontrolsinanXHTML-compliantway,meaningthatyoumust
properlynesttags.Closethetagsthataresingularelementswith/>.Forinstance,you canwritetheLabelcontrolasthefollowing:
<asp:labelrunat="server"id="label1"></asp:label>
Or,youcanwritetheLabelcontrolasthefollowing:
<asp:labelrunat="server"id="label1"/>
Table3 5 - 2 givesabriefdescriptionofthecontrolsthatarecoveredinthischapter.
Table35-2:WebControls
WebControl Description<asp:adrotator> Similartothe traditional ASP adrotator component. Thiscontrol displaysa
specified orderof images.Itis alsopossible tosetthe sequenceof imagestobe random.
<asp:button> Usedto performatask orinitiatean event.Usedto submitformstotheserver.
<asp:calendar> Arichcontrol thatdisplaysa graphical calendar,and allowstheusertoselectadatethat caninitiatean eventonthe page.
<asp:checkbox> Displaysa traditional HTMLcheck boxthat allowsuserstoclickitonoroff.
<asp:checkboxlist> Agroupof checkboxes thatallowfor mutiple selections.
<asp:datagrid> Alistcontrol thatallows data-bound informationto bedisplayed intables.The tablescanbeconstructedtoallowfor editingandsorting.
Table35-2:WebControls
WebControl Description
<asp:datalist> Alistcontrol thatallows data-bound informationto bedisplayed. Construction ofthedisplay isdoneby usinga customizable template.
<asp:dropdownlist> Displaysa traditional HTMLselect tagthatallows userstoselect anitemfroma drop-downlist ofitems.
<asp:hyperlink> Displaysa traditional HTML hyperlinkthat usersclickto performan event(suchasgoingtoanewpage).
<asp:image> Displaysan image.
<asp:imagebutton> Thesameas aButton control,but allowsan imagetobe usedforthe button.<asp:label> Displaystext thattheuser cannotedit directly.
<asp:linkbutton> Thesameas aButton control,but lookslikea hyperlink.
<asp:listbox>Similartothe drop-downlist control,but insteadofseeingjust onelistitem, theusercan seemultiple listitems.It alsooptionally allowsfor mutiple selections
Table35-2:WebControls
WebControl Description<asp:literal> Displaysstatic text.
<asp:panel> Createsa borderless divisiononthe formthat servesasa containerfor othercontrols.
<asp:placeholder> Reservesa locationinthe pagecontrol hierarchyfor controlsthat areadded programmatic ally.
<asp:radiobutton> Displaysa traditional HTMLradio button.
<asp:radiobuttonlist> Displaysa groupof traditional HTMLradio buttons.The usercan selectonly
onechoice fromthe group.
<asp:repeater> Alistcontrol thatallowsfor data-bound informationto bedisplayed usingany numberof controlsasa template.
<asp:table> Displaysa traditional HTMLtable.
Table35-2:WebControls
WebControl Description<asp:textbox> Displays a traditional HTML text box.
<asp:xml> DisplaysXML documents, andallows XSL documentsto transform them.
DataBinding
DataisveryimportanttoalmosteveryWebapplication.Today,itisquiteraretopresent onlystatictextandimageswithinyourWebdocuments.Itisdatafromavarietyof sourcesthatisdrivingcurrentWebpages.
ThiswasthegreatthingaboutASP3.0.Youcoulddeveloppagesthatwouldrender whentheuserpulledupthepageinthebrowser.Asitwasrendering,thepagewould grabdatafromallsortsofsources,andplacethisdatainappropriateplaceswithinthe documentforpresentation.ItisimportanttonotethatwithDataBinding,thecontrolisnotconnectedtothedatasource.Instead,whatyouaredoingismakingacopyofthedataandthenbindingthis copywiththeServercontrol.
WithDataBinding,notonlycanyouconnecttotraditionaldatasourcessuchas relationaldatabases,butyoucanalsomakeconnectionstoawidevarietyofotherdata sources.Youcanconnecttoanyofthefollowingdatasourcesandmore:
DataSets XMLfiles Arraylists Hashtables Properties Expressions Functions Collectionsandlists
Tobindtodatasourcestobeusedincomplexcontrolssuchasthe<asp:datalist>,<asp:datagrid>,and<asp:repeater>controls,youusetheDataBind()method
ListBoundcontrolsTherearethreeListBoundcontrolstousewithinyourapplications:<asp:datalist>,<asp:datagrid>,and<asp:repeater>.Allthreecontrolsofferoutstanding programmingfunctionalitytoyourWebpagesbyallowingyoutospecifythelayoutand appearanceofrowsofdata.Thedatathatthesecontrolspresentisdatathatyouwould bindthecontroltofordisplaying,updating,insertingand/ordeleting.
<asp:datalist>TheDataListcontrolallowsyoutodisplaydataonaWebpageusingcustom templatesandstylesthatyoudefine.Withinthecodeofthedocument,theDataList controliswrittenas<asp:datalist>.ThereareoptionswithintheDataListcontrol thatallowuserstoeditanddeletedataaswell.Thefollowingexampleshowstheuseof theDataListcontrol:
<asp:DataListid="DataList1" CellPadding="pixels"
CellSpacing="pixels" DataKeyField="DataSourceKeyField"
DataSource='<%databindingexpression%>'
ExtractTemplateRows="True|False" GridLines="None|Horizontal|Vertical|
Both" RepeatColumns="ColumnCount" RepeatDirection="Vertical|
Horizontal" RepeatLayout="Flow|Table" ShowFooter="True|False"
ShowHeader="True|False"
OnCancelCommand="OnCancelCommandMethod"
OnDeleteCommand="OnDeleteCommandMethod"
OnEditCommand="OnEditCommandMethod"
OnItemCommand="OnItemCommandMethod"
OnItemCreated="OnItemCreatedMethod"
OnUpdateCommand="OnUpdateCommandMethod" runat="server">
<AlternatingItemStyleproperty="value"/>
<EditItemStyleproperty="value"/>
<FooterStyleproperty="value"/>
<HeaderStyleproperty="value"/>
<ItemStyleproperty="value"/><SelectedItemStyleproperty="value"/>
<SeparatorStyleproperty="value"/><HeaderTemplate>HeadertemplateHTML
</HeaderTemplate>
<ItemTemplate>
ItemtemplateHTML
</ItemTemplate>
<AlternatingItemTemplate>AlternatingitemtemplateHTML
</AlternatingItemTemplate>
<EditItemTemplate>
EditeditemtemplateHTML
</EditItemTemplate>
<SelectedItemTemplate>SelecteditemtemplateHTML
</SelectedItemTemplate>
<SeparatorTemplate>SeparatortemplateHTML
</SeparatorTemplate>
<FooterTemplate>
FootertemplateHTML
</FooterTemplate></asp:DataList>ThecustomtemplatesyoucreatetodisplaythedatacancontainbothHTMLtraditional elements(suchas<b>,<table>,<select>tags)andanyofthecontrolsthatwere discussedinthissection.Thinkoftemplatesaswrappersforpresentationforcertainsectionsofthecode.TheDataListcontrolsupportsthetemplatesshownin Table35 - 5 .Table35-5:TemplatesUsedintheDataListControl
Template DescriptionItemTemplate Thisistheonlyrequired template.The ItemTemplateisrendered
onetimeforeachrowof data.
AlternatingItemTemplate Ifthistemplateisprovided withintheDataList control,itrendersforevery otherrowofdata.Usethis templateifyouwanttoprovidealternatingcolorsfortherowsofyourtable.
SelectedItemTemplate Thistemplatedisplayswhen theuserselectsanitemthatisintheItemTemplateor the AlternatingItemTempla te.Youcanchangethe backgroundcolororeven showadditionalinformation
Table35-5:TemplatesUsedintheDataListControl
Template DescriptionEditItemTemplate Thetemplatethatis displayedwhentheuseris editingoneoftherowsof data.
HeaderTemplate Ifthistemplateisprovided, itisthefirstrowbeforethe ItemTemplateis rendered.Youcandisplay columnheadingsand introductionswiththis template.
FooterTemplate Similartothe HeaderTemplate, althoughthisisthelastrow afterallthedatais displayed.
SeparatorTemplate Thistemplateisrendered betweeneach ItemTemplateor AlternatingItemTempla te.Itisusefultoprovide somesortofvisual separationofrowsofdata.Inoneofitssimplerforms, theSeparatorTemplate cancontainjustan<hr>tag.
Figure35-17: TheMicrosoftAccessCustomerstableinDesignview
Chapter36:ValidationControlsIntroductiontoValidationcontrolsHowtouseValidationcontrolswithinWebFormsHowtouseregularexpressions
What Validation MeansValidationistestingtodeterminewhethertheuserenteredsomethingintothefield.Afteryoudeterminethatsomethingwasentered,youcanalsochecktoseewhetherwhatwas enteredis eithera numberora character,andalsocompareuserinputbetweendifferent fields.
DatacollectionontheInternetisoneofthemostimportantfeaturesavailable,anditis importanttomakesurethatthedatayoucollecthasvalueandmeaning.Thewaytodo thisistomakesurethatyoueliminateanychancesthattheinformationcollecteddoes notabidebytherulesyououtline.
Thevalidationcontrolsatyourdisposalincludethefollowing:CompareValidatorCustomValidatorRangeValidatorRegularExpressionValidatorRequiredFieldValidator
ValidationSummary
Table36-1:ValidationControls
ValidationControl Description<asp:comparevalidator> AValidation controlthat allowsfor comparison sbetween theuser's
inputandanotheritemusinga comparison operator (equals, greater than,lessthan,andsoon).
<asp:customvalidator> AValidation controlthat checksthe user'sentry using custom- coded validation logic.
<asp:rangevalidator> AValidation controlthat checksthe user'sinput basedupon alower-and upper-level rangeof numbersor characters.
<asp:regularexpressionvalidator> AValidation controlthat checksthat theuser'sentry matchesa pattern
definedbya regular expression. Thisisa goodcontrol touseto checke-mail addresses andphone numbers.
Table36-1:ValidationControls
ValidationControl Description<asp:requiredfieldvalidator> AValidation controlthat ensuresthat theuserdoesnotskipaform
entryfield.
<asp:validationsummary> AValidation controlthat displaysall theerror messages fromthe validatorsin onespecific spotonthe page.
Figure36-1: TheformwithoutanyvalidationPlacethiscontrolrightunderthebanneroftheform.Testit,andnoticehowitis displayingthepageerrors.FeelfreetoswitchtheDisplaymodetobothListand Paragraphtoseehowitlaysout.Also,anothergreatfeatureofthiscontrolisthatitcan displaytheerrorsinapop-upmessageboxforLevel4browsersandabove.
Chapter38:EventsAneventoccurswhenanobjectonthepagesendsamessagetotheserverthatsome sortofactionhastakenplace.Understandingevent-drivenprogrammingisessentialto programmingVisualBasic.NETWebapplications.VisualBasic.NETisbuiltonthis principlethatthepageyoudevelopisfullofobjects,andtheseobjectssometimesreact toeventsfromtheuser,systemevents,orothereventsyouprogram.
PlacingEventsinYourControlsControlsareobjectsthatwaitforspecificeventsandnotifytheserverwhen thosespecifiedeventstakeplace.Theactthatinitiatesthenotificationiscalled atrigger,andtheobjectthatsendsthetriggeriscalledaneventsender.The codethatrunswhenaneventistriggerediscalledaneventhandler.Acommonexampleofanobjecttriggeringaneventisabuttononapage.Thebuttonistheobject,andtheuserclickingonitinitiatesthetrigger(theOnClickevent)thatisthensenttotheappropriateeventhandler.Forinstance,<asp:button>allowsthefollowingevents tobeused:
OnClickOnCommandOnDataBindingOnDisposedOnInitOnLoadOnPrerenderOnUnloadIntelliSensedisplayslightning-bolticonsnexttoevents,asshowninFigure3 8 - 1.
Figure38-1: IntelliSenseshowingtheavailableeventsfortheButtonWebcontrol
Table38-1:EventArguments
Parameters DescriptionsenderAsObject Anobject that represents theobject thatraised theevent.
Table38-2:OtherTypesofArguments
EventArgs(System.TypeName)
DescriptionFileSystemEventArgs Provides information ondirectory events,such as Created, Changed, and
Deleted.ImageClickEventArgs Provides information onwhena userclicks on an image.
KeyEventArgs Provides information onkeyboard events,such asKeyUp and KeyDown.
CommandEventArgs Provides information onthe command event.
Building EventsAfteryou'vespecifiedtheeventwithinthecontrol,youneedtogivetheevent callavalue.Thisvaluewillbethenameoftheeventhandlerforthatparticular event.Forinstance,ifyouwantedthebuttontomonitorclickevents,youwould usetheOnClickeventandthenmaketheeventhandler,Button1_Click, performthefunctionalityyouwantedbasedonthatevent.
Thesampleeventhandlerhasthefollowingformat:
SubButton1_Click(SenderAsObject,EAsEventArgs)
Button1.Text="Thebuttontexthaschanged!"
EndSub
Using Web Form EventsEventsinWebFormsareconsiderablydifferentthaneventswithindesktopapplications. Withinatypicaldesktopapplication,theevent'striggerandtheeventhandlerareboth happeningclient-side.EventswithinaWebFormaretriggeredclient-side,butinmost casestheyneedtobehandledontheserver.ASP.NETusesHTTPPosttomanage theseserver-sideevent-handlingsituations.TheASP.NETframeworkthendetermines whichmethodneedstotakecareofhandlingtheevent.
ASP.NETtakescareofallofthisforyoubehindthescenes,butit'simportantto understandwhat'sgoingonhere.SinceWebapplicationsneedtomakeround-tripsto theservertoperformserver-sideevents,usingalargenumberofservercontrolsthat containasubstantialnumberofserver-sideeventscanhaveadefiniteimpactonthe performanceofyourWebapplication.
EventargumentsTheeventhandlersthatyoubuildforWebFormapplicationscontaintwoarguments, senderAsObjectandeAsEventArgs.Table38 - 1 describesthesetwo arguments.
Table38-1:EventArguments
Parameters DescriptioneAsEventArgs Containsall theevent specificdata thattheeventsender passes along.
Inmostcases,thesetwoargumentswillbethetypicalargumentsusedwithinanyeventhandler.ThesecondargumentwilltypicallyusethetypeSystem.EventArgs,butthere arecertaincontrolsthatrequireaspecifictypetopassalonganydatapertinenttothe controlthat'ssendingtheevent.Table3 8 - 2 listssomeotherpossibletypesofarguments thatyoucanuseinplaceofEventArgs.
Table38-2:OtherTypesofArguments
EventArgs(System.TypeName)
DescriptionFileSystemEventArgs Provides information ondirectory events,such as Created, Changed, and
Deleted.ImageClickEventArgs Provides information onwhena userclicks on an image.
KeyEventArgs Provides information onkeyboard events,such asKeyUp and KeyDown.
CommandEventArgs Provides information onthe command event.
EventpostbacksWhenyou'reusingHTMLandWebcontrolsthroughoutyourpages,therearemany eventtriggersthatcauseaneventtobesenttotheservertobehandled.Forinstance, thebuttonOnClickissenttotheserverforprocessingoncetheuserclicksonthe button.However,therearealsoeventsthataretriggeredonaWebFormthatare depositedandsaveduntilthere'sapostbacktotheserverforprocessing.
Creating Event Handlers in Design Mode
Defaulteventhandlers
Followthesestepstocreateanapplicationthatallowsyoutobuildeventsforthebutton control.1. StartanewapplicationcalledEventHandlerApp.Thiswillbean
ASP.NETWebapplication.Onthepage,placeabuttonandalabel control.Figure3 8 - 3showswhatyourpageshouldlooklike.
Figure38-3: YourWebForm1.aspxpage2. Double-clickontheButtoncontroltocreateapagecalled
WebForm1.aspx.vb.Withinthispage,yourcursorwillbeplacedwithin afreshlycreatedeventhandler,abuttonclickhandler.Yourpage shouldresembleFigure 38 - 4 .
Figure38-4: WebForm1.aspx.vbandyourButton1_ClickeventhandlerVisualStudio.NETchosetheclickeventhandlerforthebuttonbecausethat's theButtoncontrol'sdefaultevent.Eachcontrolhasitsowndefaultevent.For instance,theDropDownListcontrol'sdefaulteventisthe SelectedIndexChangedevent.
3. Next,addthefollowingcodefortheButton1_Clickevent:
Label1.Text="Thebuttonhasbeenclicked!"Whenyouright-clickonWebForm1.aspxwithintheSolutionExplorerand selectBuildandBrowse,you'representedwiththenewlycreatedpage.
4. ClickthebuttonandyougetthetextwithintheLabelcontrolthat informsyouthatyouclickedthebutton,initiatinganevent.Thiswasall basedupontheeventhandlerexecutingcodebaseduponatrigger(thebuttonclick).TheresultcanbeseeninFigure38 - 5 .
Figure38-5: Youreventhandlerinaction!
Non-defaulteventhandlers
WhatifyouwanttoaddmoreeventhandlersbaseduponyourButtoncontrol?VisualStudio.NETmakesitquiteeasy.Simplyfollowthesesteps:
1. Getbacktothecode-behindpagebyclickingonthe WebForm1.aspx.vbfiletab.Therearetwodrop-downboxesatthe topofthepage.TheoneontheleftistheClassNamedrop-downbox. TheotheristheMethodNamedrop-downbox.
TheClassNamedrop-downboxcontainsalistofthecontrolsthatareonthepage.Byselectingoneofthecontrols,youcanspecifyspecificevent handlersfortheselectedcontrol.
2. SelecttheButton1control,andthenyoucanpulldownalargelistof eventsyoucanuseagainsttheButtoncontrolwithintheMethodName drop-downbox.Thedefaultevent,Click,isinbold.Youshouldseea listofevents,asshowninFigure38 - 6 .
Figure38-6: Alistofavailableeventstoprogramagainst3. SelecttheLoadevent.Thesubroutineforthiseventisthencreated instantlyinthecode-
behindpage,withtheproperarguments.4. Addthefollowingcode:
Label1.Text="Thebuttonhasloaded!"5. Right-clickonthefileandchooseBuildandBrowse.Noticethatonce
theButtoncontrolisloaded,itdisplayswhatithadintheLabelcontrol. PressingthebuttonchangesthetextwithintheLabelcontrolbased upontheButton1_Clickevent.TheresultscanbeseeninFigure38 - 7 .
Figure38-7: Whenthepageisloaded,theButton1_Loadeventistriggered.
VisualStudio.NETletsyouprogramforyourcontrol'sdefaulteventsaswellasthenon- defaultevents,asyoujustdidinthepreviousexample.
Chapter40:StateManagement
Understanding StateTraditionalWin32applicationsconsistentlymaintainedstateastheuserworkedthrough theprogram.Thestateoftheuserwasconsistentlyknowntotheapplication.Basically, stateiswhattheapplicationknowsabouttheuser.Thatincludeswhotheuseris,where heisintheprocessoftheapplication,andwhathehasenteredintotheapplicationto thatpoint.
ASP.NETincludesthefollowingfeaturesandtechniquestoapplywhenyou'reworking withstatemanagement:ViewStateQuerystringsSessionsCookies
ViewStateViewStateisthelatestASP.NETfeaturethatwasn'tavailableinASP3.0.With ViewState,youcaneasilymaintainthestateofyourcontrolsbetweenroundtripstothe server.ASP.NETrequiredthiscapabilitybecauseyoucanprogramyourWebformswith multipleroundtripstotheserver.It'spossibletoprogramyourWebcontrolssothateach controlforcesthepagetomakearoundtriptotheservereverytimethecontrolis changedinordertoperformanevent.
TogglingViewStateonandoff
KeepingtheViewStatefunctionalityonisn'talwaysgoingtobeaprioritywitheveryWeb formyoucreate.Forthisreason,youcanturntheViewStateoff,thussavingserver resourcesandincreasingthespeedofyourapplication.Youcanturnthisfunctionalityoff
intwoways.ThefirstistodisableViewStateonthepagelevel,andtheotheristodisableitonthecontrollevel.TodisableViewStatefortheentirepage,turnoffthisfunctionalitywithinthepagedirective.ToturnofftheViewStatefunctionalityfortheentirepage,justaddthefollowingattribute tothepagedirectiveatthetopofthepage.
<%@PageEnableViewState="False" %>It'salsopossibletodisableViewStateonthecontrollevel.Ifmaintainingacontrol'sstate isnotanimportantfeatureofthatcontrol,turnitoff.Thismildlyincreasesthe performanceofthepageoverall.ToturnoffViewStateforacontrol,addthe EnableViewStateattributetothecontrol:
<asp:Labelid="Label1"Runat="Server" EnableViewState="False"
/>Tip PayingattentiontowhichpagesandcontrolsareViewState-enabled
leadstobetteroverallapplicationperformance.
QuerystringsQuerystringsareaneasywaytopassdatafromonepagetothenextwithinaWeb application.Theyplaceacreatedname/valuepairandappenditontotheURLtobe passedtothenextpage.
Creatingquerystrings
Thereareanumberofdifferentwaystocreatequerystrings.Oneofthesimplerwaysis todirectlyplacethename/valuepairswiththeURL.
<ahref="WebForm2.aspx?username=Bill&employeeid=9040777>RegistrationPage</a>
WhereverthereisaURLinyourpage,youcanplacequerystringsalongwiththatURL. Forexample,youcanworkthemintoyoureventsonthecode-behindpageasfollows:
Response.Redirect("WebForm2.aspx?username=Bill")
It'salsopossibletocreatethevaluesofthequerystringsasthepageisparsedonthe serverbyconcatenatingthevaluestotheURL:
Response.Redirect("WebForm2.aspx?user="&TextBox1.Text&_
"&employeeid="&TextBox2.Text&"")
CookiesCookiesarekey/valuepairsthatarestoredontheclientcomputer.Usingcookiesto persistinformationisasimpleandeasyoptioninASP.NET.Cookiesarepassedalong withtheHTTPrequesttotheserverandareusedtoidentifytheuseruponreceipt.
Advantagestousingcookies
Therearemanyadvantagestousingcookieswithinyourapplicationstostoresimple data.Firstofall,itdoesn'trequireserverresourcesbecausenoneofthecookiesare storedontheserver.Secondly,youcansetcookiestoexpirewhenthebrowserisshut downorforanydateinthefuture.Therefore,it'spossibletoremembertheuserupon returnvisitsweeksormonthslater.
Disadvantagestousingcookies
Therearealsosomenegativestousingcookies,andforsomeapplicationstheycan accountforsomeserioussecurityflaws.Onenegativeisthatcookiesneedtobesmall. Youcannotsendlargeamountsofdatatotheclienttostoreontheirmachine.Generally, there'sa4,096-bytelimittothesizeofacookie,sothetypesofdatathatyoucanstore arelimited.Thebiggestnegativeisthatcookiesareeasyforknowledgeableusersto change.Thiscanbeamajorproblemifyou'reusingcookiesforuserstogainaccessto privateinformation.
Chapter41:ASP.NETApplicationsAWebapplicationmayconsistofacollectionofASP.NETfilesandtheGlobal.asax file.(TheGlobal.asaxfileisdiscussedinitsownsectionofthischapter.)Whenyou typeaURLintoyourbrowser(suchashttp://www.somewhere.com/), you'recalling aWebapplicationandfiringanyapplicationeventsthatgoalongwithit.Locallyonthe server,theWebapplicationresidesinavirtualdirectorythatyouspecify,typicallywithin theC:\Inetpub\wwwrootdirectory.
Creating a Web ApplicationWithclassicASP,youcouldcreateaWebapplicationbyhavingacollectionof.aspfilesandaglobal.asafilewithintherootdirectory.It'simportantto notethattheseclassicfilescanresideinthesamevirtualdirectoryasyour.aspxpageswiththeglobal.asaxfileandtheywon'tinterferewitheachother.Thesetwoapplicationswon'tsharestateorevents.Intheusualfashion, whenpeopleupgradefromoneversionofaproducttoanother,thenewversionususallyoverridestheolderone.Butinthiscase,ASP.NETdoesn't overridetheclassicASPdynamiclinklibrary(DLL).Instead,filesrunside-by- side.However,interminglingthetwomayproveproblematicbecausethetwo versionsdon'tsharestateorevents.
WiththegrowthoftheInternetandthewideacceptanceoftheWebbrowseras awaytoportinformationandapplicationsaroundtheworld,moreandmore emphasisisbeingplaceduponWebapplications.It'snowbecomingastronger necessityindevelopmenttomakeagroupofpagesworktogetherjustasa groupofformscanworktogetherinaWin32application.Theincreasing popularityoftheInternetasaportalforWebapplicationdevelopmentisdirectly relatedtothegrowthoftheInternetasawhole.Itisbecomingfareasierfor companiesandorganizationstouseabrowsertoporttheirapplications,insteadofforcinguserstoinstallacertainversionofanapplicationontheir machinesathomeoratwork.Portingtheirapplicationsthroughthebrowser guaranteesusersthelatestversionoftheapplication.Usersarealsoquite knowledgeablethesedaysaboutworkinginformsthatareinabrowser.Itis alsofarbetternottoworryabouttheenduser'shardwaresituationandpush thedata,asopposedtopullingdatainaWin32application.ProbablythebiggestconcernwithWebapplicationdevelopmentfor programmersisstatemanagementortheapplications'abilitytopassthevalue ofvariablesfromonepagetoanother.Howyouhandlethismatteralso addressesissueswithsecurityandserverresources.
WithVisualStudio.NET,creatingaWebapplicationisaneasyand straightforwardprocess.Todoso,followthesesteps:
1. FromtheStartPagethat'sdisplayedwhenyoupullupVisualStudio.NETforthefirsttime,openanyexistingapplicationsthatyou've createdinthepast,orstartanewapplication.Ifyoudonotseethe StartPagewhenyouopenupVisualStudio.NET,clickHelpShowStartPage.TheStartPageisshowninFigure 41 - 1 .
Figure41-1: StartanewapplicationinVisualStudio.NETfromtheStartPageandselectNewProject.
2. Tostartanewapplication,clickontheNewProjectbutton.This displaysthedialogboxyouseeinFigure4 1 - 2 .Ithasalargelistof variousapplicationsthatyoucancreatewithVisualStudio.NET.
Figure41-2: NewProjectdialogbox.3. ChooseASP.NETWebApplicationandclickOK.VisualStudio
.NETautomaticallycreatestheapplicationforyou,aswellasthe appropriateapplicationfiles(suchasglobal.asax).AfterVisual Studio.NETcreatestheapplication,youcanseeallthefilesinthe SolutionExplorerwindow(seeFigure41 - 3 )withinVisualStudio.NET,oryoucanviewthefilesinyourC:\Inetpub\wwwroot\directoryonthelocalserver.
Table41-1:Application-SpecificItems
ItemCreated Description\binFolder Thisfolderisusedfor.NETassembliesthatareusedby
theapplication.Global.asax Thisisafilewhereyoucanspecifyapplicationeventsand
variables.ThisisthenextversionoftheclassicASP global.asafile.
web.config ThisisanXMLfilethatallowsthedevelopertoset applicationsettingssuchassecurity,state,andanumber ofotheritems.
Figure41-3: TheSolutionExplorerdisplaystheentireWeb applicationyou'vecreated.
Noticethatbycreatingthisapplication,you'vecreatedanumberof otheritemsaswell.NotalltheitemsareshownintheSolution Exploreratthispoint,though.
4. LookatthefilesthatarelistedintheSolutionExplorer,andthengotoC:\Inetpub\wwwroot\WebApplication1andcompare what'sdifferent.Therearesomeextrafilesandfoldersinthe WindowsExplorerview.VisualStudio.NETdoesn'tshowyouallthe filesthatareactuallywithintheapplication,butonlytheonesthat youneedtoworkwithonaregularbasis.
5. ToshowmoreofthefilesandfoldersthatareatyourdisposalwithintheSolutionExplorer,clickontheShowAllFilesbuttonlocatedat thetop.Thisshowsalargerlistofavailableitems.Themost importantoftheseapplicationitemsaredescribedin Table41 - 1 .
Deleting an ApplicationDeletingordestroyinganapplicationisjustaseasyascreatingitwas.Withinthe SolutionExplorerwindowinVisualStudio.NET,right-clickontheapplicationandselect Remove.Thisremovestheapplicationfromtheserveranddeletesallthefiles.
global.asaxTheglobal.asaxfileisusedbytheapplicationtoholdapplication-levelevents, objects,andvariables.It'sthenextversionoftheglobal.asafilethatwasusedin classicASP3.0,soifyouwerecomfortablewiththat,you'llfeelquiteathomewith global.asax.
Therecanonlybeoneglobal.asaxfileforanapplication.However,it'spossiblefora global.asaxfiletoresidenexttoaglobal.asafilewithoutanyconcerns.Just realizethatrunningthemside-by-sidewon'tallowyoutosharesessionsorevents betweenthetwo.Inthissituation,your.asppageswithintheapplicationusethe global.asafile,andthe.aspxpagesuseitsapplicationfile,global.asax.Theglobal.asaxfilesupportsanumberofitems:
Directives—VerymuchlikethedirectivesthatareusedinASP.NETpages, usercontrols,andWebServices,thesedirectivesallowyoutospecify instructionstotheapplication.
Declarations—Theseallowyoutodeclarespecificitemssuchasscriptsandincludes.
Applicationevents—Theseareeventsthatcanbeinitiatedonanapplication level.
ApplicationdirectivesApplicationdirectivesareverymuchlikethedirectivesthatyoucanusewithinASP.NET pagesandWebServices.Theglobal.asaxfilesupportsthethreefollowingtypesof directives:
@Application @Import @Assembly
Beforeexploringeachofthese,it'simportantthatyouunderstandhowtowritean applicationdirectivewithinyourglobal.asaxfile.Thedirectiveiswritteninthe followingformat:
<%@[Directive][Attribute=Value]%>Thedirectivegoesatthetopofthepageintheglobal.asaxdocument.Thedirective isopenedandclosedwiththesamebracketsusedinclassicASP,withtheopening<% andclosing%>.Thedirectiveallowsforasmanyattribute/valuepairsasyouwish.Soif youhadmorethanoneattribute,thedirectivewouldbewrittenasfollows:
<%@[Directive][Attribute=Value][Attribute=Value]%>
@ApplicationThe@Applicationdirectivedefinesapplication-specificattributes.Thisdirective supportsthetwofollowingtypesofattributes:
Inheritsallowsdeveloperstospecifythebaseclassthatglobal.asaxuses.
Descriptionallowsdeveloperstospecifyadescriptionfortheentireglobal.asaxfile.
Here'sanexamplethatusesbothattributeswithinonedirective:
<%@ApplicationInherits="PM.Object"Description="TheProject
ManagementApplicationfortheSalesDepartment."%>Note TheASP.NETparserignoresthedescriptiondirectiveatruntime.
Thisisimportantifyouhavealengthydescription.
@ImportThe@Importdirectivespecifiesthenamespacestobeimportedintotheapplication, therebymakingallclassesandinterfacesavailabletothepagesoftheapplication.This directiveonlysupportsoneattribute—Namespace.TheNamespaceattributedirectlyspecifiesthenamespacetobeimported.Notethatwith the@Importdirective,itcannotcontainmorethanoneattribute/valuepair.Here'sanexamplethatimportstwodifferentnamespacesusingthe@Importdirective:
<%@ImportNamespace="System.Data" %>
<%@ImportNamespace="System.Net" %>Theimportantthingtounderstandisthattherearealreadyanumberofnamespaces beingimportedintotheapplicationautomatically.Thefollowingnamespacesarealready imported:
System System.Collections System.Collections.Specialized System.Configuration System.IO System.Text System.Text.RegularExpressions System.Web System.Web.Caching System.Web.Security System.Web.SessionState System.Web.UI System.Web.UI.HtmlControls System.Web.UI.WebControls
There'snoneedtore-importtheseitemsbecausethey'realreadythere.It'salsopossible toimportnamespacesintoyourapplicationswithintheweb.configfile,whichare discussedlaterinthechapter.Importinganamespaceintoyourapplicationallowsyoutouseitsclasseswithoutfullyidentifyingtheirnames.Forinstance,ifyouimportthenamespaceSystem. Data.OleDBintotheapplicationorintotheASP.NETpage,youcanthenreferto
classeswithinthisnamespacebyjustexpressingthesingularclassnames.Youcould refertoOLEDBConnectioninsteadofSystem.Data.OleDB.OLEDBConnection,for example.
@AssemblyThe@Assemblydirectiveattachesassembliestoapageasitcompiles,thereby makingalltheassembly'sclassesandinterfacesavailabletothepage.Thisdirective supportsthetwofollowingattributes:
Nameallowsdeveloperstospecifythenameofanassembly.Thisassemblyistheonethatisattachedtothepagefiles.Thenameofthe assemblyshouldonlyincludethefilenameandnotthefile'sextension. Forinstance,ifthefileisMyAssembly.vb,thevalueofthename attributecouldbeMyAssembly.
Srcallowsdeveloperstospecifythesourceoftheassemblyfiletouse incompilation.Note TheSrc(source)attributeisanoptionalattributethatspecifiesthe
fileofthecodethatyouwanttoincludewithinthescriptblock.Anexampleofthe@Assemblydirectiveisasfollows:
<%@AssemblyName="MyAssembly"%>
<%@AssemblySrc="MyAssembly.vb"%>Notethatthesourceattributecancontainthecompletepathaswell.Also,any assembliesthatareplacedwithinthe\bindirectoryareautomaticallyavailabletothe page.
DeclarationsCodedeclarationswithinaglobal.asaxfileworkinthesamemannerastheydowithinyourASP.NETpages.Codeisdeclaredbetween<script></script>tags,and youcandefineanynumberofvariables,eventhandlers,andmethods.Hereisan exampleofusingcodedeclaration:
<scriptrunat="server"language="LanguageType" src="FilePath">
Writeyourcodeouthere.
</script>The<script>tagmustcontainarunat=serverattribute/valuepair,andthenyoucanspecifytwootherattributeswithinthetagitself—thelanguageandsrcattributes.Thelanguageattributespecifiesthelanguagethatisusedinthescript.Forthepurposesofthisexercise,usethelanguage="VB"attribute/valuepair.Youdon'tneedtodeclarethisattributewithinthe<script>tagifyou'vedeclaredthelanguageineithertheapplicationorpagedirective,orifit'sdeclaredintheweb.configfile.Thefollowingcodedemonstrateshowtousethe<script>tagswithinaglobal.asaxfiletodefineaneventhandler:
<scriptlanguage="VB"runat=server>SubApplication_OnStart()
'Applicationstartupcodegoeshere…
EndSub
</script>
Understandingweb.configweb.configisanapplicationfilethatallowsyoutosetapplication-widesettingsfrom oneconvenientfile.Thisfileiscreatedforyouwhenyoucreateanapplication.Ifyou wantedtochangeanyoftheapplicationsettingsinclassicASP,itwasdoneintheIIS MicrosoftManagementConsole(MMC).Theadministratorhadtostopandstartyour applicationforthesettingstotakeplace.WithASP.NET,youjustneedtoopenthe web.configfileinanytexteditor,changethesettings,andresavethefile.ASP.NET canthendetectwhentherearenewconfigurationsettingsforyourapplication,andit doesn'tneedtostopandstarttheapplication.Instead,ASP.NETletscurrentusersfinish withtheapplicationundertheoldsettings,andanynewusersaredirectedtothe applicationwiththenewsettingsapplied.
Chapter42:TracingAgreatnewfeatureofASP.NETistheabilitytotracetheinformationthat'spassedfrom requestsandresponses.Thisplaysagreatroleintheerror-checkinganddebuggingof applications.
ThetracingfeatureinASP.NETisanewmeansofdebuggingaWebapplication.Oneof themoreimportantstepsindevelopingapplicationsfortheWebisunderstandingwhich
informationisbeingsentfromonepagerequesttothenext.Withtracingturnedonin yourASP.NETapplication-youcancloselyfollowallthevariablesandconditionswithin yourpagesinunprecedentedways.
Understanding the Benefits of ASP.NET Tracing Everyonemakesmistakes,andprogrammersarenoexception.These mistakescouldbeinthecode,orhowthebrowserinterpretsthecode.Theycouldevenbeinthecommunicationsbetweencomponents.ClassicASPdidn't allowdeveloperstoeasilytraceinformationinrequestsandresponses.So instead,manydevelopersbuilttheirowntypesoftracingdirectlyintothecode. Forexample,manyprogrammerswouldlittertheirapplicationswith Response.Writestatementstoseehowtheirpage'sstatewasworking.Note Response.Writeisameansofwritingcontenttothebrowser
window.Forexample,writingResponse.Write("ASP.NET iscool!") causesthespecifiedtexttobeprintedtothebrowserwhenthe usercallsthepage.
Carryingsessionsaroundfrompagetopage,andinmanycaseschangingthevalueofthesesessions,isvitaltotheproperfunctioningofyourapplications. Therefore,placingtheseResponse.Writestatementsalloweddevelopersto seewhatwashappeningwiththesessionsandotherelementsasthey progressedthroughtheapplication.Althoughthisworked,thereweremanyproblems.Ittooktimetoplacethesestatementsintheapplicationonthe pagesthatneededthem.Then,ittooktimetoeithercommentthemalloutor removethemfromtheapplicationaltogether.
Enabling TracingYoucanconfigureyourASP.NETapplicationstoenabletracingintwoplaces.Thefirstis attheapplicationlevel,andthesecondoptionisatthepagelevel.Notethatyoucanhavebothoptionsturnedonatonce.
EnablingtracingattheapplicationlevelIt'squiteeasytoenabletracingwithinyourASP.NETapplicationsateithertheapplicationlevelorthepagelevel.Toenabletracingapplication-wide,opentheweb.configfileandmakesomemodificationsthere.Youcanfindtheweb.configfilewithintherootofyourapplication.
.
Table42-1:Attributesinthe<trace>Node
Attribute DescriptionEnabled Turnsthe tracingonoroff. Thedefaultis false.
RequestLimit Thisisthe numberof HTTPrequests thatwillbe recorded.The defaultsettingis 10.Asthe requestsbuild up,ASP.NET tracingkeeps trackofthelast specified numberof requests.
Whenyouopentheweb.configfile,youseethefollowinglineofcodethatdealswith tracingintheapplication:
<traceenabled="false"requestLimit="10"pageOutput="false"
traceMode="SortByTime"localOnly="true"/>Toturntracingon,changetheenabledattributetotrue.Thisturnstracingon,but
nothingisviewableonthepagesthemselvesyet.Table4 2 - 1 listswhattheseattributes meaninthemodificationofthetracingenvironment.
Table42-1:Attributesinthe<trace>Node
Attribute DescriptionPageOutput Asettingoftrue meansthatthe tracing informationis shownoneach pageasit's
rendered,in additiontobeingrecordedinthe trace.axdfile. Thedefaultis false.
TraceMode Thisattribute specifiesthe displayorderof thetracing information. Optionsinclude SortByTimeor SortByCatego ry. SortByTimeis thedefault setting.
LocalOnly Indicates whetherthe trace informationis shownonlyon thelocalserver orisshownto remoteclients also.
Chapter43:SecurityAuthentication and AuthorizationThewaytomakesecurityworkinyourapplicationsiswithauthenticationand authorization.Eachoneplaysanimportantroleinthedevelopmentofthesecuritymodel thatyoubuildintoyoursite.
AuthenticationAuthenticationistheprocessofdeterminingtheidentityoftheuser.Oncetheuserhas beenauthenticated-youcanusehisidentitytodetermineifhehasauthorizationto proceed.
Therearemanydifferentmodesofauthenticationtousewithinyourapplications.Someofthesemodesincludebasicauthentication-digestauthentication- formsauthentication- Passport-IntegratedWindowsauthentication(suchasNTLMorKerberos)-or authenticationmethodsthatyoumightdevelopyourself.
Theweb.configfilehasthreedifferentauthenticationmodulesthatyoucanuseinthe developmentofyourWebapplications:
Windows Forms Passport
Table4 3 - 1 describesthedifferencesintheseformsofauthentication.Table43-1:AuthenticationProviders
AuthenticationProvid
Description
Windows Windows authenticati onisused together withIIS authentication.Authenticationis performed byIISinthe followingways:basic- digest-or Integrated Windows Authenticati on.WhenIIS authenticati onis complete- ASP.NET usesthe authenticate didentityto authorize access.
Forms Requests thatarenot authenticatedrequests are redirectedto anHTML formusingHTTPclient- side redirection. Theuser provideshis login information andsubmits theform.If the application authenticatestherequest-thesystem issuesa formthat containsthe credentialsora keyfor reacquiring theidentity.
Table43-1:AuthenticationProviders
AuthenticationProvid
Description
Passport A centralized authenticati onservice providedby Microsoft thatoffersa singlelogin andcore profile servicesfor member sites.
<authenticationmode="Windows|Forms|Passport|None"/>
Noticethatfourpossiblechoicesareusedindeterminingthemodeofauthentication. ThedefaultsettingisWindows.
Windows-basedauthenticationWindows-basedauthenticationexistsbetweentheWindowsserverandtheclient's browser.Windows-basedauthenticationgoestoIIStoprovidetheauthentication module.Usingthiskindofauthenticationisquiteusefulinanintranetenvironment- whereyoucanlettheserverdealwiththeauthenticationprocess.
Windows-basedauthenticationfirsttriestousetheuser'scredentialsfromthedomain login.Ifthisfails-itthenpopsupadialogboxsotheusercanre-enterhislogin information.WhenWindows-basedauthenticationisused-theuser'spasswordisn't passedfromtheclienttotheserver.Ifauserhasloggedonasadomainuseronalocal computer-theuserwon'tneedtobeauthenticatedagainwhenaccessinganetwork computerinthatdomain.ThenextstepistoconfigurethesampleapplicationsothatitusesaWindows–basedauthenticationsystem.
CreatingusersFollowthesestepstocreateusersonthelocalserver:
1.WithinWindows2000Professional- openuptheComputerManagementutility(Start ControlPanel AdministrativeTools
ComputerManagement).Youcanalsoopenuptheutilityby right-clickingontheMyComputericononyourdesktopand choosingManage.
Note TheComputerManagementutilitymanagesandcontrolsresourcesonthelocalorremoteservers.Therearemanythingsthatyoucando withintheComputerManagementutility-butyouwanttofocuson creatingusers.OpenuptheLocalUsersandGroupsbranch.
2.Afterexpandingthisbranch-twofoldersaredisplayed-UsersandGroups.
3.Right-clickontheUsersfolderandselectNewUser-asshowninFigure43 - 1 .TheNewUserdialogboxappears(seeFigure 43 - 2 ).
Figure43-1: Selectinganewuser
Figure43-2: Givetheuseranameinthisdialogbox.4.Givetheuseraname-suchasJdoe.Youcanprovidehisfullname anddescription.5.GivetheuserapasswordandunchecktheUsermustchange
passwordatnextlogoncheckbox.Thisisjustatestonyourpart- butit'sbesttoforcetheusertodothiswhenyoucreatearealuser inthesystem.
6.Onceyou'vefilledinallthenecessaryinformation-clickCreate.YourusernowappearsinthelistofusersintheComputerManagement utility.
AuthenticatingandauthorizingauserNext-arrangeforIIStoauthenticateusersonceyouprovidetheauthorizationsbased upontheseauthentications.Inordertoaccomplishthis-openuptheweb.configfile andchangesomeoftheapplicationsettingswithinthefile.Youfindtheweb.configfile withintherootdirectoryofyourapplication.Onceit'sopen- navigatedowntothe<authentication>node.Directlyafterthisnode-placethefollowingcode:
<identityimpersonate="true"/>Itdoesn'tneedtobedirectlyafterthe<authentication>node-butit'sshownthat wayhereforfilereadability.They'rerelatedintermsofthefunctionalityyou'reworking withnow.Thiscodechangestheimpersonateattributetotruesothatyoudon'thavetodealwithauthenticationandauthorizationissuesintheASP.NETapplicationcode.Instead-you're relyingonIIStoeitherauthenticatetheuserandpassanauthenticatedtokentothe ASP.NETapplicationor-ifit'sunabletoauthenticatetheuser-passanunauthenticated token.Next-changethe<authorization>nodetosuityourneeds.Theauthorization elementallowsfortwosubelements-<allow>and<deny>.Youcanhaveasmanyof thesetwosubelementswithintheauthorizationelementasyouseefit.Boththe<allow>and<deny>nodescancontaintheattributesusers-roles-and verbs.usersspecifiesindividualuserstoallowordenyaccesstotheapplication- rolesisforgroups-andverbsspecifieshowtheusercametotheapplication.(Groups arediscussedinthenextsection .)Thischapterwon'tbeshowinganyexamplesusingtheverbsattribute-butbasically-youcanallowordenyusersbasedonwhethertheycametotheapplicationusingGET-POST-HEAD-orDEBUGmethods.
<authorization>
<denyusers="*"/>
</authorization>A"*"referstoallusers-anda"?"referstoanonymoususers.Soyoujustinstructed theapplicationtodenyallusers-evenifthey'reauthenticated.Next-typeintheURL.You'reaskedtologontotheapplication-eventhoughnobodyisallowed(seeFigure43 - 3 ).You'regiventhreechancestotypeinyourlogininformation.
Figure43-3: RequesttologontotheapplicationBecauseyou'renotlettinganyuseraccesstheapplicationafterthethirdtry-you're informedthatyouweredeniedaccess(seeFigure43 - 4 ).
Figure43-4: Accessdenied
Accessing Authentication PropertiesIt'spossibletoaccessauthenticationpropertiesandusethemwithinyourcode.For instance,directlyinthecode,it'spossibletoaccesstheuser'sloginnameandfindoutif he'sanauthenticateduser.
Tochecktheuser'sloginname,youwouldusethefollowingcode: DimUserNameAsString
UserName=User.Identity.Name
Tocheckiftheuserisauthenticated,usethefollowingcode: DimUserAuthAsBoolean
UserAuth=User.Identity.IsAuthenticatedThisreturnsTrueiftheuserisauthenticatedandFalseifhe'snot.Oneexampleistouse thisstatementdirectlyinanIfThenclause,asshownhere:
IfUser.Identity.IsAuthenticated Then
'dosomething
Else
'dosomethingelse
EndIfPerforming Forms-Based AuthenticationAnotherpopularwaytoauthenticateandauthorizeuserstohaveaccessto applicationresourcesistohavethemtypeintheircredentialsintoHTMLforms. Whenauserattemptstoentertheapplicationbutisunauthenticated,he's redirectedtoaspecifiedloginpage.Herehecantypeinhisusernameand passwordtogetauthenticated.Oncehe'sauthenticated,theuserreceivesa HTTPcookietouseonsubsequentrequests.Toactivateforms-basedauthentication,youfirstneedtochangetheweb.configfileasfollows:
<authenticationmode="Forms">
<formsname="MyForm"path="/"loginUrl="login.aspx"
protection="ALL"timeout="30">
<credentialspasswordFormat="Clear">
<username="Jdoe"password="Password"/>
<username="Bill"password="Obiwan"/>
</credentials>
</forms>
</authentication>
<authorization>
<allowusers="Jdoe,Bill"/>
<denyusers="?"/>
</authorization>Theattributesoftheformselementaredefinedasfollows:
name—Thisisthenamethatisassignedtothecookie.Thedefaultvalue is.ASPXAUTH.
loginUrl—SpecifiestheURLtowhichtherequestisredirectedfor loginifnovalidauthenticationcookieisfound.Thedefaultvalueis default.aspx.
protection—Specifiestheamountofprotectionyouwanttoapplytothecookie.Therearefouravailablesettings:All,None,Encryption,andValidation.
All—Specifiesthattheapplicationusesbothdatavalidationand encryptiontoprotectthecookie.Allisthedefault(and recommended)value.
None—Appliesnoencryptiontothecookie.Thisisn'tthebestsettingtouse,butitcouldbeusedforpersonalizationandforsettingsthatdon't requireanyamountoftruesecurity.Thisoptionistheleastresource- intensiveofthefourchoices.
Encryption—Thisisasettingwherethecookieisencryptedbutdata validationisn'tperformedonit.Cookiesusedinthiswaymightbe subjecttochosenplaintextattacks.
Validation—ThisistheoppositeofEncryption.Datavalidationisperformed,butthecookieisnotencrypted.
path—Specifiesthepathforcookiesissuedbytheapplication.Inmost casesyouwanttouse"/",whichisthedefaultsetting.
timeout—Specifiestheamountoftime,inminutes,afterwhichthe cookieexpires.Thedefaultvalueis30.
PartVII:WebServicesChapter44:IntroductiontoWebServices Chapter45:WebServicesInfrastructure Chapter46:SOAPChapter47:BuildingaWebServiceChapter48:DeployingandPublishingWebServicesChapter49:FindingWebServicesChapter50:ConsumingWebServices
Chapter44:Introduction to Web ServicesThe Next-Generation InternetThenextgenerationoftheInternetisuponus.Manytalentedandenergeticpeopleare workingveryhardtodelivertheinfrastructurethatwillmaketheInternetaplatformfor doingbusinessinwaysthatwereunimaginableonlyafewyearsago.ThisInternetofthe futureholdsgreatpotentialforallowingbusinessestocollaborateandintegratedataand applicationsasneverbefore.Itpromisestopulltogetherislandsofinformationintoa transparentlycoordinatedwholeanddeliverthatinformationtoallkindsofdevices, includingcellphones,personaldigitalassistants,handhelddevices,laptops,pagers,and others.Theheartandsoulofthesenext-generationservicesareExtensibleMarkupLanguage (XML),HypertextTransferProtocol(HTTP),andWebServices.XMLisaWorldWide WebConsortiumstandardthatpermitsdatatobeportableandself-describing,soitcan beexchangedeasilybetweenapplicationsanddevicesonmanyplatforms.Web ServicesallowuserstoprogrammaticallyexchangestructureddataencodedasXML overtheInternetviaHTTP.YoucanthinkofWebServicesasprogrammableURLs.
Statedanotherway,aWebServiceisanapplicationcomponentthatcanbecalled remotely.Thus,anysystemthatsupportsthesebasic,standardprotocolsiscapableof supportingWebServices.
Understanding the Need for Web ServicesWebServicessolveabasicbutpervasiveproblemthatmanyofusexperiencewith today'sInternet.Althoughthereareliterallybillionsofpagesofusefuldataand informationontheWeb,it'stypicallydifficulttoextract,examine,andusethatdata programmatically.MuchofthisdifficultyarisesfromthefactthattheWeb(atleastasitexiststoday)isdesignedforhumanconsumption.Consequently,dataispresentedinaformthat'seasyforpeopletoreadbutrelativelydifficultanderror-proneforapplications toreadandprocessreliably.
Asanexample,manye-commercesitesneedtocalculateshippingchargesbasedona varietyofshippingoptions.Typically,suchasitemightmaintainasetofdatabasetables thatdescribetheshippingoptionsandchargesforeachshippingcompany.Obviously, thiscanbecomeatime-consumingprocessbecausethedataislikelytochangeoften andsomeonemustupdatethetablesrepeatedly.Amoresophisticatedapproachmightincorporateaprocesscalledscreenscraping,whichanalyzesthedatainapageforcertainpatternsandextractsthisdataforfurther processing.SupposethatoneoftheshippingcompaniesmaintainsaWebsitethat convenientlyliststhevariousshippingoptionsandassociatedcharges.Byusingscreen scraping,aprogramcanexaminetheWebpageandextracttheshippinginformation fromthatpage.
Ofcourse,therearemanyotherpotentiallyvaluableapplicationsofWebServices.Some examplesoftheseservicesincludethefollowing:
Creditcardvalidation,financialaccountmanagement,stockquotes,and soon.Theseareservicesthatmightbetoodifficultortooexpensiveto implementyourself.
Userauthentication,usagebilling,usageauditing,andsoon.These servicesprovidecommonlyneededfunctionalityforotherservices.
Travelbooking.Thistypeofserviceaggregatesdistributed,discreteservices intoanorchestratedwhole.Accountsreceivable,accountspayable,invoicing,purchaseorders,and
soon.Theseservicesprovidetheabilitytointegrateyourbusiness systemswithyourpartners(orotherbusinesssystemswithinyourown organization).
Packagingapplicationcodeintoreusablecomponentsthatcanbecalledacrossprocess andmachineboundariesisn'tanewconcept.Today,wehavetechnologiessuchasthe ComponentObjectModel(COM),theCommonObjectRequestBrokerArchitecture (CORBA),InternetInter-ORBProtocol(IIOP)andRemoteMethodInvocation(RMI),to nameafew.Akeylimitationofthesetechnologiesisthatthey'renoteasilyinteroperable betweenthetremendousnumberofheterogeneoussystemsthatmakeuptheInternet.
Basic Elements of Web ServicesMicrosoftprovidesanexcellentplatformforbuildingandconsumingWebServiceswith the.NETFramework,whichvirtuallyeliminatestheneedtolearnaboutthe"plumbing" involvedinbuildingandconsumingWebServices.Ifthingsworkedrightallthetime,therewouldbenoneedtoevendiscussthisplumbing.Butofcourse,thingsdon'talways workright,soit'susefultohaveabasicunderstandingofthefoundationuponwhichWebServicesarebuilt.
Thekeytothebroad-reachingcapabilitiesofWebServicesontheInternetisasoftware infrastructurebuiltonInternetstandardsthatdoesn'trelyonanyplatform-specific technology.Thisinfrastructuresuppliesstandards-basedservicesthatprovidethe followingcapabilitiestoWebServices:
Describingdatainastructured,portablemannerCommunicatingrequestsandresponsesbymeansofanextensiblemessage formatDescribingthecapabilitiesofWebServicesDiscoveringavailableWebServicesDeterminingwhichsitesprovideWebServices
ThefollowingsectionswillhelpyoutounderstandwhytheseissuesareimportantandwillintroduceyoutothetechnologiesthatprovidethesecapabilitiestotheWebServices platform.
DescribingdataToenableWebServicestocommunicatetheirdataunambiguously,efficiently,and effectively,youmustuseacommon,portable,andstandardmethodfordescribingdata. Thesimple(andlogical)answerisXML.
XMLisusedextensivelyineveryaspectofWebServices.It'sastandards-basedmethod fordescribingdata(alsoknownasmetadata).XMLcandescribedatabyusingasimple grammarthatishighlyinteroperablebetweenthemanyhetero-geneoussystemsthatareconnectedtotheInternet.UsingthebasicelementsoftheXMLlanguage,youcandescribebothsimpleandcomplexdatatypesandrelationships.
XMLhasseveralkeystrengthsthathavehelpedittobecomethedefactomethodfor describingdata(especiallycomparedtoHTMLandotherbinaryformats).Theseinclude thefollowing:
It'satext-basedlanguage,whichmakesiteasilyreadableandmoreportablethanbinarydataformats.
Youcandefineyourowntagstodescribedataanditsrelationshipsto otherdata(hencetheword"extensible"initsname).
Itstrictlyenforcesitslanguagesyntax,unlikeHTML. ParsersarewidelyavailabletoaccuratelyparseandvalidateXML
structuresthatyoudefine,whichmeansyoudon'thavetodoityourself!
ThefollowingsectionsbrieflyexaminethesyntaxandstructureofXMLdocuments.
Specifically,whenyou'recreatinganXMLdocument,it'sveryimportantthatyoufollow thesebasicrules: Allelementsmusthaveanendtag. Allelementsmustbecleanlynested(nooverlapping). Allattributevaluesmustbeenclosedinquotationmarks. Eachdocumentmusthaveauniquefirstelement(thedocumentroot).
Chapter45:WebServicesInfrastructure
Microsoft WebServices PlatformOneoftheprimarymotivationsbehindthecreationoftheWebServicesarchitecturewas theinadequacyoftheexistingdistributedobjectmodeltechnologies,suchasthe DistributedComponentObjectModel(DCOM),theCommonObjectRequestBroker Architecture(CORBA),andtheInternetInter-OrbProtocol(IIOP)forInternet-based applications.Althougheachofthesetechnologiesworkedwellinacontrolled, homogeneousenvironment,thisobviouslycannotbeguaranteedforsystemsonthe Internet.What'smore,theselegacyobjecttechnologiescouldalsobeextremelylarge andcomplex(somemorethanothers).Again,thismakesitdifficulttorelyontheseolder technologiesasafoundationfordistributedcomputingontheInternet.
ThemajoradvantagesoftheWebServicesfoundationareitssimplicityanditsreliance onexisting(oremerging)Internetstandards.ThisensuresthatWebServicescanbe implementedallacrosstheInternet.AlthoughtheWebServicesfoundationdoesagreatjobofenablingaprogrammableInternetcomposedofdistributedbuildingblocks,there'sreallymuchmoretocreating scalable,robust,distributedapplications.Eachindividualplatformmustsupplythese servicesbecausetheWebServicesfoundationdoesn'tattempttoaddresstheseissues. TheMicrosoft.NETplatformisspecificallydesignedtoprovidetheseessentialservices thatmakeiteasytocreateworldclassWebServices.Figure4 5 - 1 illustratesthe MicrosoftWebServicesplatformarchitecture.
Figure45-1: TheMicrosoftWebServicesplatformarchitecture
AsshowninFigure45 - 1 ,theCommonLanguageRuntime(CLR)isbuiltontopofthe
systemservicesplatform(suchasWindows2000).LayeredontheCLRisthe.NET FrameworkClassLibrary,whichprovidesalargesetofservicesviaahierarchically arrangedcollectionofclassesandtypes.OntopofthisbasearetheASP.NETWeb platformandWindowsFormsenvironments.Thischapterlooksatmostofthese architecturalpieces,astheyrelatetothedevelopmentandconsumptionofWeb Services.
OneoftheprimarygoalsoftheMicrosoftWebServicesplatformistomakeiteasyto buildWebServicesthatcansolvecomplex,business-criticalproblems.Thefollowing sectionswilltakealookattheWebServicesplatformfeaturesthatmakeiteasyto createthesetypesofapplications.TheMicrosoft.NETFramework
The.NETFrameworkisMicrosoft'spremierplatformforbuildinganddeployingrobust WebServices.It providesbuilt-insupportfor creatingand consumingWebServicesin threekeyareas:
TheCommonLanguageRuntime(CLR) The.NETFrameworkClassLibrary ASP.NET
Let'sexaminesomeofthefeaturesofthesekey.NETFrameworkpieces,whichprovide arobustenvironmentforthecreationandexecutionofworld-classWebServices.
The CommonLanguageRuntimeTheCLRprovidesthefoundationforthe.NETFramework.It'sresponsibleformanaging codeatexecutiontimeandprovidesthefollowingservices:
Automaticmemorymanagement—Garbagecollectionishandledbytheruntime,relievingtheprogrammerfrommanagingmemory.This improvesthereliabilityandstabilityofapplications.
Codesafetyandsecurity—Codecanbe"lockeddown"topreventunauthorized,oruntrustedaccess.Thissecurityinfrastructureishighly flexibleandconfigurable.
Codeversioninganddeploymentsupport—Multipleversionsofcodecanberuninside-by-sidemode,thusprovidingmorereliable operationforolderapplicationsthatrelyonolderversionsofcode libraries.
Cross-languageintegration—Enablesallprogramminglanguagestosharedataconsistentlyviaacommontypesystem.
Remoting—Extendsthecallingofcomponentsacrossprocessand machineboundariesusinganextremelyefficientwireprotocol. Self-describingobjects—Metadatathatdescribesanobject's
capabilitiesisstoredwiththeobject,makingiteasytodynamically determinehowtointeractwithanobject.
Threadmanagement—Asimpleyetflexiblethreadmanagementinfrastructuremakesiteasytocreatemulti-
threadedapplications.CodethattargetstheCLRiscalledmanagedcode.Compatiblelanguagecompilersgeneratecodethatenablestheruntimetomanagetheexecutionofyourapplications.Todothis,compilersgenerateMicrosoftIntermediateLanguage(MSIL).Thisintermediatecodeisplatform-independentandcanbehostedonanyprocessorarchitecturesupportedbytheCLR.AJust-In-Time(JIT)compilerisusedtoconvertMSILintoprocessor-specificcodeatruntime.Duringexecution,CLR-managedcodeautomatically receivesthebenefitsofmemorymanagement,cross-languagedebuggingsupport, security,andmanyotherfeatures.Managedcodeispackagedintounitscalledassemblies.Thesearethebuildingblocksof.NETFrameworkapplicationsandformthefundamentalunitofdeployment,version control,reuse,andsecurity.Anassemblycontainsalloftheinformationnecessaryfor theCLRtoprovideitsservices.
AmajordesigngoaloftheCLR(asistrueofallthepiecesintheWebServicesarchi- tecture)istomakethedevelopmentprocesseasier.Asyoucansee,theCLRprovidesanexcellentexecutionenvironmentforWebServices.Thedeveloperdoesn'tneedtoprovideandmanagethesefeatureshimself,makingitquickandeasytobuildanddeployrobustWebServiceapplicationsthattakeadvantageoftheCLR.
The.NETFrameworkClassLibraryThe.NETFrameworkClassLibraryisacollectionofclassesthatareorganizedintoa singlehierarchicaltreeofnamespaces.Theclasslibraryprovidesaccesstosystem featuresviaclasses,interfaces,andvaluetypesthatgreatlyenhanceprogrammer productivityandsimplifythedevelopmentprocess.Theclasslibraryisbuiltontopofthe CommonLanguageRuntime,whichwasjustdiscussed.Therefore,it'salsomanaged
codethatreceivesallthebenefitsprovidedbytheCLR.
AttherootoftheclasslibraryhierarchyistheSystemnamespace.Thisnamespace containsover100coretypesandclassesthatareusedbyall.NETapplications.In additiontotheSystemnamespace,theclasslibrarycontainsnamespacesforabstract baseclassesandderivedclassimplementations.ThisincludesfileI/O,messaging, networking,security,andaccesstotheInternet.Youcanusetheseclassesas-isor derivefromthemtocreateyourownimplementations.The.NETFrameworkusesadot-basednamingschemetorepresentgroupedclassesandtypesthatmakeupanamespace.Namespacesmakeiteasiertosearchforand referenceclassesandtypes.Thenamespacenameincludeseverythingfromthe beginningofthenameuptothelastdotinthename.Theremainingpartofthename identifiesthetypename.Forexample,theSystem.WebnamespacedefinestheWeb type,whichbelongstotheSystemnamespace.Table45 - 1 listssomeofthe namespacesthatimplementfeaturesofWebServicesonthe.NETplatform.
Table45-1:.NETWebServiceNamespaces
Namespace Purpose
System.Web.Services Contains classes that enable youto buildand consume Web Services.
Table45-1:.NETWebServiceNamespaces
Namespace Purpose
System.Web.Services.Description Contains classes that enable youto describe aWeb Service viathe Web Service Descripti on Languag e (WSDL).
System.Web.Services.Discovery Contains classes that impleme ntthe discoveryprocessusedby Web Service consumersto locate available Web Services.
System.Web.Services.Protocols Contains classes that implementthe protocols usedto exchangeWeb Service message s between Web Services andWeb Service consumers.
ASP.NETASP.NETisaunifiedWebdevelopmentplatformthatprovidesadvancedservicesfor buildingWebapplicationsandWebServices.Itprovidesanewprogrammingmodeland infrastructurethatallowsyoutocreatepowerfulWebapplicationswithunprecedented speed,flexibility,andease.ASP.NETisfullysupportedbythe.NETFramework,allowing youtotakefulladvantageoftheCommonLanguageRuntime(CLR),typesafety, inheritance,andalloftheotherfeaturesofthatplatform.
ASP.NETofferstwoprogrammingmodels:WebFormsandWebServices.Developers canuseWebFormstocreatethemoretraditionaltypeofWebapplicationwhereusers interactwithindividualpagesandinputforms.WebServices,ofcourse,isthefocusof thispartofthebook.
BothoftheseprogrammingmodelsoffertwotechniquesforcodingWebpagesandWeb Services.Usingembeddedimplementationcode,thelogicforaWebpageorWeb Serviceisembeddedinthepageitself(muchlikethatofthetraditionalASP programmingenvironment).Contrastthistechniquewiththecode-behindfileapproach. Usingcode-behind,thelogicforaWebpageorWebServiceisstoredinaseparatefile fromtheuserinterfaceofaWebpageortheentrypointdeclarationofaWebService.
Bydefault,VisualStudiocreatesASP.NETWebFormsandWebServicesbyusingthe code-behindtechnique.Thiscreatesacleardistinctionbetweenthedefinitionoftheuser interface(orWebService)andthecodethatimplementsitsbehavior.
ThenextfewsectionssurveysomeofthefeaturesoftheASP.NETplatformthatare availabletoASP.NETWebServices.
ASP.NETapplicationsAnASP.NETapplicationconsistsofallthefiles,pages,handlers,modules,and executablecodeinaWebservervirtualdirectory(andanysubdirectories).WebServices
arealsoASP.NETapplicationsandthereforearegovernedbythesameconfiguration rulesasanyotherASP.NETapplication.EachASP.NETapplicationcanincludeanoptionalGlobal.asaxfileintherootvirtualdirectory.Thisfilecontainshandlersforapplication-leveleventsthatcanberaisedby ASP.NET.Forexample,youcanhandlesucheventsasApplication_OnStartand Application_OnEndintheGlobal.asaxfile.Inadditiontotheseevents,youhaveaccesstoanyeventsexposedbyHTTPModules.AnHTTPModuleisaclassthatcanprocessinformationfromanyHTTPrequestsmade toyourASP.NETapplication.Youcancustomizeorextendmodulessuppliedby ASP.NETorcreateyourown.AnyeventsraisedbyHTTPModulesarehandledwithin theGlobal.asaxfile.WebServiceprojectscreatedwithVisualStudioautomaticallycreateaGlobal.asaxfile.Thisemploysacode-behindfiletocontainthecodethathandlestheaforementioned events.Thecode-behindfileisdeclaredintheGlobal.asaxfilebyusingtheASP.NET Applicationdirective:
Web Services InfrastructureWebServiceDirectoriesWebServiceDiscoveryWebServiceDescriptionWebServiceWireFormats
WebServicediscoveryWebServicediscoveryistheprocessoflocatingoneormorerelateddocumentsthat describeaspecificWebService.ThesecapabilitiesaredescribedinastandardwaybyusingtheWebService DescriptionLanguage(WSDL),whichisanXMLgrammarspecificallydesignedforthis purpose.
BeforeyoucansubmitrequeststoaWebService,youmustknowhowtoformata requestforaparticularservice.Itmustbeintheformofamessagethatencodesthe operationrequested(suchasconvertingatemperaturefromoneunittoanother),aswell asanydatarequiredtocarryouttheoperation(suchastheinputtemperature,thesourceunits,andthetargetunits).Inaddition,youmustknowwhetherornottoexpectaresponsemessagefromtheWebServiceandwhatformatthisresponsewilltake(such astheconvertedtemperaturevalue).
TheWebServicediscoveryprocesspermitsaconsumertosearchforandlocatethe WSDLdocumentforaWebService.AconsumermusthavetheWSDLdocumentbefore anyrequestscanbeproperlyformattedanddeliveredtotheWebService.
TheDISCOspecificationdefinesanXML-basedgrammarandalgorithmfordiscovering theexistenceofWebServicesandlocatingtheirWSDLdocuments.UsingDISCO,you candefinesearchtreesthatareprocessedaccordingtotheDISCOalgorithmtolocate WebServicedescriptions.
DiscoverydocumentsareXMLfilesthathaveafiletypeof.discoor.vsdisco (whenautomaticallygeneratedbyVisualStudio).Adiscoverydocument isacontainerfortwotypesofelements:pointerstoWSDLdocuments,andpointersto otherdiscoverydocuments.ThesepointerstaketheformofURLsandcanbeabsolute orrelative.The<contractRef>elementisusedtolinktoWebServiceWSDL documents,whereasthe<discoveryRef>elementisusedtolinktootherdiscovery documents.
WebServicedescriptionAWebServicedescriptionisanXMLdocumentthatdefinesthecapabilitiesofaWeb Service.UsingtheWebServiceDescriptionLanguage(WSDL)XMLgrammar,youcan clearlyandunambiguouslydefinetheWeb-addressableentrypoints,therequest messagesthataWebServicewillaccept,andtheresponsemessagesaWebService canreturn.Alsoincludedinthisdescriptionarethesupportedprotocolbindingsanda descriptionofthedatatypesprocessedbytheWebService.
Recallthatthe.NETFrameworksupportsself-describingassemblies.Thisis accomplishedbystoringmetadatawiththeassemblythatdescribestheinterfaces,data types,andotherinformationabouttheclassesintheassembly.Usingtheself-describing natureof.NETassemblies,the.NETFrameworkcangenerateWSDLdocumentsto describeWebServicecapabilitiesfromthe.NETassembliesthatcontainASP.NETWeb Servicecode.
Chapter46:SOAPWhat Is SOAP?TheSimpleObjectAccessProtocol(SOAP)isalightweight-XML-basedprotocolfor exchanginginformationinadecentralized-distributedenvironmentsuchasthatoffered bytheInternet.Inotherwords-SOAPenablestwoprocesses(possiblyondifferent machines)tocommunicatewitheachotherregardlessofthehardwareandsoftware platformsonwhichthey'rerunning.OneofthegreatestbenefitsofSOAPisthatit'spartofanopenprocessthathasbeen embracedatanunprecedentedlevelbymostofthemajorhardwareandsoftware vendors.TheSOAPspecificationisanopentechnology(havingbeensubmittedtothe W3C)thatprovidesthebasisforapplication-to-applicationintegrationknownasWeb Services.
BenefitsofusingXMLwithSOAP
ThefundamentalbuildingblockofSOAPisXML.SOAPdefinesaspecializedyetflexible XMLgrammarthatstandardizestheformatandstructureofmessages.Messagesare-in turn-thefundamentalmethodforexchanginginformationbetweenWebServicesand WebServiceconsumers.UsingXMLtoencodeSOAPmessagesprovidesseveral benefits-suchasthefollowing:
It'shuman-readable-makingiteasiertounderstandanddebug. Parsersandrelatedtechnologiesarewidelyavailable. It'sanopenstandard. ManyrelatedtechnologiesthatcanbeleveragedinSOAPare included.
Thus-XMLisanaturalchoiceforencodingSOAPmessages-anditcontributestothe simplicityofthespecification(atleastinrelationtomorecomplexbinaryprotocolssuch asCOMandCORBA).
The SOAP SpecificationTheSOAPprotocolspecificationisaW3C-submittednotethat'snowundertheumbrella oftheXMLProtocolsworkinggroup.Version1.2ofthespecification(thefollow-upto version1.1)wasunderdevelopmentasaworkingdraftatthebeginningofJuly2001. The.NETFrameworkandASP.NETWebServicesproduceandconsumeSOAP messagesthatarecompliantwithversion1.1oftheSOAPprotocolspecification.
TheSOAPprotocolspecificationhasfourprimaryparts,eachofwhichhasaspecific purpose:Adefinitionforamandatory,extensiblemessageenvelopethatencapsulates
allSOAPdata.TheSOAPenvelopeisthefundamentalmessagecarrier thatformsthebasisforSOAPmessageexchangebetweenSOAP-aware endpoints.ThisistheonlypartoftheSOAPspecificationthat'smandatory.
Asetofdataencodingrulesforrepresentingapplication-defineddatatypes,andamodelforserializingdatathatappearswithintheSOAPenvelope.
AdefinitionforanRPC-style(request/response)messageexchangepattern.SOAPdoesn'trequiretwo-waymessageexchanges,butWebServices typicallyimplementsuchRPC-stylerequest/responsepatternswhenused withHTTPasthetransportprotocol.Thus,therequest/responseRPC-style protocolisafunctionofHTTPandnotofSOAP.
AdefinitionforaprotocolbindingbetweenSOAPandHTTP.ThisdescribeshowSOAPmessagesaretransmittedusingHTTPasthetransport protocol.
SincetheSOAPenvelopeistheonlymandatorypartofthespecification,let'sfirsttakea
lookattheelementsthatmakeupaSOAPmessage.
Elements ofa SOAP MessageASOAPmessageiscomposedofthethreefollowingprimaryelements,eachofwhich performsaspecialpurpose:
Envelope—ServesasacontainerfortheremainingSOAPmessageelements.
Header—Containsoptionaldatathataconsumermayormaynotberequired tounderstandinordertoprocessthemessageproperly.Thisistheprimary extensibilitymechanismofSOAP.
Body—Containstheactualencodingofamethodcall,andanyinput argumentsoranencodedresponsethatcontainstheresultsofthemethod call.
Thenextfewsectionslookatthesemessageelementsindetail.
TheSOAPenvelopeTheSOAPenvelopeelementisarequiredpartofaSOAPmessage.Itservesasa containerforallremainingSOAPmessageelements.Typically,thisincludestheSOAP headerandbodyelements.Inaddition,theenvelopedefinesthenamespacesusedby theseelements.Figure46 - 1depictsthestructureofacompleteSOAPmessage.
Figure46-1: TheSOAPmessagestructureTodeliveraSOAPmessagetoanendpoint,addressinginformationthat'sspecifictothe transportprotocolbindingisusedtoensurethatthemessageisdeliveredtothecorrect endpoint.It'smuchlikeputtingarecipient'snameandaddressonarealenvelopesoa postalauthoritycandeliverit.InthecaseofHTTP,acustomHTTPheadernamed SOAPActionisusedtodirectthemessagetotheproperendpoint.
TheSOAPheader
TheSOAPheaderelementisanoptionalpartofaSOAPmessage.Itdefinesadditional informationthatcanberelatedtothemethodrequestinthebodyelement.Or,more likely,itdefinesinformationindependentofthemethodrequestthat'srequiredor otherwiseusefultoyourapplication.SOAPdoesn'tdefinethespecificcontentsor semanticsforaSOAPheader.SOAPheadersarequitesimilarinconcepttotheMETAtagsfoundinHTMLdocuments. Theydefinemetadatathatcanbeusedtoprovidecontextto,orotherwisedirectthe processingof,themessage.
TheSOAPbody
TheSOAPbodyelementisarequiredpartofaSOAPmessagethatcontainsthedata specifictoaparticularmethodcall,suchasthemethodnameandanyinput/output argumentsorthereturnvaluesproducedbythemethod.ThecontentsoftheSOAPbody dependonwhetherthemessageisarequestoraresponse.Arequestmessagecontainsmethodcallinformation,whereasaresponsemessagecontainsmethodcallresultdata.
SOAP Data Type SupportTheSOAPspecificationdefinesdatatypesupportintermsofXSD,theXML Schemaspecification.Thisspecificationdefinesstandardsfordescribing primitivedatatypes,aswellascomplex,hierarchicalstructures.Asyouwould expect,there'ssupportforintegers,strings,floats,andmanyotherprimitive types,aswellaslists(orarrays)oftheseprimitivetypes.
Inadditiontoprimitivetypes,user-definedstructurescanberepresented.This pavesthewayfordescribingcomplex,hierarchicaldatarelationshipssuchas thosefoundinaninvoiceorpurchaseorder.Thebottomlinehereisthatit's possibletodescribeanytypeofdatausingXSD.Thus,SOAPcansupportany datatype,fromthebuilt-inprimitivesdefinedbyXSDallthewaytoany arbitraryuser-definedstructure.ThisisoneoftheprimaryreasonsthatSOAP isthepreferredprotocolforexchangingWebServicerequestandresponse messages.ItenablesWebServicestoacceptaswellasreturnanytypeofdatathatcanberepresentedbyanXSDschema.TheCommonLanguageRuntime(CLR)within.NETsupportsawidevarietyof thecommondatatypes.Allofthesedatatypesaresharedequallyacrossallof
the.NETlanguagesandalsohaveawell-definedmappingtoXSDdatatypes, asshownin Table46 - 1 .
Table46-1:XSDDataTypesvs.CLRDataTypes
XMLSchemaDefinition CommonLanguageRuntime
Boolean BooleanByte N/A
Table46-1:XSDDataTypesvs.CLRDataTypes
XMLSchemaDefinition CommonLanguageRuntime
double Doubledatatype N/Adecimal Decimalenumeration Enumfloat Singleint Int32long Int64Qname XmlQualifiedNameshort Int16string StringtimeInstant DateTimeunsignedByte N/AunsignedInt UInt32unsignedLong UInt64unsignedShort UInt16
SOAP in the .NET FrameworkFortunately,everythingthatyou'velearnedaboutSOAPuptothispointislargely unnecessarywithrespecttoimplementingsimpleASP.NETWebServices.Thisis becauseASP.NETandthe.NETFrameworkautomaticallygenerateandprocessSOAPmessagesforyourWebService,leavingyoutofocusonwritingthelogicofyourWebServiceapplicationusingafamiliarobject-orienteddesignapproach.
However,moresophisticatedWebServicesmayrequireaccesstotheSOAPmessages inordertoaddcustomheaders,examineincoming/outgoingSOAPmessages,or otherwisealterthedefaultformatofmessagesgeneratedbythe.NETXMLserializer wheninteroperatingwithSOAPmessageprocessorsonotherplatforms.
IfSOAPmessagecustomizationbecomesnecessaryforaparticularWebServicethat youwanttoimplement,the.NETFrameworkandASP.NETcangiveyouaccesstothe SOAPmessages.ThissectionwilllookatthefollowingfeaturesprovidedbyASP.NET forcustomizingthedefaultSOAPmessageformatsandcontents:
SOAPheadersSOAPextensionsSOAPexceptions
The .NETSoapHeaderattributeAsyousawinthelastexample,theSoapHeaderattributeisusedtoenablesupportfor SOAPheadersonspecificWebServicemethodsthataredeclaredwiththeWebMethod attribute.Specifically,theSoapHeaderattributeissuppliedwiththenameofamember variablethat'saninstanceofyourcustomSoapHeaderclass.Technically,thissyntaxis settingapropertyoftheSoapHeaderattribute,namelytheMemberName-property.The
SoapHeaderattributesupportsthesethreeproperties: MemberName Direction Required
TheMemberName-propertyoftheSoapHeaderattributeidentifiesthenameoftheclass variablethatdeterminesthetypeoftheSOAPheader.Inthisexample,thetypeofthe SOAPheaderisobtainedfromtheAuthSoapHeadermembervariablewithinthe MyWebServiceclass.TheDirectionpropertyoftheSoapHeaderattributeisusedtospecifyinwhichdirectiontheheaderisexpectedtobesupplied.Bydefault,SOAPheadersareattached tomethodrequestsonlyandaresaidtobeinboundtotheWebService.Usingthis property,youcanchangethisdefaultbehavior.TheDirectionpropertyacceptsan enumerationnamedSoapHeaderDirectionthatsupportsthefollowingthreevalues:
SoapHeaderDirection.In:DeclaresthattheSOAPheaderisexpectedtobesuppliedtorequestmessagesgeneratedbytheWebService consumer.
SoapHeaderDirection.Out: DeclaresthattheSOAPheaderis expectedtobesuppliedbyresponsemessagesgeneratedbytheWeb Service.
SoapHeaderDirection.InOut: DeclaresthattheSOAPheaderisexpectedtobesuppliedbyboththerequestandresponsemessages.
Here'sanexampleoftheDirectionpropertyinVB.NET:
<SoapHeader("AuthSoapHeader", Direction:=SoapHeaderDirection.Out>Finally,theRequiredpropertyoftheSoapHeaderattributeisaBooleanpropertythat controlswhetherornottheSOAPheaderisrequired.Bydefault,thispropertyissetto true.Thismeansthatiftheheaderisn'tsupplied,aSoapexceptionwillberaised.Setting thispropertytofalsemakestheheaderoptional,asinthefollowingexample:
<SoapHeader("AuthSoapHeader", Required:="false")>
ThesearethebasicsforusingSOAPheadersinASP.NETWebServices.Buthowdoes aconsumeraccesstheSOAPheadertosetthevaluesthatneededtobepassed? Fortunately,thesedetailsarehandledforyoubyASP.NETwhentheWebServiceproxy classiscreated.ThismakessettingSOAPheadervaluesassimpleassettingaproperty ontheproxyclassinstance.You'lllearnallaboutWebServiceproxyclasses(theprimarymeansbywhichaconsumerinteractswithaWebService)inthechapteraboutconsumingWebServices.
Now,let'slookataslightlymoreadvancedfeatureofASP.NETcalledSOAPextensions.
UsingSOAPextensions
OneofthemoreadvancedfeaturesofSOAPwithinthe.NETFrameworkistheSOAP extensionstechnology.ThisletsyouinspectormodifyaSOAPmessageatspecific stagesinmessageprocessingoneithertheclient(theconsumeroftheWebService)or server(theWebServiceitself).Ofcourse,thisassumesthattheclientandserverare bothbasedonthe.NETFramework.
Thisisapowerfulfeaturebecauseitallowsyoutoimplementsomeveryinteresting applicationsthatcanbeleveragedbyWebServicesand/ortheirclientsinacompletely transparentmanner.Forexample,youcancreateextensionsthat
Encryptmessagestoprotectthecontentswhileintransit. Compressmessagestoreducethesizeofthetransmissionstream. Logmessagesforauditingortracingmessageactivity(especiallyuseful indebugging). ProcessSOAPattachments.
Chapter47:BuildingaWebServiceThischapterteachesyouhowtobuildasimpleWebServiceusingVisualBasic.NETin MicrosoftVisualStudio.Itgoesstep-by-stepthroughtheprocessofcreatingaWeb ServicethatconvertsgiventemperaturesbetweenFahrenheit,Celsius,Kelvin,and Rankine.Alongtheway,I'lldescribesomeoftheVisualStudioimplementationoptions relatedtobuildingWebServices.
Creating the Temperature Conversion Web ServiceThetemperatureconversionWebServiceconvertsspecifiedtemperaturevaluesfrom FahrenheitorCelsiustoeitherFahrenheit,Celsius,Kelvin,orRankine.Eachofthese unitconversionsisdefinedbyawell-
knownarithmeticformulathatcanbeeasily representedinVisualBasicanddoesn'trequirealotofcode.Thischapterkeepsit simplesothatyoucanfocusmoreonthevariousarchitecturalelementsofASP.NET WebServices,ratherthanthedetailsofthealgorithmimplementedbythecode.
Beforeyoustartbuildingthisservice,youshouldknowalittleaboutthefollowing componentsofthisexample:Temperatureconversionformulas
Table47-1:TemperatureConversionFormulas
From/To Fahrenheit(F)
Celsius(C)
Kelvin(K)
Rankine(R)
Celsius ((C*9)/5)+32
N/A C+273.15
F+459.67
Fahrenheit N/A ((F-32)*5)/9
C+273.15
F+459.67
MethoddescriptionsMethodargumentsMethodbehavior
TemperatureconversionformulasTable4 7 - 1 showstheconversionsthataresupportedbytheserviceandthe correspondingformulasusedtoperformtheconversion:
Asyoucanseefromthetable,someoftheconversionsarespecifiedassuminganinitial conversiontoanotherunit.Forexample,toconvertaCelsiustemperaturetoRankine, thetemperaturevalueisfirstconvertedtoFahrenheitandthentheremainingconversion rulesareapplied.
Finally,inkeepingwiththegoalofcodesimplicityandbrevity,theserviceonlysupports temperatureconversionsfromCelsiusorFahrenheittoanyoftheotherapplicableunits.
MethoddescriptionThetemperatureconversionWebServicesupportsasinglemethodnamedCTemp, whichismodeledalongthelinesoftheclassicVisualBasictypeconversionfunctions suchasCBool,CLng,CDbl,etc.Theobviousdifference,ofcourse,isthatyou're convertingtoothernumericunitsinsteadofconvertingtootherdatatypes.
MethodargumentsThetemperatureconversionmethodacceptsthethreeargumentsthataresummarized inTable 47 - 2 .Table47-2:TemperatureConversionMethodArguments
ArgumentName DataType
Comments
Temperature Decimal Any numeric valuethat canbe specifiedby the Decimal datatype.
FromUnits String Valid valuesare Cfor Celsiusor FforFahrenheit.
ToUnits String Valid valuesare Cfor Celsius,F forFahrenheit,KforKelvin,and Rfor Rankine.
ThemethodreturnsaDecimalresult,whichisthevalueoftheconversiontotheunitsspecifiedintheToUnitsargument.
MethodbehaviorIftheFromUnitsandToUnitsargumentsarethesame,themethodcallissuccessful andtheTemperatureargumentisreturnedunchanged.IftheFromUnitsand/or ToUnitsdon'tspecifyvalidunitidentifiers,anArgumentExceptionexceptionis thrown.Likewise,iftheconversionspecifiedbytheFromUnitsandToUnits argumentsisn'tsupported,anArgumentExceptionexceptionisthrown.
BuildingtheWebServiceinVisualStudioTheVisualStudioIntegratedDevelopmentEnvironment(IDE)isahighlyproductivetool forbuildingWebServices.AsyoulearnedinthepreviouschaptersofPartVI I ,Web Servicesrequireanaddressableentrypointfile,anassemblythatimplementsthe functionalityoftheservice,aWebServiceDescription(WSDL)document,anoptional Discovery(DISCO)document,andanoptionalUDDIregistration.Fortunately,the.NET FrameworkandVisualStudioimplementmuchofthisinfrastructureforyou,allowingyou tofocusyoureffortsonthefeaturesoftheWebService.
WebServicesbuiltwithVisualStudioareASP.NETWebServices.Thismeansthata WebServicebuiltinVisualStudioleveragestheASP.NETinfrastructure,tools,and runtime.Ofcourse,ASP.NETitselfisbuiltuponthefoundationofthe.NETFramework
andtheCommonLanguageRuntime(CLR),providingallofthebenefitsofthese technologiestoyourWebServiceimplementation.
TheserelationshipsarealsoimportantbecausetheyaffectthephysicalstructureofWeb ServiceswithintheVisualStudioenvironment.Thepowerofthismodelisquiteevident asyoubegintodissectthevariouspiecesofaWebServiceonthe.NETplatformand understandtheirfeatures.Thischaptercoversthesepointsasyouworkyourway throughthetemperatureconversionWebServiceimplementation.
BeforeyoustartworkingwithVisualStudiotobuildaWebServiceapplication,youmust considerafewenvironmentalfactorsrelatedtoyoursoftwareandnetworkconfiguration. Theseconsiderationsdirectlyaffecthowyoubuild,debug,anddeployWebServices usingVisualStudio.Theyfallintotwocategories:
WebServiceDevelopmentEnvironment—DescribesthesoftwareenvironmentnecessaryfordevelopingaWebService. WebServiceProjectAccessMethods—Describesthemethodsfor
managingtheWebServiceprojectfilesonaWebserver.
ASP.NETWebServicedevelopmentenvironment requirementsThetypicaldevelopmentenvironmentforanASP.NETWebServiceapplicationusually consistsofthefollowingelements:
ApersonalworkstationcontainingtheVisualStudiodevelopmentsoftwareand.NETframeworkSDKusedtodesignandbuildyourWebService.
AdevelopmentWebserverthat'sconfiguredtohostandruna development(non-release)versionofyourWebService.
AproductionWebserverthat'sconfiguredtohostthefinalruntime(release)versionofyourWebService.
CreatingaWebService projectThefirststeptobuildingthetemperatureconversionWebServiceoutlinedatthe beginningofthischapteristocreateaWebServiceprojectinVisualStudio.Afteryou've startedVisualStudio,chooseNewfromtheFilemenuandthenchooseProjectfromthe submenu.VisualStudiodisplaystheNewProjectdialogshowninFigure 4 7 - 3 .
Figure47-3: VisualStudio.NETNewProjectdialogbox
TheNewProjectdialogboxiswhereyoucancreatemanydifferenttypesofprojects basedonpreconfiguredprojecttemplates.Thesetemplatesdefinesuchthingsasthe basicstructureofaproject,thefilestobeincluded,andtheparametersnecessaryto buildanddeployyourproject.
TocreateaVisualBasic.NETWebServiceproject,followthesesteps:1.ChoosetheVisualBasicProjectsfolderfromthelistofprojecttypes
ontheleft.Next,choosetheASP.NETWebServiceiconfromthe listoftemplatesontheright.2.Specifyanameforyourproject.ThesampleprojectisnamedCTemp,
soenterCTempintheNametextbox.Noticethatasyoutypeinto thetextbox,VisualStudioautomaticallyfillsouttheprojectlocation, showingyouwhereyourprojectfileswillbestored.
3.TheprojectlocationtextboxdefineswhichWebserveryouusetostoreandexecuteyourWebServiceprojectfilesduring developmentinVisualStudio.
B
ydefault,theprojectlocationpointstothelocalWebserveronyourcomputer.MycomputernameisJDC7200CTE,whichresultsinarootlocation ofhttp://jdc7200CTE.Yournamewillbedifferent,ofcourse.Usually,you shoulddevelopandtestyourWebServiceusingyourlocalcomputer'sWeb serverbecausethat'sthesimplestconfiguration.
UnderneaththeLocationtextbox,thedialogboxdisplaysthecompletepath toyournewWebService.ThisisthepaththatconsumersofyourWeb Servicecanusewhencallingyourservice(atleastwhileit'sunder development).
4.ClicktheOKbuttontocreatetheproject.Atthispoint,VisualStudioconnectstotheWebserveryouspecifiedintheLocationtextbox andcreatestheWebServiceprojectfilestructure.VisualStudio alsocreatesasolutionfileonyourlocalcomputer.
Note IftheWebserveryouspecifiedisn'tonyourlocalcomputer,thesolutionfileistheonlyfilethat'sstoredlocally.
WhenVisualStudiohasfinishedcreatingtheproject,theIDElookssimilartoFigure47 - 4 .
Figure47-4: VisualBasic.NETWebServiceprojectinVisualStudio
CreatingWeb methodsNowthatyou'veupdatedtheclassname,you'rereadytoinserttheimplementationcode foryourWebService.Beginbyenteringthefollowingmethoddeclarationintothecode windowinsideyourTempConverterclass:
<WebMethod()>PublicFunctionCTemp(_
ByValTemperatureAsDecimal,_ ByValFromUnitsAsString,_
ByValToUnitsAsString)AsDecimal
Adding theimplementationcode
SelectCaseFromUnits.ToUpper.Chars(0) Case"F"'Fahrenheit
SelectCaseToUnits.ToUpper.Chars(0)
Case"F"'Noconversionnecessary
ReturnTemperature
Case"C"'ConvertFahrenheittoCelsius
Return((Temperature-32)*5)/9
Case"K"'ConvertFahrenheittoKelvin
Return(((Temperature-32)*5)/9)+273.15
Case"R"'ConvertFahrenheittoRankine
ReturnTemperature+459.67
CaseElse
'Throwexception
ThrowNewArgumentException("BadToUnitsarg.") EndSelect
Case"C"'Celsius
SelectCaseToUnits.ToUpper.Chars(0)
Case"C"'Noconversionnecessary
ReturnTemperature
Case"F"'ConvertCelsiustoFahrenheit
Return((Temperature*9)/5)+32
Case"K"'ConvertCelsiustoKelvin
ReturnTemperature+273.15
Case"R"'ConvertCelsiustoRankine
Return(((Temperature*9)/5)+32)+459.67
CaseElse
'Throwexception
ThrowNewArgumentException("Bad ToUnitsarg.") EndSelect
CaseElse
'Throwexception
ThrowNewArgumentException("BadFromUnitsarg.") EndSelect
EndFunction
Building the Web ServiceNowthatyou'veaddedalloftheimplementationcodeforyourCTempWeb Service,you'rereadytobuildit.WhenyoubuildaVisualStudioASP.NETWeb Serviceproject,thefollowingoccurs:
1. VisualStudiosavesallofthefilesintheprojectyoumodifiedsincethelastbuild.
2. VisualStudiocopiesthe{servicename}.asmxfileandthe defaultprojectfilestothedevelopmentWebserver.
3. The{servicename}.asmx.vbclassfileandtheGlobal.asaxclassfilearecompiledintotheproject.dllfile,whichisthencopiedtotheserverinthedefault\Bindirectoryofthetargetvirtual directory.Iftheprojectissettocompileadebugversion,Visual Studiocreatesaproject.pdbfileinthe\Bindirectory.
TobuildtheCTempWebService,chooseBuildfromtheBuildmenu.VisualStudiodisplaystheOutputwindowtoshowtheprogressandfinalresultsofthe buildprocessforyourproject,asshowninFigure47 - 6 .
Figure47-6: ResultsofbuildingtheWebServiceinVisualStudioNowthatyou'vesuccessfullybuiltyourWebService,you'rereadytotestit. Thenextsectio n coversWebServicetesting.
Testing the Web ServiceVisualStudioandthe.NETFrameworkprovideseveralmethodsyoucanusetotestyourWebService.ThesimplestandquickestmethodtotestyourWebServiceistousea WebbrowserusingtheHTTP-GETprotocol.Thistechniquedoesn'trequiredevelopinga consumerapplication.
Note ThistechniqueworksonlyfortheHTTP-GETprotocolsupportthat'sprovidedbythebrowser.Bydefault,anASP.NETWeb ServicebuiltinVisualStudiosupportstheHTTP-GET,HTTP- POST,andHTTP-SOAPprotocols.
InadditiontousingaWebbrowserwithHTTP-GET,youcanalsotestyourWebService usingaWebbrowserwithHTTP-POST,withaslightmodificationtothedefaultASP.NETpageusedtoviewWebServices.Finally,youcantestyourWebServiceby developingacustomconsumerapplication.TestingtheWebServicewithHTTP-GET
UsingaWebbrowsertotestyourWebServicewiththeHTTP-GETprotocoldoesn't requireyoutodevelopaconsumerapplication.Therefore,thisisaquickandeasyway toperformsomeinitialtestingofyourWebService.TheHTTP-GETprotocolencodes data(inthiscase,methodarguments)asquerystringparameterswhenpostingtothe server.Thisencodingmethodisusedtopassthepropermethodinputargumentsas querystringarguments.
TherearetwowaystoinvoketheHTTP-GETprotocolusingaWebbrowsertotestyour WebService.Youcanusethebuilt-intestpageofferedbytheASP.NETruntimeoryou canencodethecompleteURLtoyourWebServiceusinglocation,methodnameandanyinputargumentsasquerystringparametersintheaddressbarofyourbrowser.ThissectionillustrateseachofthesetechniquesusingtheCTempWebServiceasan example.
Chapter48:DeployingandPublishingWebServicesDeployingaWebServiceenablesittoexecuteonaspecifichostWebserver,whereas publishingaWebServiceenablespotentialconsumerstolocateandinterrogatethe capabilitiesoftheWebServicebeforeactuallycallinganymethodsoftheservice.This chapterdiscusseswhatyouneedtodobeforedeployingaWebService,theoptionsfor deployingandpublishingaWebServiceusing.NETtechniques,andthesupportbuilt intoVisualStudio.
Deployment PreparationBeforeyoudeployaWebService,youmustmakesurethattheWebService specifiesauniqueXMLnamespace.Thisname- spaceisusedwithintheWeb ServiceWSDLdocumenttouniquelyidentifythecallableentrypointsofthe service.Asmentionedin Chapter4
Table48-1:FilesDeployedwithaWebService
Folder File Description\inetpub\wwwroot\CTemp CTemp.asmx TheWeb Service entrypoint file.The
folder containing thisfile shouldbe configured asaWeb application directoryin IIS.
Global.asax The ASP.NET application startupfile.
Web.config The ASP.NET application configurationfile.
\inetpub\wwwroot\CTemp\bin
CTemp.dll TheWeb Service assembly thatcontainstheimplementationclasses fortheWeb Service,as wellasany dependent assemblies thataren't partofthe.NETFramework.
7,thedefaultWebServicenamespaceissettohttp://tempuri.org/whenyou'rebuildingaWebServiceinVisual Studio.NowthatyouarereadytodeployandpublishyourWebService,you mustchangethistemporarynamespacedesignatortoapermanentvalue.
BeforeyoudeploytheCTempWebService,youneedtochangethedefaultname-spacetoamoresuitablevalue.Todothis,followthesesteps:
1. StartVisualStudio.2. LoadtheCTempproject.3. IftheimplementationcodeintheCTemp.asmx.vbfileisnot displayed,openitbyright-
clickingonthefileintheSolutionExplorer windowandchoosingOpen.4. OntheTempConverterclassdeclarationline,addthe
<WebService>attributealongwiththeNamespacepropertyand setittotheappropriatevalue.
Deploying Web ServicesGenerallyspeaking,thedeploymentprocessforaWebServiceinvolvescopyingthe WebServiceentrypointfile(the.asmxfile),theWebServiceassemblyalongwithany dependentassemblies(excludingthe.NETframeworkassemblies),andrelatedsupport files(suchastheWebServicecontractfile)toanappropriatelyconfiguredvirtual directoryfilestructureonthetargetWebserver.
Insharpcontrastfromdeployingprevious-generationWindowsapplications,Web Servicestypicallyareeasytodeploy.VisualStudiomakesthisprocesseveneasierby providingseveraldeploymentoptionsthatareavailabledirectlywithintheVisualStudio environment.AtypicalWebServicebuiltinVisualStudioconsistsoftheWebServiceentrypointfile(the.asmxfile),theWeb.configfile,theWSDLfile,theDISCOfile,theWebService assemblythatcontainstheimplementationclassesfortheWebService,andany dependentassembliestheWebServicereferences(excludingthe.NETFramework).Table4 8 - 1 summarizesthestandardfilestructurefordeployingtheCTempWebService builtwithVisualStudio.
WebServicedeploymenttools
ThereareseveralchoicesfortoolsyoucanusetodeployaWebService,dependingon thecomplexityandcircumstancesofthatparticularproject.Thesechoicesare
VisualStudioWebSetupProject VisualStudioProjectCopy DOSXCOPYCommand GenericFileTransferMethod
Publishing Web ServicesPublishingaWebServiceenablespotentialconsumerstolocateandinterrogateservice descriptionsthatinstructtheconsumeronhowtointeractwiththeWebService.The processoflocatingandinterrogatingWebServicedescriptionsisreferredtoasthe discoveryprocess.ThetwomethodsforenablingdiscoveryofaWebServiceareDISCO andUDDI.Youmaychoosetouseoneorbothofthesemethodsbasedontheconsumeraudienceyouaretryingtoreach.
Table48-1:FilesDeployedwithaWebService
Folder File Description\inetpub\wwwroot\CTemp CTemp.asmx TheWeb Service entrypoint file.The
folder containing thisfile shouldbe configured asaWeb application directoryin IIS.
Global.asax The ASP.NET application startupfile.
Web.config The ASP.NET application configurationfile.
\inetpub\wwwroot\CTemp\bin
CTemp.dll TheWeb Service assembly thatcontainstheimplementationclasses fortheWeb Service,as wellasany dependent assemblies thataren't partofthe.NETFramework.
PublishingwithDISCOConsumersofWebServicesenactadiscoveryprocesstolocatethoseservices.The discoveryprocesssearchesforXML-encodeddiscoverydocumentsthatcontainpointers tootherresourcesthatdescribetheWebService.EncodingdiscoverydocumentsinXMLenablestoolssuchasVisualStudiotoprogrammaticallydiscovertheavailabilityof WebServices(ifyouknowtheURLtotheserver).ThisishowtheWebReference metaphorworksinVisualStudiowhenyouprovideitwithaspecificdiscoveryURL. Alternatively,youcanusethedisco.exetoolthatcomeswiththe.NETFramework SDKtodiscoverWebServices.WebServicediscoveryviaVisualStudio'sWebReferencefeatureortheNET FrameworkSDK'sdisco.exetoolisusefulwhentheconsumerknowstheURLtothe serverthat'shostingtheWebServiceortheapplicationvirtualdirectory.VisualStudioautomaticallycreatesaDISCOfilewhenyoucreateaWebServiceproject. Thisfilehasatypeof.vsdiscoandisstoredinthemainapplicationvirtualdirectory (alongwiththe.asmxfile).Asanexample,yourCTempWebServiceprojectcontainsa filenamedCTemp.vsdisco.Thisfilecontainslinkstotheresourcesthatdescribethe CTempWebService.
PublishingwithUDDI
DiscoveryofWebServicesviaDISCOissufficientifyouknowtheURLtotheWebserverortheapplicationvirtualdirectorythathoststheWebService.However,incaseswherethisinformationisunavailable,youmustuseamoregeneralizedsearchtool.UniversalDescription,Discovery,andIntegration(UDDI)enablesaWebServiceconsumertosearchforandlocateWebServices,eveniftheconsumerisunawareoftheexactlocation,owner,orauthorofthoseWebServices.
UDDIistoWebServiceswhatLycosandAltaVistaaretoWebpages.UDDIhelps consumerslocateWebServicesbasedonalogicallycentralized,globallyavailable registryofbusinessesaccessibleviatheInternet.UDDIconsistsoftwobasicparts:
AnXMLschemathatdescribesandcategorizesabusinessandtheWebServicesthatitoffers.
Thebusinessregistry(ordatabase)thatcontainsallknowninformation aboutbusinessesandWebServicesbasedontheXMLschema.
Chapter49:FindingWebServices
FindingWebServiceswiththediscotoolThe.NETFrameworkprovidesatoolnameddisco.exetolocateWebServicesata givenURLandcopytheWebServicedescriptionsthatitfindstoyourlocalharddrive. Theoutputofthediscotoolistypicallyusedasinputtothewsdltooltocreateaproxy classwithwhichtoconsumetheWebService.Thegeneralformatofthediscocommandlineis
disco[options]URLHere,URLspecifiestheHTTPaddressofthetargetWebserverthatyouwanttosearch fordiscovery(.disco)documents.Thediscotoolsupportsthecommand-lineoptionslistedinTable4 9 - 1 .Table49-1:DiscoToolCommand-LineOptions
Option Description/d[omain]:domain Specifiesthe domain nametouse when connecting toaproxy serverthat requires
authentication.
/nosave The discovered documents orresults (.wsdl,.xsd,.disco, and.discomapfiles)arenot savedto disk.The defaultisto savethese documents.
/nologo Suppresses
FindingWebServiceswithUDDIWhilethediscotoolisaneffectivemeansoflocatingWebServicedescriptions,it requiresyoutoknoweithertheURLtoaspecifictargetserverwheretheWebServiceis deployedortheURLtoaspecificWebServicevirtualdirectoryonaWebserver.Inany case,youwon'tbeabletofindanyWebServicesusingdiscowithoutknowingaURL.
Asmentionedpreviously,UDDIisamoregeneralizedsearchtoolforlocatingWeb Services.UsingUDDI,youcanspecifysearchtermsthatallowyoutopinpointWeb Servicesyouwanttousebasedoncompany,industry,servicetypes,andmanyother classifications.Usingthesemoregeneralizedsearchterms,UDDIcanreturninalistof URLswithinformationaboutspecificWebServices,includingtheWSDLdocumentthat youaresearchingfor.
InthemiddleofthepageistheAdvancedSearchform.Fromhere,youcanentertextin theSearchFortextboxtoperformacustomsearchofvariousfieldswithinthedatabase. YoucanlocateWebServicesinthismannerbysearchinganyoneofthefollowingfield types:
Businessname—Usethisfieldtosearchwithinregisteredbusinessnames.Forexample,youcouldsearchforservicesprovidedbyIBM.
Businesslocation—Usethisfieldtosearchbygeographiclocation.Forexample,youcouldsearchforcompaniesthatprovideservices withintheSt.Louisarea.
Servicetypebyname—Usethisfieldtosearchservicessubmittedbyacompanybytheservicename.
Businessidentifier—Identifiersarepiecesofdatathatareuniqueto anindividualbusiness,suchasthestandardD-U-N-S(r)Number. Thereareseveralstandardidentifiers,aswellascustomones,thata companycanregister.
DiscoveryURL—Providesalocationwithdetailsaboutaparticularentity,suchastheURLtoacompanyWebsiteoraparticularWebService.
GeoWebTaxonomy—Providesastandard,hierarchicalclassification ofgeographiclocationsbywhichtosearch.
NAICSCodes—TheNorthAmericanIndustryClassificationSystem (NAICS)providesastandard,hierarchicalclassificationofbusinesses basedontheproductsorservicestheyprovide.
SICCodes—StandardIndustrialClassification(SIC)providesa standard,hierarchicalclassificationofbusinessesbasedonindustry.
UNSPSCCodes—UniversalStandardProductsandServicesCodes (UNSPSC)providesastandard,hierarchicalclassificationof businessesbasedontheproductsandservicestheyprovide.
ISO3166GeographicTaxonomy—SimilartotheGeoWebTaxonomy,providesastandard,hierarchicalclassificationof businessesbasedongeography.
RealNamesKeyword—RealNamesisakeyword-likename,similartoAOLkeywords,thatisregisteredtoaspecificcompany.
Chapter50:ConsumingWebServicesWeb Service Consumer OverviewAWebServiceconsumerisanyapplicationthatreferencesandusesaWebService.It cantakemanyforms:aclientapplication,aserverapplication,acomponent,oreven anotherWebService.Itdoesnotmatter,aslongasitcancallWebServicesbyusing HTTPandSOAP.
ToconsumeaWebService,youneedtodothefollowing:FindtheWebService.ObtainitsWSDLservicecontract.GenerateaproxyclasswithwhichtocalltheWebService.
Createaninstanceoftheproxyclass.Callthemethodsexposedbytheproxy.
Creating the Web Application ProjectLet'sbeginbyusingVisualStudiotocreatetheprojectfilesforyourWebServiceconsumerapplication:
1. Ifyouhavenotalreadydoneso,startVisualStudionowandchooseNewfromtheFilemenu,andthenchooseProjectfromthe submenu.ThisdisplaystheNewProjectdialogbox,asshownin Figure50 - 1 .
2. IntheNewProjectdialogbox,selecttheVisualBasicProjectsfolderfromthelist of projecttypeson theleftsideof thedialogbox.Then chooseASP.NETWebApplicationfromthe listof templatesonthe rightsideofthedialogbox.
3. Next,typeCTempClientintheProjectNametextbox.Notethat,bydefault,theprojectfilesarelocatedonyourlocalWebserverina virtualfoldernamedCTempClient.
Figure50-1: TheVisualStudioNewProjectdialogbox.4. Afteryouhaveenteredthisinformation,clicktheOKbuttonto
createtheproject.VisualStudioautomaticallycreatestheproject andalloftherelatedprojectfilesnecessarytocreateanASP.NET WebapplicationonyourlocalWebserver.Afteryou'vecreated, loaded,andbuilttheproject,theVisualStudiowindowshould resembleFigure 50 - 2 .
Figure50-2: ASP.NETWebapplicationskeletoninVisualStudio.VisualStudiodisplaystheformdesignersurfaceofthedefaultASP.NETWebForm(namedWebForm1.aspx).Eventually,thisformwilldisplaytheuserinterfaceforrequestingtemperatureconversionsinaWebbrowser.
WhenyoucreateanASP.NETWebapplicationprojectinVisualStudioby usingtheWebapplicationprojecttemplate,aprojectfilestructureiscreatedon thetargetWebserverandaVisualStudioSolutionfileiscreatedonyourlocal computer.ThefileslistedinTable50 - 1areautomaticallycreatedbyVisualStudioandplacedinthefilestructureonthetargetdevelopmentWebserver.
Table50-1:VisualStudioWebApplicationProjectFiles
ProjectFile DescriptionWebform1.aspx Thisfile containsthe form definition,userinterface controls,and soonthat makeupthe
WebForm. WebForm1.aspxisthe defaultname giventothe pageby VisualStudio whentheWeb application projectisfirst created.
WebForm1.aspx.vb Thisfile containsthe code-behind classthat handlesthe eventsand related functionality represented bytheWeb Form.
AssemblyInfo.vb Thisfile contains information aboutthe assemblies withinthe WebService project.
Web.config ThisXMLfile contains ASP.NET application configuration information fortheWeb Service.
Table50-1:VisualStudioWebApplicationProjectFiles
ProjectFile DescriptionGlobal.asax Thisfileis responsible forhandling ASP.NET application- levelevents.
Global.asax.vb Thisfile containsthe code-behind classthat handlesthe ASP.NET application- levelevents. Thisfileis referencedby the Global.asa xfileinits ASP.NET application directive.By default,this filedoesnot appearinthe Solution Explorer.
{projectname}.vbproj Thisfile contains project metadata suchasthe listofproject files,build settings,and
soon.
{projectname}.vbproj.webinfo
Thisfile containsa pointertothe Webserver virtual directorythat hostsyour Web application projectfiles.
{projectname}.vsdisco
Thisfile containsthe links(URLs)tothe discovery (disco) information forthis application.
Building the Web FormNowthatyou'vecreatedthebaseprojectfilesforyourconsumerapplication andaddedaWebReferencetotheCTempWebService-you'rereadytobuild aformthatallowsyoutoentervaluesthatcanbepassedtotheCTempWeb Serviceanddisplaytheresultsafteracallismade.IfthedesignersurfacefortheWebForm1.aspxpageisnotcurrentlydisplayed-clickthetabinthemainwindowareaofVisualStudiocorresponding tothisfile.TheWebFormdesignerallowsyoutodraganddropcontrolsonto thedesignersurfaceandmanipulatetheminaWYSIWYGmanner.
Thisapplicationusesthefollowingcontrols:Twotextboxes-onefortheinputtemperatureandonefortheoutput temperatureTworadiobuttonlists-onetoselecttheinputtemperatureunitsandone toselecttheoutputtemperatureunitsOnecommandbuttontoexecutetheunitsconversion
Draganddropthesecontrolsontothedesignersurfaceoftheform.The controlsareavailableinthecontroltoolboxfromtheleftsideofthemainVisual Studiowindow.Ifthecontroltoolboxisnotvisible-chooseToolboxfromthe Viewmenu.Youshouldbeabletofindthecontrolsthatyouneedwithinthe WebFormssectionofthecontroltoolbox.
Afteryouhaveaddedthecontrolstothedesignersurface-youneedtoset somecontrolproperties.MakesurethePropertieswindowappearsby choosingPropertiesWindowfromtheViewmenu.
FollowthesestepstoinitializethecontrolpropertiesofeachcontrolontheWebForm:
1. Clickoneofthetextboxestoselectit.2. InthePropertieswindow-eraseanytextintheTextpropertyand
changetheIDpropertytotxtInputTemp.Thistextboxallowsthe usertoenteraninputtemperaturevalue.Notethatthetextstoredin theIDpropertyisusedtoreferencethiscontrolwithinyourform codeatruntime.
3. Clicktheremainingtextboxtoselectit.4. InthePropertieswindow-eraseanytextintheTextproperty-
changetheReadOnlypropertytoTrue-andchangetheID propertytotxtOutputTemp.Thistextboxisusedtodisplaythe temperatureconversionvalue.TheReadOnlypropertyprevents usersfrommodifyingthetextinthetextbox(sincethisissettothe appropriatevaluebytheformafterobtainingtheresultsoftheunit conversion).
5. Clickthecommandbuttontoselectit.6. InthePropertieswindow-changetheTextpropertytoConverts
ToandchangetheIDpropertytobtnConvert.Clickingthisbutton executestheunitsconversionbasedonthesettingschosenbytheuserintheothercontrols.TheTextpropertyisusedtodisplaya stringonthefaceofthebutton.
7. Clickoneoftheoptionbuttonliststoselectit.8. InthePropertieswindow-changetheIDpropertyto optFromUnits.Next-
selecttheItemspropertyandclickthe detailsbutton(thebuttonwiththeellipsis).ThisdisplaystheListItem CollectionEditordialogbox-asshowninFigure50 - 6 .
Figure50-6: VisualStudioListItemCollectionEditordialogbox.9. Addtwoentriestothelist:onenamedCelsiuswithavalueofCand
onenamedFahrenheitwithavalueofF.SettheFahrenheititem's SelectedpropertytoTruesothatthisentryisselectedbydefault whentheformisdisplayedforthefirsttime.Whenyouarefinished addingtheoptionbuttonlistitems-closetheListItemCollection EditordialogboxbyclickingtheOKbutton.
10.Clicktheremainingoptionbuttonlisttoselectit.11.InthePropertieswindow-changetheIDpropertytooptToUnits.
Next-selecttheItemspropertyandclickthedetailsbutton.This displaystheListItemCollectionEditordialogboxonceagain.
12.RepeatthestepsyouusedtopopulatetheoptFromUnitsoptionbuttonlist_to_addthevariousoutputunititemsto thislist.You shouldaddoptionsforFahrenheit(valueF)-Celsius(valueC)- Kelvin(valueK)-andRankine(valueR).SettheCelsiusitem'sSelectedpropertytoTruesothatthisentryisselectedbydefault whentheformisdisplayedforthefirsttime.Whenyouarefinished addingtheoptionbuttonlistitems-closetheListItemCollection EditordialogboxbyclickingtheOKbutton.
Afteryouhavecompletedthesesteps- rearrangethecontrolsontheformsothattheyresembletheformlayoutshowninFigure50 - 7 .
Figure50-7: ArrangementofuserinterfacecontrolsontheWebForm.NowthatyouhaveyourWebFormcreatedandinitialized-youarereadyto addthecodetotheformthatcreatesaninstanceoftheCTempproxyclassso youcaninteractwiththeproxyclasstoperformtemperatureunitconversions.
Application Execution ModelTheconsumerapplicationisstartedwhenauserrequeststhemainformofthe application:
1. AuserrequeststhemainformoftheCTempClientapplication,suchashttp://localhost/CTempClient/WebForm1.aspx.2.
TheIISWebserveronlocalhostreceivestherequest(technically,anHTTPGETrequest)andhandsitofftotheASP.NETruntimeforexecutionofthepage(becausetherequested pagehasan.aspxextension).Thishand-offoccursviaanISAPI filterextensionthatisregisteredwithinIIStohandleallofthe ASP.NETfiletypes.3. TheASP.NETruntimecreatesaninstanceofthepageclassthat
representstheWebFormandexecutesthepage.4. ThepageclassgeneratestheHTMLandsendsittothebrowser,
causingtheformtoberenderedintheuser'sbrowserwindow.5. ThepageclassisthendestroyedbytheASP.NETruntimealong
withanyothernecessaryrequestcleanupprocessing.(Remember, HTTPisastatelessprotocol,sothereisnoneedtokeepthepage classaroundaftertheHTMLhasbeentransmittedtotheclient.)
6. TheuserentersinformationintotheformandclickstheConvertTobutton.ThiscausestheformtobepostedbacktotheWebserver.
7. Again,theWebserverhandsofftherequest(technically,anHTTP POSTrequest)totheASP.NETruntime,whichcreatesanew instanceofthepageclassthatimplementstheWebFormand executesthepage.
8. Becausethisisapostbackrequest,theserver-sidebuttoncontrol'sClickeventcodeisexecuted.Recallthatthisiswhereyouadded yourcodetocreateandcalltheCTempWebService.
9. TheClickeventcodecreatesaninstanceoftheCTempWeb Serviceproxyclass.Thisclassinheritsfromthe System.Web.Services.Protocols.SoapHttpClientProtoc olclass.ThisprovidesthefoundationforcommunicatingthemethodrequestandresponseviaSOAPmessagesovertheHTTPtransport.
10.TheClickeventcodenow callsthesynchronousCTempmethod ontheproxyobject,passingtheinputargumentsobtainedfromthe postbackdataoftheform(viaserver-sidecontrolproperties).
11.TheWebServiceproxycallstheInvokemethod,passingalongthe inputarguments.ThismethodserializestheCTempmethodcallinto aSOAPmessagethatmatchesthemethodsignaturedefinedinthe WSDLdocument.TheSOAPmessageisthenaddedtothepayload ofanHTTPrequestanddeliveredtotheWebServiceendpoint(the URLofthe.asmxfile).
12.TheIISWebserverthathoststheCTempWebService(inthisspecificcase,localhost)receivestherequest(technically,a
SOAPPOSTrequest)andhandsitofftotheASP.NETruntimeto executetherequestedpage.13.TheASP.NETruntimedeserializestheSOAPpayloadfromthe
request,createsaninstanceoftheCTempWebService implementationclass,andexecutestheCTempmethod,passingthe inputarguments.
14.Next,theASP.NETruntimetakestheresultoftheCTempmethod callandserializesitintoaSOAPresponsemessage.Thismessage isthenaddedtothepayloadofanHTTPresponseanddelivered backtotheclient(inthiscase,yourproxyclass).
15.TheInvokemethodoftheproxyclassdeserializestheresultfromtheSOAPresponsemessageintoageneric.NETObjecttype.This typeisthenexplicitlycasttothereturndatatypeexpectedbythe caller(inthiscase,aDecimaltemperaturevalue)andreturnedto yourconsumerapplication.
16.TheClickeventcodeinyourconsumerapplicationtakestheresult,convertsittoastringdatatype,andassignstheresulttothe outputtextboxintheWebForm,formattedtotwodecimalplaces. Theeventcodeprocessingisnowcompletedandpageexecution continues.
17.Thepageexecutesthroughitsrenderingphasetogeneratethe HTMLthatis returnedto theuser'sbrowser.Justas before,the pageclassis thentorndownby theASP.NETruntime,andany othercleanupprocessingthatisnecessaryisexecuted.