Tải bản đầy đủ - 0 (trang)
Chapter 6. Building Data Sources, DataSets, and TableAdapters

Chapter 6. Building Data Sources, DataSets, and TableAdapters

Tải bản đầy đủ - 0trang

creatingstronglytypedDataSetclasses.You'llseewherethese

classesmakesenseandmakeitclearwheretheyjustgetinthe

way.Alongtheway,I'llbrieflypointouttheXMLstructures

usedtoimplementtheseclasses,butIdon'tplantowadeinto

thatswamp.Atleastoneofusdoesnotthinkadeveloper

needstoeditXMLtogethisorherjobdonebutitdoesn'thurt

toknowwhat'sgoingonbehindthecurtains.WhenIdiscuss

theReportViewercontrolinChapter14"CreatingandManaging

Reports",you'llseehowcreatingaVisualStudioReportcanbe

facilitatedbyusingtheDataSourceConfigurationwizard

(DSCW)andTableAdapterConfigurationwizard(TACW)to

auto-generateaTableAdapter,butyou'llalsoseehowthat's

reallynotnecessary.I'llalsoshowyouhowtoactuallyuse

thesegeneratedcodeclassesinyourapplications.



IMHO

Frankly,theDataSourceandTableAdapterclassmake

impressive,virtually"codeless"demos,butdon'tfeel

threatenedIdon'tthinkthey'regoingtocompletelyreplacethe

connectionmanagement,dataaccess,andbindingcodein

seriousapplications.



Incidentally,youwon'tfindtheDataSourceConfiguration

wizardwhenyouopenaWebServiceorASP.NETprojectthey

aren'tsupportedinthosedevelopmentmodesinVisualStudio

2005.Forthoseprojecttypes,you'restillgoingtohavetouse

theServerExplorertoexposedatasources(Tables,Views,and

storedprocedures)anddraganddroptheseobjectstoyourASP

formsorboundcontrols.



WhyCreateYADAI?

The"DataWorks"teamatMicrosoft(thefolkswhoinvented

ADO.NET)hasbeenhardatworkreinventingADO.NET(again),

and,yes,theymanagedtocreateyetanotherdataaccess

interface(YADAI)forVisualStudio2005.Tobefair,the

DataWorksteamfeelstheneedtobuilddataaccessanduser

interfacestohelpdevelopersfromalllevelsofexperience,from

rankamateurtofront-lineprofessional.WhiletheclassesI

discussinthischapterwon'thelpeveryone,theycanhelpsome

developersastheytrytobuildmanybasic-to-intermediate

applications.IfyoudelveintoSQLServerEverywhereyou'll

alsofindthatthesewizardsandclassesareanalmostperfect

fit.That'sbecausetheSSEvengineisdesignedtosupport

small,single-userdatabases.Sure,developers(and

applications)mightoutgrowthesedrag-and-dropandpickfrom-a-dizzying-list-of-optionsUIcodegenerators,butuntil

theydo,it'sbesttounderstandhowtheywork,whattheyare

capableofdoing,and(mostimportantly)whattheycan'tbe

expectedtodo.And,yes,thesetoolscanhelpbuildserious

applications,butwithanumberoflimitationsthatIdiscuss

throughoutthebook.

TheDataWorksteamhasbeenstrugglingwithanumberof

problems.Someoftheseinclude:

TheDataAdapterConfigurationwizardgeneratescodethat

simplypopulatesanuntypedDataSet.Microsoftwants

developerstocreatestronglytypedDataSetandDataTable

classes.Theytellusthatstronglytypeddatastructures

withtheir"type-safe"dataelementsaremoresecureand

easiertoworkwith.

TheinabilityoftheDataAdaptertosupportcustom

(developer-defined)Fillmethodsespeciallythosethataccept



parameters.ThismakesitdifficulttousetheDataAdapter

toreturnrowsetsfromotherthantheone(andonly)

SelectCommandSQLquery.

TheDataAdapterConfigurationwizarddidnotprovide

enoughflexibilityforanumberofscenarios.Themost

importantoftheseissuesistheinabilitytodeterminehow

collisiondetectionistobeperformed.

TheUpdatemethodmakesaround-tripforeachrowinthe

targetDataTablethat'sadded,changed,ordeleted.Roundtripsareexpensive,andthisapproachdegrades

performance.

Developerswantedtobeabletoalterthecodegenerated

bytheDataAdapterConfigurationwizard(DACW)butwere

thwarted,asanycustomizationmadetothegeneratedclass

codewasoverlaidiftheDACWwasreexecuted.

TheinabilityoftheDataTabletobeserializedorsupport

DataSetmethodsneededbysomedevelopers.Many

developershavefeltthattheDataSetimposedtooheavya

burdenwhenasingleDataTablewouldhavesufficed.

Intheory,VisualStudio2005permitsdevelopersto

generatecodesourcedfromXMLWebServices,custom

businessobjects,aswellastraditionalrelationaldata

sources.Anynewdataaccessinterfacemustsupportallof

thesesources.

ASP.NETWebServicesandbusinessobjectsareagrowing

sourceofdata,andthecurrenttoolsdon'tadequatelyhelp

buildapplicationstoexposetheirdata.

ThenewReportViewerandotherboundcontrolsneededan

easierwaytodefineaConnection,queries,androwsets



neededtopopulatethereportsandcontrols.

DotheDataSourceConfigurationwizardandTableAdapter

addresstheseproblems?Yes,theydoatleast,toalargeextent.

Manyoftheotherissuesaredealtwithbyfundamentalchanges

inthe.NETFrameworkandtheCLRlanguages.

ConsiderthatVisualStudiohasevolvedoverthelast8years

(orso)fromaCOM-basedlinkagebuildertoacodegenerator.

IntheVisualBasic6.0days,developerswereencouragedto

draganddrop(justastheyaretoday),buttheIDEwas

chargedwithconnectinguser-writtencodetothepropertiesof

canned(black-box)COMobjectsliketheDataEnvironment

Designer.TheVB6DataObjectwizard(DOW)wasthefirst

prototypeoftheDataAdapterConfigurationwizard,which

furtherevolvedintotheDataSourceConfigurationwizardand

TableAdaptercodegenerators.Today,VisualStudio2005isa

sophisticatedcodegeneratorthevolumeandcomplexityofthe

codeitgeneratesisstartling(andoftenintimidating).

Fortunately,VisualStudio2005doesapassablejobofkeeping

thisauto-generatedcode,hidden,correct,andprotectedfrom

changesyoumaketootherpartsoftheproject.



IsStronglyTypedDataImportant?

Somewouldhaveyoubelievethattheonlywaytobuildadata

structureistouseoneofthestronglytypedclasscode

generatorsexposedinVisualStudio.Ah,developersalloverthe

planethavebeencreatingmainstream,high-performance,and

highlyscalableapplicationswithoutstronglytypeddata

structuresfordecades.Sowhatmakesastronglytyped

DataSetspecial?Well,insteadofdeclaringanobjectasa

System.Data.DataTableandpopulatingtheColumnscollection

withhand-codedorADO.NET-generatedschema,youeither

tediouslyhardcodethethousandsoflinesofcodetobuild

individualcolumnsaspropertiesusingspecificsystemtypesin

yourowncustom"AuthorsDataTable"oryougetoneofthe

VisualStudiotoolstodoitforyou.That'swhatthischapteris

abouthowtogetVisualStudiotocreatethenewstronglytyped

TableAdapterclassforyou.

Behindthescenes,astronglytypeddatastructurehasa

matchingschemafile(.XSD)thatdefinesthestructurewhatit

shouldcontainandhowitshouldbestored.Itcanalsodefine

relationshipsbetweentheclassesaswellasotherconstraints,

customproperties,andmethods.ThisXSDfileisusedto

generatethecodeusedtoaccessthetargeteddatabase

element.

AnuntypedDataTable(oranyobject)hasnosuchdefined

schema(outsideofthedatabase),soit'sbuiltwithgeneric

system"object"typesthatcanholdanythingit'ssimplya

transportvehicle.Whenyouexecuteaquerythatreturnsa

rowset,theADO.NETDataAdapterFillorDataTableLoad

methodsconstructaDataTablewhoseColumnscollection

matchestheschemaoftheincomingrowset.ADO.NETcan

identifyaprimarykeybutnotintertablerelationships.Whilethe

DataTypepropertyissettomatchthetypeoftherowset

column,it'simplementedasanobjectnotasastronglytyped



property.

ThinkofastronglytypedDataTableasaneggcartonandan

untypedDataTableasabasketdesignedtocarryanythingyou

happentocollect.DoesthismeanthestronglytypedDataTable

canstoreegg-sizechunksofstuffyoumightfindinabarnyard?

Sure.Acityslickerwon'tknowtheyaren'teggsuntilhetriesto

crackoneopeninthekitchen.However,ifyouwanttoensure

youonlyputreal(chicken?)eggsinyourstronglytypedegg

carton,you'llhavetoaddcustomcodetotesteachitemasit

arrives.Eachblockofcustomcriteria-testingcodeyouadd

furtherrestrictswhatthecartoncancontain.Italsomeansthat

ifyoubuyaduck,youwon'tnecessarilybeabletouseyour

stronglytypedcartonswithoutgoingbackandmodifyingevery

singleapplicationthatusesthestronglytypedclasstoaccept

thenewtypeofegg.Thankstopartialclasses,VisualStudio

2005doesnotoverlaythecustomizationsyoumakewhenyou

rerunthewizardsusedtocreatestronglytypeddataclasses,so

itcanmakethisprocessabiteasierbutjustabit.

SowhatbenefitdoesastronglytypedDataTable(orDataSet)

returnforyourinvestmentintimeandthecompile-time

requiredforhundreds,possiblytensofthousands,oflinesof

brittlecode?Yes,ifadatastructure(likeaDataTable)is

definedexplicitly,itcannotacceptvaluesthatareoutoftype.

Thatis,ifyoudefineastronglytypedDataTable(astheData

SourceConfigurationwizarddoes),thecolumnsmarkedas

Int16won'tacceptastringoranInt32,butdoesthatmake

yourdatapure?Nothardly.AstronglytypedInt16fieldthat's

supposedtoholdthecustomerdiscount(whichcanbe0,10,

20,or30%)isnotpreventedfromholdinganyInt16value

unlessyoufurthereditthegeneratedcodetoimposethis

businessrule.Asyoucansee,thiscanbeveryexpensiveto

implementandevenmoreexpensivetomaintain.

AsIseeit,theproblemisandalwayshasbeenthatwhenthe

underlyingdataschemaorbusinessruleschange(asthey

invariablydo),thestronglytypedclassyouorVisualStudio



createnolongermatchthedatastructureasdefinedinthe

database.Inouropinion,thisisthemoreseriousandinsidious

problem.Fromthedawnoftime,datastructureinconsistency

(whatIusedtocall"dataexceptions")hascausedanynumber

ofcripplingproblemsthathard-codeddatastructuresdonot

address.

OneofthemostimportantvulnerabilitiesoftheDataSource

paradigmisthatthegeneratedcodeisdirectlydependenton

thedatabaseschema(structure)usedtogeneratethecode.If

theschemachangesatdesigntime,VisualStudiousuallygets

confusedanddisplayswhatIcallthe"whitewindowofdeath."

You'relucky,thoughthere'sawork-aroundforthisproblem.

ClosetheForm'sdesignwindow,right-clickontheFormfilein

theSolutionExplorer,andclickRefresh.TheFormwindow

shouldrebuilditself.

Iftheschemachangespost-deployment,you'repooched.

ApplicationsthatusetheDSCW-generatedcodearehard-coded

tomatchdatabasetableandviewdefinitions,storeprocedure

andfunctionsignatures,andusercredentials.Ifanyofthese

change,eveninsubtleways,yourcodewilllikelycrash.Atthis

point,youronlyalternativeistorebuild,recompile,retestand

redeploy,andpossiblylookforanothercustomer.



WhatIsaDataSource?

A"DataSource"(accordingtoVisualStudio2005'snew[1]

definition)isameansofgeneratingoneormoreTableAdapter

classes.TheDataSourceXSDdesigner(showninFigure6.1)

andtheDataSourceConfigurationwizardaredesignedto

provideawaytogeneratevisualizerelationaltables,stored

procedures,views,orobjectsexposedviaanXMLWebService

orbusinessobjectinterface.TheseDataSourceobjectsexpose

namedDataSetandTableAdapterclassesasiconsthatcanbe

draggedfromtheDataSourceswindowtoaWindowsForma

processthatinstructsVisualStudiotogeneratetheconnection,

linkage,binding,navigation,andactionqueriescodeneededto

display,captureparameters,showposition,navigatethrougha

query'srowset,andupdatethedataondemand.

[1]Theterm"DataSource"hasbeenusedforavarietyofclasses,objects,concepts,andotherrandomstufffor

decades.



Figure6.1.ApopulatedDataSourceDesigner

window.



[Viewfullsizeimage]



ThecodegeneratedbytheDataSourceConfigurationwizardis

savedtoa"Designer"fileinyoursolutionthatcanbeinspected

(butIdon'trecommendthatyouchangeit)toseehowthe

classisimplemented.



Duringmanualconfiguration(arequiredstep,asfarasI'm

concerned)youshould:

Refinethequerybeingexecuted.Forexample,youcanadd

aWHEREorTOPclausetolimitthenumberofrows

returned.

Defineparameterstofurtherfocusthequery.



DesignatewhatcodeandUIelementsaregeneratedwhen

youdragtheicontoaWindowsorASP.NETForm.

Designatethecodemethodsusedtopopulatethe

underlyingcustomstronglytypedDataTableobjects.

AddTableAdapterclassestotheDataSourceandtunethe

relationshipsbetweenthoseclasses.

Defineorrefinethecodeusedtoupdatethetargetrowset.

SpecifyhoweachTableAdaptercolumnistoberenderedin

boundcontrols.

YoucanchooseappropriateWindowsformscontrolsto

displaythecolumnvalueorwriteacustomcontrolto

displayit.



Tip

The.XSSfilecreatedbyVisualStudioisusedtomapthe

objectsshownintheDataSourcesDesignerwindow.



Theaforementionedwizardsalsodealverynicelywithquery

parameters(ifyouspecifythem)andprovideacleannavigation

tooltostepfromrowtorowtoimplementsimplecontrol

binding.IbuiltasampleofthisUIbycreatinga"codeless"

interfacetotheAuthorsByYearBornstoredprocedureincluding

thequeryparameters(asshowninFigure6.2).



Figure6.2.DataSourceConfiguration

wizardgeneratedcodepopulatedthisform.



Simplecontrolbindingconnectsdatafromadatasource

(DataTablesingleRowvalue)toasingle-itemcontrol(likea

TextBox).Incontrast,"complex"databindingiswhereyou

pointtheDataSourcepropertyataDataTable(or,betteryet,a

DataView)andletthecontroldisplayallrowsatonce.



WhiletheDataSourceConfigurationwizardworksprettywell

forsimple(andsmall)databasetables,itquicklylosessteam

whenyoutrytoleverageittoaccesslargetables,Web

Services,orbusinessobjectsthesearen'tnearlyasintuitive,

andyou'llendupdoingalotmoreworkthanyoumightfeelis

warranted.

ForthosetransitioningfromearlierversionsofVisualStudio,

youmightrecallthatstronglytypedDataSetclasseswere

createdbytheirownwizardthatwaslaunchedfromtheData

menu.Well,Microsofthaschosentohidethatwizardtheywant



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 6. Building Data Sources, DataSets, and TableAdapters

Tải bản đầy đủ ngay(0 tr)

×