Tải bản đầy đủ (.pdf) (1,308 trang)

Visual basic NET power tools (2004)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.23 MB, 1,308 trang )

TeamFly

Cover

TeamFly


TeamFly


Pageiii


VisualBasic™.NetPowerTools
EvangelosPetroutsosandRichardMansfield

TeamFly




TeamFly


Pagevii


Acknowledgments
WEWEREFORTUNATETOhaveseveralsmart,thoughtfuleditorsassistusin
polishingthismanuscript.First,we'dliketothankDevelopmentEditorTom
Cirtin.Hedeservescreditforhisdiscernment,andthehighqualityofhisediting.


He'sverygoodatdealingwithhisauthors,andequallyskilledatraising
importantquestionsandimprovingtheirchapters.
TechnicalEditorGregGuntlecarefullyreviewedthemanuscriptandmademany
usefulsuggestions,caughtanumberofinconsistencies,andhelpedimprove
severalcodeexamples.ProductionEditorLeslieLightensuredthatthisbook
movedsmoothlythroughproductionandwasmosthelpfulwithsuggestions
aboutthegraphics,drawings,andscreenshots.SuzanneGoraj,copyeditor,
combedthrougheverylineofourtext,makingimprovementsthroughout.
Toallthese,andtheothergoodpeopleatSybexwhocontributedtothisbook,
ourthanksfortheintelligenceandcarethattheybroughttothisbook.In
addition,theauthorswouldliketogivespecialthankstotheiragents,Matt
WagnerandDavidFugate,ofWatersideProductions,whosecontributionstothe
authors'careersgoesaboveandbeyondthecallofduty.
TeamFly




TeamFly


Pageviii


ContentsataGlance
xix
Introduction
Chapter1•Understandingthe.NET
Framework
Chapter2•NewWaysofDoingTraditional

Jobs

1
23
59

Chapter3•SerializationTechniques
Chapter4•LeveragingMicrosoftOfficein
YourApplications

93
119

Chapter5•Understanding.NETSecurity
Chapter6•Encryption,Hashing,andCreating
Keys

139
159

Chapter7•AdvancedPrinting
191
Chapter8•UponReflection
Chapter9•BuildingBug-FreeandRobust
Applications

215
243

Chapter10•DeployingWindowsApplications

Chapter11•BuildingData-DrivenWeb

271


Applications
289
Chapter12•Peer-to-PeerProgramming
319
Chapter13•AdvancedWebServices
Chapter14•BuildingAsynchronous
ApplicationswithMessageQueues

341
391

Chapter15•PracticalADO.NET
Chapter16•BuildingMiddle-Tier
Components

441
475

Chapter17•ExploringXMLTechniques
Chapter18•DesigningData-DrivenWindows
Applications

505

Chapter19•WorkingwithRegular

Expressions

543
589

Chapter20•AdvancedGraphics
623
Chapter21•DesigningtheUserInterface
Chapter22•Usingthe.NETCompact
FrameworkandItsEmergingTechnologies

643
665

Index
TeamFly




TeamFly


Pageix


Contents
xix
Introduction
Chapter1•Understandingthe.NET

Framework
WhyReadThisChapter
Help!
GrapplingwithFrameworkClass
Descriptions
TheHuntforaGrammar
WhyTwoWays?
AboutConstructors
AssembliesThreeWays
UnderstandingDataTypes
AboutSystem.Object
MemberWiseClone

1
2
3
5
6
10
10
11
11
12
12


Equals
ReferenceEquals
TheMainPointaboutEquality
GetHashCode

GetType
ToString
StrongTypingWeakens
IsColoraDataType?
ExploitingtheFramework
AUsefulClassViewUtility
ABriefLexicon
Summary
Chapter2•NewWaysofDoingTraditional
Jobs
ClipboardAccess
Workingwith''ControlArrays"

12
13
14
16
16
16
17
17
18
20
21
22
23
23
24



MultipleHandles

UsingArrays
Zero-BasedCollections(Sometimes)
Initialization
ArraysofObjects
ArraySearchandSortMethods
CustomizedSorting
ManyPropertiesandMethods
TheFlexibleArrayList
MassManipulation
DataBinding
Enumerators
UsingHashTables
NewDate/TimeTechniques
AddingTime

27
28
28
30
30
31
33
34
35
36
36
37
37

38
39


TeamFly




TeamFly


Pagexix


Introduction
THISBOOKACTUALLYBEGANinAthens,Greecein1993.EvangelosPetroutsos
wroteaveryinterestingoutline,andseveralsamplechapters,forabookabout
"fascinatingandsophisticatedthings"youcoulddowithVisualBasic.Iagreed
withmypublisherthathisideashadpotential,butEvangeloswasafirst-time
author.Ihadatrackrecord,though,sothepublishersaidthey'dinvestinthis
"PowerToolkit"bookifIagreedtoco-authorit.Evenasmallbookrepresentsa
$50,000gambleforapublishinghouse,andthiswasaverylargebook.
ImerrilyagreedbecauseIthoughtthetopicswerecompelling—fractals,
encryption,processinggraphics,animatedtransitions,multimedia,manipulating
colorpalettes,recursion,andothertopicsthatwerelargelyignoredbyotherVB
books.Toourdelight,thebookbecamearunawaybestsellerin1995.Evidently
manyVisualBasicprogrammerswerereadyforabookaboutadvanced,cuttingedgeprogrammingtechniques.
In2002,wedecidedtorevisitthisconcept.Nearlyadecadehaspassed,andwe
nowhavewhatamountstoabrandnewVisualBasiclanguage:VB.NET.We

decidedtofollowthesamepaththatwewentdownadecadeago:toexplore
aspectsofVB.NETthathavebeenlargelyignoredinotherbooks,butareuseful
orinteresting,orboth.
Mostofthetopicscoveredtenyearsagointhepreviousbookarenotrepeated
here—timeshavechanged.Butwefeelthatthesubjectsexploredinthisnew
bookarecompellingintheirownright.

Aesthetics
Whywouldcaptivatingtopicsbelargelyignoredincomputerbooks?Wethink
therearetwoprimaryreasons.Thefirstcategoryofignoredtopicsisseenas
"trivial"or"marginal."Putanotherway,thesesubjectsinvolveaesthetics.
Programmersbyandlargeprefertoconsiderthemselvespartofthescientific


community,soexaminingsuchunscientificconceptsasbeautyorappearance
seemstomanyprogrammerstobeastepdown.Twoofthechaptersinthisbook,
nonetheless,boldlyexploreaestheticsubjects.
Truthbetold,programmingisanart,notascience.Someprofessorsconjureup
theoreticalconstructsandspecialterminology,butairyobfuscationandloftysoundingjargondonot,bythemselves,createascience—andalltoooften
actuallyinhibitrationaldiscourse.
StudieshaveshownthatthebestprogrammersarefrequentlyEnglishormusic
majors.Someofthebestdevelopersaroundtodaygotintoprogrammingwhen
theypurchasedtheirfirstAmigacomputer—anearlymachinedevotedtothe
creativesideofcomputing.Andalthoughacademicprogrammingisgenerally
alliedwithmathematicsdepartments,thereisverylittlerealrelationshipbetween
TeamFly





TeamFly


Pagexx

math(orscience)andprogramming—justasthereisoftenverylittlerelationship
ingeneralbetweenmanyotheracademicstudiesandtherealworld.
Considertheprimarycurrentcomputerapplications:wordprocessing,database
management,Internetcommunications,andspreadsheets.Onlyspreadsheets
havemuchatalltodowithmath.Programmingcan,ofcourse,involvemath,
butit'srarelycentraltotheprogrammer'stask.Youcouldwriteanentireword
processingprogramwithoutevenknowinglongdivision,muchlessalgebraor
anythingbeyond.
Andprogrammingobviouslyisn'tascience.Scienceinvolvestheorizingand
controlledexperimentation,behaviorsrarelyassociatedwithprogramming.Sure,
there'sakindofexperimentalhackingthatgoesonwhiletryingtofixbugs—but
that'snotscientificexperimentationbyanystretchoftheimagination.
Debuggingismuchclosertosearchingforalostsetofkeysthansendingakite
upintoathunderstorm.
Programmingisbasicallycommunication—albeitbetweenhumansand
machines.Butitisalinguisticandexpressiveact.It'snotexactlyrhetorical(we
don'tneedtopersuadethemachines,atleastnotyet).Butit'scertainly
descriptive,grammatical,andfundamentallycommunicative.
Thetwochaptersinthisbookthatsomewillconsider''unscientific"areChapter
21,"DesigningtheUserInterface,"andChapter20,"Fractals:InfinityMade
Visible."Weagree.Butthenwethinktheentiresubjectofprogrammingis
unscientific,andwe'renotbotheredbythatfact.

ComplexityandtheAvant-Garde
Mostoftheremainingtopicsinthisbookfallintothesecondcategory:topics

thatareeithertoocutting-edgeortoocomplexforinclusioninmanybooks.For
example,notmuchiswrittenaboutVB.NET'ssplendidandextensivesecurity
features—eventhoughsecurityisaprimaryongoingchallengeforthe
computingcommunity.


Security-relatedVB.NETprogrammingisavoidednotbecausetheprogramming
involvedisinherentlydifficultornovel,butratherbecausetheconcepts
underlyingcryptologyandotheraspectsofsecurityarefundamentallycomplex.
Manycomputerbookauthorssimplydon'tknowenoughaboutencryption,for
example,toexplainitsimplementationincomputerprogramming.Fortunately,
cryptologyhaslongbeenahobbyofoneoftheauthorsofthisbook.
Othertopicsareperhapstoonewtobewidelyunderstoodorimplemented.
Asynchronousprogramming,Webservices,employingOfficeobjects,using
reflection,andthenew.NETCompactFramework(howtosqueeze
programmingandI/Ointothehighlyrestrictiveplatformofsmall,portable
devicessuchasPDAsandcellphones)allfallintothiscategory.
Severalofthechaptersinthisbook,weadmit,havebeencoveredfairly
extensivelyinotherbooks(databaseprogramming,debugging,printing),butwe
includedthembecausewefeelthatwehavesomethingnewtosay.Forexample,
we'veyettofindanybookthatcorrectlydescribeshowtoprinthardcopyin
VB.NET.Alltheprogrammingexampleswe'veseeneithercutlettersinhalfat
theendoflines,orcutlinesinhalfattheendofpages.Thisdoesn'thappenon
everylineorattheendofeverypage,butyou'llagreethatit'sprettybadwhenit
happensevenintermittently.Ifyou'vebeenlookingforthesolutiontothis
problem,seeChapter7.
Chapter1isunusualbecauseittacklesanessential,yetwidelyavoided,
question:WhywasVisualBasic.NETdesignedbyCprogrammers,andwhat
aretheimplications?It'sasiftheRomanshadbeengiventhejobofrebuilding
Thebes—theresultmightbeimpressive,butitcertainlywouldn'tremain

Egyptian.
TeamFly




TeamFly


Pagexxi

Chapter1beginslikethis:
VisualBasic.NETWASnotwrittenbyVisualBasicprogrammers.Theentire.NETfamilyof
languageswascreatedbyCprogrammers.C—anditscohortOOP—isanacademiclanguage.
VisualBasicisapopularlanguage.Thesefactshaveconsequences.

Theauthorsofthisbookarenotbeholdentoanyorganization.We'renotwriting
forMicrosoftPress,norareweaffiliatedwithanycorporationorschool.Indeed,
weliketothinkthatwe'renotdependentonanyoneforourpaycheck—other
thanyou,dearreader—andcanthereforebemoreobjectivethanmanyofour
colleagues.
WecanaskhereticalquestionssuchaswhyOOPshouldbeusedinall
programmingsituationsasmanyofitsproponentsinsist.Wecanquestionthe
wisdomofallowingCprogrammerstowritethenarrativesandcodeexamples
fortheHelpsysteminVB.NET.Wecanwonderwhystructuresareincludedin
VB.NETifOOPexpertsinsistthatyoushouldneverusethem.
WecanfreelyapplaudVB.NETwhenitimprovesontraditionalVB
programmingfeatures(streamingandserialization,forinstance),andpointout
whenVB.NETcreatesneedlessconfusion.(SomecollectionsinVB.NETare
zero-based;someareone-based.Andthere'snorhymeorreasoninvolved,no

patternyoucandiscover,noruleyoucanlearn,todealwiththisproblem.)
Anotherbenefitofbeingoutsideprogrammingandacademicofficialdomisthat
wecanbeclear.Thereisalingodevelopingaroundprogramming,andtoomuch
ofitappearstoservenorealpurposeotherthanjobprotection.Ifotherscannot
readyoursourcecode,orevenunderstandyourcomments,thenit'slikelythey'll
respectyouandyou'llkeepyourjob.Likewise,ifyoufollowthepartylineand
keepyourgeek-speakup-to-date,you'llbeontheteam.Sotheusuallittleclosed
societyofapriestclassisbeingbuilt.Rememberthatonlyashorttimeagomass
wassaidinLatin,alanguagethatthechurchgoerscouldn'tunderstand.Andif
youvisitacollegeclassinmusictheoryorfilmtheorytoday,youwon't
comprehendmostofwhat'sbeingsaid.
Whenwedonowandthenindulgeintechiejargoninthisbook,it'susuallytolet


youknowwhat'smeantbythelatestcatchphrases.True,thetermoverloaded
signatureisusedinthisbook,butrightnexttoitistheparentheticalexplanation
(morethanoneargumentlist),justsoyou'llknowwhattheheckisbeing
discussed.Andwhenterminology,suchasstronglytyped,hasseveraldifferent
meanings,wepointthatouttoyou.
There'sonefinalbenefitderivedfromtheauthors'statusasindependentwriters,
freeofanyobligationtoparticularcorporationsorinstitutions:wecanbe
entertaining,oratleastlessboringthantheaveragecomputerbook.Academic
articlesandbooks,includingmanyprogrammingbooks,deliberatelyavoid
amusingorinterestingwriting.It'sthoughtinsomecirclesthatifyourwriting
isn'tobscureortedious,thenyoumustnotbediscussinganythingsufficiently
serious.Wetakethepositionthathonest,understandable,direct,andinteresting
writingispreferabletothealternative.

WhoShouldReadThisBook,andWhy?
Thisbookisintendedtoprovidesolutionsforprogrammerswhoarereadyto

takethenextstepuptomorecomplex,cutting-edge,orsophisticatedtopics.
Chapters1and2areusefulifyou'remakingthetransitiontoVB.NETfrom
anotherprogramminglanguage(suchasclassicVisualBasic,versions6and
earlier).
Thisbookis,webelieve,accessibletoanyintelligentpersonwithprogramming
experience.Wehavetriedtobeclearthroughoutthebook,explainingeverything
asdirectlyaspossible,regardlessofdegreeofdifficultyofthevarioustopics.
TeamFly




TeamFly


Page1


Chapter1
Understandingthe.NETFramework
VISUALBASIC.NETwasnotwrittenbyVisualBasicprogrammers.Theentire
.NETfamilyoflanguageswascreatedbyCprogrammers.C—anditscohort
OOP—isanacademiclanguage.VisualBasicisapopularlanguage.
Thesefactshaveconsequences.VisualBasicwasconceivedin1990specifically
asanalternativetoC.VBwasdesignedasarapidapplication-development
language—blessedlyfreeofcantandobscurantism.VBwascreatedespecially
forthesmallbusinessmanwhowantedtoquicklyputtogetheralittletax
calculationutility,orthemotherwhowantedtowritealittlegeographyquizto
helpBillywithhishomework.VBwasprogrammingforthepeople.Several
hundredthousandpeopleuseC;millionsuseVisualBasic.

Aswithmanycultures—RomeversusEgypt,USAversusFrance,townversus
gown—programminglanguagesquicklydividedintotwocamps.Candits
offspring(C++,Java,C#,andothers)representonegreatcampofprogrammers.
VisualBasicistheothercamp.However,.NETisanattempttomergeVisual
BasicwiththeClanguages—whilestillretainingasmuchaspossibleofthe
famouspopulistVBpunctuation(direct,clear,straightforward,English-like),
syntax,anddiction.
Manyprofessors,blessthem,thriveonabstraction,classification,andfine
distinctions.That'sonereasonwhyVB.NETisinsomewaysmoreconfusing
thannecessary.Ithasmanylayersof''accessibility"(scoping)andmanyvarieties
ofwaystoorganizedata,somemoreusefulthanothers.Ithasmultiple
"qualification"schemes;considerableredundancy;singletermswithmultiple
meanings(strongtyping,forexample);multipletermsforasinglebehavior
(ImportsversusImport);andallkindsofexceptionstoitsownrules.
VB.NET,however,isclearlyanimprovementoverearlierversionsofVBin
manyrespects.Wemustallfindwaysofmovingfromlocaltodistributed
programmingtechniques.AndVB.NETisalsoquiteabitmorepowerfulthan


previousversions.Forexample,streamingreplacestraditionalfileI/O,but
streamingcanalsohandledataflowingfromseveralsources—notjustthehard
drive.Streamingconsiderablyexpandsyourdatamanagementtools.Youcan
replaceaFileStreamwithaWebResponseobject,andsendyourdatatoaWeb
client.
Nonetheless,intheefforttomergeallcomputerlanguagesunderthe.NET
umbrella,VBhadtogiveupsomeofitsclarityandsimplicity.Infact,VBnow
producesthesamecompiledcode
TeamFly





TeamFly


Page2

thatalltheother.NETlanguagesdo—sounderthehood,thereisnolongerany
distinctiontobemadebetweenthetwolinguisticcultures.It'sjustonthe
surface,whereweprogrammerswork,thatthedifferencesreside.
OOPitself,likebiology,involvesacomplexsystemofclassification.Thismeans
thatpeopleusingOOPmustspendagoodamountoftheirtimeperforming
clericalduties(Wheredoesthisgo?HowdoIdescribethis?Whatcategoryis
thisin?Arethetext-manipulationfunctionslocatedintheTextnamespace,or
theStringnamespace?Doesthisobjecthavetobeinstantiated,orcanIjustuse
itsmethodsdirectlywithoutcreatingtheobjectfirst?)

WhyReadThisChapter
Ifyou'reoneofthemillionsofVBprogrammerswho,likeme,cameupon
VB.NETwiththehighlyintelligentreaction''Whaaaaa??!!,"thischaptermight
beofusetoyou.
I'mnotunintelligent,andI'massumingyou'renoteither.Butsloggingthrough
theVB.NETworldmakesoneseemratherslow,especiallyatfirst.Thischapter
givesyousomehard-wonadvicethatcansaveyouconsiderableconfusion.
VB.NETis,ofcourse,fareasiertonavigateifyouhaveabackgroundinC
programminglanguages(anditslovelywife,object-orientedprogramming).
MillionsofVBprogrammersdeliberatelydecidednottouseC.That'swhywe
becameVBprogrammersinthefirstplace.WepreferredthepowerofVB's
rapidapplicationdevelopmenttools.Wedidn'tcareforthereverse-Polish
backwardsyntax,theredundantpunctuation(allthosesemicolons)andother

aspectsofCanditsdaughterlanguages.
TheInternetchangedallthat—wemustdevelopnewskillsandadapttonew
programmingstyles.Leavingthecozyandpredictableworldoflocal
programming(applicationsforWindows,runningonasinglecomputer)requires
newtechniques.Youdon'thavetoswitchtoCoritsilk,butyoudohaveto
expandyourVBvocabularyandskills.


Today'sprogramsaresometimesfracturedintomultipleprogramlets(distributed
applications)residingindifferentlocationsondifferentharddrivesand
sometimesevenusingdifferentplatformsorlanguages.WebServicesarethe
waveofthefuture,andthiskindofcomputinggreatlyincreasestheimpactof
communicationandsecurityissues.Nottomentionthenecessityof
encapsulatingcodeintoobjects.
Sogirdyourloinsorwhateverelseyougirdwhenthreatened,andgetreadyfor
somenewideas.You'vegottodealwithsomedifferentnotions.
Eachofus(theauthors)haswrittenseveralbooksonVB.NETinthepastfew
years—workingwithinthe.NETworlddailyforthreeyearsnow—andwe're
stilldiscoveringnewtools,concepts,andfeatures.Partofthisissimplygetting
toknowthehuge.NETFramework,andpartofitisadjustingtoOOPandother
C-likeelementsthatarenowpartofVB.
WhattheysayofquantummechanicsappliestoOOP:onlytenpeopleinthe
worldunderstanditwell,andnobodyunderstandsitcompletely.Sobebrave.
Youcanlearnsomepatternsandrulestohelpyougetresultsin.NET,andthe
benefitisthatVB.NETisquiteabitmorepowerfulandflexiblethantraditional
VB.Thereareconsiderablerewardsforyourpatienceandefforts.
You'llfindideasinthischapterthatwilldeepenyourunderstandingofthegreat,
vast.NETenvironmentandframework.You'llfindusefulinformationherethat
willimproveyourVB.NETprogramming—guaranteed.Forexample:Whatare
structures,andwhenshouldyouusethem?(They're

TeamFly




×