DataTable.cs 273 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398
  1. //------------------------------------------------------------------------------
  2. // <copyright file="DataTable.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data {
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  13. using System.Diagnostics;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Runtime.Serialization;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Xml;
  20. using System.Xml.Schema;
  21. using System.Xml.Serialization;
  22. using System.Data.Common;
  23. using System.Runtime.Versioning;
  24. using System.Runtime.CompilerServices;
  25. /// <devdoc>
  26. /// <para>Represents one table of in-memory data.</para>
  27. /// </devdoc>
  28. [
  29. ToolboxItem(false),
  30. DesignTimeVisible(false),
  31. DefaultProperty("TableName"),
  32. Editor("Microsoft.VSDesigner.Data.Design.DataTableEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
  33. DefaultEvent("RowChanging"),
  34. XmlSchemaProvider("GetDataTableSchema"),
  35. Serializable
  36. ]
  37. public class DataTable : MarshalByValueComponent, System.ComponentModel.IListSource, ISupportInitializeNotification, ISerializable, IXmlSerializable{
  38. private DataSet dataSet;
  39. private DataView defaultView = null;
  40. // rows
  41. /// <summary>
  42. /// Monotonically increasing number representing the order <see cref="DataRow"/> have been added to <see cref="DataRowCollection"/>.
  43. /// </summary>
  44. /// <remarks>This limits <see cref="DataRowCollection.Add(DataRow)"/> to <see cref="Int32.MaxValue"/> operations.</remarks>
  45. internal long nextRowID;
  46. internal readonly DataRowCollection rowCollection;
  47. // columns
  48. internal readonly DataColumnCollection columnCollection;
  49. // constraints
  50. private readonly ConstraintCollection constraintCollection;
  51. //SimpleContent implementation
  52. private int elementColumnCount = 0;
  53. // relations
  54. internal DataRelationCollection parentRelationsCollection;
  55. internal DataRelationCollection childRelationsCollection;
  56. // RecordManager
  57. internal readonly RecordManager recordManager;
  58. // index mgmt
  59. internal readonly List<Index> indexes;
  60. private List<Index> shadowIndexes;
  61. private int shadowCount;
  62. // props
  63. internal PropertyCollection extendedProperties = null;
  64. private string tableName = "";
  65. internal string tableNamespace = null;
  66. private string tablePrefix = "";
  67. internal DataExpression displayExpression;
  68. internal bool fNestedInDataset = true;
  69. // globalization stuff
  70. private CultureInfo _culture;
  71. private bool _cultureUserSet;
  72. private CompareInfo _compareInfo;
  73. private CompareOptions _compareFlags = CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth;
  74. private IFormatProvider _formatProvider;
  75. private StringComparer _hashCodeProvider;
  76. private bool _caseSensitive;
  77. private bool _caseSensitiveUserSet;
  78. // XML properties
  79. internal string encodedTableName; // For XmlDataDocument only
  80. internal DataColumn xmlText; // text values of a complex xml element
  81. internal DataColumn _colUnique;
  82. internal bool textOnly = false; // the table has only text value with possible attributes
  83. internal decimal minOccurs = 1; // default = 1
  84. internal decimal maxOccurs = 1; // default = 1
  85. internal bool repeatableElement = false;
  86. private object typeName = null;
  87. // primary key info
  88. private readonly static Int32[] zeroIntegers = new Int32[0];
  89. internal readonly static DataColumn[] zeroColumns = new DataColumn[0];
  90. internal readonly static DataRow[] zeroRows = new DataRow[0];
  91. internal UniqueConstraint primaryKey;
  92. internal readonly static IndexField[] zeroIndexField = new IndexField[0];
  93. internal IndexField[] _primaryIndex = zeroIndexField;
  94. private DataColumn[] delayedSetPrimaryKey = null;
  95. // Loading Schema and/or Data related optimization
  96. private Index loadIndex;
  97. private Index loadIndexwithOriginalAdded = null;
  98. private Index loadIndexwithCurrentDeleted = null;
  99. private int _suspendIndexEvents;
  100. private bool savedEnforceConstraints = false;
  101. private bool inDataLoad = false;
  102. private bool initialLoad;
  103. private bool schemaLoading = false;
  104. private bool enforceConstraints = true;
  105. internal bool _suspendEnforceConstraints = false;
  106. protected internal bool fInitInProgress = false;
  107. private bool inLoad = false;
  108. internal bool fInLoadDiffgram = false;
  109. private byte _isTypedDataTable; // 0 == unknown, 1 = yes, 2 = No
  110. private DataRow[] EmptyDataRowArray;
  111. // Property Descriptor Cache for DataBinding
  112. private PropertyDescriptorCollection propertyDescriptorCollectionCache = null;
  113. // Cache for relation that has this table as nested child table.
  114. private static readonly DataRelation[] EmptyArrayDataRelation = new DataRelation[0];
  115. private DataRelation[] _nestedParentRelations = EmptyArrayDataRelation;
  116. // Dependent column list for expression evaluation
  117. internal List<DataColumn> dependentColumns = null;
  118. // events
  119. private bool mergingData = false;
  120. private DataRowChangeEventHandler onRowChangedDelegate;
  121. private DataRowChangeEventHandler onRowChangingDelegate;
  122. private DataRowChangeEventHandler onRowDeletingDelegate;
  123. private DataRowChangeEventHandler onRowDeletedDelegate;
  124. private DataColumnChangeEventHandler onColumnChangedDelegate;
  125. private DataColumnChangeEventHandler onColumnChangingDelegate;
  126. private DataTableClearEventHandler onTableClearingDelegate;
  127. private DataTableClearEventHandler onTableClearedDelegate;
  128. private DataTableNewRowEventHandler onTableNewRowDelegate;
  129. private PropertyChangedEventHandler onPropertyChangingDelegate;
  130. private System.EventHandler onInitialized;
  131. // misc
  132. private readonly DataRowBuilder rowBuilder;
  133. private const String KEY_XMLSCHEMA = "XmlSchema";
  134. private const String KEY_XMLDIFFGRAM = "XmlDiffGram";
  135. private const String KEY_NAME = "TableName";
  136. internal readonly List<DataView> delayedViews = new List<DataView>();
  137. private readonly List<DataViewListener> _dataViewListeners = new List<DataViewListener>();
  138. // private bool serializeHierarchy = false;
  139. internal Hashtable rowDiffId = null;
  140. internal readonly ReaderWriterLock indexesLock = new ReaderWriterLock();
  141. internal int ukColumnPositionForInference= -1;
  142. // default remoting format is Xml
  143. private SerializationFormat _remotingFormat = SerializationFormat.Xml;
  144. private static int _objectTypeCount; // Bid counter
  145. private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
  146. /// <devdoc>
  147. /// <para>Initializes a new instance of the <see cref='System.Data.DataTable'/> class with no arguments.</para>
  148. /// </devdoc>
  149. public DataTable() {
  150. GC.SuppressFinalize(this);
  151. Bid.Trace("<ds.DataTable.DataTable|API> %d#\n", ObjectID);
  152. nextRowID = 1;
  153. recordManager = new RecordManager(this);
  154. _culture = CultureInfo.CurrentCulture;
  155. this.columnCollection = new DataColumnCollection(this);
  156. this.constraintCollection = new ConstraintCollection(this);
  157. this.rowCollection = new DataRowCollection(this);
  158. this.indexes = new List<Index>();
  159. rowBuilder = new DataRowBuilder(this, -1);
  160. }
  161. /// <devdoc>
  162. /// <para>Intitalizes a new instance of the <see cref='System.Data.DataTable'/> class with the specified table
  163. /// name.</para>
  164. /// </devdoc>
  165. public DataTable(string tableName) : this() {
  166. this.tableName = tableName == null ? "" : tableName;
  167. }
  168. public DataTable(string tableName, string tableNamespace) : this(tableName) {
  169. this.Namespace = tableNamespace;
  170. }
  171. // Deserialize the table from binary/xml stream.
  172. protected DataTable(SerializationInfo info, StreamingContext context) : this()
  173. {
  174. bool isSingleTable = context.Context != null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true;
  175. SerializationFormat remotingFormat = SerializationFormat.Xml;
  176. SerializationInfoEnumerator e = info.GetEnumerator();
  177. while (e.MoveNext()) {
  178. switch(e.Name) {
  179. case "DataTable.RemotingFormat" : //DataTable.RemotingFormat does not exist in V1/V1.1 versions
  180. remotingFormat = (SerializationFormat)e.Value;
  181. break;
  182. }
  183. }
  184. DeserializeDataTable(info, context, isSingleTable, remotingFormat);
  185. }
  186. [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
  187. public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
  188. SerializationFormat remotingFormat = RemotingFormat;
  189. bool isSingleTable = context.Context != null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true;
  190. SerializeDataTable(info, context, isSingleTable, remotingFormat);
  191. }
  192. // Serialize the table schema and data.
  193. private void SerializeDataTable(SerializationInfo info, StreamingContext context, bool isSingleTable, SerializationFormat remotingFormat) {
  194. info.AddValue("DataTable.RemotingVersion", new Version(2, 0));
  195. // SqlHotFix 299, SerializationFormat enumeration types don't exist in V1.1 SP1
  196. if (SerializationFormat.Xml != remotingFormat) {
  197. info.AddValue("DataTable.RemotingFormat", remotingFormat);
  198. }
  199. if (remotingFormat != SerializationFormat.Xml) {//Binary
  200. SerializeTableSchema(info, context, isSingleTable);
  201. if (isSingleTable) {
  202. SerializeTableData(info, context, 0);
  203. }
  204. } else {//XML/V1.0/V1.1
  205. string tempDSNamespace = "";
  206. Boolean fCreatedDataSet = false;
  207. if (dataSet == null) {
  208. DataSet ds = new DataSet("tmpDataSet");
  209. // if user set values on DataTable, it isn't necessary
  210. // to set them on the DataSet because they won't be inherited
  211. // but it is simpler to set them in both places
  212. // if user did not set values on DataTable, it is required
  213. // to set them on the DataSet so the table will inherit
  214. // the value already on the Datatable
  215. ds.SetLocaleValue(_culture, _cultureUserSet);
  216. ds.CaseSensitive = this.CaseSensitive;
  217. ds.namespaceURI = this.Namespace;
  218. Debug.Assert(ds.RemotingFormat == SerializationFormat.Xml, "RemotingFormat must be SerializationFormat.Xml");
  219. ds.Tables.Add(this);
  220. fCreatedDataSet = true;
  221. } else {
  222. tempDSNamespace = this.DataSet.Namespace;
  223. this.DataSet.namespaceURI = this.Namespace; //this.DataSet.Namespace = this.Namespace; ??
  224. }
  225. info.AddValue(KEY_XMLSCHEMA, dataSet.GetXmlSchemaForRemoting(this));
  226. info.AddValue(KEY_XMLDIFFGRAM, dataSet.GetRemotingDiffGram(this));
  227. if (fCreatedDataSet) {
  228. dataSet.Tables.Remove(this);
  229. }
  230. else{
  231. dataSet.namespaceURI = tempDSNamespace;
  232. }
  233. }
  234. }
  235. // Deserialize the table schema and data.
  236. internal void DeserializeDataTable(SerializationInfo info, StreamingContext context, bool isSingleTable, SerializationFormat remotingFormat) {
  237. if (remotingFormat != SerializationFormat.Xml) {//Binary
  238. DeserializeTableSchema(info, context, isSingleTable);
  239. if (isSingleTable) {
  240. DeserializeTableData(info, context, 0);
  241. this.ResetIndexes();
  242. }
  243. } else {//XML/V1.0/V1.1
  244. string strSchema = (String)info.GetValue(KEY_XMLSCHEMA, typeof(System.String));
  245. string strData = (String)info.GetValue(KEY_XMLDIFFGRAM, typeof(System.String));
  246. if (strSchema != null) {
  247. DataSet ds = new DataSet();
  248. // fxcop: ReadXmlSchema will provide the CaseSensitive, Locale, Namespace information
  249. ds.ReadXmlSchema(new XmlTextReader( new StringReader( strSchema ) ) );
  250. Debug.Assert(ds.Tables.Count == 1, "There should be exactly 1 table here");
  251. DataTable table = ds.Tables[0];
  252. table.CloneTo(this, null, false);// WebData 111656
  253. //this is to avoid the cascading rules in the namespace
  254. this.Namespace = table.Namespace;
  255. if (strData != null) {
  256. ds.Tables.Remove(ds.Tables[0]);
  257. ds.Tables.Add(this);
  258. ds.ReadXml(new XmlTextReader( new StringReader( strData ) ), XmlReadMode.DiffGram);
  259. ds.Tables.Remove(this);
  260. }
  261. }
  262. }
  263. }
  264. // Serialize the columns
  265. internal void SerializeTableSchema(SerializationInfo info, StreamingContext context, bool isSingleTable) {
  266. //DataTable basic properties
  267. info.AddValue("DataTable.TableName", TableName);
  268. info.AddValue("DataTable.Namespace", Namespace);
  269. info.AddValue("DataTable.Prefix", Prefix);
  270. info.AddValue("DataTable.CaseSensitive", _caseSensitive);
  271. info.AddValue("DataTable.caseSensitiveAmbient", !_caseSensitiveUserSet);
  272. info.AddValue("DataTable.LocaleLCID", Locale.LCID);
  273. info.AddValue("DataTable.MinimumCapacity", recordManager.MinimumCapacity);
  274. //info.AddValue("DataTable.DisplayExpression", DisplayExpression);
  275. //DataTable state internal properties
  276. info.AddValue("DataTable.NestedInDataSet", fNestedInDataset);
  277. info.AddValue("DataTable.TypeName", TypeName.ToString());
  278. info.AddValue("DataTable.RepeatableElement", repeatableElement);
  279. //ExtendedProperties
  280. info.AddValue("DataTable.ExtendedProperties", ExtendedProperties);
  281. //Columns
  282. info.AddValue("DataTable.Columns.Count", Columns.Count);
  283. //Check for closure of expression in case of single table.
  284. if (isSingleTable) {
  285. List<DataTable> list = new List<DataTable>();
  286. list.Add(this);
  287. if (!CheckForClosureOnExpressionTables(list))
  288. throw ExceptionBuilder.CanNotRemoteDataTable();
  289. }
  290. IFormatProvider formatProvider = CultureInfo.InvariantCulture;
  291. for (int i = 0; i < Columns.Count; i++) {
  292. //DataColumn basic properties
  293. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnName", i), Columns[i].ColumnName);
  294. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.Namespace", i), Columns[i]._columnUri);
  295. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.Prefix", i), Columns[i].Prefix);
  296. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnMapping", i), Columns[i].ColumnMapping);
  297. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.AllowDBNull", i), Columns[i].AllowDBNull);
  298. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrement", i), Columns[i].AutoIncrement);
  299. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementStep", i), Columns[i].AutoIncrementStep);
  300. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementSeed", i), Columns[i].AutoIncrementSeed);
  301. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.Caption", i), Columns[i].Caption);
  302. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.DefaultValue", i), Columns[i].DefaultValue);
  303. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.ReadOnly", i), Columns[i].ReadOnly);
  304. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.MaxLength", i), Columns[i].MaxLength);
  305. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.DataType", i), Columns[i].DataType);
  306. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.XmlDataType", i), Columns[i].XmlDataType);
  307. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.SimpleType", i), Columns[i].SimpleType);
  308. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.DateTimeMode", i), Columns[i].DateTimeMode);
  309. //DataColumn internal state properties
  310. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementCurrent", i), Columns[i].AutoIncrementCurrent);
  311. //Expression
  312. if (isSingleTable) {
  313. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.Expression", i), Columns[i].Expression);
  314. }
  315. //ExtendedProperties
  316. info.AddValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.ExtendedProperties", i), Columns[i].extendedProperties);
  317. }
  318. //Constraints
  319. if (isSingleTable) {
  320. SerializeConstraints(info, context, 0, false);
  321. }
  322. }
  323. // Deserialize all the Columns
  324. internal void DeserializeTableSchema(SerializationInfo info, StreamingContext context, bool isSingleTable) {
  325. //DataTable basic properties
  326. tableName = info.GetString("DataTable.TableName");
  327. tableNamespace = info.GetString("DataTable.Namespace");
  328. tablePrefix = info.GetString("DataTable.Prefix");
  329. bool caseSensitive = info.GetBoolean("DataTable.CaseSensitive");
  330. SetCaseSensitiveValue(caseSensitive, true, false);
  331. _caseSensitiveUserSet = !info.GetBoolean("DataTable.caseSensitiveAmbient");
  332. int lcid = (int)info.GetValue("DataTable.LocaleLCID", typeof(int));
  333. CultureInfo culture = new CultureInfo(lcid);
  334. SetLocaleValue(culture, true, false);
  335. _cultureUserSet = true;
  336. MinimumCapacity = info.GetInt32("DataTable.MinimumCapacity");
  337. //DisplayExpression = info.GetString("DataTable.DisplayExpression");
  338. //DataTable state internal properties
  339. fNestedInDataset = (bool) info.GetBoolean("DataTable.NestedInDataSet");
  340. string tName = info.GetString("DataTable.TypeName");
  341. typeName = new XmlQualifiedName(tName);
  342. repeatableElement = info.GetBoolean("DataTable.RepeatableElement");
  343. //ExtendedProperties
  344. extendedProperties = (PropertyCollection) info.GetValue("DataTable.ExtendedProperties", typeof(PropertyCollection));
  345. //Columns
  346. int colCount = info.GetInt32("DataTable.Columns.Count");
  347. string [] expressions = new string[colCount];
  348. Debug.Assert(Columns.Count == 0, "There is column in Table");
  349. IFormatProvider formatProvider = CultureInfo.InvariantCulture;
  350. for (int i = 0; i < colCount; i++) {
  351. DataColumn dc = new DataColumn();
  352. //DataColumn public state properties
  353. dc.ColumnName = info.GetString(String.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnName", i));
  354. dc._columnUri = info.GetString(String.Format(formatProvider, "DataTable.DataColumn_{0}.Namespace", i));
  355. dc.Prefix = info.GetString(String.Format(formatProvider, "DataTable.DataColumn_{0}.Prefix", i));
  356. dc.DataType = (Type) info.GetValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.DataType", i), typeof(Type));
  357. dc.XmlDataType = (string) info.GetValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.XmlDataType", i), typeof(string));
  358. dc.SimpleType = (SimpleType) info.GetValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.SimpleType", i), typeof(SimpleType));
  359. dc.ColumnMapping = (MappingType) info.GetValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnMapping", i), typeof(MappingType));
  360. dc.DateTimeMode = (DataSetDateTime) info.GetValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.DateTimeMode", i), typeof(DataSetDateTime));
  361. dc.AllowDBNull = info.GetBoolean(String.Format(formatProvider, "DataTable.DataColumn_{0}.AllowDBNull", i));
  362. dc.AutoIncrement = info.GetBoolean(String.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrement", i));
  363. dc.AutoIncrementStep = info.GetInt64(String.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementStep", i));
  364. dc.AutoIncrementSeed = info.GetInt64(String.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementSeed", i));
  365. dc.Caption = info.GetString(String.Format(formatProvider, "DataTable.DataColumn_{0}.Caption", i));
  366. dc.DefaultValue = info.GetValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.DefaultValue", i), typeof(object));
  367. dc.ReadOnly = info.GetBoolean(String.Format(formatProvider, "DataTable.DataColumn_{0}.ReadOnly", i));
  368. dc.MaxLength= info.GetInt32(String.Format(formatProvider, "DataTable.DataColumn_{0}.MaxLength", i));
  369. //DataColumn internal state properties
  370. dc.AutoIncrementCurrent = info.GetValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementCurrent", i), typeof(object));
  371. //Expression
  372. if (isSingleTable) {
  373. expressions[i] = info.GetString(String.Format(formatProvider, "DataTable.DataColumn_{0}.Expression", i));
  374. }
  375. //ExtendedProperties
  376. dc.extendedProperties = (PropertyCollection) info.GetValue(String.Format(formatProvider, "DataTable.DataColumn_{0}.ExtendedProperties", i), typeof(PropertyCollection));
  377. Columns.Add(dc);
  378. }
  379. if (isSingleTable) {
  380. for(int i = 0; i < colCount; i++) {
  381. if (expressions[i] != null) {
  382. Columns[i].Expression = expressions[i];
  383. }
  384. }
  385. }
  386. //Constraints
  387. if (isSingleTable) {
  388. DeserializeConstraints(info, context, /*table index */ 0, /* serialize all constraints */false);// since single table, send table index as 0, meanwhile passing
  389. // false for 'allConstraints' means, handle all the constraint related to the table
  390. }
  391. }
  392. /*
  393. Serialize constraints availabe on the table - note this function is marked internal because it is called by the DataSet deserializer.
  394. ***Schema for Serializing ArrayList of Constraints***
  395. Unique Constraint - ["U"]->[constraintName]->[columnIndexes]->[IsPrimaryKey]->[extendedProperties]
  396. Foriegn Key Constraint - ["F"]->[constraintName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[AcceptRejectRule, UpdateRule, DeleteRule]->[extendedProperties]
  397. */
  398. internal void SerializeConstraints(SerializationInfo info, StreamingContext context, int serIndex, bool allConstraints) {
  399. if (allConstraints) {
  400. Debug.Assert(DataSet != null);
  401. }
  402. ArrayList constraintList = new ArrayList();
  403. for (int i = 0; i < Constraints.Count; i++) {
  404. Constraint c = Constraints[i];
  405. UniqueConstraint uc = c as UniqueConstraint;
  406. if (uc != null) {
  407. int[] colInfo = new int[uc.Columns.Length];
  408. for (int j = 0; j < colInfo.Length; j++) {
  409. colInfo[j] = uc.Columns[j].Ordinal;
  410. }
  411. ArrayList list = new ArrayList();
  412. list.Add("U");
  413. list.Add(uc.ConstraintName);
  414. list.Add(colInfo);
  415. list.Add(uc.IsPrimaryKey);
  416. list.Add(uc.ExtendedProperties);
  417. constraintList.Add(list);
  418. } else {
  419. ForeignKeyConstraint fk = c as ForeignKeyConstraint;
  420. Debug.Assert(fk != null);
  421. bool shouldSerialize = (allConstraints == true) || (fk.Table == this && fk.RelatedTable == this);
  422. if (shouldSerialize) {
  423. int[] parentInfo = new int[fk.RelatedColumns.Length + 1];
  424. parentInfo[0] = allConstraints ? this.DataSet.Tables.IndexOf(fk.RelatedTable) : 0;
  425. for (int j = 1; j < parentInfo.Length; j++) {
  426. parentInfo[j] = fk.RelatedColumns[j - 1].Ordinal;
  427. }
  428. int[] childInfo = new int[fk.Columns.Length + 1];
  429. childInfo[0] = allConstraints ? this.DataSet.Tables.IndexOf(fk.Table) : 0 ; //Since the constraint is on the current table, this is the child table.
  430. for (int j = 1; j < childInfo.Length; j++) {
  431. childInfo[j] = fk.Columns[j - 1].Ordinal;
  432. }
  433. ArrayList list = new ArrayList();
  434. list.Add("F");
  435. list.Add(fk.ConstraintName);
  436. list.Add(parentInfo);
  437. list.Add(childInfo);
  438. list.Add(new int[] { (int) fk.AcceptRejectRule, (int) fk.UpdateRule, (int) fk.DeleteRule });
  439. list.Add(fk.ExtendedProperties);
  440. constraintList.Add(list);
  441. }
  442. }
  443. }
  444. info.AddValue(String.Format(CultureInfo.InvariantCulture, "DataTable_{0}.Constraints", serIndex), constraintList);
  445. }
  446. /*
  447. Deserialize the constraints on the table.
  448. ***Schema for Serializing ArrayList of Constraints***
  449. Unique Constraint - ["U"]->[constraintName]->[columnIndexes]->[IsPrimaryKey]->[extendedProperties]
  450. Foriegn Key Constraint - ["F"]->[constraintName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[AcceptRejectRule, UpdateRule, DeleteRule]->[extendedProperties]
  451. */
  452. internal void DeserializeConstraints(SerializationInfo info, StreamingContext context, int serIndex, bool allConstraints) {
  453. ArrayList constraintList = (ArrayList) info.GetValue(String.Format(CultureInfo.InvariantCulture, "DataTable_{0}.Constraints", serIndex), typeof(ArrayList));
  454. foreach (ArrayList list in constraintList) {
  455. string con = (string) list[0];
  456. if (con.Equals("U")) { //Unique Constraints
  457. string constraintName = (string) list[1];
  458. int[] keyColumnIndexes = (int[]) list[2];
  459. bool isPrimaryKey = (bool) list[3];
  460. PropertyCollection extendedProperties = (PropertyCollection) list[4];
  461. DataColumn[] keyColumns = new DataColumn[keyColumnIndexes.Length];
  462. for (int i = 0; i < keyColumnIndexes.Length; i++) {
  463. keyColumns[i] = Columns[keyColumnIndexes[i]];
  464. }
  465. //Create the constraint.
  466. UniqueConstraint uc = new UniqueConstraint(constraintName, keyColumns, isPrimaryKey);
  467. uc.extendedProperties = extendedProperties;
  468. //Add the unique constraint and it will in turn set the primary keys also if needed.
  469. Constraints.Add(uc);
  470. } else { //ForeignKeyConstraints
  471. Debug.Assert(con.Equals("F"));
  472. string constraintName = (string) list[1];
  473. int[] parentInfo = (int[]) list[2];
  474. int[] childInfo = (int[]) list[3];
  475. int[] rules = (int[]) list[4];
  476. PropertyCollection extendedProperties = (PropertyCollection) list[5];
  477. //ParentKey Columns.
  478. DataTable parentTable = (allConstraints == false) ? this : this.DataSet.Tables[parentInfo[0]];
  479. DataColumn[] parentkeyColumns = new DataColumn[parentInfo.Length - 1];
  480. for (int i = 0; i < parentkeyColumns.Length; i++) {
  481. parentkeyColumns[i] = parentTable.Columns[parentInfo[i + 1]];
  482. }
  483. //ChildKey Columns.
  484. DataTable childTable = (allConstraints == false) ? this : this.DataSet.Tables[childInfo[0]];
  485. DataColumn[] childkeyColumns = new DataColumn[childInfo.Length - 1];
  486. for (int i = 0; i < childkeyColumns.Length; i++) {
  487. childkeyColumns[i] = childTable.Columns[childInfo[i + 1]];
  488. }
  489. //Create the Constraint.
  490. ForeignKeyConstraint fk = new ForeignKeyConstraint(constraintName, parentkeyColumns, childkeyColumns);
  491. fk.AcceptRejectRule = (AcceptRejectRule) rules[0];
  492. fk.UpdateRule = (Rule) rules[1];
  493. fk.DeleteRule = (Rule) rules[2];
  494. fk.extendedProperties = extendedProperties;
  495. //Add just the foreign key constraint without creating unique constraint.
  496. Constraints.Add(fk, false);
  497. }
  498. }
  499. }
  500. // Serialize the expressions on the table - Marked internal so that DataSet deserializer can call into this
  501. internal void SerializeExpressionColumns(SerializationInfo info, StreamingContext context, int serIndex) {
  502. int colCount = Columns.Count;
  503. for (int i = 0; i < colCount; i++) {
  504. info.AddValue(String.Format(CultureInfo.InvariantCulture, "DataTable_{0}.DataColumn_{1}.Expression", serIndex, i), Columns[i].Expression);
  505. }
  506. }
  507. // Deserialize the expressions on the table - Marked internal so that DataSet deserializer can call into this
  508. internal void DeserializeExpressionColumns(SerializationInfo info, StreamingContext context, int serIndex) {
  509. int colCount = Columns.Count;
  510. for (int i = 0; i < colCount; i++) {
  511. string expr = info.GetString(String.Format(CultureInfo.InvariantCulture, "DataTable_{0}.DataColumn_{1}.Expression", serIndex, i));
  512. if (0 != expr.Length) {
  513. Columns[i].Expression = expr;
  514. }
  515. }
  516. }
  517. // Serialize all the Rows.
  518. internal void SerializeTableData(SerializationInfo info, StreamingContext context, int serIndex) {
  519. //Cache all the column count, row count
  520. int colCount = Columns.Count;
  521. int rowCount = Rows.Count;
  522. int modifiedRowCount = 0;
  523. int editRowCount = 0;
  524. //Compute row states and assign the bits accordingly - 00[Unchanged], 01[Added], 10[Modifed], 11[Deleted]
  525. BitArray rowStates = new BitArray(rowCount * 3, false); //All bit flags are set to false on initialization of the BitArray.
  526. for (int i = 0; i < rowCount; i++) {
  527. int bitIndex = i * 3;
  528. DataRow row = Rows[i];
  529. DataRowState rowState = row.RowState;
  530. switch (rowState) {
  531. case DataRowState.Unchanged:
  532. //rowStates[bitIndex] = false;
  533. //rowStates[bitIndex + 1] = false;
  534. break;
  535. case DataRowState.Added:
  536. //rowStates[bitIndex] = false;
  537. rowStates[bitIndex + 1] = true;
  538. break;
  539. case DataRowState.Modified:
  540. rowStates[bitIndex] = true;
  541. //rowStates[bitIndex + 1] = false;
  542. modifiedRowCount++;
  543. break;
  544. case DataRowState.Deleted:
  545. rowStates[bitIndex] = true;
  546. rowStates[bitIndex + 1] = true;
  547. break;
  548. default:
  549. throw ExceptionBuilder.InvalidRowState(rowState);
  550. }
  551. if (-1 != row.tempRecord) {
  552. rowStates[bitIndex + 2] = true;
  553. editRowCount++;
  554. }
  555. }
  556. //Compute the actual storage records that need to be created.
  557. int recordCount = rowCount + modifiedRowCount + editRowCount;
  558. //Create column storages.
  559. ArrayList storeList = new ArrayList();
  560. ArrayList nullbitList = new ArrayList();
  561. if (recordCount > 0) { //Create the storage only if have records.
  562. for (int i = 0; i < colCount; i++) {
  563. object store = Columns[i].GetEmptyColumnStore(recordCount);
  564. storeList.Add(store);
  565. BitArray nullbits = new BitArray(recordCount);
  566. nullbitList.Add(nullbits);
  567. }
  568. }
  569. //Copy values into column storages
  570. int recordsConsumed = 0;
  571. Hashtable rowErrors = new Hashtable();
  572. Hashtable colErrors = new Hashtable();
  573. for (int i = 0; i < rowCount; i++) {
  574. int recordsPerRow = Rows[i].CopyValuesIntoStore(storeList, nullbitList, recordsConsumed);
  575. GetRowAndColumnErrors(i, rowErrors, colErrors);
  576. recordsConsumed += recordsPerRow;
  577. }
  578. IFormatProvider formatProvider = CultureInfo.InvariantCulture;
  579. //Serialize all the computed values.
  580. info.AddValue(String.Format(formatProvider, "DataTable_{0}.Rows.Count", serIndex), rowCount);
  581. info.AddValue(String.Format(formatProvider, "DataTable_{0}.Records.Count", serIndex), recordCount);
  582. info.AddValue(String.Format(formatProvider, "DataTable_{0}.RowStates", serIndex), rowStates);
  583. info.AddValue(String.Format(formatProvider, "DataTable_{0}.Records", serIndex), storeList);
  584. info.AddValue(String.Format(formatProvider, "DataTable_{0}.NullBits", serIndex), nullbitList);
  585. info.AddValue(String.Format(formatProvider, "DataTable_{0}.RowErrors", serIndex), rowErrors);
  586. info.AddValue(String.Format(formatProvider, "DataTable_{0}.ColumnErrors", serIndex), colErrors);
  587. }
  588. // Deserialize all the Rows.
  589. internal void DeserializeTableData(SerializationInfo info, StreamingContext context, int serIndex) {
  590. bool enforceConstraintsOrg = enforceConstraints;
  591. bool inDataLoadOrg = inDataLoad;
  592. try {
  593. enforceConstraints = false;
  594. inDataLoad = true;
  595. IFormatProvider formatProvider = CultureInfo.InvariantCulture;
  596. int rowCount = info.GetInt32(String.Format(formatProvider, "DataTable_{0}.Rows.Count", serIndex));
  597. int recordCount = info.GetInt32(String.Format(formatProvider, "DataTable_{0}.Records.Count", serIndex));
  598. BitArray rowStates = (BitArray) info.GetValue(String.Format(formatProvider, "DataTable_{0}.RowStates", serIndex), typeof(BitArray));
  599. ArrayList storeList = (ArrayList) info.GetValue(String.Format(formatProvider, "DataTable_{0}.Records", serIndex), typeof(ArrayList));
  600. ArrayList nullbitList = (ArrayList) info.GetValue(String.Format(formatProvider, "DataTable_{0}.NullBits", serIndex), typeof(ArrayList));
  601. Hashtable rowErrors = (Hashtable) info.GetValue(String.Format(formatProvider, "DataTable_{0}.RowErrors", serIndex), typeof(Hashtable));
  602. rowErrors.OnDeserialization(this);//OnDeSerialization must be called since the hashtable gets deserialized after the whole graph gets deserialized
  603. Hashtable colErrors = (Hashtable) info.GetValue(String.Format(formatProvider, "DataTable_{0}.ColumnErrors", serIndex), typeof(Hashtable));
  604. colErrors.OnDeserialization(this);//OnDeSerialization must be called since the hashtable gets deserialized after the whole graph gets deserialized
  605. if (recordCount <= 0) { //No need for deserialization of the storage and errors if there are no records.
  606. return;
  607. }
  608. //Point the record manager storage to the deserialized values.
  609. for (int i = 0; i < Columns.Count; i++) {
  610. Columns[i].SetStorage(storeList[i], (BitArray) nullbitList[i]);
  611. }
  612. //Create rows and set the records appropriately.
  613. int recordIndex = 0;
  614. DataRow[] rowArr = new DataRow[recordCount];
  615. for (int i = 0; i < rowCount; i++) {
  616. //Create a new row which sets old and new records to -1.
  617. DataRow row = NewEmptyRow();
  618. rowArr[recordIndex] = row;
  619. int bitIndex = i * 3;
  620. switch (ConvertToRowState(rowStates, bitIndex)) {
  621. case DataRowState.Unchanged:
  622. row.oldRecord = recordIndex;
  623. row.newRecord = recordIndex;
  624. recordIndex += 1;
  625. break;
  626. case DataRowState.Added:
  627. row.oldRecord = -1;
  628. row.newRecord = recordIndex;
  629. recordIndex += 1;
  630. break;
  631. case DataRowState.Modified:
  632. row.oldRecord = recordIndex;
  633. row.newRecord = recordIndex + 1;
  634. rowArr[recordIndex + 1] = row;
  635. recordIndex += 2;
  636. break;
  637. case DataRowState.Deleted:
  638. row.oldRecord = recordIndex;
  639. row.newRecord = -1;
  640. recordIndex += 1;
  641. break;
  642. }
  643. if (rowStates[bitIndex + 2]) {
  644. row.tempRecord = recordIndex;
  645. rowArr[recordIndex] = row;
  646. recordIndex += 1;
  647. } else {
  648. row.tempRecord = -1;
  649. }
  650. Rows.ArrayAdd(row);
  651. row.rowID = nextRowID;
  652. nextRowID++;
  653. ConvertToRowError(i, rowErrors, colErrors);
  654. }
  655. recordManager.SetRowCache(rowArr);
  656. ResetIndexes();
  657. } finally {
  658. enforceConstraints = enforceConstraintsOrg;
  659. inDataLoad = inDataLoadOrg;
  660. }
  661. }
  662. // Constructs the RowState from the two bits in the bitarray.
  663. private DataRowState ConvertToRowState(BitArray bitStates, int bitIndex) {
  664. Debug.Assert(bitStates != null);
  665. Debug.Assert(bitStates.Length > bitIndex);
  666. bool b1 = bitStates[bitIndex];
  667. bool b2 = bitStates[bitIndex + 1];
  668. if (!b1 && !b2) {
  669. return DataRowState.Unchanged;
  670. } else if (!b1 && b2) {
  671. return DataRowState.Added;
  672. } else if (b1 && !b2) {
  673. return DataRowState.Modified;
  674. } else if (b1 && b2) {
  675. return DataRowState.Deleted;
  676. } else {
  677. throw ExceptionBuilder.InvalidRowBitPattern();
  678. }
  679. }
  680. // Get the error on the row and columns - Marked internal so that DataSet deserializer can call into this
  681. internal void GetRowAndColumnErrors(int rowIndex, Hashtable rowErrors, Hashtable colErrors) {
  682. Debug.Assert(Rows.Count > rowIndex);
  683. Debug.Assert(rowErrors != null);
  684. Debug.Assert(colErrors != null);
  685. DataRow row = Rows[rowIndex];
  686. if (row.HasErrors) {
  687. rowErrors.Add(rowIndex, row.RowError);
  688. DataColumn[] dcArr = row.GetColumnsInError();
  689. if (dcArr.Length > 0) {
  690. int[] columnsInError = new int[dcArr.Length];
  691. string[] columnErrors = new string[dcArr.Length];
  692. for (int i = 0; i < dcArr.Length; i++) {
  693. columnsInError[i] = dcArr[i].Ordinal;
  694. columnErrors[i] = row.GetColumnError(dcArr[i]);
  695. }
  696. ArrayList list = new ArrayList();
  697. list.Add(columnsInError);
  698. list.Add(columnErrors);
  699. colErrors.Add(rowIndex, list);
  700. }
  701. }
  702. }
  703. // Set the row and columns in error..
  704. private void ConvertToRowError(int rowIndex, Hashtable rowErrors, Hashtable colErrors) {
  705. Debug.Assert(Rows.Count > rowIndex);
  706. Debug.Assert(rowErrors != null);
  707. Debug.Assert(colErrors != null);
  708. DataRow row = Rows[rowIndex];
  709. if (rowErrors.ContainsKey(rowIndex)) {
  710. row.RowError = (string) rowErrors[rowIndex];
  711. }
  712. if (colErrors.ContainsKey(rowIndex)) {
  713. ArrayList list = (ArrayList) colErrors[rowIndex];
  714. int[] columnsInError = (int[]) list[0];
  715. string[] columnErrors = (string[]) list[1];
  716. Debug.Assert(columnsInError.Length == columnErrors.Length);
  717. for (int i = 0; i < columnsInError.Length; i++) {
  718. row.SetColumnError(columnsInError[i], columnErrors[i]);
  719. }
  720. }
  721. }
  722. /// <devdoc>
  723. /// <para>Indicates whether string comparisons within the table are case-sensitive.</para>
  724. /// </devdoc>
  725. [ResDescriptionAttribute(Res.DataTableCaseSensitiveDescr)]
  726. public bool CaseSensitive {
  727. get {
  728. //The following assert is valid except when calling DataSet.set_CaseSensitive which Validates constraints and failing here
  729. //Debug.Assert(_caseSensitiveUserSet || (null == dataSet) || (dataSet.CaseSensitive == _caseSensitive), "CaseSensitive mismatch");
  730. return _caseSensitive;
  731. }
  732. set {
  733. if (_caseSensitive != value) {
  734. bool oldValue = _caseSensitive;
  735. bool oldUserSet = _caseSensitiveUserSet;
  736. _caseSensitive = value;
  737. _caseSensitiveUserSet = true;
  738. if (DataSet != null && !DataSet.ValidateCaseConstraint()) {
  739. _caseSensitive = oldValue;
  740. _caseSensitiveUserSet = oldUserSet;
  741. throw ExceptionBuilder.CannotChangeCaseLocale();
  742. }
  743. SetCaseSensitiveValue(value, true, true);
  744. }
  745. _caseSensitiveUserSet = true;
  746. }
  747. }
  748. internal bool AreIndexEventsSuspended {
  749. get { return (0 < _suspendIndexEvents); }
  750. }
  751. internal void RestoreIndexEvents(bool forceReset) {
  752. Bid.Trace("<ds.DataTable.RestoreIndexEvents|Info> %d#, %d\n", ObjectID, _suspendIndexEvents);
  753. if (0 < _suspendIndexEvents) {
  754. _suspendIndexEvents--;
  755. if (0 == _suspendIndexEvents) {
  756. Exception first = null;
  757. SetShadowIndexes();
  758. try{
  759. // the length of shadowIndexes will not change
  760. // but the array instance may change during
  761. // events during Index.Reset
  762. int numIndexes = shadowIndexes.Count;
  763. for (int i = 0; i < numIndexes; i++) {
  764. Index ndx = shadowIndexes[i];// shadowindexes may change, see ShadowIndexCopy()
  765. try {
  766. if (forceReset || ndx.HasRemoteAggregate) {
  767. ndx.Reset(); // resets & fires
  768. }
  769. else {
  770. ndx.FireResetEvent(); // fire the Reset event we were firing
  771. }
  772. }
  773. catch(Exception e) {
  774. if (!ADP.IsCatchableExceptionType (e)) {
  775. throw;
  776. }
  777. ExceptionBuilder.TraceExceptionWithoutRethrow(e);
  778. if (null == first) {
  779. first = e;
  780. }
  781. }
  782. }
  783. if (null != first) {
  784. throw first;
  785. }
  786. }
  787. finally {
  788. RestoreShadowIndexes();
  789. }
  790. }
  791. }
  792. }
  793. internal void SuspendIndexEvents() {
  794. Bid.Trace("<ds.DataTable.SuspendIndexEvents|Info> %d#, %d\n", ObjectID, _suspendIndexEvents);
  795. _suspendIndexEvents++;
  796. }
  797. [Browsable(false)]
  798. public bool IsInitialized {
  799. get {
  800. return !fInitInProgress;
  801. }
  802. }
  803. private bool IsTypedDataTable {
  804. get {
  805. switch (_isTypedDataTable) {
  806. case 0:
  807. _isTypedDataTable = (byte)((this.GetType() != typeof(DataTable))? 1 : 2);
  808. return (1 == _isTypedDataTable);
  809. case 1:
  810. return true;
  811. default:
  812. return false;
  813. }
  814. }
  815. }
  816. internal bool SetCaseSensitiveValue(bool isCaseSensitive, bool userSet, bool resetIndexes) {
  817. if (userSet || (!_caseSensitiveUserSet && (_caseSensitive != isCaseSensitive))) {
  818. _caseSensitive = isCaseSensitive;
  819. if (isCaseSensitive) {
  820. _compareFlags = CompareOptions.None;
  821. }
  822. else {
  823. _compareFlags = CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth;
  824. }
  825. if (resetIndexes) {
  826. ResetIndexes();
  827. foreach (Constraint constraint in Constraints) {
  828. constraint.CheckConstraint();
  829. }
  830. }
  831. return true;
  832. }
  833. return false;
  834. }
  835. private void ResetCaseSensitive() {
  836. // this method is used design-time scenarios via reflection
  837. // by the property grid context menu to show the Reset option or not
  838. SetCaseSensitiveValue((null != dataSet) && dataSet.CaseSensitive, true, true);
  839. _caseSensitiveUserSet = false;
  840. }
  841. internal bool ShouldSerializeCaseSensitive() {
  842. // this method is used design-time scenarios via reflection
  843. // by the property grid to show the CaseSensitive property in bold or not
  844. // by the code dom for persisting the CaseSensitive property or not
  845. return _caseSensitiveUserSet;
  846. }
  847. internal bool SelfNested {
  848. get {
  849. // Is this correct? if ((top[i].nestedParentRelation!= null) && (top[i].nestedParentRelation.ParentTable == top[i]))
  850. foreach(DataRelation rel in ParentRelations) {
  851. if (rel.Nested && rel.ParentTable == this) {
  852. return true;
  853. }
  854. }
  855. return false;
  856. }
  857. }
  858. /* internal bool SelfNestedWithOneRelation {
  859. get {
  860. return (this.ParentRelations.Count == 1 && (this.ParentRelations[0].ParentTable == this));
  861. }
  862. }
  863. */
  864. [DebuggerBrowsable(DebuggerBrowsableState.Never)] // don't have debugger view expand this
  865. internal List<Index> LiveIndexes {
  866. get {
  867. if (!AreIndexEventsSuspended) {
  868. for (int i = indexes.Count-1; 0 <= i; --i) {
  869. Index index = indexes[i];
  870. if (index.RefCount <= 1) {
  871. index.RemoveRef();
  872. }
  873. }
  874. }
  875. return indexes;
  876. }
  877. }
  878. [
  879. DefaultValue(SerializationFormat.Xml)
  880. ]
  881. public SerializationFormat RemotingFormat {
  882. get {
  883. return _remotingFormat;
  884. }
  885. set {
  886. if (value != SerializationFormat.Binary && value != SerializationFormat.Xml) {
  887. throw ExceptionBuilder.InvalidRemotingFormat(value);
  888. }
  889. // table can not have different format than its dataset, unless it is stand alone datatable
  890. if (this.DataSet != null && value != this.DataSet.RemotingFormat) {
  891. throw ExceptionBuilder.CanNotSetRemotingFormat();
  892. }
  893. _remotingFormat = value;
  894. }
  895. }
  896. // used to keep temporary state of unique Key posiotion to be added for inference only
  897. internal int UKColumnPositionForInference {
  898. get {
  899. return ukColumnPositionForInference;
  900. }
  901. set{
  902. ukColumnPositionForInference= value;
  903. }
  904. }
  905. /// <devdoc>
  906. /// <para>Gets the collection of child relations for this <see cref='System.Data.DataTable'/>.</para>
  907. /// </devdoc>
  908. [
  909. Browsable(false),
  910. ResDescriptionAttribute(Res.DataTableChildRelationsDescr),
  911. DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
  912. ]
  913. public DataRelationCollection ChildRelations {
  914. get {
  915. if (childRelationsCollection == null)
  916. childRelationsCollection = new DataRelationCollection.DataTableRelationCollection(this, false);
  917. return childRelationsCollection;
  918. }
  919. }
  920. /// <devdoc>
  921. /// <para>Gets the collection of columns that belong to this table.</para>
  922. /// </devdoc>
  923. [
  924. DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
  925. ResCategoryAttribute(Res.DataCategory_Data),
  926. ResDescriptionAttribute(Res.DataTableColumnsDescr)
  927. ]
  928. public DataColumnCollection Columns {
  929. get {
  930. return columnCollection;
  931. }
  932. }
  933. private void ResetColumns() {
  934. // this method is used design-time scenarios via reflection
  935. // by the property grid context menu to show the Reset option or not
  936. Columns.Clear();
  937. }
  938. private CompareInfo CompareInfo {
  939. get {
  940. if (null == _compareInfo) {
  941. _compareInfo = Locale.CompareInfo;
  942. }
  943. return _compareInfo;
  944. }
  945. }
  946. /// <devdoc>
  947. /// <para>Gets the collection of constraints maintained by this table.</para>
  948. /// </devdoc>
  949. [
  950. DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
  951. ResCategoryAttribute(Res.DataCategory_Data),
  952. ResDescriptionAttribute(Res.DataTableConstraintsDescr)
  953. ]
  954. public ConstraintCollection Constraints {
  955. get {
  956. return constraintCollection;
  957. }
  958. }
  959. /// <devdoc>
  960. /// <para>
  961. /// Resets the <see cref='System.Data.DataTable.Constraints'/> property to its default state.
  962. /// </para>
  963. /// </devdoc>
  964. private void ResetConstraints() {
  965. Constraints.Clear();
  966. }
  967. /// <devdoc>
  968. /// <para>Gets the <see cref='System.Data.DataSet'/> that this table belongs to.</para>
  969. /// </devdoc>
  970. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false), ResDescriptionAttribute(Res.DataTableDataSetDescr)]
  971. public DataSet DataSet {
  972. get {
  973. return dataSet;
  974. }
  975. }
  976. /// <devdoc>
  977. /// Internal method for setting the DataSet pointer.
  978. /// </devdoc>
  979. internal void SetDataSet(DataSet dataSet) {
  980. if (this.dataSet != dataSet) {
  981. this.dataSet = dataSet;
  982. // Inform all the columns of the dataset being set.
  983. DataColumnCollection cols = Columns;
  984. for (int i = 0; i < cols.Count; i++)
  985. cols[i].OnSetDataSet();
  986. if (this.DataSet != null) {
  987. defaultView = null;
  988. }
  989. //Set the remoting format variable directly
  990. if (dataSet != null) {
  991. _remotingFormat = dataSet.RemotingFormat;
  992. }
  993. }
  994. }
  995. /// <devdoc>
  996. /// <para>Gets a customized view of the table which may include a
  997. /// filtered view, or a cursor position.</para>
  998. /// </devdoc>
  999. [Browsable(false), ResDescriptionAttribute(Res.DataTableDefaultViewDescr)]
  1000. public DataView DefaultView {
  1001. get {
  1002. DataView view = defaultView;
  1003. if (null == view) {
  1004. if (null != dataSet) {
  1005. view = dataSet.DefaultViewManager.CreateDataView(this);
  1006. }
  1007. else {
  1008. view = new DataView(this, true);
  1009. view.SetIndex2("", DataViewRowState.CurrentRows, null, true);
  1010. }
  1011. // avoid HostProtectionAttribute(Synchronization=true) by not calling virtual methods from inside a lock
  1012. view = Interlocked.CompareExchange<DataView>(ref defaultView, view, null);
  1013. if (null == view) {
  1014. view = defaultView;
  1015. }
  1016. }
  1017. return view;
  1018. }
  1019. }
  1020. /// <devdoc>
  1021. /// <para>Gets or sets the expression that will return a value used to represent
  1022. /// this table in UI.</para>
  1023. /// </devdoc>
  1024. [
  1025. DefaultValue(""),
  1026. ResCategoryAttribute(Res.DataCategory_Data),
  1027. ResDescriptionAttribute(Res.DataTableDisplayExpressionDescr)
  1028. ]
  1029. public string DisplayExpression {
  1030. get {
  1031. return DisplayExpressionInternal;
  1032. }
  1033. set {
  1034. if (value != null && value.Length > 0) {
  1035. this.displayExpression = new DataExpression(this, value);
  1036. }
  1037. else {
  1038. this.displayExpression = null;
  1039. }
  1040. }
  1041. }
  1042. internal string DisplayExpressionInternal {
  1043. get {
  1044. return(displayExpression != null ? displayExpression.Expression : "");
  1045. }
  1046. }
  1047. internal bool EnforceConstraints {
  1048. get {
  1049. if (SuspendEnforceConstraints) {
  1050. return false;
  1051. }
  1052. if (dataSet != null)
  1053. return dataSet.EnforceConstraints;
  1054. return this.enforceConstraints;
  1055. }
  1056. set {
  1057. if (dataSet == null && this.enforceConstraints != value) {
  1058. if (value)
  1059. EnableConstraints();
  1060. this.enforceConstraints = value;
  1061. }
  1062. }
  1063. }
  1064. internal bool SuspendEnforceConstraints {
  1065. get {
  1066. return _suspendEnforceConstraints ;
  1067. }
  1068. set {
  1069. _suspendEnforceConstraints = value;
  1070. }
  1071. }
  1072. internal void EnableConstraints()
  1073. {
  1074. bool errors = false;
  1075. foreach (Constraint constr in Constraints)
  1076. {
  1077. if (constr is UniqueConstraint)
  1078. errors |= constr.IsConstraintViolated();
  1079. }
  1080. foreach (DataColumn column in Columns) {
  1081. if (!column.AllowDBNull) {
  1082. errors |= column.IsNotAllowDBNullViolated();
  1083. }
  1084. if (column.MaxLength >= 0) {
  1085. errors |= column.IsMaxLengthViolated();
  1086. }
  1087. }
  1088. if (errors) {
  1089. this.EnforceConstraints = false;
  1090. throw ExceptionBuilder.EnforceConstraint();
  1091. }
  1092. }
  1093. /// <devdoc>
  1094. /// <para>Gets the collection of customized user information.</para>
  1095. /// </devdoc>
  1096. [
  1097. ResCategoryAttribute(Res.DataCategory_Data),
  1098. Browsable(false),
  1099. ResDescriptionAttribute(Res.ExtendedPropertiesDescr)
  1100. ]
  1101. public PropertyCollection ExtendedProperties {
  1102. get {
  1103. if (extendedProperties == null) {
  1104. extendedProperties = new PropertyCollection();
  1105. }
  1106. return extendedProperties;
  1107. }
  1108. }
  1109. internal IFormatProvider FormatProvider {
  1110. get {
  1111. // used for Formating/Parsing
  1112. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemglobalizationcultureinfoclassisneutralculturetopic.asp
  1113. if (null == _formatProvider) {
  1114. CultureInfo culture = Locale;
  1115. if (culture.IsNeutralCulture) {
  1116. culture = CultureInfo.InvariantCulture;
  1117. }
  1118. _formatProvider = (IFormatProvider)culture;
  1119. }
  1120. return _formatProvider;
  1121. }
  1122. }
  1123. /// <devdoc>
  1124. /// <para>Gets a value indicating whether there are errors in any of the rows in any of
  1125. /// the tables of the <see cref='System.Data.DataSet'/> to which the table belongs.</para>
  1126. /// </devdoc>
  1127. [Browsable(false), ResDescriptionAttribute(Res.DataTableHasErrorsDescr)]
  1128. public bool HasErrors {
  1129. get {
  1130. for (int i = 0; i < Rows.Count; i++) {
  1131. if (Rows[i].HasErrors) {
  1132. return true;
  1133. }
  1134. }
  1135. return false;
  1136. }
  1137. }
  1138. /// <devdoc>
  1139. /// <para>Gets or sets the locale information used to compare strings within the table.</para>
  1140. /// <para>Also used for locale sensitive, case,kana,width insensitive column name lookups</para>
  1141. /// <para>Also used for converting values to and from string</para>
  1142. /// </devdoc>
  1143. [ResDescriptionAttribute(Res.DataTableLocaleDescr)]
  1144. public CultureInfo Locale {
  1145. get {
  1146. // used for Comparing not Formatting/Parsing
  1147. Debug.Assert(null != _culture, "null culture");
  1148. Debug.Assert(_cultureUserSet || (null == dataSet) || _culture.Equals(dataSet.Locale), "Locale mismatch");
  1149. return _culture;
  1150. }
  1151. set {
  1152. IntPtr hscp;
  1153. Bid.ScopeEnter(out hscp, "<ds.DataTable.set_Locale|API> %d#\n", ObjectID);
  1154. try {
  1155. bool userSet = true;
  1156. if (null == value) {
  1157. // reset Locale to inherit from DataSet
  1158. userSet = false;
  1159. value = (null != dataSet) ? dataSet.Locale : _culture;
  1160. }
  1161. if (_culture != value && !_culture.Equals(value)) {
  1162. bool flag = false;
  1163. bool exceptionThrown = false;
  1164. CultureInfo oldLocale = _culture;
  1165. bool oldUserSet = _cultureUserSet;
  1166. try {
  1167. _cultureUserSet = true;
  1168. SetLocaleValue(value, true, false);
  1169. if ((null == DataSet) || DataSet.ValidateLocaleConstraint()) {
  1170. flag = false;
  1171. SetLocaleValue(value, true, true);
  1172. flag = true;
  1173. }
  1174. }
  1175. catch {
  1176. exceptionThrown = true;
  1177. throw;
  1178. }
  1179. finally {
  1180. if (!flag) { // reset old locale if ValidationFailed or exception thrown
  1181. try {
  1182. SetLocaleValue(oldLocale, true, true);
  1183. }
  1184. catch(Exception e) { // failed to reset all indexes for all constraints
  1185. if (!Common.ADP.IsCatchableExceptionType(e)) {
  1186. throw;
  1187. }
  1188. Common.ADP.TraceExceptionWithoutRethrow(e);
  1189. }
  1190. _cultureUserSet = oldUserSet;
  1191. if (!exceptionThrown) {
  1192. throw ExceptionBuilder.CannotChangeCaseLocale(null);
  1193. }
  1194. }
  1195. }
  1196. SetLocaleValue(value, true, true);
  1197. }
  1198. _cultureUserSet = userSet;
  1199. }
  1200. finally{
  1201. Bid.ScopeLeave(ref hscp);
  1202. }
  1203. }
  1204. }
  1205. internal bool SetLocaleValue(CultureInfo culture, bool userSet, bool resetIndexes) {
  1206. Debug.Assert(null != culture, "SetLocaleValue: no locale");
  1207. if (userSet || resetIndexes || (!_cultureUserSet && !_culture.Equals(culture))) {
  1208. _culture = culture;
  1209. _compareInfo = null;
  1210. _formatProvider = null;
  1211. _hashCodeProvider = null;
  1212. foreach(DataColumn column in Columns) {
  1213. column._hashCode = GetSpecialHashCode(column.ColumnName);
  1214. }
  1215. if (resetIndexes) {
  1216. ResetIndexes();
  1217. foreach (Constraint constraint in Constraints) {
  1218. constraint.CheckConstraint();
  1219. }
  1220. }
  1221. return true;
  1222. }
  1223. return false;
  1224. }
  1225. internal bool ShouldSerializeLocale() {
  1226. // this method is used design-time scenarios via reflection
  1227. // by the property grid to show the Locale property in bold or not
  1228. // by the code dom for persisting the Locale property or not
  1229. // we always want the locale persisted if set by user or different the current thread if standalone table
  1230. // but that logic should by performed by the serializion code
  1231. return _cultureUserSet;
  1232. }
  1233. /// <devdoc>
  1234. /// <para>Gets or sets the initial starting size for this table.</para>
  1235. /// </devdoc>
  1236. [
  1237. DefaultValue(50),
  1238. ResCategoryAttribute(Res.DataCategory_Data),
  1239. ResDescriptionAttribute(Res.DataTableMinimumCapacityDescr)
  1240. ]
  1241. public int MinimumCapacity {
  1242. get {
  1243. return recordManager.MinimumCapacity;
  1244. }
  1245. set {
  1246. if (value != recordManager.MinimumCapacity) {
  1247. recordManager.MinimumCapacity = value;
  1248. }
  1249. }
  1250. }
  1251. internal int RecordCapacity {
  1252. get {
  1253. return recordManager.RecordCapacity;
  1254. }
  1255. }
  1256. internal int ElementColumnCount {
  1257. get {
  1258. return elementColumnCount;
  1259. }
  1260. set {
  1261. if ((value > 0) && (xmlText != null))
  1262. throw ExceptionBuilder.TableCannotAddToSimpleContent();
  1263. else elementColumnCount = value;
  1264. }
  1265. }
  1266. /// <devdoc>
  1267. /// <para>Gets the collection of parent relations for this <see cref='System.Data.DataTable'/>.</para>
  1268. /// </devdoc>
  1269. [
  1270. Browsable(false),
  1271. ResDescriptionAttribute(Res.DataTableParentRelationsDescr),
  1272. DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
  1273. ]
  1274. public DataRelationCollection ParentRelations {
  1275. get {
  1276. if (parentRelationsCollection == null)
  1277. parentRelationsCollection = new DataRelationCollection.DataTableRelationCollection(this, true);
  1278. return parentRelationsCollection;
  1279. }
  1280. }
  1281. internal bool MergingData {
  1282. get {
  1283. return mergingData;
  1284. }
  1285. set {
  1286. mergingData = value;
  1287. }
  1288. }
  1289. internal DataRelation[] NestedParentRelations {
  1290. get {
  1291. #if DEBUG
  1292. DataRelation[] nRel = FindNestedParentRelations();
  1293. Debug.Assert(nRel.Length == _nestedParentRelations.Length, "nestedParent cache is broken");
  1294. for(int i = 0; i < nRel.Length; i++) {
  1295. Debug.Assert(null != nRel[i], "null relation");
  1296. Debug.Assert(null != _nestedParentRelations[i], "null relation");
  1297. Debug.Assert(nRel[i] == _nestedParentRelations[i], "unequal relations");
  1298. }
  1299. #endif
  1300. return _nestedParentRelations;
  1301. }
  1302. }
  1303. internal bool SchemaLoading {
  1304. get {
  1305. return schemaLoading;
  1306. }
  1307. }
  1308. internal void CacheNestedParent() {
  1309. _nestedParentRelations = FindNestedParentRelations();
  1310. }
  1311. private DataRelation[] FindNestedParentRelations() {
  1312. List<DataRelation> nestedParents = null;
  1313. foreach(DataRelation relation in this.ParentRelations) {
  1314. if(relation.Nested) {
  1315. if (null == nestedParents) {
  1316. nestedParents = new List<DataRelation>();
  1317. }
  1318. nestedParents.Add(relation);
  1319. }
  1320. }
  1321. if ((null == nestedParents) || (nestedParents.Count == 0)) {
  1322. return EmptyArrayDataRelation;
  1323. }
  1324. return nestedParents.ToArray();
  1325. }
  1326. internal int NestedParentsCount {
  1327. get {
  1328. int count = 0;
  1329. foreach(DataRelation relation in this.ParentRelations) {
  1330. if(relation.Nested)
  1331. count++;
  1332. }
  1333. return count;
  1334. }
  1335. }
  1336. /// <devdoc>
  1337. /// <para>Gets or sets an array of columns that function as primary keys for the data
  1338. /// table.</para>
  1339. /// </devdoc>
  1340. [
  1341. TypeConverter(typeof(PrimaryKeyTypeConverter)),
  1342. ResDescriptionAttribute(Res.DataTablePrimaryKeyDescr),
  1343. ResCategoryAttribute(Res.DataCategory_Data),
  1344. Editor("Microsoft.VSDesigner.Data.Design.PrimaryKeyEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing)
  1345. ]
  1346. public DataColumn[] PrimaryKey {
  1347. get {
  1348. UniqueConstraint primayKeyConstraint = primaryKey;
  1349. if (null != primayKeyConstraint) {
  1350. Debug.Assert(2 <= primaryKey.ConstraintIndex.RefCount, "bad primaryKey index RefCount");
  1351. return primayKeyConstraint.Key.ToArray();
  1352. }
  1353. return zeroColumns;
  1354. }
  1355. set {
  1356. UniqueConstraint key = null;
  1357. UniqueConstraint existingKey = null;
  1358. // Loading with persisted property
  1359. if (fInitInProgress && value != null) {
  1360. delayedSetPrimaryKey = value;
  1361. return;
  1362. }
  1363. if ((value != null) && (value.Length != 0)) {
  1364. int count = 0;
  1365. for (int i = 0; i < value.Length; i++) {
  1366. if (value[i] != null)
  1367. count++;
  1368. else
  1369. break;
  1370. }
  1371. if (count != 0) {
  1372. DataColumn[] newValue = value;
  1373. if (count != value.Length) {
  1374. newValue = new DataColumn[count];
  1375. for (int i = 0; i < count; i++)
  1376. newValue[i] = value[i];
  1377. }
  1378. key = new UniqueConstraint(newValue);
  1379. if (key.Table != this)
  1380. throw ExceptionBuilder.TableForeignPrimaryKey();
  1381. }
  1382. }
  1383. if (key == primaryKey || (key != null && key.Equals(primaryKey)))
  1384. return;
  1385. // Use an existing UniqueConstraint that matches if one exists
  1386. if ((existingKey = (UniqueConstraint)Constraints.FindConstraint(key)) != null) {
  1387. key.ColumnsReference.CopyTo(existingKey.Key.ColumnsReference, 0);
  1388. key = existingKey;
  1389. }
  1390. UniqueConstraint oldKey = primaryKey;
  1391. primaryKey = null;
  1392. if (oldKey != null) {
  1393. oldKey.ConstraintIndex.RemoveRef();
  1394. // SQLBU 429176: if PrimaryKey is removed, reset LoadDataRow indexes
  1395. if (null != loadIndex) {
  1396. loadIndex.RemoveRef();
  1397. loadIndex = null;
  1398. }
  1399. if (null != loadIndexwithOriginalAdded) {
  1400. loadIndexwithOriginalAdded.RemoveRef();
  1401. loadIndexwithOriginalAdded = null;
  1402. }
  1403. if (null != loadIndexwithCurrentDeleted) {
  1404. loadIndexwithCurrentDeleted.RemoveRef();
  1405. loadIndexwithCurrentDeleted = null;
  1406. }
  1407. Constraints.Remove(oldKey);
  1408. }
  1409. // Add the key if there isnt an existing matching key in collection
  1410. if (key != null && existingKey == null)
  1411. Constraints.Add(key);
  1412. primaryKey = key;
  1413. Debug.Assert(Constraints.FindConstraint(primaryKey) == primaryKey, "PrimaryKey is not in ConstraintCollection");
  1414. _primaryIndex = (key != null) ? key.Key.GetIndexDesc() : zeroIndexField;
  1415. if (primaryKey != null) {
  1416. // must set index for DataView.Sort before setting AllowDBNull which can fail
  1417. key.ConstraintIndex.AddRef();
  1418. for (int i = 0; i < key.ColumnsReference.Length; i++)
  1419. key.ColumnsReference[i].AllowDBNull = false;
  1420. }
  1421. }
  1422. }
  1423. /// <devdoc>
  1424. /// <para>
  1425. /// Indicates whether the <see cref='System.Data.DataTable.PrimaryKey'/> property should be persisted.
  1426. /// </para>
  1427. /// </devdoc>
  1428. private bool ShouldSerializePrimaryKey() {
  1429. return(primaryKey != null);
  1430. }
  1431. /// <devdoc>
  1432. /// <para>
  1433. /// Resets the <see cref='System.Data.DataTable.PrimaryKey'/> property to its default state.
  1434. /// </para>
  1435. /// </devdoc>
  1436. private void ResetPrimaryKey() {
  1437. PrimaryKey = null;
  1438. }
  1439. /// <devdoc>
  1440. /// <para>Gets the collection of rows that belong to this table.</para>
  1441. /// </devdoc>
  1442. [Browsable(false), ResDescriptionAttribute(Res.DataTableRowsDescr)]
  1443. public DataRowCollection Rows {
  1444. get {
  1445. return rowCollection;
  1446. }
  1447. }
  1448. /// <devdoc>
  1449. /// <para>Gets or sets the name of the table.</para>
  1450. /// </devdoc>
  1451. [
  1452. RefreshProperties(RefreshProperties.All),
  1453. DefaultValue(""),
  1454. ResCategoryAttribute(Res.DataCategory_Data),
  1455. ResDescriptionAttribute(Res.DataTableTableNameDescr)
  1456. ]
  1457. public string TableName {
  1458. get {
  1459. return tableName;
  1460. }
  1461. set {
  1462. IntPtr hscp;
  1463. Bid.ScopeEnter(out hscp, "<ds.DataTable.set_TableName|API> %d#, value='%ls'\n", ObjectID, value);
  1464. try {
  1465. if (value == null) {
  1466. value = "";
  1467. }
  1468. CultureInfo currentLocale = this.Locale;
  1469. if (String.Compare(tableName, value, true, currentLocale) != 0) {
  1470. if (dataSet != null) {
  1471. if (value.Length == 0)
  1472. throw ExceptionBuilder.NoTableName();
  1473. if ((0 == String.Compare(value, dataSet.DataSetName, true, dataSet.Locale)) && !fNestedInDataset)
  1474. throw ExceptionBuilder.DatasetConflictingName(dataSet.DataSetName);
  1475. DataRelation[] nestedRelations = NestedParentRelations;
  1476. if (nestedRelations.Length == 0) {
  1477. dataSet.Tables.RegisterName(value, this.Namespace);
  1478. }
  1479. else {
  1480. foreach(DataRelation rel in nestedRelations) {
  1481. if (!rel.ParentTable.Columns.CanRegisterName(value)) {
  1482. throw ExceptionBuilder.CannotAddDuplicate2(value);
  1483. }
  1484. }
  1485. // if it cannot register the following line will throw exception
  1486. dataSet.Tables.RegisterName(value, this.Namespace);
  1487. foreach(DataRelation rel in nestedRelations) {
  1488. rel.ParentTable.Columns.RegisterColumnName(value, null);
  1489. rel.ParentTable.Columns.UnregisterName(this.TableName);
  1490. }
  1491. }
  1492. if (tableName.Length != 0) {
  1493. dataSet.Tables.UnregisterName(tableName);
  1494. }
  1495. }
  1496. RaisePropertyChanging("TableName");
  1497. tableName = value;
  1498. encodedTableName = null;
  1499. }
  1500. else if (String.Compare(tableName, value, false, currentLocale) != 0) {
  1501. RaisePropertyChanging("TableName");
  1502. tableName = value;
  1503. encodedTableName = null;
  1504. }
  1505. }
  1506. finally {
  1507. Bid.ScopeLeave(ref hscp);
  1508. }
  1509. }
  1510. }
  1511. internal string EncodedTableName {
  1512. get {
  1513. string encodedTblName = this.encodedTableName;
  1514. if (null == encodedTblName) {
  1515. encodedTblName = XmlConvert.EncodeLocalName( this.TableName );
  1516. this.encodedTableName = encodedTblName;
  1517. }
  1518. return encodedTblName;
  1519. }
  1520. }
  1521. private string GetInheritedNamespace(List<DataTable> visitedTables){
  1522. // if there is nested relation: ie: this table is nested child of a another table and
  1523. // if it is not self nested, return parent tables NS: Meanwhile make sure SQLBUDT 240219 is FIXED
  1524. DataRelation[] nestedRelations = NestedParentRelations;
  1525. if (nestedRelations.Length > 0) {
  1526. for(int i =0; i < nestedRelations.Length; i++) {
  1527. DataRelation rel = nestedRelations[i];
  1528. if (rel.ParentTable.tableNamespace != null) {
  1529. return rel.ParentTable.tableNamespace; // if parent table has a non-null NS, return it
  1530. }
  1531. }
  1532. // Assumption, in hierarchy of multiple nested relation, a child table with no NS, has DataRelation
  1533. // only and only with parent DataTable witin the same namespace
  1534. int j = 0;
  1535. while(j < nestedRelations.Length &&((nestedRelations[j].ParentTable == this)||(visitedTables.Contains(nestedRelations[j].ParentTable)))) {
  1536. j++;
  1537. }
  1538. if (j < nestedRelations.Length) {
  1539. DataTable parentTable = nestedRelations[j].ParentTable;
  1540. if (!visitedTables.Contains(parentTable))
  1541. visitedTables.Add(parentTable);
  1542. return parentTable.GetInheritedNamespace(visitedTables);// this is the same as return parentTable.Namespace
  1543. }
  1544. } // dont put else
  1545. if (DataSet != null) { // if it cant return from parent tables, return NS from dataset, if exists
  1546. return DataSet.Namespace;
  1547. }
  1548. else {
  1549. return string.Empty;
  1550. }
  1551. }
  1552. /// <devdoc>
  1553. /// <para>
  1554. /// Gets or sets the namespace for the <see cref='System.Data.DataTable'/>.
  1555. /// </para>
  1556. /// </devdoc>
  1557. [
  1558. ResCategoryAttribute(Res.DataCategory_Data),
  1559. ResDescriptionAttribute(Res.DataTableNamespaceDescr)
  1560. ]
  1561. public string Namespace {
  1562. get {
  1563. if (tableNamespace == null) {
  1564. return GetInheritedNamespace(new List<DataTable>());
  1565. }
  1566. return tableNamespace;
  1567. }
  1568. set {
  1569. IntPtr hscp;
  1570. Bid.ScopeEnter(out hscp, "<ds.DataTable.set_Namespace|API> %d#, value='%ls'\n", ObjectID, value);
  1571. try {
  1572. if(value != tableNamespace) {
  1573. if (dataSet != null) {
  1574. string realNamespace = (value == null ? GetInheritedNamespace(new List<DataTable>()) : value);
  1575. if (realNamespace != Namespace) {
  1576. // do this extra check only if the namespace is really going to change
  1577. // inheritance-wise.
  1578. if (dataSet.Tables.Contains( this.TableName, realNamespace, true, true))
  1579. throw ExceptionBuilder.DuplicateTableName2(this.TableName, realNamespace);
  1580. CheckCascadingNamespaceConflict(realNamespace);
  1581. }
  1582. }
  1583. CheckNamespaceValidityForNestedRelations(value);
  1584. DoRaiseNamespaceChange();
  1585. }
  1586. tableNamespace = value;
  1587. }
  1588. finally{
  1589. Bid.ScopeLeave(ref hscp);
  1590. }
  1591. }
  1592. }
  1593. internal bool IsNamespaceInherited() {
  1594. return (null == tableNamespace);
  1595. }
  1596. internal void CheckCascadingNamespaceConflict(string realNamespace){
  1597. foreach (DataRelation rel in ChildRelations)
  1598. if ((rel.Nested) && (rel.ChildTable != this) && (rel.ChildTable.tableNamespace == null)) {
  1599. DataTable childTable = rel.ChildTable;
  1600. if (dataSet.Tables.Contains( childTable.TableName, realNamespace, false, true))
  1601. throw ExceptionBuilder.DuplicateTableName2(this.TableName, realNamespace);
  1602. childTable.CheckCascadingNamespaceConflict(realNamespace);
  1603. }
  1604. }
  1605. internal void CheckNamespaceValidityForNestedRelations(string realNamespace){
  1606. foreach(DataRelation rel in ChildRelations) {
  1607. if (rel.Nested) {
  1608. if (realNamespace != null) {
  1609. rel.ChildTable.CheckNamespaceValidityForNestedParentRelations(realNamespace, this);
  1610. }
  1611. else{
  1612. rel.ChildTable.CheckNamespaceValidityForNestedParentRelations(GetInheritedNamespace(new List<DataTable>()), this);
  1613. }
  1614. }
  1615. }
  1616. if (realNamespace == null) { // this will affect this table if it has parent relations
  1617. this.CheckNamespaceValidityForNestedParentRelations(GetInheritedNamespace(new List<DataTable>()), this);
  1618. }
  1619. }
  1620. internal void CheckNamespaceValidityForNestedParentRelations(string ns, DataTable parentTable) {
  1621. foreach(DataRelation rel in ParentRelations){
  1622. if (rel.Nested) {
  1623. if (rel.ParentTable != parentTable && rel.ParentTable.Namespace != ns) {
  1624. throw ExceptionBuilder.InValidNestedRelation(this.TableName);
  1625. }
  1626. }
  1627. }
  1628. }
  1629. internal void DoRaiseNamespaceChange(){
  1630. RaisePropertyChanging("Namespace");
  1631. // raise column Namespace change
  1632. foreach (DataColumn col in Columns)
  1633. if (col._columnUri == null)
  1634. col.RaisePropertyChanging("Namespace");
  1635. foreach (DataRelation rel in ChildRelations)
  1636. if ((rel.Nested) && (rel.ChildTable != this)) {
  1637. DataTable childTable = rel.ChildTable;
  1638. rel.ChildTable.DoRaiseNamespaceChange();
  1639. }
  1640. }
  1641. /// <devdoc>
  1642. /// <para>
  1643. /// Indicates whether the <see cref='System.Data.DataTable.Namespace'/> property should be persisted.
  1644. /// </para>
  1645. /// </devdoc>
  1646. private bool ShouldSerializeNamespace() {
  1647. return(tableNamespace != null);
  1648. }
  1649. /// <devdoc>
  1650. /// <para>
  1651. /// Resets the <see cref='System.Data.DataTable.Namespace'/> property to its default state.
  1652. /// </para>
  1653. /// </devdoc>
  1654. private void ResetNamespace() {
  1655. this.Namespace = null;
  1656. }
  1657. /// <devdoc>
  1658. /// <para>[To be supplied.]</para>
  1659. /// </devdoc>
  1660. virtual public void BeginInit() {
  1661. fInitInProgress = true;
  1662. }
  1663. /// <devdoc>
  1664. /// <para>[To be supplied.]</para>
  1665. /// </devdoc>
  1666. virtual public void EndInit() {
  1667. if (dataSet == null || !dataSet.fInitInProgress) {
  1668. Columns.FinishInitCollection();
  1669. Constraints.FinishInitConstraints();
  1670. foreach(DataColumn dc in Columns){
  1671. if (dc.Computed) {
  1672. dc.Expression = dc.Expression;
  1673. }
  1674. }
  1675. }
  1676. fInitInProgress = false; // [....] : 77890. It is must that we set off this flag after calling FinishInitxxx();
  1677. if (delayedSetPrimaryKey != null) {
  1678. PrimaryKey = delayedSetPrimaryKey;
  1679. delayedSetPrimaryKey = null;
  1680. }
  1681. if (delayedViews.Count > 0) {
  1682. foreach(DataView dv in delayedViews) {
  1683. dv.EndInit();
  1684. }
  1685. delayedViews.Clear();
  1686. }
  1687. OnInitialized();
  1688. }
  1689. /// <devdoc>
  1690. /// <para>[To be supplied.]</para>
  1691. /// </devdoc>
  1692. [
  1693. DefaultValue(""),
  1694. ResCategoryAttribute(Res.DataCategory_Data),
  1695. ResDescriptionAttribute(Res.DataTablePrefixDescr)
  1696. ]
  1697. public string Prefix {
  1698. get { return tablePrefix;}
  1699. set {
  1700. if (value == null) {
  1701. value = "";
  1702. }
  1703. Bid.Trace("<ds.DataTable.set_Prefix|API> %d#, value='%ls'\n", ObjectID, value);
  1704. if ((XmlConvert.DecodeName(value) == value) &&
  1705. (XmlConvert.EncodeName(value) != value))
  1706. throw ExceptionBuilder.InvalidPrefix(value);
  1707. tablePrefix = value;
  1708. }
  1709. }
  1710. internal DataColumn XmlText {
  1711. get {
  1712. return xmlText;
  1713. }
  1714. set {
  1715. if (xmlText != value) {
  1716. if (xmlText != null) {
  1717. if (value != null) {
  1718. throw ExceptionBuilder.MultipleTextOnlyColumns();
  1719. }
  1720. Columns.Remove(xmlText);
  1721. }
  1722. else {
  1723. Debug.Assert(value != null, "Value shoud not be null ??");
  1724. Debug.Assert(value.ColumnMapping == MappingType.SimpleContent, "should be text node here");
  1725. if (value != Columns[value.ColumnName])
  1726. Columns.Add(value);
  1727. }
  1728. xmlText = value;
  1729. }
  1730. }
  1731. }
  1732. internal decimal MaxOccurs {
  1733. get {
  1734. return maxOccurs;
  1735. }
  1736. set {
  1737. maxOccurs = value;
  1738. }
  1739. }
  1740. internal decimal MinOccurs {
  1741. get {
  1742. return minOccurs;
  1743. }
  1744. set {
  1745. minOccurs = value;
  1746. }
  1747. }
  1748. internal void SetKeyValues(DataKey key, object[] keyValues, int record) {
  1749. for (int i = 0; i < keyValues.Length; i++) {
  1750. key.ColumnsReference[i][record] = keyValues[i];
  1751. }
  1752. }
  1753. internal DataRow FindByIndex(Index ndx, object[] key) {
  1754. Range range = ndx.FindRecords(key);
  1755. if (range.IsNull) {
  1756. return null;
  1757. }
  1758. return this.recordManager[ndx.GetRecord(range.Min)];
  1759. }
  1760. internal DataRow FindMergeTarget(DataRow row, DataKey key, Index ndx) {
  1761. DataRow targetRow = null;
  1762. // Primary key match
  1763. if (key.HasValue) {
  1764. Debug.Assert(ndx != null);
  1765. int findRecord = (row.oldRecord == -1) ? row.newRecord : row.oldRecord;
  1766. object[] values = key.GetKeyValues(findRecord);
  1767. targetRow = FindByIndex(ndx, values);
  1768. }
  1769. return targetRow;
  1770. }
  1771. private void SetMergeRecords(DataRow row, int newRecord, int oldRecord, DataRowAction action) {
  1772. if (newRecord != -1) {
  1773. SetNewRecord(row, newRecord, action, true, true);
  1774. SetOldRecord(row, oldRecord);
  1775. }
  1776. else {
  1777. SetOldRecord(row, oldRecord);
  1778. if (row.newRecord != -1) {
  1779. Debug.Assert(action == DataRowAction.Delete, "Unexpected SetNewRecord action in merge function.");
  1780. SetNewRecord(row, newRecord, action, true, true);
  1781. }
  1782. }
  1783. }
  1784. internal DataRow MergeRow(DataRow row, DataRow targetRow, bool preserveChanges, Index idxSearch) {
  1785. if (targetRow == null) {
  1786. targetRow = this.NewEmptyRow();
  1787. targetRow.oldRecord = recordManager.ImportRecord(row.Table, row.oldRecord);
  1788. targetRow.newRecord = targetRow.oldRecord;
  1789. if(row.oldRecord != row.newRecord) {
  1790. targetRow.newRecord = recordManager.ImportRecord(row.Table, row.newRecord);
  1791. }
  1792. InsertRow(targetRow, -1);
  1793. }
  1794. else {
  1795. // SQLBU 500789: Record Manager corruption during Merge when target row in edit state
  1796. // the newRecord would be freed and overwrite tempRecord (which became the newRecord)
  1797. // this would leave the DataRow referencing a freed record and leaking memory for the now lost record
  1798. int proposedRecord = targetRow.tempRecord; // by saving off the tempRecord, EndEdit won't free newRecord
  1799. targetRow.tempRecord = -1;
  1800. try {
  1801. DataRowState saveRowState = targetRow.RowState;
  1802. int saveIdxRecord = (saveRowState == DataRowState.Added) ? targetRow.newRecord : saveIdxRecord = targetRow.oldRecord;
  1803. int newRecord;
  1804. int oldRecord;
  1805. if (targetRow.RowState == DataRowState.Unchanged && row.RowState == DataRowState.Unchanged) {
  1806. // unchanged row merging with unchanged row
  1807. oldRecord = targetRow.oldRecord;
  1808. newRecord = (preserveChanges) ? recordManager.CopyRecord(this, oldRecord, -1) : targetRow.newRecord;
  1809. oldRecord = recordManager.CopyRecord(row.Table, row.oldRecord, targetRow.oldRecord);
  1810. SetMergeRecords(targetRow, newRecord, oldRecord, DataRowAction.Change);
  1811. }
  1812. else if (row.newRecord == -1) {
  1813. // Incoming row is deleted
  1814. oldRecord = targetRow.oldRecord;
  1815. if (preserveChanges) {
  1816. newRecord = (targetRow.RowState == DataRowState.Unchanged)? recordManager.CopyRecord(this, oldRecord, -1) : targetRow.newRecord;
  1817. }
  1818. else
  1819. newRecord = -1;
  1820. oldRecord = recordManager.CopyRecord(row.Table, row.oldRecord, oldRecord);
  1821. // Change index record, need to update index
  1822. if (saveIdxRecord != ((saveRowState == DataRowState.Added) ? newRecord : oldRecord)) {
  1823. SetMergeRecords(targetRow, newRecord, oldRecord, (newRecord == -1) ? DataRowAction.Delete : DataRowAction.Change);
  1824. idxSearch.Reset();
  1825. saveIdxRecord = ((saveRowState == DataRowState.Added) ? newRecord : oldRecord);
  1826. } else {
  1827. SetMergeRecords(targetRow, newRecord, oldRecord, (newRecord == -1) ? DataRowAction.Delete : DataRowAction.Change);
  1828. }
  1829. }
  1830. else {
  1831. // incoming row is added, modified or unchanged (targetRow is not unchanged)
  1832. oldRecord = targetRow.oldRecord;
  1833. newRecord = targetRow.newRecord;
  1834. if (targetRow.RowState == DataRowState.Unchanged) {
  1835. newRecord = recordManager.CopyRecord(this, oldRecord, -1);
  1836. }
  1837. oldRecord = recordManager.CopyRecord(row.Table, row.oldRecord, oldRecord);
  1838. if (!preserveChanges) {
  1839. newRecord = recordManager.CopyRecord(row.Table, row.newRecord, newRecord);
  1840. }
  1841. SetMergeRecords(targetRow, newRecord, oldRecord, DataRowAction.Change);
  1842. }
  1843. if (saveRowState == DataRowState.Added && targetRow.oldRecord != -1)
  1844. idxSearch.Reset();
  1845. Debug.Assert(saveIdxRecord == ((saveRowState == DataRowState.Added) ? targetRow.newRecord : targetRow.oldRecord), "oops, you change index record without noticing it");
  1846. }
  1847. finally {
  1848. targetRow.tempRecord = proposedRecord;
  1849. }
  1850. }
  1851. // Merge all errors
  1852. if (row.HasErrors) {
  1853. if (targetRow.RowError.Length == 0) {
  1854. targetRow.RowError = row.RowError;
  1855. } else {
  1856. targetRow.RowError += " ]:[ " + row.RowError;
  1857. }
  1858. DataColumn[] cols = row.GetColumnsInError();
  1859. for (int i = 0; i < cols.Length; i++) {
  1860. DataColumn col = targetRow.Table.Columns[cols[i].ColumnName];
  1861. targetRow.SetColumnError(col, row.GetColumnError(cols[i]));
  1862. }
  1863. }else {
  1864. if (!preserveChanges) {
  1865. targetRow.ClearErrors();
  1866. }
  1867. }
  1868. return targetRow;
  1869. }
  1870. /// <devdoc>
  1871. /// <para>Commits all the changes made to this table since the last time <see cref='System.Data.DataTable.AcceptChanges'/> was called.</para>
  1872. /// </devdoc>
  1873. public void AcceptChanges() {
  1874. IntPtr hscp;
  1875. Bid.ScopeEnter(out hscp, "<ds.DataTable.AcceptChanges|API> %d#\n", ObjectID);
  1876. try {
  1877. DataRow[] oldRows = new DataRow[Rows.Count];
  1878. Rows.CopyTo(oldRows, 0);
  1879. // delay updating of indexes until after all
  1880. // AcceptChange calls have been completed
  1881. SuspendIndexEvents();
  1882. try {
  1883. for (int i = 0; i < oldRows.Length; ++i) {
  1884. if (oldRows[i].rowID != -1) {
  1885. oldRows[i].AcceptChanges();
  1886. }
  1887. }
  1888. }
  1889. finally {
  1890. RestoreIndexEvents(false);
  1891. }
  1892. }
  1893. finally{
  1894. Bid.ScopeLeave(ref hscp);
  1895. }
  1896. }
  1897. // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
  1898. [MethodImpl(MethodImplOptions.NoInlining)]
  1899. protected virtual DataTable CreateInstance() {
  1900. return (DataTable) Activator.CreateInstance(this.GetType(), true);
  1901. }
  1902. public virtual DataTable Clone() {
  1903. return Clone(null);
  1904. }
  1905. internal DataTable Clone(DataSet cloneDS) {
  1906. IntPtr hscp;
  1907. Bid.ScopeEnter(out hscp, "<ds.DataTable.Clone|INFO> %d#, cloneDS=%d\n", ObjectID, (cloneDS != null) ? cloneDS.ObjectID : 0);
  1908. try {
  1909. DataTable clone = CreateInstance();
  1910. if (clone.Columns.Count > 0) // [....] : To clean up all the schema in strong typed dataset.
  1911. clone.Reset();
  1912. return CloneTo(clone, cloneDS, false);
  1913. }
  1914. finally {
  1915. Bid.ScopeLeave(ref hscp);
  1916. }
  1917. }
  1918. private DataTable IncrementalCloneTo (DataTable sourceTable, DataTable targetTable) {
  1919. foreach(DataColumn dc in sourceTable.Columns) {
  1920. if (targetTable.Columns[dc.ColumnName] == null) {
  1921. targetTable.Columns.Add(dc.Clone());
  1922. }
  1923. }
  1924. return targetTable;
  1925. }
  1926. private DataTable CloneHierarchy (DataTable sourceTable, DataSet ds, Hashtable visitedMap) {
  1927. if (visitedMap == null)
  1928. visitedMap = new Hashtable();
  1929. if (visitedMap.Contains(sourceTable))
  1930. return ((DataTable)visitedMap[sourceTable]);
  1931. DataTable destinationTable = ds.Tables[sourceTable.TableName, sourceTable.Namespace];
  1932. if ((destinationTable != null && destinationTable.Columns.Count > 0)) {
  1933. destinationTable = IncrementalCloneTo(sourceTable,destinationTable);
  1934. // get extra columns from source into destination , increamental read
  1935. }
  1936. else {
  1937. if (destinationTable == null) {
  1938. destinationTable = new DataTable();
  1939. // fxcop: new DataTable values for CaseSensitive, Locale, Namespace will come from CloneTo
  1940. ds.Tables.Add(destinationTable);
  1941. }
  1942. destinationTable = sourceTable.CloneTo(destinationTable, ds, true);
  1943. }
  1944. visitedMap[sourceTable] = destinationTable;
  1945. // start cloning relation
  1946. foreach( DataRelation r in sourceTable.ChildRelations ) {
  1947. DataTable childTable = CloneHierarchy((DataTable)r.ChildTable, ds, visitedMap);
  1948. }
  1949. return destinationTable;
  1950. }
  1951. private DataTable CloneTo(DataTable clone, DataSet cloneDS, bool skipExpressionColumns) {
  1952. // we do clone datatables while we do readxmlschema, so we do not want to clone columnexpressions if we call this from ReadXmlSchema
  1953. // it will cause exception to be thrown in cae expression refers to a table that is not in hirerachy or not created yet
  1954. Debug.Assert(clone != null, "The table passed in has to be newly created empty DataTable.");
  1955. // set All properties
  1956. clone.tableName = tableName;
  1957. clone.tableNamespace = tableNamespace;
  1958. clone.tablePrefix = tablePrefix;
  1959. clone.fNestedInDataset = fNestedInDataset;
  1960. clone._culture = _culture;
  1961. clone._cultureUserSet = _cultureUserSet;
  1962. clone._compareInfo = _compareInfo;
  1963. clone._compareFlags = _compareFlags;
  1964. clone._formatProvider = _formatProvider;
  1965. clone._hashCodeProvider = _hashCodeProvider;
  1966. clone._caseSensitive = _caseSensitive;
  1967. clone._caseSensitiveUserSet = _caseSensitiveUserSet;
  1968. clone.displayExpression = displayExpression;
  1969. clone.typeName = typeName; //[....]
  1970. clone.repeatableElement = repeatableElement; //[....]
  1971. clone.MinimumCapacity = MinimumCapacity;
  1972. clone.RemotingFormat = RemotingFormat;
  1973. // clone.SerializeHierarchy = SerializeHierarchy;
  1974. // add all columns
  1975. DataColumnCollection clmns = this.Columns;
  1976. for (int i = 0; i < clmns.Count; i++) {
  1977. clone.Columns.Add(clmns[i].Clone());
  1978. }
  1979. // add all expressions if Clone is invoked only on DataTable otherwise DataSet.Clone will assign expressions after creating all relationships.
  1980. if (!skipExpressionColumns && cloneDS == null) {
  1981. for (int i = 0; i < clmns.Count; i++) {
  1982. clone.Columns[clmns[i].ColumnName].Expression = clmns[i].Expression;
  1983. }
  1984. }
  1985. // Create PrimaryKey
  1986. DataColumn[] pkey = PrimaryKey;
  1987. if (pkey.Length > 0) {
  1988. DataColumn[] key = new DataColumn[pkey.Length];
  1989. for (int i = 0; i < pkey.Length; i++) {
  1990. key[i] = clone.Columns[pkey[i].Ordinal];
  1991. }
  1992. clone.PrimaryKey = key;
  1993. }
  1994. // now clone all unique constraints
  1995. // Rename first
  1996. for (int j = 0; j < Constraints.Count; j++) {
  1997. ForeignKeyConstraint foreign = Constraints[j] as ForeignKeyConstraint;
  1998. UniqueConstraint unique = Constraints[j] as UniqueConstraint;
  1999. if (foreign != null) {
  2000. if (foreign.Table == foreign.RelatedTable) {
  2001. ForeignKeyConstraint clonedConstraint = foreign.Clone(clone);
  2002. Constraint oldConstraint = clone.Constraints.FindConstraint(clonedConstraint);
  2003. if (oldConstraint != null) {
  2004. oldConstraint.ConstraintName = Constraints[j].ConstraintName;
  2005. }
  2006. }
  2007. }
  2008. else if (unique != null) {
  2009. UniqueConstraint clonedConstraint = unique.Clone(clone);
  2010. Constraint oldConstraint = clone.Constraints.FindConstraint(clonedConstraint);
  2011. if (oldConstraint != null) {
  2012. oldConstraint.ConstraintName = Constraints[j].ConstraintName;
  2013. foreach (Object key in clonedConstraint.ExtendedProperties.Keys) {
  2014. oldConstraint.ExtendedProperties[key] = clonedConstraint.ExtendedProperties[key];
  2015. }
  2016. }
  2017. }
  2018. }
  2019. // then add
  2020. for (int j = 0; j < Constraints.Count; j++) {
  2021. if (! clone.Constraints.Contains(Constraints[j].ConstraintName, true)) {
  2022. ForeignKeyConstraint foreign = Constraints[j] as ForeignKeyConstraint;
  2023. UniqueConstraint unique = Constraints[j] as UniqueConstraint;
  2024. if (foreign != null) {
  2025. if (foreign.Table == foreign.RelatedTable) {
  2026. ForeignKeyConstraint newforeign = foreign.Clone(clone);
  2027. if (newforeign != null) { // we cant make sure that we recieve a cloned FKC,since it depends if table and relatedtable be the same
  2028. clone.Constraints.Add(newforeign);
  2029. }
  2030. }
  2031. }
  2032. else if (unique != null) {
  2033. clone.Constraints.Add(unique.Clone(clone));
  2034. }
  2035. }
  2036. }
  2037. // ...Extended Properties...
  2038. if (this.extendedProperties != null) {
  2039. foreach(Object key in this.extendedProperties.Keys) {
  2040. clone.ExtendedProperties[key]=this.extendedProperties[key];
  2041. }
  2042. }
  2043. return clone;
  2044. }
  2045. public DataTable Copy(){
  2046. IntPtr hscp;
  2047. Bid.ScopeEnter(out hscp, "<ds.DataTable.Copy|API> %d#\n", ObjectID);
  2048. try {
  2049. DataTable destTable = this.Clone();
  2050. foreach (DataRow row in Rows)
  2051. CopyRow(destTable, row);
  2052. return destTable;
  2053. }
  2054. finally {
  2055. Bid.ScopeLeave(ref hscp);
  2056. }
  2057. }
  2058. /// <devdoc>
  2059. /// <para>Occurs when a value has been submitted for this column.</para>
  2060. /// </devdoc>
  2061. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableColumnChangingDescr)]
  2062. public event DataColumnChangeEventHandler ColumnChanging {
  2063. add {
  2064. Bid.Trace("<ds.DataTable.add_ColumnChanging|API> %d#\n", ObjectID);
  2065. onColumnChangingDelegate += value;
  2066. }
  2067. remove {
  2068. Bid.Trace("<ds.DataTable.remove_ColumnChanging|API> %d#\n", ObjectID);
  2069. onColumnChangingDelegate -= value;
  2070. }
  2071. }
  2072. /// <devdoc>
  2073. /// <para>[To be supplied.]</para>
  2074. /// </devdoc>
  2075. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableColumnChangedDescr)]
  2076. public event DataColumnChangeEventHandler ColumnChanged {
  2077. add {
  2078. Bid.Trace("<ds.DataTable.add_ColumnChanged|API> %d#\n", ObjectID);
  2079. onColumnChangedDelegate += value;
  2080. }
  2081. remove {
  2082. Bid.Trace("<ds.DataTable.remove_ColumnChanged|API> %d#\n", ObjectID);
  2083. onColumnChangedDelegate -= value;
  2084. }
  2085. }
  2086. [
  2087. ResCategoryAttribute(Res.DataCategory_Action),
  2088. ResDescriptionAttribute(Res.DataSetInitializedDescr)
  2089. ]
  2090. public event System.EventHandler Initialized {
  2091. add {
  2092. onInitialized += value;
  2093. }
  2094. remove {
  2095. onInitialized -= value;
  2096. }
  2097. }
  2098. internal event PropertyChangedEventHandler PropertyChanging {
  2099. add {
  2100. Bid.Trace("<ds.DataTable.add_PropertyChanging|INFO> %d#\n", ObjectID);
  2101. onPropertyChangingDelegate += value;
  2102. }
  2103. remove {
  2104. Bid.Trace("<ds.DataTable.remove_PropertyChanging|INFO> %d#\n", ObjectID);
  2105. onPropertyChangingDelegate -= value;
  2106. }
  2107. }
  2108. /// <devdoc>
  2109. /// <para>
  2110. /// Occurs after a row in the table has been successfully edited.
  2111. /// </para>
  2112. /// </devdoc>
  2113. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableRowChangedDescr)]
  2114. public event DataRowChangeEventHandler RowChanged {
  2115. add {
  2116. Bid.Trace("<ds.DataTable.add_RowChanged|API> %d#\n", ObjectID);
  2117. onRowChangedDelegate += value;
  2118. }
  2119. remove {
  2120. Bid.Trace("<ds.DataTable.remove_RowChanged|API> %d#\n", ObjectID);
  2121. onRowChangedDelegate -= value;
  2122. }
  2123. }
  2124. /// <devdoc>
  2125. /// <para>
  2126. /// Occurs when the <see cref='System.Data.DataRow'/> is changing.
  2127. /// </para>
  2128. /// </devdoc>
  2129. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableRowChangingDescr)]
  2130. public event DataRowChangeEventHandler RowChanging {
  2131. add {
  2132. Bid.Trace("<ds.DataTable.add_RowChanging|API> %d#\n", ObjectID);
  2133. onRowChangingDelegate += value;
  2134. }
  2135. remove {
  2136. Bid.Trace("<ds.DataTable.remove_RowChanging|API> %d#\n", ObjectID);
  2137. onRowChangingDelegate -= value;
  2138. }
  2139. }
  2140. /// <devdoc>
  2141. /// <para>
  2142. /// Occurs before a row in the table is
  2143. /// about to be deleted.
  2144. /// </para>
  2145. /// </devdoc>
  2146. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableRowDeletingDescr)]
  2147. public event DataRowChangeEventHandler RowDeleting {
  2148. add {
  2149. Bid.Trace("<ds.DataTable.add_RowDeleting|API> %d#\n", ObjectID);
  2150. onRowDeletingDelegate += value;
  2151. }
  2152. remove {
  2153. Bid.Trace("<ds.DataTable.remove_RowDeleting|API> %d#\n", ObjectID);
  2154. onRowDeletingDelegate -= value;
  2155. }
  2156. }
  2157. /// <devdoc>
  2158. /// <para>
  2159. /// Occurs after a row in the
  2160. /// table has been deleted.
  2161. /// </para>
  2162. /// </devdoc>
  2163. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableRowDeletedDescr)]
  2164. public event DataRowChangeEventHandler RowDeleted {
  2165. add {
  2166. Bid.Trace("<ds.DataTable.add_RowDeleted|API> %d#\n", ObjectID);
  2167. onRowDeletedDelegate += value;
  2168. }
  2169. remove {
  2170. Bid.Trace("<ds.DataTable.remove_RowDeleted|API> %d#\n", ObjectID);
  2171. onRowDeletedDelegate -= value;
  2172. }
  2173. }
  2174. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableRowsClearingDescr)]
  2175. public event DataTableClearEventHandler TableClearing {
  2176. add {
  2177. Bid.Trace("<ds.DataTable.add_TableClearing|API> %d#\n", ObjectID);
  2178. onTableClearingDelegate += value;
  2179. }
  2180. remove {
  2181. Bid.Trace("<ds.DataTable.remove_TableClearing|API> %d#\n", ObjectID);
  2182. onTableClearingDelegate -= value;
  2183. }
  2184. }
  2185. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableRowsClearedDescr)]
  2186. public event DataTableClearEventHandler TableCleared {
  2187. add {
  2188. Bid.Trace("<ds.DataTable.add_TableCleared|API> %d#\n", ObjectID);
  2189. onTableClearedDelegate += value;
  2190. }
  2191. remove {
  2192. Bid.Trace("<ds.DataTable.remove_TableCleared|API> %d#\n", ObjectID);
  2193. onTableClearedDelegate -= value;
  2194. }
  2195. }
  2196. [ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataTableRowsNewRowDescr)]
  2197. public event DataTableNewRowEventHandler TableNewRow {
  2198. add {
  2199. onTableNewRowDelegate += value;
  2200. }
  2201. remove {
  2202. onTableNewRowDelegate -= value;
  2203. }
  2204. }
  2205. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  2206. public override ISite Site {
  2207. get {
  2208. return base.Site;
  2209. }
  2210. set {
  2211. ISite oldSite = Site;
  2212. if (value == null && oldSite != null) {
  2213. IContainer cont = oldSite.Container;
  2214. if (cont != null) {
  2215. for (int i = 0; i < Columns.Count; i++) {
  2216. if (Columns[i].Site != null) {
  2217. cont.Remove(Columns[i]);
  2218. }
  2219. }
  2220. }
  2221. }
  2222. base.Site = value;
  2223. }
  2224. }
  2225. internal DataRow AddRecords(int oldRecord, int newRecord) {
  2226. DataRow row;
  2227. if (oldRecord == -1 && newRecord == -1)
  2228. {
  2229. row = NewRow(-1);
  2230. AddRow(row);
  2231. }
  2232. else
  2233. {
  2234. row = NewEmptyRow();
  2235. row.oldRecord = oldRecord;
  2236. row.newRecord = newRecord;
  2237. InsertRow(row, -1);
  2238. }
  2239. return row;
  2240. }
  2241. internal void AddRow(DataRow row) {
  2242. AddRow(row, -1);
  2243. }
  2244. internal void AddRow(DataRow row, int proposedID) {
  2245. InsertRow(row, proposedID, -1);
  2246. }
  2247. internal void InsertRow(DataRow row, int proposedID, int pos) {
  2248. InsertRow(row, proposedID, pos, /*fireEvent*/true);
  2249. }
  2250. internal void InsertRow(DataRow row, long proposedID, int pos, bool fireEvent) {
  2251. Exception deferredException = null;
  2252. if (row == null) {
  2253. throw ExceptionBuilder.ArgumentNull("row");
  2254. }
  2255. if (row.Table != this) {
  2256. throw ExceptionBuilder.RowAlreadyInOtherCollection();
  2257. }
  2258. if (row.rowID != -1) {
  2259. throw ExceptionBuilder.RowAlreadyInTheCollection();
  2260. }
  2261. row.BeginEdit(); // ensure something's there.
  2262. int record = row.tempRecord;
  2263. row.tempRecord = -1;
  2264. if (proposedID == -1) {
  2265. proposedID = this.nextRowID;
  2266. }
  2267. bool rollbackOnException;
  2268. if (rollbackOnException = (nextRowID <= proposedID)) { // WebData 109005
  2269. nextRowID = checked(proposedID + 1);
  2270. }
  2271. try {
  2272. try {
  2273. row.rowID = proposedID;
  2274. // this method may cause DataView.OnListChanged in which another row may be added
  2275. SetNewRecordWorker(row, record, DataRowAction.Add, false, false, pos, fireEvent, out deferredException); // now we do add the row to collection before OnRowChanged (RaiseRowChanged)
  2276. }
  2277. catch {
  2278. if (rollbackOnException && (nextRowID == proposedID+1)) {
  2279. nextRowID = proposedID;
  2280. }
  2281. row.rowID = -1;
  2282. row.tempRecord = record;
  2283. throw;
  2284. }
  2285. // since expression evaluation occurred in SetNewRecordWorker, there may have been a problem that
  2286. // was deferred to this point. If so, throw now since row has already been added.
  2287. if (deferredException != null)
  2288. throw deferredException;
  2289. if (EnforceConstraints && !inLoad ) { // if we are evaluating expression, we need to validate constraints
  2290. int columnCount = columnCollection.Count;
  2291. for (int i = 0; i < columnCount; ++i) {
  2292. DataColumn column = columnCollection[i];
  2293. if (column.Computed) {
  2294. column.CheckColumnConstraint(row, DataRowAction.Add);
  2295. }
  2296. }
  2297. }
  2298. }
  2299. finally {
  2300. row.ResetLastChangedColumn();// if expression is evaluated while adding, before return, we want to clear it
  2301. }
  2302. }
  2303. internal void CheckNotModifying(DataRow row) {
  2304. if (row.tempRecord != -1) {
  2305. row.EndEdit();
  2306. //throw ExceptionBuilder.ModifyingRow();
  2307. }
  2308. }
  2309. /// <devdoc>
  2310. /// <para>
  2311. /// Clears the table of all data.</para>
  2312. /// </devdoc>
  2313. public void Clear() {
  2314. Clear(true);
  2315. }
  2316. internal void Clear(bool clearAll) {
  2317. IntPtr hscp;
  2318. Bid.ScopeEnter(out hscp, "<ds.DataTable.Clear|INFO> %d#, clearAll=%d{bool}\n", ObjectID, clearAll);
  2319. try {
  2320. Debug.Assert(null == rowDiffId, "wasn't previously cleared");
  2321. rowDiffId = null;
  2322. if (dataSet != null)
  2323. dataSet.OnClearFunctionCalled(this);
  2324. bool shouldFireClearEvents = (this.Rows.Count != 0); // if Rows is already empty, this is noop
  2325. DataTableClearEventArgs e = null;
  2326. if (shouldFireClearEvents) {
  2327. e = new DataTableClearEventArgs (this);
  2328. OnTableClearing(e);
  2329. }
  2330. if (dataSet != null && dataSet.EnforceConstraints) {
  2331. for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(dataSet, this); constraints.GetNext();) {
  2332. ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint();
  2333. constraint.CheckCanClearParentTable(this);
  2334. }
  2335. }
  2336. recordManager.Clear(clearAll);
  2337. // SQLBU 415729: Serious performance issue when calling Clear()
  2338. // this improves performance by iterating over rows instead of computing by index
  2339. foreach(DataRow row in Rows) {
  2340. row.oldRecord = -1;
  2341. row.newRecord = -1;
  2342. row.tempRecord = -1;
  2343. row.rowID = -1;
  2344. row.RBTreeNodeId = 0;
  2345. }
  2346. Rows.ArrayClear();
  2347. ResetIndexes();
  2348. if (shouldFireClearEvents) {
  2349. OnTableCleared(e);
  2350. }
  2351. // SQLBU 501916 - DataTable internal index is corrupted:'5'
  2352. foreach(DataColumn column in Columns) {
  2353. EvaluateDependentExpressions(column);
  2354. }
  2355. }
  2356. finally {
  2357. Bid.ScopeLeave(ref hscp);
  2358. }
  2359. }
  2360. internal void CascadeAll(DataRow row, DataRowAction action) {
  2361. if (DataSet != null && DataSet.fEnableCascading) {
  2362. for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(dataSet, this); constraints.GetNext();) {
  2363. constraints.GetForeignKeyConstraint().CheckCascade(row, action);
  2364. }
  2365. }
  2366. }
  2367. internal void CommitRow(DataRow row) {
  2368. // Fire Changing event
  2369. DataRowChangeEventArgs drcevent = OnRowChanging(null, row, DataRowAction.Commit);
  2370. if (!inDataLoad)
  2371. CascadeAll(row, DataRowAction.Commit);
  2372. SetOldRecord(row, row.newRecord);
  2373. OnRowChanged(drcevent, row, DataRowAction.Commit);
  2374. }
  2375. internal int Compare(string s1, string s2) {
  2376. return Compare(s1, s2, null);
  2377. }
  2378. internal int Compare(string s1, string s2, CompareInfo comparer) {
  2379. object obj1 = s1;
  2380. object obj2 = s2;
  2381. if (obj1 == obj2)
  2382. return 0;
  2383. if (obj1 == null)
  2384. return -1;
  2385. if (obj2 == null)
  2386. return 1;
  2387. int leng1 = s1.Length;
  2388. int leng2 = s2.Length;
  2389. for (; leng1 > 0; leng1--) {
  2390. if (s1[leng1-1] != 0x20 && s1[leng1-1] != 0x3000) // 0x3000 is Ideographic Whitespace
  2391. break;
  2392. }
  2393. for (; leng2 > 0; leng2--) {
  2394. if (s2[leng2-1] != 0x20 && s2[leng2-1] != 0x3000)
  2395. break;
  2396. }
  2397. return (comparer ?? this.CompareInfo).Compare(s1, 0, leng1, s2, 0, leng2, _compareFlags);
  2398. }
  2399. internal int IndexOf(string s1, string s2) {
  2400. return CompareInfo.IndexOf(s1, s2, _compareFlags);
  2401. }
  2402. internal bool IsSuffix(string s1, string s2) {
  2403. return CompareInfo.IsSuffix(s1, s2, _compareFlags);
  2404. }
  2405. /// <devdoc>
  2406. /// <para>Computes the given expression on the current rows that pass the filter criteria.</para>
  2407. /// </devdoc>
  2408. public object Compute(string expression, string filter) {
  2409. DataRow[] rows = Select(filter, "", DataViewRowState.CurrentRows);
  2410. DataExpression expr = new DataExpression(this, expression);
  2411. return expr.Evaluate(rows);
  2412. }
  2413. bool System.ComponentModel.IListSource.ContainsListCollection {
  2414. get {
  2415. return false;
  2416. }
  2417. }
  2418. internal void CopyRow(DataTable table, DataRow row)
  2419. {
  2420. int oldRecord = -1, newRecord = -1;
  2421. if (row == null)
  2422. return;
  2423. if (row.oldRecord != -1) {
  2424. oldRecord = table.recordManager.ImportRecord(row.Table, row.oldRecord);
  2425. }
  2426. if (row.newRecord != -1) {
  2427. if (row.newRecord != row.oldRecord) {
  2428. newRecord = table.recordManager.ImportRecord(row.Table, row.newRecord);
  2429. }
  2430. else
  2431. newRecord = oldRecord;
  2432. }
  2433. DataRow targetRow = table.AddRecords(oldRecord, newRecord);
  2434. if (row.HasErrors) {
  2435. targetRow.RowError = row.RowError;
  2436. DataColumn[] cols = row.GetColumnsInError();
  2437. for (int i = 0; i < cols.Length; i++) {
  2438. DataColumn col = targetRow.Table.Columns[cols[i].ColumnName];
  2439. targetRow.SetColumnError(col, row.GetColumnError(cols[i]));
  2440. }
  2441. }
  2442. }
  2443. internal void DeleteRow(DataRow row) {
  2444. if (row.newRecord == -1) {
  2445. throw ExceptionBuilder.RowAlreadyDeleted();
  2446. }
  2447. // Store.PrepareForDelete(row);
  2448. SetNewRecord(row, -1, DataRowAction.Delete, false, true);
  2449. }
  2450. private void CheckPrimaryKey() {
  2451. if (primaryKey == null) throw ExceptionBuilder.TableMissingPrimaryKey();
  2452. }
  2453. internal DataRow FindByPrimaryKey(object[] values) {
  2454. CheckPrimaryKey();
  2455. return FindRow(primaryKey.Key, values);
  2456. }
  2457. internal DataRow FindByPrimaryKey(object value) {
  2458. CheckPrimaryKey();
  2459. return FindRow(primaryKey.Key, value);
  2460. }
  2461. private DataRow FindRow(DataKey key, object[] values) {
  2462. Index index = GetIndex(NewIndexDesc(key));
  2463. Range range = index.FindRecords(values);
  2464. if (range.IsNull)
  2465. return null;
  2466. return recordManager[index.GetRecord(range.Min)];
  2467. }
  2468. private DataRow FindRow(DataKey key, object value) {
  2469. Index index = GetIndex(NewIndexDesc(key));
  2470. Range range = index.FindRecords(value);
  2471. if (range.IsNull)
  2472. return null;
  2473. return recordManager[index.GetRecord(range.Min)];
  2474. }
  2475. internal string FormatSortString(IndexField[] indexDesc) {
  2476. StringBuilder builder = new StringBuilder();
  2477. foreach (IndexField field in indexDesc) {
  2478. if (0 < builder.Length) {
  2479. builder.Append(", ");
  2480. }
  2481. builder.Append(field.Column.ColumnName);
  2482. if (field.IsDescending) {
  2483. builder.Append(" DESC");
  2484. }
  2485. }
  2486. return builder.ToString();
  2487. }
  2488. internal void FreeRecord(ref int record) {
  2489. recordManager.FreeRecord(ref record);
  2490. }
  2491. public DataTable GetChanges() {
  2492. IntPtr hscp;
  2493. Bid.ScopeEnter(out hscp, "<ds.DataTable.GetChanges|API> %d#\n", ObjectID);
  2494. try {
  2495. DataTable dtChanges = this.Clone();
  2496. DataRow row = null;
  2497. for (int i = 0; i < Rows.Count; i++) {
  2498. row = Rows[i];
  2499. if (row.oldRecord != row.newRecord)
  2500. dtChanges.ImportRow(row);
  2501. }
  2502. if (dtChanges.Rows.Count == 0)
  2503. return null;
  2504. return dtChanges;
  2505. }
  2506. finally {
  2507. Bid.ScopeLeave(ref hscp);
  2508. }
  2509. }
  2510. public DataTable GetChanges(DataRowState rowStates)
  2511. {
  2512. IntPtr hscp;
  2513. Bid.ScopeEnter(out hscp, "<ds.DataTable.GetChanges|API> %d#, rowStates=%d{ds.DataRowState}\n", ObjectID, (int)rowStates);
  2514. try {
  2515. DataTable dtChanges = this.Clone();
  2516. DataRow row = null;
  2517. // check that rowStates is valid DataRowState
  2518. Debug.Assert(Enum.GetUnderlyingType(typeof(DataRowState)) == typeof(Int32), "Invalid DataRowState type");
  2519. for (int i = 0; i < Rows.Count; i++) {
  2520. row = Rows[i];
  2521. if ((row.RowState & rowStates) != 0)
  2522. dtChanges.ImportRow(row);
  2523. }
  2524. if (dtChanges.Rows.Count == 0)
  2525. return null;
  2526. return dtChanges;
  2527. }
  2528. finally {
  2529. Bid.ScopeLeave(ref hscp);
  2530. }
  2531. }
  2532. /// <devdoc>
  2533. /// <para>Returns an array of <see cref='System.Data.DataRow'/> objects that contain errors.</para>
  2534. /// </devdoc>
  2535. public DataRow[] GetErrors() {
  2536. List<DataRow> errorList = new List<DataRow>();
  2537. for (int i = 0; i < Rows.Count; i++) {
  2538. DataRow row = Rows[i];
  2539. if (row.HasErrors) {
  2540. errorList.Add(row);
  2541. }
  2542. }
  2543. DataRow[] temp = NewRowArray(errorList.Count);
  2544. errorList.CopyTo(temp);
  2545. return temp;
  2546. }
  2547. internal Index GetIndex(IndexField[] indexDesc) {
  2548. return GetIndex(indexDesc, DataViewRowState.CurrentRows, (IFilter)null);
  2549. }
  2550. internal Index GetIndex(string sort, DataViewRowState recordStates, IFilter rowFilter) {
  2551. return GetIndex(ParseSortString(sort), recordStates, rowFilter);
  2552. }
  2553. internal Index GetIndex(IndexField[] indexDesc, DataViewRowState recordStates, IFilter rowFilter) {
  2554. indexesLock.AcquireReaderLock(-1);
  2555. try {
  2556. for (int i = 0; i < indexes.Count; i++) {
  2557. Index index = indexes[i];
  2558. if (index != null) {
  2559. if (index.Equal(indexDesc, recordStates, rowFilter)) {
  2560. return index;
  2561. }
  2562. }
  2563. }
  2564. }
  2565. finally {
  2566. indexesLock.ReleaseReaderLock();
  2567. }
  2568. Index ndx = new Index(this, indexDesc, recordStates, rowFilter);
  2569. ndx.AddRef();
  2570. return ndx;
  2571. }
  2572. IList System.ComponentModel.IListSource.GetList() {
  2573. return DefaultView;
  2574. }
  2575. internal List<DataViewListener> GetListeners() {
  2576. return _dataViewListeners;
  2577. }
  2578. // We need a HashCodeProvider for Case, Kana and Width insensitive
  2579. internal int GetSpecialHashCode(string name) {
  2580. int i;
  2581. for (i = 0; (i < name.Length) && (0x3000 > name[i]); ++i);
  2582. if (name.Length == i) {
  2583. if (null == _hashCodeProvider) {
  2584. // it should use the CaseSensitive property, but V1 shipped this way
  2585. _hashCodeProvider = StringComparer.Create(Locale, true);
  2586. }
  2587. return _hashCodeProvider.GetHashCode(name);
  2588. }
  2589. else {
  2590. return 0;
  2591. }
  2592. }
  2593. public void ImportRow(DataRow row)
  2594. {
  2595. IntPtr hscp;
  2596. Bid.ScopeEnter(out hscp, "<ds.DataTable.ImportRow|API> %d#\n", ObjectID);
  2597. try {
  2598. int oldRecord = -1, newRecord = -1;
  2599. if (row == null)
  2600. return;
  2601. if (row.oldRecord != -1) {
  2602. oldRecord = recordManager.ImportRecord(row.Table, row.oldRecord);
  2603. }
  2604. if (row.newRecord != -1) { // row not deleted
  2605. if (row.RowState != DataRowState.Unchanged) { // not unchanged, it means Added or modified
  2606. newRecord = recordManager.ImportRecord(row.Table, row.newRecord);
  2607. }
  2608. else
  2609. newRecord = oldRecord;
  2610. }
  2611. if (oldRecord != -1 || newRecord != -1) {
  2612. DataRow targetRow = AddRecords(oldRecord, newRecord);
  2613. if (row.HasErrors) {
  2614. targetRow.RowError = row.RowError;
  2615. DataColumn[] cols = row.GetColumnsInError();
  2616. for (int i = 0; i < cols.Length; i++) {
  2617. DataColumn col = targetRow.Table.Columns[cols[i].ColumnName];
  2618. targetRow.SetColumnError(col, row.GetColumnError(cols[i]));
  2619. }
  2620. }
  2621. }
  2622. }
  2623. finally {
  2624. Bid.ScopeLeave(ref hscp);
  2625. }
  2626. }
  2627. internal void InsertRow(DataRow row, long proposedID) {
  2628. IntPtr hscp;
  2629. Bid.ScopeEnter(out hscp, "<ds.DataTable.InsertRow|INFO> %d#, row=%d\n", ObjectID, row.ObjectID);
  2630. try {
  2631. if (row.Table != this) {
  2632. throw ExceptionBuilder.RowAlreadyInOtherCollection();
  2633. }
  2634. if (row.rowID != -1) {
  2635. throw ExceptionBuilder.RowAlreadyInTheCollection();
  2636. }
  2637. if (row.oldRecord == -1 && row.newRecord == -1) {
  2638. throw ExceptionBuilder.RowEmpty();
  2639. }
  2640. if (proposedID == -1)
  2641. proposedID = nextRowID;
  2642. row.rowID = proposedID;
  2643. if (nextRowID <= proposedID)
  2644. nextRowID = checked(proposedID + 1);
  2645. DataRowChangeEventArgs drcevent = null;
  2646. if (row.newRecord != -1) {
  2647. row.tempRecord = row.newRecord;
  2648. row.newRecord = -1;
  2649. try {
  2650. drcevent = RaiseRowChanging(null, row, DataRowAction.Add, true);
  2651. }
  2652. catch {
  2653. row.tempRecord = -1;
  2654. throw;
  2655. }
  2656. row.newRecord = row.tempRecord;
  2657. row.tempRecord = -1;
  2658. }
  2659. if (row.oldRecord != -1)
  2660. recordManager[row.oldRecord] = row;
  2661. if (row.newRecord != -1)
  2662. recordManager[row.newRecord] = row;
  2663. Rows.ArrayAdd(row); // SQL BU Defect Tracking 247738, 323482 row should be in the
  2664. // collection when maintaining the indexes
  2665. if (row.RowState == DataRowState.Unchanged){ // how about row.oldRecord == row.newRecord both == -1
  2666. RecordStateChanged(row.oldRecord, DataViewRowState.None, DataViewRowState.Unchanged);
  2667. }
  2668. else {
  2669. RecordStateChanged(row.oldRecord, DataViewRowState.None, row.GetRecordState(row.oldRecord),
  2670. row.newRecord, DataViewRowState.None, row.GetRecordState(row.newRecord));
  2671. }
  2672. if (dependentColumns != null && dependentColumns.Count > 0)
  2673. EvaluateExpressions(row, DataRowAction.Add, null);
  2674. RaiseRowChanged(drcevent, row, DataRowAction.Add);
  2675. }
  2676. finally {
  2677. Bid.ScopeLeave(ref hscp);
  2678. }
  2679. }
  2680. private IndexField [] NewIndexDesc(DataKey key) {
  2681. Debug.Assert(key.HasValue);
  2682. IndexField[] indexDesc = key.GetIndexDesc();
  2683. IndexField[] newIndexDesc = new IndexField[indexDesc.Length];
  2684. Array.Copy(indexDesc, 0, newIndexDesc, 0, indexDesc.Length);
  2685. return newIndexDesc;
  2686. }
  2687. internal int NewRecord() {
  2688. return NewRecord(-1);
  2689. }
  2690. internal int NewUninitializedRecord() {
  2691. return recordManager.NewRecordBase();
  2692. }
  2693. internal int NewRecordFromArray(object[] value) {
  2694. int colCount = columnCollection.Count; // Perf: use the readonly columnCollection field directly
  2695. if (colCount < value.Length) {
  2696. throw ExceptionBuilder.ValueArrayLength();
  2697. }
  2698. int record = recordManager.NewRecordBase();
  2699. try {
  2700. for (int i = 0; i < value.Length; i++) {
  2701. if (null != value[i]) {
  2702. columnCollection[i][record] = value[i];
  2703. }
  2704. else {
  2705. columnCollection[i].Init(record); // Increase AutoIncrementCurrent
  2706. }
  2707. }
  2708. for (int i = value.Length; i < colCount; i++) {
  2709. columnCollection[i].Init(record);
  2710. }
  2711. return record;
  2712. }
  2713. catch (Exception e) {
  2714. //
  2715. if (Common.ADP.IsCatchableOrSecurityExceptionType (e)) {
  2716. FreeRecord(ref record); // WebData 104246
  2717. }
  2718. throw;
  2719. }
  2720. }
  2721. internal int NewRecord(int sourceRecord) {
  2722. int record = recordManager.NewRecordBase();
  2723. int count = columnCollection.Count;
  2724. if (-1 == sourceRecord) {
  2725. for (int i = 0; i < count; ++i) {
  2726. columnCollection[i].Init(record);
  2727. }
  2728. }
  2729. else {
  2730. for (int i = 0; i < count; ++i) {
  2731. columnCollection[i].Copy(sourceRecord, record);
  2732. }
  2733. }
  2734. return record;
  2735. }
  2736. internal DataRow NewEmptyRow() {
  2737. rowBuilder._record = -1;
  2738. DataRow dr = NewRowFromBuilder( rowBuilder );
  2739. if (dataSet != null) {
  2740. DataSet.OnDataRowCreated( dr );
  2741. }
  2742. return dr;
  2743. }
  2744. private DataRow NewUninitializedRow() {
  2745. DataRow dr = NewRow(NewUninitializedRecord());
  2746. return dr;
  2747. }
  2748. /// <devdoc>
  2749. /// <para>Creates a new <see cref='System.Data.DataRow'/>
  2750. /// with the same schema as the table.</para>
  2751. /// </devdoc>
  2752. public DataRow NewRow() {
  2753. DataRow dr = NewRow(-1);
  2754. NewRowCreated(dr); // this is the only API we want this event to be fired
  2755. return dr;
  2756. }
  2757. // Only initialize DataRelation mapping columns (approximately hidden columns)
  2758. internal DataRow CreateEmptyRow() {
  2759. DataRow row = this.NewUninitializedRow();
  2760. foreach( DataColumn c in this.Columns ) {
  2761. if (!XmlToDatasetMap.IsMappedColumn(c)) {
  2762. if (!c.AutoIncrement) {
  2763. if (c.AllowDBNull) {
  2764. row[c] = DBNull.Value;
  2765. }
  2766. else if(c.DefaultValue!=null){
  2767. row[c] = c.DefaultValue;
  2768. }
  2769. }
  2770. else {
  2771. c.Init(row.tempRecord);
  2772. }
  2773. }
  2774. }
  2775. return row;
  2776. }
  2777. private void NewRowCreated(DataRow row) {
  2778. if (null != onTableNewRowDelegate) {
  2779. DataTableNewRowEventArgs eventArg = new DataTableNewRowEventArgs(row);
  2780. OnTableNewRow(eventArg);
  2781. }
  2782. }
  2783. internal DataRow NewRow(int record) {
  2784. if (-1 == record) {
  2785. record = NewRecord(-1);
  2786. }
  2787. rowBuilder._record = record;
  2788. DataRow row = NewRowFromBuilder( rowBuilder );
  2789. recordManager[record] = row;
  2790. if (dataSet != null)
  2791. DataSet.OnDataRowCreated( row );
  2792. return row;
  2793. }
  2794. // This is what a subclassed dataSet overrides to create a new row.
  2795. protected virtual DataRow NewRowFromBuilder(DataRowBuilder builder) {
  2796. return new DataRow(builder);
  2797. }
  2798. /// <devdoc>
  2799. /// <para>Gets the row type.</para>
  2800. /// </devdoc>
  2801. protected virtual Type GetRowType() {
  2802. return typeof(DataRow);
  2803. }
  2804. // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
  2805. [MethodImpl(MethodImplOptions.NoInlining)]
  2806. protected internal DataRow[] NewRowArray(int size) {
  2807. if (IsTypedDataTable) {
  2808. if (0 == size) {
  2809. if (null == EmptyDataRowArray) {
  2810. EmptyDataRowArray = (DataRow[]) Array.CreateInstance(GetRowType(), 0);
  2811. }
  2812. return EmptyDataRowArray;
  2813. }
  2814. return (DataRow[]) Array.CreateInstance(GetRowType(), size);
  2815. }
  2816. else {
  2817. return ((0 == size) ? DataTable.zeroRows : new DataRow[size]);
  2818. }
  2819. }
  2820. internal bool NeedColumnChangeEvents {
  2821. get {
  2822. return (IsTypedDataTable || (null != onColumnChangingDelegate) || (null != onColumnChangedDelegate));
  2823. }
  2824. }
  2825. protected internal virtual void OnColumnChanging(DataColumnChangeEventArgs e) {
  2826. // intentionally allow exceptions to bubble up. We haven't committed anything yet.
  2827. Debug.Assert(e != null, "e should not be null");
  2828. if (onColumnChangingDelegate != null) {
  2829. Bid.Trace("<ds.DataTable.OnColumnChanging|INFO> %d#\n", ObjectID);
  2830. onColumnChangingDelegate(this, e);
  2831. }
  2832. }
  2833. protected internal virtual void OnColumnChanged(DataColumnChangeEventArgs e) {
  2834. Debug.Assert(e != null, "e should not be null");
  2835. if (onColumnChangedDelegate != null) {
  2836. Bid.Trace("<ds.DataTable.OnColumnChanged|INFO> %d#\n", ObjectID);
  2837. onColumnChangedDelegate(this, e);
  2838. }
  2839. }
  2840. protected virtual void OnPropertyChanging(PropertyChangedEventArgs pcevent) {
  2841. if (onPropertyChangingDelegate != null) {
  2842. Bid.Trace("<ds.DataTable.OnPropertyChanging|INFO> %d#\n", ObjectID);
  2843. onPropertyChangingDelegate(this, pcevent);
  2844. }
  2845. }
  2846. internal void OnRemoveColumnInternal(DataColumn column) {
  2847. OnRemoveColumn(column);
  2848. }
  2849. /// <devdoc>
  2850. /// <para>Notifies the <see cref='System.Data.DataTable'/> that a <see cref='System.Data.DataColumn'/> is
  2851. /// being removed.</para>
  2852. /// </devdoc>
  2853. protected virtual void OnRemoveColumn(DataColumn column) {
  2854. }
  2855. private DataRowChangeEventArgs OnRowChanged(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction) {
  2856. if ((null != onRowChangedDelegate) || IsTypedDataTable) {
  2857. if (null == args) {
  2858. args = new DataRowChangeEventArgs(eRow, eAction);
  2859. }
  2860. OnRowChanged(args);
  2861. }
  2862. return args;
  2863. }
  2864. private DataRowChangeEventArgs OnRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction) {
  2865. if ((null != onRowChangingDelegate) || IsTypedDataTable) {
  2866. if (null == args) {
  2867. args = new DataRowChangeEventArgs(eRow, eAction);
  2868. }
  2869. OnRowChanging(args);
  2870. }
  2871. return args;
  2872. }
  2873. /// <devdoc>
  2874. /// <para>
  2875. /// Raises the <see cref='System.Data.DataTable.RowChanged'/> event.
  2876. /// </para>
  2877. /// </devdoc>
  2878. protected virtual void OnRowChanged(DataRowChangeEventArgs e) {
  2879. Debug.Assert((null != e) && ((null != onRowChangedDelegate) || IsTypedDataTable), "OnRowChanged arguments");
  2880. if (onRowChangedDelegate != null) {
  2881. Bid.Trace("<ds.DataTable.OnRowChanged|INFO> %d#\n", ObjectID);
  2882. onRowChangedDelegate(this, e);
  2883. }
  2884. }
  2885. /// <devdoc>
  2886. /// <para>
  2887. /// Raises the <see cref='System.Data.DataTable.RowChanging'/> event.
  2888. /// </para>
  2889. /// </devdoc>
  2890. protected virtual void OnRowChanging(DataRowChangeEventArgs e) {
  2891. Debug.Assert((null != e) && ((null != onRowChangingDelegate) || IsTypedDataTable), "OnRowChanging arguments");
  2892. if (onRowChangingDelegate != null) {
  2893. Bid.Trace("<ds.DataTable.OnRowChanging|INFO> %d#\n", ObjectID);
  2894. onRowChangingDelegate(this, e);
  2895. }
  2896. }
  2897. /// <devdoc>
  2898. /// <para>
  2899. /// Raises the <see cref='System.Data.DataTable.OnRowDeleting'/> event.
  2900. /// </para>
  2901. /// </devdoc>
  2902. protected virtual void OnRowDeleting(DataRowChangeEventArgs e) {
  2903. Debug.Assert((null != e) && ((null != onRowDeletingDelegate) || IsTypedDataTable), "OnRowDeleting arguments");
  2904. if (onRowDeletingDelegate != null) {
  2905. Bid.Trace("<ds.DataTable.OnRowDeleting|INFO> %d#\n", ObjectID);
  2906. onRowDeletingDelegate(this, e);
  2907. }
  2908. }
  2909. /// <devdoc>
  2910. /// <para>
  2911. /// Raises the <see cref='System.Data.DataTable.OnRowDeleted'/> event.
  2912. /// </para>
  2913. /// </devdoc>
  2914. protected virtual void OnRowDeleted(DataRowChangeEventArgs e) {
  2915. Debug.Assert((null != e) && ((null != onRowDeletedDelegate) || IsTypedDataTable), "OnRowDeleted arguments");
  2916. if (onRowDeletedDelegate != null) {
  2917. Bid.Trace("<ds.DataTable.OnRowDeleted|INFO> %d#\n", ObjectID);
  2918. onRowDeletedDelegate(this, e);
  2919. }
  2920. }
  2921. protected virtual void OnTableCleared(DataTableClearEventArgs e) {
  2922. if (onTableClearedDelegate != null) {
  2923. Bid.Trace("<ds.DataTable.OnTableCleared|INFO> %d#\n", ObjectID);
  2924. onTableClearedDelegate(this, e);
  2925. }
  2926. }
  2927. protected virtual void OnTableClearing(DataTableClearEventArgs e) {
  2928. if (onTableClearingDelegate != null) {
  2929. Bid.Trace("<ds.DataTable.OnTableClearing|INFO> %d#\n", ObjectID);
  2930. onTableClearingDelegate(this, e);
  2931. }
  2932. }
  2933. protected virtual void OnTableNewRow(DataTableNewRowEventArgs e) {
  2934. if (onTableNewRowDelegate != null) {
  2935. Bid.Trace("<ds.DataTable.OnTableNewRow|INFO> %d#\n", ObjectID);
  2936. onTableNewRowDelegate(this, e);
  2937. }
  2938. }
  2939. private void OnInitialized() {
  2940. if (onInitialized != null) {
  2941. Bid.Trace("<ds.DataTable.OnInitialized|INFO> %d#\n", ObjectID);
  2942. onInitialized(this, EventArgs.Empty);
  2943. }
  2944. }
  2945. internal IndexField[] ParseSortString(string sortString) {
  2946. IndexField[] indexDesc = zeroIndexField;
  2947. if ((null != sortString) && (0 < sortString.Length)) {
  2948. string[] split = sortString.Split(new char[] { ','});
  2949. indexDesc = new IndexField[split.Length];
  2950. for (int i = 0; i < split.Length; i++) {
  2951. string current = split[i].Trim();
  2952. // handle ASC and DESC.
  2953. int length = current.Length;
  2954. bool descending = false;
  2955. if (length >= 5 && String.Compare(current, length - 4, " ASC", 0, 4, StringComparison.OrdinalIgnoreCase) == 0) {
  2956. current = current.Substring(0, length - 4).Trim();
  2957. }
  2958. else if (length >= 6 && String.Compare(current, length - 5, " DESC", 0, 5, StringComparison.OrdinalIgnoreCase) == 0) {
  2959. descending = true;
  2960. current = current.Substring(0, length - 5).Trim();
  2961. }
  2962. // handle brackets.
  2963. if (current.StartsWith("[", StringComparison.Ordinal)) {
  2964. if (current.EndsWith("]", StringComparison.Ordinal)) {
  2965. current = current.Substring(1, current.Length - 2);
  2966. }
  2967. else {
  2968. throw ExceptionBuilder.InvalidSortString(split[i]);
  2969. }
  2970. }
  2971. // find the column.
  2972. DataColumn column = Columns[current];
  2973. if(column == null) {
  2974. throw ExceptionBuilder.ColumnOutOfRange(current);
  2975. }
  2976. indexDesc[i] = new IndexField(column, descending);
  2977. }
  2978. }
  2979. return indexDesc;
  2980. }
  2981. internal void RaisePropertyChanging(string name) {
  2982. OnPropertyChanging(new PropertyChangedEventArgs(name));
  2983. }
  2984. // Notify all indexes that record changed.
  2985. // Only called when Error was changed.
  2986. internal void RecordChanged(int record) {
  2987. Debug.Assert (record != -1, "Record number must be given");
  2988. SetShadowIndexes(); // how about new assert?
  2989. try {
  2990. int numIndexes = shadowIndexes.Count;
  2991. for (int i = 0; i < numIndexes; i++) {
  2992. Index ndx = shadowIndexes[i];// shadowindexes may change, see ShadowIndexCopy()
  2993. if (0 < ndx.RefCount) {
  2994. ndx.RecordChanged(record);
  2995. }
  2996. }
  2997. }
  2998. finally{
  2999. RestoreShadowIndexes();
  3000. }
  3001. }
  3002. // for each index in liveindexes invok RecordChanged
  3003. // oldIndex and newIndex keeps position of record before delete and after insert in each index in order
  3004. // LiveIndexes[n-m] will have its information in oldIndex[n-m] and newIndex[n-m]
  3005. internal void RecordChanged(int[] oldIndex, int[] newIndex) {
  3006. SetShadowIndexes();
  3007. Debug.Assert (oldIndex.Length == newIndex.Length, "Size oldIndexes and newIndexes should be the same");
  3008. Debug.Assert (oldIndex.Length == shadowIndexes.Count, "Size of OldIndexes should be the same as size of Live indexes");
  3009. try{
  3010. int numIndexes = shadowIndexes.Count;
  3011. for (int i = 0; i < numIndexes; i++) {
  3012. Index ndx = shadowIndexes[i];// shadowindexes may change, see ShadowIndexCopy()
  3013. if (0 < ndx.RefCount) {
  3014. ndx.RecordChanged(oldIndex[i], newIndex[i]);
  3015. }
  3016. }
  3017. }
  3018. finally{
  3019. RestoreShadowIndexes();
  3020. }
  3021. }
  3022. internal void RecordStateChanged(int record, DataViewRowState oldState, DataViewRowState newState) {
  3023. SetShadowIndexes();
  3024. try{
  3025. int numIndexes = shadowIndexes.Count;
  3026. for (int i = 0; i < numIndexes; i++) {
  3027. Index ndx = shadowIndexes[i];// shadowindexes may change, see ShadowIndexCopy()
  3028. if (0 < ndx.RefCount) {
  3029. ndx.RecordStateChanged(record, oldState, newState);
  3030. }
  3031. }
  3032. }
  3033. finally{
  3034. RestoreShadowIndexes();
  3035. }
  3036. // System.Data.XML.Store.Store.OnROMChanged(record, oldState, newState);
  3037. }
  3038. internal void RecordStateChanged(int record1, DataViewRowState oldState1, DataViewRowState newState1,
  3039. int record2, DataViewRowState oldState2, DataViewRowState newState2) {
  3040. SetShadowIndexes();
  3041. try{
  3042. int numIndexes = shadowIndexes.Count;
  3043. for (int i = 0; i < numIndexes; i++) {
  3044. Index ndx = shadowIndexes[i];// shadowindexes may change, see ShadowIndexCopy()
  3045. if (0 < ndx.RefCount) {
  3046. if (record1 != -1 && record2 != -1)
  3047. ndx.RecordStateChanged(record1, oldState1, newState1,
  3048. record2, oldState2, newState2);
  3049. else if (record1 != -1)
  3050. ndx.RecordStateChanged(record1, oldState1, newState1);
  3051. else if (record2 != -1)
  3052. ndx.RecordStateChanged(record2, oldState2, newState2);
  3053. }
  3054. }
  3055. }
  3056. finally {
  3057. RestoreShadowIndexes();
  3058. }
  3059. // System.Data.XML.Store.Store.OnROMChanged(record1, oldState1, newState1, record2, oldState2, newState2);
  3060. }
  3061. // RemoveRecordFromIndexes removes the given record (using row and version) from all indexes and it stores and returns the position of deleted
  3062. // record from each index
  3063. // IT SHOULD NOT CAUSE ANY EVENT TO BE FIRED
  3064. internal int[] RemoveRecordFromIndexes(DataRow row, DataRowVersion version) {
  3065. int indexCount = LiveIndexes.Count;
  3066. int [] positionIndexes = new int[indexCount];
  3067. int recordNo = row.GetRecordFromVersion(version);
  3068. DataViewRowState states = row.GetRecordState(recordNo);
  3069. while (--indexCount >= 0) {
  3070. if (row.HasVersion(version) && ((states & indexes[indexCount].RecordStates) != DataViewRowState.None)) {
  3071. int index = indexes[indexCount].GetIndex(recordNo);
  3072. if (index > -1) {
  3073. positionIndexes [indexCount] = index;
  3074. indexes[indexCount].DeleteRecordFromIndex(index); // this will delete the record from index and MUSt not fire event
  3075. }
  3076. else {
  3077. positionIndexes [indexCount] = -1; // this means record was not in index
  3078. }
  3079. }
  3080. else {
  3081. positionIndexes [indexCount] = -1; // this means record was not in index
  3082. }
  3083. }
  3084. return positionIndexes;
  3085. }
  3086. // InsertRecordToIndexes inserts the given record (using row and version) to all indexes and it stores and returns the position of inserted
  3087. // record to each index
  3088. // IT SHOULD NOT CAUSE ANY EVENT TO BE FIRED
  3089. internal int[] InsertRecordToIndexes(DataRow row, DataRowVersion version) {
  3090. int indexCount = LiveIndexes.Count;
  3091. int [] positionIndexes = new int[indexCount];
  3092. int recordNo = row.GetRecordFromVersion(version);
  3093. DataViewRowState states = row.GetRecordState(recordNo);
  3094. while (--indexCount >= 0) {
  3095. if (row.HasVersion(version)) {
  3096. if ((states & indexes[indexCount].RecordStates) != DataViewRowState.None) {
  3097. positionIndexes [indexCount] = indexes[indexCount].InsertRecordToIndex(recordNo);
  3098. }
  3099. else {
  3100. positionIndexes [indexCount] = -1;
  3101. }
  3102. }
  3103. }
  3104. return positionIndexes;
  3105. }
  3106. internal void SilentlySetValue(DataRow dr, DataColumn dc, DataRowVersion version, object newValue) {
  3107. // get record for version
  3108. int record = dr.GetRecordFromVersion(version);
  3109. bool equalValues = false;
  3110. if (DataStorage.IsTypeCustomType(dc.DataType) && newValue != dc[record]) {
  3111. // if UDT storage, need to check if reference changed. See bug 385182
  3112. equalValues = false;
  3113. }
  3114. else {
  3115. equalValues = dc.CompareValueTo(record, newValue, true);
  3116. }
  3117. // if expression has changed
  3118. if (!equalValues) {
  3119. int[] oldIndex = dr.Table.RemoveRecordFromIndexes(dr, version);// conditional, if it exists it will try to remove with no event fired
  3120. dc.SetValue(record, newValue);
  3121. int[] newIndex = dr.Table.InsertRecordToIndexes(dr, version);// conditional, it will insert if it qualifies, no event will be fired
  3122. if (dr.HasVersion(version)) {
  3123. if (version != DataRowVersion.Original) {
  3124. dr.Table.RecordChanged(oldIndex, newIndex);
  3125. }
  3126. if (dc.dependentColumns != null) {
  3127. //BugBug - passing in null for cachedRows. This means expression columns as keys does not work when key changes.
  3128. dc.Table.EvaluateDependentExpressions(dc.dependentColumns, dr, version, null);
  3129. }
  3130. }
  3131. }
  3132. dr.ResetLastChangedColumn();
  3133. }
  3134. /// <devdoc>
  3135. /// <para>Rolls back all changes that have been made to the table
  3136. /// since it was loaded, or the last time <see cref='System.Data.DataTable.AcceptChanges'/> was called.</para>
  3137. /// </devdoc>
  3138. public void RejectChanges() {
  3139. IntPtr hscp;
  3140. Bid.ScopeEnter(out hscp, "<ds.DataTable.RejectChanges|API> %d#\n", ObjectID);
  3141. try{
  3142. DataRow[] oldRows = new DataRow[Rows.Count];
  3143. Rows.CopyTo(oldRows, 0);
  3144. for (int i = 0; i < oldRows.Length; i++) {
  3145. RollbackRow(oldRows[i]);
  3146. }
  3147. }
  3148. finally{
  3149. Bid.ScopeLeave(ref hscp);
  3150. }
  3151. }
  3152. internal void RemoveRow(DataRow row, bool check) {
  3153. if (row.rowID == -1) {
  3154. throw ExceptionBuilder.RowAlreadyRemoved();
  3155. }
  3156. if (check && dataSet != null) {
  3157. for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(dataSet, this); constraints.GetNext();) {
  3158. constraints.GetForeignKeyConstraint().CheckCanRemoveParentRow(row);
  3159. }
  3160. }
  3161. int oldRecord = row.oldRecord;
  3162. int newRecord = row.newRecord;
  3163. DataViewRowState oldRecordStatePre = row.GetRecordState(oldRecord);
  3164. DataViewRowState newRecordStatePre = row.GetRecordState(newRecord);
  3165. row.oldRecord = -1;
  3166. row.newRecord = -1;
  3167. if (oldRecord == newRecord) {
  3168. oldRecord = -1;
  3169. }
  3170. RecordStateChanged(oldRecord, oldRecordStatePre, DataViewRowState.None,
  3171. newRecord, newRecordStatePre, DataViewRowState.None);
  3172. FreeRecord(ref oldRecord);
  3173. FreeRecord(ref newRecord);
  3174. row.rowID = -1;
  3175. Rows.ArrayRemove(row);
  3176. }
  3177. // Resets the table back to its original state.
  3178. public virtual void Reset() {
  3179. IntPtr hscp;
  3180. Bid.ScopeEnter(out hscp, "<ds.DataTable.Reset|API> %d#\n", ObjectID);
  3181. try {
  3182. Clear();
  3183. ResetConstraints();
  3184. DataRelationCollection dr = this.ParentRelations;
  3185. int count = dr.Count;
  3186. while (count > 0) {
  3187. count--;
  3188. dr.RemoveAt(count);
  3189. }
  3190. dr = this.ChildRelations;
  3191. count = dr.Count;
  3192. while (count > 0) {
  3193. count--;
  3194. dr.RemoveAt(count);
  3195. }
  3196. Columns.Clear();
  3197. indexes.Clear();
  3198. }
  3199. finally{
  3200. Bid.ScopeLeave(ref hscp);
  3201. }
  3202. }
  3203. internal void ResetIndexes() {
  3204. ResetInternalIndexes(null);
  3205. }
  3206. internal void ResetInternalIndexes(DataColumn column) {
  3207. Debug.Assert(null != indexes, "unexpected null indexes");
  3208. SetShadowIndexes();
  3209. try{
  3210. // the length of shadowIndexes will not change
  3211. // but the array instance may change during
  3212. // events during Index.Reset
  3213. int numIndexes = shadowIndexes.Count;
  3214. for (int i = 0; i < numIndexes; i++) {
  3215. Index ndx = shadowIndexes[i];// shadowindexes may change, see ShadowIndexCopy()
  3216. if (0 < ndx.RefCount) {
  3217. if (null == column) {
  3218. ndx.Reset();
  3219. }
  3220. else {
  3221. // SQLBU 501916: DataTable internal index is corrupted:'5'
  3222. bool found = false;
  3223. foreach(IndexField field in ndx.IndexFields) {
  3224. if (Object.ReferenceEquals(column, field.Column)) {
  3225. found = true;
  3226. break;
  3227. }
  3228. }
  3229. if (found) {
  3230. ndx.Reset();
  3231. }
  3232. }
  3233. }
  3234. }
  3235. }
  3236. finally {
  3237. RestoreShadowIndexes();
  3238. }
  3239. }
  3240. internal void RollbackRow(DataRow row) {
  3241. row.CancelEdit();
  3242. SetNewRecord(row, row.oldRecord, DataRowAction.Rollback, false, true);
  3243. }
  3244. private DataRowChangeEventArgs RaiseRowChanged(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction) {
  3245. try {
  3246. if (UpdatingCurrent(eRow, eAction) && (IsTypedDataTable || (null != onRowChangedDelegate))) {
  3247. args = OnRowChanged(args, eRow, eAction);
  3248. }
  3249. // check if we deleting good row
  3250. else if (DataRowAction.Delete == eAction && eRow.newRecord == -1 && (IsTypedDataTable || (null != onRowDeletedDelegate))) {
  3251. if (null == args) {
  3252. args = new DataRowChangeEventArgs(eRow, eAction);
  3253. }
  3254. OnRowDeleted(args);
  3255. }
  3256. }
  3257. catch (Exception f) {
  3258. //
  3259. if (!Common.ADP.IsCatchableExceptionType(f)) {
  3260. throw;
  3261. }
  3262. ExceptionBuilder.TraceExceptionWithoutRethrow(f);
  3263. // ignore the exception
  3264. }
  3265. return args;
  3266. }
  3267. private DataRowChangeEventArgs RaiseRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction) {
  3268. if (UpdatingCurrent(eRow, eAction) && (IsTypedDataTable || (null != onRowChangingDelegate))) {
  3269. eRow.inChangingEvent = true;
  3270. // don't catch
  3271. try {
  3272. args = OnRowChanging(args, eRow, eAction);
  3273. }
  3274. finally {
  3275. eRow.inChangingEvent = false;
  3276. }
  3277. }
  3278. // check if we deleting good row
  3279. else if (DataRowAction.Delete == eAction && eRow.newRecord != -1 && (IsTypedDataTable || (null != onRowDeletingDelegate))) {
  3280. eRow.inDeletingEvent = true;
  3281. // don't catch
  3282. try {
  3283. if (null == args) {
  3284. args = new DataRowChangeEventArgs(eRow, eAction);
  3285. }
  3286. OnRowDeleting(args);
  3287. }
  3288. finally {
  3289. eRow.inDeletingEvent = false;
  3290. }
  3291. }
  3292. return args;
  3293. }
  3294. private DataRowChangeEventArgs RaiseRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction, bool fireEvent) {
  3295. // check all constraints
  3296. if (EnforceConstraints && !inLoad ) {
  3297. int columnCount = columnCollection.Count;
  3298. for(int i = 0; i < columnCount; ++i) {
  3299. DataColumn column = columnCollection[i];
  3300. if (!column.Computed || eAction != DataRowAction.Add) {
  3301. column.CheckColumnConstraint(eRow, eAction);
  3302. }
  3303. }
  3304. int constraintCount = constraintCollection.Count;
  3305. for(int i = 0; i < constraintCount; ++i) {
  3306. constraintCollection[i].CheckConstraint(eRow, eAction);
  3307. }
  3308. }
  3309. // $$anandra. Check this event out. May be an issue.
  3310. if (fireEvent) {
  3311. args = RaiseRowChanging(args, eRow, eAction);
  3312. }
  3313. if (!inDataLoad) {
  3314. // cascade things...
  3315. if (!MergingData && eAction != DataRowAction.Nothing && eAction != DataRowAction.ChangeOriginal) {
  3316. CascadeAll(eRow, eAction);
  3317. }
  3318. }
  3319. return args;
  3320. }
  3321. /// <devdoc>
  3322. /// <para>Returns an array of all <see cref='System.Data.DataRow'/> objects.</para>
  3323. /// </devdoc>
  3324. public DataRow[] Select() {
  3325. Bid.Trace("<ds.DataTable.Select|API> %d#\n", ObjectID);
  3326. return new Select(this, "", "", DataViewRowState.CurrentRows).SelectRows();
  3327. }
  3328. /// <devdoc>
  3329. /// <para>Returns an array of all <see cref='System.Data.DataRow'/> objects that match the filter criteria in order of
  3330. /// primary key (or lacking one, order of addition.)</para>
  3331. /// </devdoc>
  3332. public DataRow[] Select(string filterExpression) {
  3333. Bid.Trace("<ds.DataTable.Select|API> %d#, filterExpression='%ls'\n", ObjectID, filterExpression);
  3334. return new Select(this, filterExpression, "", DataViewRowState.CurrentRows).SelectRows();
  3335. }
  3336. /// <devdoc>
  3337. /// <para>Returns an array of all <see cref='System.Data.DataRow'/> objects that match the filter criteria, in the the
  3338. /// specified sort order.</para>
  3339. /// </devdoc>
  3340. public DataRow[] Select(string filterExpression, string sort) {
  3341. Bid.Trace("<ds.DataTable.Select|API> %d#, filterExpression='%ls', sort='%ls'\n", ObjectID, filterExpression, sort);
  3342. return new Select(this, filterExpression, sort, DataViewRowState.CurrentRows).SelectRows();
  3343. }
  3344. /// <devdoc>
  3345. /// <para>Returns an array of all <see cref='System.Data.DataRow'/> objects that match the filter in the order of the
  3346. /// sort, that match the specified state.</para>
  3347. /// </devdoc>
  3348. public DataRow[] Select(string filterExpression, string sort, DataViewRowState recordStates) {
  3349. Bid.Trace("<ds.DataTable.Select|API> %d#, filterExpression='%ls', sort='%ls', recordStates=%d{ds.DataViewRowState}\n", ObjectID, filterExpression, sort, (int)recordStates);
  3350. return new Select(this, filterExpression, sort, recordStates).SelectRows();
  3351. }
  3352. internal void SetNewRecord(DataRow row, int proposedRecord, DataRowAction action = DataRowAction.Change, bool isInMerge = false, bool fireEvent = true, bool suppressEnsurePropertyChanged = false) {
  3353. Exception deferredException = null;
  3354. SetNewRecordWorker(row, proposedRecord, action, isInMerge, suppressEnsurePropertyChanged, -1, fireEvent, out deferredException); // we are going to call below overload from insert
  3355. if (deferredException != null) {
  3356. throw deferredException;
  3357. }
  3358. }
  3359. private void SetNewRecordWorker(DataRow row, int proposedRecord, DataRowAction action, bool isInMerge, bool suppressEnsurePropertyChanged,
  3360. int position, bool fireEvent, out Exception deferredException) {
  3361. // this is the event workhorse... it will throw the changing/changed events
  3362. // and update the indexes. Used by change, add, delete, revert.
  3363. // order of execution is as follows
  3364. //
  3365. // 1) set temp record
  3366. // 2) Check constraints for non-expression columns
  3367. // 3) Raise RowChanging/RowDeleting with temp record
  3368. // 4) set the new record in storage
  3369. // 5) Update indexes with recordStateChanges - this will fire ListChanged & PropertyChanged events on associated views
  3370. // 6) Evaluate all Expressions (exceptions are deferred)- this will fire ListChanged & PropertyChanged events on associated views
  3371. // 7) Raise RowChanged/ RowDeleted
  3372. // 8) Check constraints for expression columns
  3373. Debug.Assert(row != null, "Row can't be null.");
  3374. deferredException = null;
  3375. if (row.tempRecord != proposedRecord) {
  3376. // $HACK: for performance reasons, EndUpdate calls SetNewRecord with tempRecord == proposedRecord
  3377. if (!inDataLoad) {
  3378. row.CheckInTable();
  3379. CheckNotModifying(row);
  3380. }
  3381. if (proposedRecord == row.newRecord) {
  3382. if (isInMerge) {
  3383. Debug.Assert(fireEvent, "SetNewRecord is called with wrong parameter");
  3384. RaiseRowChanged(null, row, action);
  3385. }
  3386. return;
  3387. }
  3388. Debug.Assert(!row.inChangingEvent, "How can this row be in an infinite loop?");
  3389. row.tempRecord = proposedRecord;
  3390. }
  3391. DataRowChangeEventArgs drcevent = null;
  3392. try {
  3393. row._action = action;
  3394. drcevent = RaiseRowChanging(null, row, action, fireEvent);
  3395. }
  3396. catch {
  3397. row.tempRecord = -1;
  3398. throw;
  3399. }
  3400. finally {
  3401. row._action = DataRowAction.Nothing;
  3402. }
  3403. row.tempRecord = -1;
  3404. int currentRecord = row.newRecord;
  3405. // if we're deleting, then the oldRecord value will change, so need to track that if it's distinct from the newRecord.
  3406. int secondRecord = (proposedRecord != -1 ?
  3407. proposedRecord :
  3408. (row.RowState != DataRowState.Unchanged ?
  3409. row.oldRecord :
  3410. -1));
  3411. if (action == DataRowAction.Add) { //if we come here from insert we do insert the row to collection
  3412. if (position == -1)
  3413. Rows.ArrayAdd(row);
  3414. else
  3415. Rows.ArrayInsert(row, position);
  3416. }
  3417. List<DataRow> cachedRows = null;
  3418. if ((action == DataRowAction.Delete || action == DataRowAction.Change)
  3419. && dependentColumns != null && dependentColumns.Count > 0) {
  3420. // if there are expression columns, need to cache related rows for deletes and updates (key changes)
  3421. // before indexes are modified.
  3422. cachedRows = new List<DataRow>();
  3423. for (int j = 0; j < ParentRelations.Count; j++) {
  3424. DataRelation relation = ParentRelations[j];
  3425. if (relation.ChildTable != row.Table) {
  3426. continue;
  3427. }
  3428. cachedRows.InsertRange(cachedRows.Count, row.GetParentRows(relation));
  3429. }
  3430. for (int j = 0; j < ChildRelations.Count; j++) {
  3431. DataRelation relation = ChildRelations[j];
  3432. if (relation.ParentTable != row.Table) {
  3433. continue;
  3434. }
  3435. cachedRows.InsertRange(cachedRows.Count, row.GetChildRows(relation));
  3436. }
  3437. }
  3438. // Dev10 Bug 688779: DataRowView.PropertyChanged are not raised on RejectChanges
  3439. // if the newRecord is changing, the propertychanged event should be allowed to triggered for ListChangedType.Changed or .Moved
  3440. // unless the specific condition is known that no data has changed, like DataRow.SetModified()
  3441. if (!suppressEnsurePropertyChanged && !row.HasPropertyChanged && (row.newRecord != proposedRecord)
  3442. && (-1 != proposedRecord) // explictly not fixing Dev10 Bug 692044: DataRowView.PropertyChanged are not raised on DataTable.Delete when mixing current and original records in RowStateFilter
  3443. && (-1 != row.newRecord)) // explictly not fixing parts of Dev10 Bug 697909: when mixing current and original records in RowStateFilter
  3444. {
  3445. // DataRow will believe multiple edits occured and
  3446. // DataView.ListChanged event w/ ListChangedType.ItemChanged will raise DataRowView.PropertyChanged event and
  3447. // PropertyChangedEventArgs.PropertyName will now be empty string so
  3448. // WPF will refresh the entire row
  3449. row.LastChangedColumn = null;
  3450. row.LastChangedColumn = null;
  3451. }
  3452. // Check whether we need to update indexes
  3453. if (LiveIndexes.Count != 0) {
  3454. // Dev10 bug #463087: DataTable internal index is currupted: '5'
  3455. if ((-1 == currentRecord) && (-1 != proposedRecord) && (-1 != row.oldRecord) && (proposedRecord != row.oldRecord)) {
  3456. // the transition from DataRowState.Deleted -> DataRowState.Modified
  3457. // with same orginal record but new current record
  3458. // needs to raise an ItemChanged or ItemMoved instead of ItemAdded in the ListChanged event.
  3459. // for indexes/views listening for both DataViewRowState.Deleted | DataViewRowState.ModifiedCurrent
  3460. currentRecord = row.oldRecord;
  3461. }
  3462. DataViewRowState currentRecordStatePre = row.GetRecordState(currentRecord);
  3463. DataViewRowState secondRecordStatePre = row.GetRecordState(secondRecord);
  3464. row.newRecord = proposedRecord;
  3465. if (proposedRecord != -1)
  3466. this.recordManager[proposedRecord] = row;
  3467. DataViewRowState currentRecordStatePost = row.GetRecordState(currentRecord);
  3468. DataViewRowState secondRecordStatePost = row.GetRecordState(secondRecord);
  3469. // may raise DataView.ListChanged event
  3470. RecordStateChanged(currentRecord, currentRecordStatePre, currentRecordStatePost,
  3471. secondRecord, secondRecordStatePre, secondRecordStatePost);
  3472. }
  3473. else {
  3474. row.newRecord = proposedRecord;
  3475. if (proposedRecord != -1)
  3476. this.recordManager[proposedRecord] = row;
  3477. }
  3478. // Dev10 Bug 461199 - reset the last changed column here, after all
  3479. // DataViews have raised their DataRowView.PropertyChanged event
  3480. row.ResetLastChangedColumn();
  3481. // SQLBU 278737: Record manager corruption when reentrant write operations
  3482. // free the 'currentRecord' only after all the indexes have been updated.
  3483. // Corruption! { if (currentRecord != row.oldRecord) { FreeRecord(ref currentRecord); } }
  3484. // RecordStateChanged raises ListChanged event at which time user may do work
  3485. if (-1 != currentRecord) {
  3486. if (currentRecord != row.oldRecord)
  3487. {
  3488. if ((currentRecord != row.tempRecord) && // Delete, AcceptChanges, BeginEdit
  3489. (currentRecord != row.newRecord) && // RejectChanges & SetAdded
  3490. (row == recordManager[currentRecord])) // AcceptChanges, NewRow
  3491. {
  3492. FreeRecord(ref currentRecord);
  3493. }
  3494. }
  3495. }
  3496. if (row.RowState == DataRowState.Detached && row.rowID != -1) {
  3497. RemoveRow(row, false);
  3498. }
  3499. if (dependentColumns != null && dependentColumns.Count > 0) {
  3500. try {
  3501. EvaluateExpressions(row, action, cachedRows);
  3502. }
  3503. catch (Exception exc) {
  3504. // For DataRows being added, throwing of exception from expression evaluation is
  3505. // deferred until after the row has been completely added.
  3506. if (action != DataRowAction.Add) {
  3507. throw exc;
  3508. }
  3509. else {
  3510. deferredException = exc;
  3511. }
  3512. }
  3513. }
  3514. try {
  3515. if (fireEvent) {
  3516. RaiseRowChanged(drcevent, row, action);
  3517. }
  3518. }
  3519. catch (Exception e) {
  3520. //
  3521. if (!Common.ADP.IsCatchableExceptionType(e)) {
  3522. throw;
  3523. }
  3524. ExceptionBuilder.TraceExceptionWithoutRethrow(e);
  3525. // ignore the exception
  3526. }
  3527. }
  3528. // this is the event workhorse... it will throw the changing/changed events
  3529. // and update the indexes.
  3530. internal void SetOldRecord(DataRow row, int proposedRecord) {
  3531. if (!inDataLoad) {
  3532. row.CheckInTable();
  3533. CheckNotModifying(row);
  3534. }
  3535. if (proposedRecord == row.oldRecord) {
  3536. return;
  3537. }
  3538. int originalRecord = row.oldRecord; // cache old record after potential RowChanging event
  3539. try {
  3540. // Check whether we need to update indexes
  3541. if (LiveIndexes.Count != 0) {
  3542. // Dev10 bug #463087: DataTable internal index is currupted: '5'
  3543. if ((-1 == originalRecord) && (-1 != proposedRecord) && (-1 != row.newRecord) && (proposedRecord != row.newRecord)) {
  3544. // the transition from DataRowState.Added -> DataRowState.Modified
  3545. // with same current record but new original record
  3546. // needs to raise an ItemChanged or ItemMoved instead of ItemAdded in the ListChanged event.
  3547. // for indexes/views listening for both DataViewRowState.Added | DataViewRowState.ModifiedOriginal
  3548. originalRecord = row.newRecord;
  3549. }
  3550. DataViewRowState originalRecordStatePre = row.GetRecordState(originalRecord);
  3551. DataViewRowState proposedRecordStatePre = row.GetRecordState(proposedRecord);
  3552. row.oldRecord = proposedRecord;
  3553. if (proposedRecord != -1)
  3554. this.recordManager[proposedRecord] = row;
  3555. DataViewRowState originalRecordStatePost = row.GetRecordState(originalRecord);
  3556. DataViewRowState proposedRecordStatePost = row.GetRecordState(proposedRecord);
  3557. RecordStateChanged(originalRecord, originalRecordStatePre, originalRecordStatePost,
  3558. proposedRecord, proposedRecordStatePre, proposedRecordStatePost);
  3559. }
  3560. else {
  3561. row.oldRecord = proposedRecord;
  3562. if (proposedRecord != -1)
  3563. this.recordManager[proposedRecord] = row;
  3564. }
  3565. }
  3566. finally {
  3567. if ((originalRecord != -1) && (originalRecord != row.tempRecord) &&
  3568. (originalRecord != row.oldRecord) && (originalRecord != row.newRecord)) {
  3569. FreeRecord(ref originalRecord);
  3570. }
  3571. // else during an event 'row.AcceptChanges(); row.BeginEdit(); row.EndEdit();'
  3572. if (row.RowState == DataRowState.Detached && row.rowID != -1) {
  3573. RemoveRow(row, false);
  3574. }
  3575. }
  3576. }
  3577. private void RestoreShadowIndexes() {
  3578. Debug.Assert(1 <= shadowCount, "unexpected negative shadow count");
  3579. shadowCount--;
  3580. if (0 == shadowCount) {
  3581. shadowIndexes = null;
  3582. }
  3583. }
  3584. private void SetShadowIndexes() {
  3585. if (null == shadowIndexes) {
  3586. Debug.Assert(0 == shadowCount, "unexpected count");
  3587. shadowIndexes = LiveIndexes;
  3588. shadowCount = 1;
  3589. }
  3590. else {
  3591. Debug.Assert(1 <= shadowCount, "unexpected negative shadow count");
  3592. shadowCount++;
  3593. }
  3594. }
  3595. internal void ShadowIndexCopy(){
  3596. if (shadowIndexes == indexes) {
  3597. Debug.Assert(0 < indexes.Count, "unexpected");
  3598. shadowIndexes = new List<Index>(indexes);
  3599. }
  3600. }
  3601. /// <devdoc>
  3602. /// <para>Returns the <see cref='System.Data.DataTable.TableName'/> and <see cref='System.Data.DataTable.DisplayExpression'/>, if there is one as a concatenated string.</para>
  3603. /// </devdoc>
  3604. public override string ToString() {
  3605. if (this.displayExpression == null)
  3606. return this.TableName;
  3607. else
  3608. return this.TableName + " + " + this.DisplayExpressionInternal;
  3609. }
  3610. /// <devdoc>
  3611. /// <para>[To be supplied.]</para>
  3612. /// </devdoc>
  3613. public void BeginLoadData() {
  3614. IntPtr hscp;
  3615. Bid.ScopeEnter(out hscp, "<ds.DataTable.BeginLoadData|API> %d#\n", ObjectID);
  3616. try {
  3617. if (inDataLoad)
  3618. return;
  3619. inDataLoad = true;
  3620. Debug.Assert(null == loadIndex, "loadIndex should already be null");
  3621. loadIndex = null;
  3622. // LoadDataRow may have been called before BeginLoadData and already
  3623. // initialized loadIndexwithOriginalAdded & loadIndexwithCurrentDeleted
  3624. initialLoad = (Rows.Count == 0);
  3625. if(initialLoad) {
  3626. SuspendIndexEvents();
  3627. } else {
  3628. if (primaryKey != null) {
  3629. loadIndex = primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows);
  3630. }
  3631. if(loadIndex != null) {
  3632. loadIndex.AddRef();
  3633. }
  3634. }
  3635. if (DataSet != null) {
  3636. savedEnforceConstraints = DataSet.EnforceConstraints;
  3637. DataSet.EnforceConstraints = false;
  3638. }
  3639. else {
  3640. this.EnforceConstraints = false;
  3641. }
  3642. }
  3643. finally{
  3644. Bid.ScopeLeave(ref hscp);
  3645. }
  3646. }
  3647. /// <devdoc>
  3648. /// <para>[To be supplied.]</para>
  3649. /// </devdoc>
  3650. public void EndLoadData() {
  3651. IntPtr hscp;
  3652. Bid.ScopeEnter(out hscp, "<ds.DataTable.EndLoadData|API> %d#\n", ObjectID);
  3653. try {
  3654. if (!inDataLoad)
  3655. return;
  3656. if(loadIndex != null) {
  3657. loadIndex.RemoveRef();
  3658. }
  3659. if (loadIndexwithOriginalAdded != null) {
  3660. loadIndexwithOriginalAdded.RemoveRef();
  3661. }
  3662. if (loadIndexwithCurrentDeleted != null) {
  3663. loadIndexwithCurrentDeleted.RemoveRef();
  3664. }
  3665. loadIndex = null;
  3666. loadIndexwithOriginalAdded = null;
  3667. loadIndexwithCurrentDeleted = null;
  3668. inDataLoad = false;
  3669. RestoreIndexEvents(false);
  3670. if (DataSet != null)
  3671. DataSet.EnforceConstraints = savedEnforceConstraints;
  3672. else
  3673. this.EnforceConstraints = true;
  3674. }
  3675. finally{
  3676. Bid.ScopeLeave(ref hscp);
  3677. }
  3678. }
  3679. /// <devdoc>
  3680. /// <para>Finds and updates a specific row. If no matching
  3681. /// row is found, a new row is created using the given values.</para>
  3682. /// </devdoc>
  3683. public DataRow LoadDataRow(object[] values, bool fAcceptChanges) {
  3684. IntPtr hscp;
  3685. Bid.ScopeEnter(out hscp, "<ds.DataTable.LoadDataRow|API> %d#, fAcceptChanges=%d{bool}\n", ObjectID, fAcceptChanges);
  3686. try {
  3687. DataRow row;
  3688. if (inDataLoad) {
  3689. int record = NewRecordFromArray(values);
  3690. if (loadIndex != null) {
  3691. // not expecting LiveIndexes to clear the index we use between calls to LoadDataRow
  3692. Debug.Assert(2 <= loadIndex.RefCount, "bad loadIndex.RefCount");
  3693. int result = loadIndex.FindRecord(record);
  3694. if (result != -1) {
  3695. int resultRecord = loadIndex.GetRecord(result);
  3696. row = recordManager[resultRecord];
  3697. Debug.Assert (row != null, "Row can't be null for index record");
  3698. row.CancelEdit();
  3699. if (row.RowState == DataRowState.Deleted)
  3700. SetNewRecord(row, row.oldRecord, DataRowAction.Rollback, false, true);
  3701. SetNewRecord(row, record, DataRowAction.Change, false, true);
  3702. if (fAcceptChanges)
  3703. row.AcceptChanges();
  3704. return row;
  3705. }
  3706. }
  3707. row = NewRow(record);
  3708. AddRow(row);
  3709. if (fAcceptChanges)
  3710. row.AcceptChanges();
  3711. return row;
  3712. }
  3713. else {
  3714. // In case, BeginDataLoad is not called yet
  3715. row = UpdatingAdd(values);
  3716. if (fAcceptChanges)
  3717. row.AcceptChanges();
  3718. return row;
  3719. }
  3720. }
  3721. finally{
  3722. Bid.ScopeLeave(ref hscp);
  3723. }
  3724. }
  3725. /// <devdoc>
  3726. /// <para>Finds and updates a specific row. If no matching
  3727. /// row is found, a new row is created using the given values.</para>
  3728. /// </devdoc>
  3729. public DataRow LoadDataRow(object[] values, LoadOption loadOption) {
  3730. IntPtr hscp;
  3731. Bid.ScopeEnter(out hscp, "<ds.DataTable.LoadDataRow|API> %d#, loadOption=%d{ds.LoadOption}\n", ObjectID, (int)loadOption);
  3732. try {
  3733. Index indextoUse = null;
  3734. if (this.primaryKey != null) {
  3735. if (loadOption == LoadOption.Upsert) { // CurrentVersion, and Deleted
  3736. if (loadIndexwithCurrentDeleted == null) {
  3737. loadIndexwithCurrentDeleted = this.primaryKey.Key.GetSortIndex(DataViewRowState.CurrentRows |DataViewRowState.Deleted);
  3738. Debug.Assert(loadIndexwithCurrentDeleted != null, "loadIndexwithCurrentDeleted should not be null" );
  3739. if (loadIndexwithCurrentDeleted != null) {
  3740. loadIndexwithCurrentDeleted.AddRef();
  3741. }
  3742. }
  3743. indextoUse = loadIndexwithCurrentDeleted;
  3744. }
  3745. else {// CurrentVersion, and Deleted : OverwriteRow, PreserveCurrentValues
  3746. if (loadIndexwithOriginalAdded == null) {
  3747. loadIndexwithOriginalAdded = this.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows |DataViewRowState.Added);
  3748. Debug.Assert(loadIndexwithOriginalAdded != null, "loadIndexwithOriginalAdded should not be null");
  3749. if (loadIndexwithOriginalAdded != null) {
  3750. loadIndexwithOriginalAdded.AddRef();
  3751. }
  3752. }
  3753. indextoUse = loadIndexwithOriginalAdded;
  3754. }
  3755. // not expecting LiveIndexes to clear the index we use between calls to LoadDataRow
  3756. Debug.Assert(2 <= indextoUse.RefCount, "bad indextoUse.RefCount");
  3757. }
  3758. if(inDataLoad && !AreIndexEventsSuspended) { // we do not want to fire any listchanged in new Load/Fill
  3759. SuspendIndexEvents();// so suspend events here(not suspended == table already has some rows initially)
  3760. }
  3761. DataRow dataRow = LoadRow(values, loadOption, indextoUse);// if indextoUse == null, it means we dont have PK,
  3762. // so LoadRow will take care of just adding the row to end
  3763. return dataRow;
  3764. }
  3765. finally {
  3766. Bid.ScopeLeave(ref hscp);
  3767. }
  3768. }
  3769. internal DataRow UpdatingAdd(object[] values) {
  3770. Index index = null;
  3771. if (this.primaryKey != null) {
  3772. index = this.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows);
  3773. }
  3774. if (index != null) {
  3775. int record = NewRecordFromArray(values);
  3776. int result = index.FindRecord(record);
  3777. if (result != -1) {
  3778. int resultRecord = index.GetRecord(result);
  3779. DataRow row = this.recordManager[resultRecord];
  3780. Debug.Assert (row != null, "Row can't be null for index record");
  3781. row.RejectChanges();
  3782. this.SetNewRecord(row, record);
  3783. return row;
  3784. }
  3785. DataRow row2 = NewRow(record);
  3786. Rows.Add(row2);
  3787. return row2;
  3788. }
  3789. return Rows.Add(values);
  3790. }
  3791. internal bool UpdatingCurrent(DataRow row, DataRowAction action) {
  3792. return(action == DataRowAction.Add || action == DataRowAction.Change ||
  3793. action == DataRowAction.Rollback || action == DataRowAction.ChangeOriginal ||
  3794. action == DataRowAction.ChangeCurrentAndOriginal);
  3795. // (action == DataRowAction.Rollback && row.tempRecord != -1));
  3796. }
  3797. internal DataColumn AddUniqueKey(int position) {
  3798. if (_colUnique != null)
  3799. return _colUnique;
  3800. // check to see if we can use already existant PrimaryKey
  3801. DataColumn[] pkey = PrimaryKey;
  3802. if (pkey.Length == 1)
  3803. // We have one-column primary key, so we can use it in our heirarchical relation
  3804. return pkey[0];
  3805. // add Unique, but not primaryKey to the table
  3806. string keyName = XMLSchema.GenUniqueColumnName(TableName + "_Id", this);
  3807. DataColumn key = new DataColumn(keyName, typeof(Int32), null, MappingType.Hidden);
  3808. key.Prefix = tablePrefix;
  3809. key.AutoIncrement = true;
  3810. key.AllowDBNull = false;
  3811. key.Unique = true;
  3812. if (position == -1)
  3813. Columns.Add(key);
  3814. else { // we do have a problem and Imy idea is it is bug. Ask Enzo while Code review. Why we do not set ordinal when we call AddAt?
  3815. for(int i = Columns.Count -1; i >= position; i--) {
  3816. this.Columns[i].SetOrdinalInternal(i+1);
  3817. }
  3818. Columns.AddAt(position, key);
  3819. key.SetOrdinalInternal(position);
  3820. }
  3821. if (pkey.Length == 0)
  3822. PrimaryKey = new DataColumn[] {
  3823. key
  3824. };
  3825. _colUnique = key;
  3826. return _colUnique;
  3827. }
  3828. internal DataColumn AddUniqueKey() {
  3829. return AddUniqueKey(-1);
  3830. }
  3831. internal DataColumn AddForeignKey(DataColumn parentKey) {
  3832. Debug.Assert(parentKey != null, "AddForeignKey: Invalid paramter.. related primary key is null");
  3833. string keyName = XMLSchema.GenUniqueColumnName(parentKey.ColumnName, this);
  3834. DataColumn foreignKey = new DataColumn(keyName, parentKey.DataType, null, MappingType.Hidden);
  3835. Columns.Add(foreignKey);
  3836. return foreignKey;
  3837. }
  3838. internal void UpdatePropertyDescriptorCollectionCache() {
  3839. propertyDescriptorCollectionCache = null;
  3840. }
  3841. /// <devdoc>
  3842. /// Retrieves an array of properties that the given component instance
  3843. /// provides. This may differ from the set of properties the class
  3844. /// provides. If the component is sited, the site may add or remove
  3845. /// additional properties. The returned array of properties will be
  3846. /// filtered by the given set of attributes.
  3847. /// </devdoc>
  3848. internal PropertyDescriptorCollection GetPropertyDescriptorCollection(Attribute[] attributes) {
  3849. if (propertyDescriptorCollectionCache == null) {
  3850. int columnsCount = Columns.Count;
  3851. int relationsCount = ChildRelations.Count;
  3852. PropertyDescriptor[] props = new PropertyDescriptor[columnsCount + relationsCount]; {
  3853. for (int i = 0; i < columnsCount; i++) {
  3854. props[i] = new DataColumnPropertyDescriptor(Columns[i]);
  3855. }
  3856. for (int i = 0; i < relationsCount; i++) {
  3857. props[columnsCount + i] = new DataRelationPropertyDescriptor(ChildRelations[i]);
  3858. }
  3859. }
  3860. propertyDescriptorCollectionCache = new PropertyDescriptorCollection(props);
  3861. }
  3862. return propertyDescriptorCollectionCache;
  3863. }
  3864. internal XmlQualifiedName TypeName {
  3865. get {
  3866. return ((typeName == null) ? XmlQualifiedName.Empty : (XmlQualifiedName)typeName);
  3867. }
  3868. set {
  3869. typeName = value;
  3870. }
  3871. }
  3872. public void Merge(DataTable table)
  3873. {
  3874. Merge(table, false, MissingSchemaAction.Add);
  3875. }
  3876. public void Merge(DataTable table, bool preserveChanges)
  3877. {
  3878. Merge(table, preserveChanges, MissingSchemaAction.Add);
  3879. }
  3880. public void Merge(DataTable table, bool preserveChanges, MissingSchemaAction missingSchemaAction)
  3881. {
  3882. IntPtr hscp;
  3883. Bid.ScopeEnter(out hscp, "<ds.DataTable.Merge|API> %d#, table=%d, preserveChanges=%d{bool}, missingSchemaAction=%d{ds.MissingSchemaAction}\n", ObjectID, (table != null) ? table.ObjectID : 0, preserveChanges, (int)missingSchemaAction);
  3884. try{
  3885. if (table == null)
  3886. throw ExceptionBuilder.ArgumentNull("table");
  3887. switch(missingSchemaAction) { // @perfnote: Enum.IsDefined
  3888. case MissingSchemaAction.Add:
  3889. case MissingSchemaAction.Ignore:
  3890. case MissingSchemaAction.Error:
  3891. case MissingSchemaAction.AddWithKey:
  3892. Merger merger = new Merger(this, preserveChanges, missingSchemaAction);
  3893. merger.MergeTable(table);
  3894. break;
  3895. default:
  3896. throw Common.ADP.InvalidMissingSchemaAction(missingSchemaAction);
  3897. }
  3898. }
  3899. finally{
  3900. Bid.ScopeLeave(ref hscp);
  3901. }
  3902. }
  3903. public void Load (IDataReader reader){
  3904. Load(reader, LoadOption.PreserveChanges, null);
  3905. }
  3906. public void Load (IDataReader reader, LoadOption loadOption) {
  3907. Load(reader, loadOption, null);
  3908. }
  3909. public virtual void Load (IDataReader reader, LoadOption loadOption, FillErrorEventHandler errorHandler){
  3910. IntPtr hscp;
  3911. Bid.ScopeEnter(out hscp, "<ds.DataTable.Load|API> %d#, loadOption=%d{ds.LoadOption}\n", ObjectID, (int)loadOption);
  3912. try {
  3913. if (this.PrimaryKey.Length == 0) {
  3914. DataTableReader dtReader = reader as DataTableReader;
  3915. if (dtReader != null && dtReader.CurrentDataTable == this)
  3916. return; // if not return, it will go to infinite loop
  3917. }
  3918. Common.LoadAdapter adapter = new Common.LoadAdapter();
  3919. adapter.FillLoadOption = loadOption;
  3920. adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  3921. if (null != errorHandler) {
  3922. adapter.FillError += errorHandler;
  3923. }
  3924. adapter.FillFromReader(new DataTable[] { this }, reader, 0, 0);
  3925. if (!reader.IsClosed && !reader.NextResult()) { //
  3926. reader.Close();
  3927. }
  3928. }
  3929. finally {
  3930. Bid.ScopeLeave(ref hscp);
  3931. }
  3932. }
  3933. private DataRow LoadRow(object[] values, LoadOption loadOption, Index searchIndex) {
  3934. int recordNo;
  3935. DataRow dataRow = null;
  3936. if (searchIndex != null) {
  3937. int[] primaryKeyIndex = new int[0];
  3938. if (this.primaryKey != null) { // I do check above for PK, but in case if someone else gives me some index unrelated to PK
  3939. primaryKeyIndex = new int[this.primaryKey.ColumnsReference.Length];
  3940. for(int i = 0; i < this.primaryKey.ColumnsReference.Length; i++) {
  3941. primaryKeyIndex[i] = this.primaryKey.ColumnsReference[i].Ordinal;
  3942. }
  3943. }
  3944. object[] keys = new object[primaryKeyIndex.Length];
  3945. for(int i = 0; i < primaryKeyIndex.Length; i++) {
  3946. keys[i] = values[primaryKeyIndex[i]];
  3947. }
  3948. Range result = searchIndex.FindRecords(keys);
  3949. if (!result.IsNull) {
  3950. int deletedRowUpsertCount = 0;
  3951. for(int i = result.Min; i <= result.Max; i++) {
  3952. int resultRecord = searchIndex.GetRecord(i);
  3953. dataRow = this.recordManager[resultRecord];
  3954. recordNo = NewRecordFromArray(values);
  3955. //SQLBU DT 33648
  3956. // values array is being reused by DataAdapter, do not modify the values array
  3957. for(int count = 0; count < values.Length; count++) {
  3958. if (null == values[count]) {
  3959. columnCollection[count].Copy(resultRecord, recordNo);
  3960. }
  3961. }
  3962. for(int count = values.Length; count < columnCollection.Count ; count++) {
  3963. columnCollection[count].Copy(resultRecord, recordNo); // if there are missing values
  3964. }
  3965. if (loadOption != LoadOption.Upsert || dataRow.RowState != DataRowState.Deleted) {
  3966. SetDataRowWithLoadOption(dataRow , recordNo, loadOption, true);
  3967. }
  3968. else {
  3969. deletedRowUpsertCount++;
  3970. }
  3971. }
  3972. if (0 == deletedRowUpsertCount) {
  3973. return dataRow;
  3974. }
  3975. }
  3976. }
  3977. recordNo = NewRecordFromArray(values);
  3978. dataRow = NewRow(recordNo);
  3979. // fire rowChanging event here
  3980. DataRowAction action;
  3981. DataRowChangeEventArgs drcevent = null;
  3982. switch(loadOption) {
  3983. case LoadOption.OverwriteChanges:
  3984. case LoadOption.PreserveChanges:
  3985. action = DataRowAction.ChangeCurrentAndOriginal;
  3986. break;
  3987. case LoadOption.Upsert:
  3988. action = DataRowAction.Add;
  3989. break;
  3990. default:
  3991. throw ExceptionBuilder.ArgumentOutOfRange("LoadOption");
  3992. }
  3993. drcevent = RaiseRowChanging(null, dataRow, action);
  3994. this.InsertRow (dataRow, -1, -1, false);
  3995. switch(loadOption) {
  3996. case LoadOption.OverwriteChanges:
  3997. case LoadOption.PreserveChanges:
  3998. this.SetOldRecord(dataRow, recordNo);
  3999. break;
  4000. case LoadOption.Upsert:
  4001. break;
  4002. default:
  4003. throw ExceptionBuilder.ArgumentOutOfRange("LoadOption");
  4004. }
  4005. RaiseRowChanged(drcevent, dataRow, action);
  4006. return dataRow;
  4007. }
  4008. private void SetDataRowWithLoadOption (DataRow dataRow, int recordNo, LoadOption loadOption, bool checkReadOnly) {
  4009. bool hasError = false;
  4010. if (checkReadOnly) {
  4011. foreach(DataColumn dc in this.Columns) {
  4012. if (dc.ReadOnly && !dc.Computed) {
  4013. switch(loadOption) {
  4014. case LoadOption.OverwriteChanges:
  4015. if ((dataRow[dc, DataRowVersion.Current] != dc[recordNo]) ||(dataRow[dc, DataRowVersion.Original] != dc[recordNo]))
  4016. hasError = true;
  4017. break;
  4018. case LoadOption.Upsert:
  4019. if (dataRow[dc, DataRowVersion.Current] != dc[recordNo])
  4020. hasError = true;
  4021. break;
  4022. case LoadOption.PreserveChanges:
  4023. if (dataRow[dc, DataRowVersion.Original] != dc[recordNo])
  4024. hasError = true;
  4025. break;
  4026. }
  4027. }
  4028. }
  4029. } // No Event should be fired in SenNewRecord and SetOldRecord
  4030. // fire rowChanging event here
  4031. DataRowChangeEventArgs drcevent = null;
  4032. DataRowAction action = DataRowAction.Nothing;
  4033. int cacheTempRecord = dataRow.tempRecord;
  4034. dataRow.tempRecord = recordNo;
  4035. switch(loadOption) {
  4036. case LoadOption.OverwriteChanges:
  4037. action = DataRowAction.ChangeCurrentAndOriginal;
  4038. break;
  4039. case LoadOption.Upsert:
  4040. switch(dataRow.RowState) {
  4041. case DataRowState.Unchanged:
  4042. // let see if the incomming value has the same values as existing row, so compare records
  4043. foreach(DataColumn dc in dataRow.Table.Columns) {
  4044. if (0 != dc.Compare(dataRow.newRecord, recordNo)) {
  4045. action = DataRowAction.Change;
  4046. break;
  4047. }
  4048. }
  4049. break;
  4050. case DataRowState.Deleted:
  4051. Debug.Assert(false, "LoadOption.Upsert with deleted row, should not be here");
  4052. break;
  4053. default :
  4054. action = DataRowAction.Change;
  4055. break;
  4056. }
  4057. break;
  4058. case LoadOption.PreserveChanges:
  4059. switch(dataRow.RowState) {
  4060. case DataRowState.Unchanged:
  4061. action = DataRowAction.ChangeCurrentAndOriginal;
  4062. break;
  4063. default:
  4064. action = DataRowAction.ChangeOriginal;
  4065. break;
  4066. }
  4067. break;
  4068. default:
  4069. throw ExceptionBuilder.ArgumentOutOfRange("LoadOption");
  4070. }
  4071. try {
  4072. drcevent = RaiseRowChanging(null, dataRow, action);
  4073. if (action == DataRowAction.Nothing) { // RaiseRowChanging does not fire for DataRowAction.Nothing
  4074. dataRow.inChangingEvent = true;
  4075. try {
  4076. drcevent = OnRowChanging(drcevent, dataRow, action);
  4077. }
  4078. finally {
  4079. dataRow.inChangingEvent = false;
  4080. }
  4081. }
  4082. }
  4083. finally {
  4084. Debug.Assert(dataRow.tempRecord == recordNo, "tempRecord has been changed in event handler");
  4085. if (DataRowState.Detached == dataRow.RowState) {
  4086. // 'row.Table.Remove(row);'
  4087. if (-1 != cacheTempRecord) {
  4088. FreeRecord(ref cacheTempRecord);
  4089. }
  4090. }
  4091. else {
  4092. if (dataRow.tempRecord != recordNo) {
  4093. // 'row.EndEdit(); row.BeginEdit(); '
  4094. if (-1 != cacheTempRecord) {
  4095. FreeRecord(ref cacheTempRecord);
  4096. }
  4097. if (-1 != recordNo) {
  4098. FreeRecord(ref recordNo);
  4099. }
  4100. recordNo = dataRow.tempRecord;
  4101. }
  4102. else {
  4103. dataRow.tempRecord = cacheTempRecord;
  4104. }
  4105. }
  4106. }
  4107. if (dataRow.tempRecord != -1) {
  4108. dataRow.CancelEdit();
  4109. }
  4110. switch(loadOption) {
  4111. case LoadOption.OverwriteChanges:
  4112. this.SetNewRecord(dataRow, recordNo, DataRowAction.Change, false, false);
  4113. this.SetOldRecord(dataRow, recordNo);
  4114. break;
  4115. case LoadOption.Upsert:
  4116. if (dataRow.RowState == DataRowState.Unchanged) {
  4117. this.SetNewRecord(dataRow, recordNo, DataRowAction.Change, false, false);
  4118. if (!dataRow.HasChanges()) {
  4119. this.SetOldRecord(dataRow, recordNo);
  4120. }
  4121. }
  4122. else {
  4123. if (dataRow.RowState == DataRowState.Deleted)
  4124. dataRow.RejectChanges();
  4125. this.SetNewRecord(dataRow, recordNo, DataRowAction.Change, false, false);
  4126. }
  4127. break;
  4128. case LoadOption.PreserveChanges:
  4129. if (dataRow.RowState == DataRowState.Unchanged) {
  4130. // SQLBU 500706: DataTable internal index is corrupted: '8'
  4131. // if ListChanged event deletes dataRow
  4132. this.SetOldRecord(dataRow, recordNo); // do not fire event
  4133. this.SetNewRecord(dataRow, recordNo, DataRowAction.Change, false, false);
  4134. }
  4135. else { // if modified/ added / deleted we want this operation to fire event (just for LoadOption.PreserveCurrentValues)
  4136. this.SetOldRecord(dataRow, recordNo);
  4137. }
  4138. break;
  4139. default:
  4140. throw ExceptionBuilder.ArgumentOutOfRange("LoadOption");
  4141. }
  4142. if (hasError) {
  4143. string error = Res.GetString(Res.Load_ReadOnlyDataModified);
  4144. if (dataRow.RowError.Length == 0) { // WebData 112272, append the row error
  4145. dataRow.RowError = error;
  4146. }
  4147. else {
  4148. dataRow.RowError += " ]:[ " + error ;
  4149. }
  4150. foreach(DataColumn dc in this.Columns) {
  4151. if (dc.ReadOnly && !dc.Computed)
  4152. dataRow.SetColumnError(dc, error);
  4153. }
  4154. }
  4155. drcevent = RaiseRowChanged(drcevent, dataRow, action);
  4156. if (action == DataRowAction.Nothing) { // RaiseRowChanged does not fire for DataRowAction.Nothing
  4157. dataRow.inChangingEvent = true;
  4158. try {
  4159. OnRowChanged(drcevent, dataRow, action);
  4160. }
  4161. finally {
  4162. dataRow.inChangingEvent = false;
  4163. }
  4164. }
  4165. }
  4166. public DataTableReader CreateDataReader() {
  4167. return new DataTableReader(this);
  4168. }
  4169. public void WriteXml(Stream stream)
  4170. {
  4171. WriteXml(stream, XmlWriteMode.IgnoreSchema, false);
  4172. }
  4173. public void WriteXml(Stream stream, bool writeHierarchy)
  4174. {
  4175. WriteXml(stream, XmlWriteMode.IgnoreSchema, writeHierarchy);
  4176. }
  4177. public void WriteXml(TextWriter writer)
  4178. {
  4179. WriteXml(writer, XmlWriteMode.IgnoreSchema, false);
  4180. }
  4181. public void WriteXml(TextWriter writer, bool writeHierarchy)
  4182. {
  4183. WriteXml(writer, XmlWriteMode.IgnoreSchema, writeHierarchy);
  4184. }
  4185. public void WriteXml(XmlWriter writer)
  4186. {
  4187. WriteXml(writer, XmlWriteMode.IgnoreSchema, false);
  4188. }
  4189. public void WriteXml(XmlWriter writer, bool writeHierarchy)
  4190. {
  4191. WriteXml(writer, XmlWriteMode.IgnoreSchema, writeHierarchy);
  4192. }
  4193. [ResourceExposure(ResourceScope.Machine)]
  4194. [ResourceConsumption(ResourceScope.Machine)]
  4195. public void WriteXml(String fileName)
  4196. {
  4197. WriteXml(fileName, XmlWriteMode.IgnoreSchema, false);
  4198. }
  4199. [ResourceExposure(ResourceScope.Machine)]
  4200. [ResourceConsumption(ResourceScope.Machine)]
  4201. public void WriteXml(String fileName, bool writeHierarchy)
  4202. {
  4203. WriteXml(fileName, XmlWriteMode.IgnoreSchema, writeHierarchy);
  4204. }
  4205. public void WriteXml(Stream stream, XmlWriteMode mode)
  4206. {
  4207. WriteXml(stream, mode, false);
  4208. }
  4209. public void WriteXml(Stream stream, XmlWriteMode mode, bool writeHierarchy)
  4210. {
  4211. if (stream != null) {
  4212. XmlTextWriter w = new XmlTextWriter(stream, null) ;
  4213. w.Formatting = Formatting.Indented;
  4214. WriteXml( w, mode, writeHierarchy);
  4215. }
  4216. }
  4217. public void WriteXml(TextWriter writer, XmlWriteMode mode)
  4218. {
  4219. WriteXml(writer, mode, false);
  4220. }
  4221. public void WriteXml(TextWriter writer, XmlWriteMode mode, bool writeHierarchy)
  4222. {
  4223. if (writer != null) {
  4224. XmlTextWriter w = new XmlTextWriter(writer) ;
  4225. w.Formatting = Formatting.Indented;
  4226. WriteXml(w, mode, writeHierarchy);
  4227. }
  4228. }
  4229. public void WriteXml(XmlWriter writer, XmlWriteMode mode)
  4230. {
  4231. WriteXml(writer, mode, false);
  4232. }
  4233. public void WriteXml(XmlWriter writer, XmlWriteMode mode, bool writeHierarchy)
  4234. {
  4235. IntPtr hscp;
  4236. Bid.ScopeEnter(out hscp, "<ds.DataTable.WriteXml|API> %d#, mode=%d{ds.XmlWriteMode}\n", ObjectID, (int)mode);
  4237. try{
  4238. if (this.tableName.Length == 0) {
  4239. throw ExceptionBuilder.CanNotSerializeDataTableWithEmptyName();
  4240. }
  4241. // Generate SchemaTree and write it out
  4242. if (writer != null) {
  4243. if (mode == XmlWriteMode.DiffGram) { // FIX THIS
  4244. // Create and save the updates
  4245. new NewDiffgramGen(this, writeHierarchy).Save(writer, this);
  4246. }
  4247. else {
  4248. // Create and save xml data
  4249. if (mode == XmlWriteMode.WriteSchema) {
  4250. DataSet ds = null;
  4251. string tablenamespace = this.tableNamespace;
  4252. if (null == this.DataSet) {
  4253. ds = new DataSet();
  4254. // if user set values on DataTable, it isn't necessary
  4255. // to set them on the DataSet because they won't be inherited
  4256. // but it is simpler to set them in both places
  4257. // if user did not set values on DataTable, it is required
  4258. // to set them on the DataSet so the table will inherit
  4259. // the value already on the Datatable
  4260. ds.SetLocaleValue(_culture, _cultureUserSet);
  4261. ds.CaseSensitive = this.CaseSensitive;
  4262. ds.Namespace = this.Namespace;
  4263. ds.RemotingFormat = this.RemotingFormat;
  4264. ds.Tables.Add(this);
  4265. }
  4266. if (writer != null) {
  4267. XmlDataTreeWriter xmldataWriter = new XmlDataTreeWriter(this, writeHierarchy);
  4268. xmldataWriter.Save(writer, /*mode == XmlWriteMode.WriteSchema*/true);
  4269. }
  4270. if (null != ds) {
  4271. ds.Tables.Remove(this);
  4272. this.tableNamespace = tablenamespace;
  4273. }
  4274. }
  4275. else {
  4276. XmlDataTreeWriter xmldataWriter = new XmlDataTreeWriter(this, writeHierarchy);
  4277. xmldataWriter.Save(writer,/*mode == XmlWriteMode.WriteSchema*/ false);
  4278. }
  4279. }
  4280. }
  4281. }
  4282. finally {
  4283. Bid.ScopeLeave(ref hscp);
  4284. }
  4285. }
  4286. [ResourceExposure(ResourceScope.Machine)]
  4287. [ResourceConsumption(ResourceScope.Machine)]
  4288. public void WriteXml(String fileName, XmlWriteMode mode)
  4289. {
  4290. WriteXml(fileName, mode, false);
  4291. }
  4292. [ResourceExposure(ResourceScope.Machine)]
  4293. [ResourceConsumption(ResourceScope.Machine)]
  4294. public void WriteXml(String fileName, XmlWriteMode mode, bool writeHierarchy)
  4295. {
  4296. IntPtr hscp;
  4297. Bid.ScopeEnter(out hscp, "<ds.DataTable.WriteXml|API> %d#, fileName='%ls', mode=%d{ds.XmlWriteMode}\n", ObjectID, fileName, (int)mode);
  4298. try {
  4299. using(XmlTextWriter xw = new XmlTextWriter( fileName, null )) {
  4300. xw.Formatting = Formatting.Indented;
  4301. xw.WriteStartDocument(true);
  4302. WriteXml(xw, mode, writeHierarchy);
  4303. xw.WriteEndDocument();
  4304. }
  4305. }
  4306. finally {
  4307. Bid.ScopeLeave(ref hscp);
  4308. }
  4309. }
  4310. public void WriteXmlSchema(Stream stream) {
  4311. WriteXmlSchema(stream, false);
  4312. }
  4313. public void WriteXmlSchema(Stream stream, bool writeHierarchy)
  4314. {
  4315. if (stream == null)
  4316. return;
  4317. XmlTextWriter w = new XmlTextWriter(stream, null) ;
  4318. w.Formatting = Formatting.Indented;
  4319. WriteXmlSchema( w, writeHierarchy );
  4320. }
  4321. public void WriteXmlSchema( TextWriter writer ) {
  4322. WriteXmlSchema( writer, false );
  4323. }
  4324. public void WriteXmlSchema( TextWriter writer, bool writeHierarchy )
  4325. {
  4326. if (writer == null)
  4327. return;
  4328. XmlTextWriter w = new XmlTextWriter(writer);
  4329. w.Formatting = Formatting.Indented;
  4330. WriteXmlSchema( w, writeHierarchy );
  4331. }
  4332. private bool CheckForClosureOnExpressions(DataTable dt, bool writeHierarchy) {
  4333. List<DataTable> tableList = new List<DataTable>();
  4334. tableList.Add(dt);
  4335. if (writeHierarchy) { // WebData 112161
  4336. CreateTableList(dt, tableList);
  4337. }
  4338. return CheckForClosureOnExpressionTables(tableList);
  4339. }
  4340. private bool CheckForClosureOnExpressionTables(List<DataTable> tableList) {
  4341. Debug.Assert(tableList != null, "tableList shouldnot be null");
  4342. foreach(DataTable datatable in tableList) {
  4343. foreach(DataColumn dc in datatable.Columns) {
  4344. if (dc.Expression.Length != 0) {
  4345. DataColumn[] dependency = dc.DataExpression.GetDependency();
  4346. for (int j = 0; j < dependency.Length; j++) {
  4347. if (!(tableList.Contains(dependency[j].Table))) {
  4348. return false;
  4349. }
  4350. }
  4351. }
  4352. }
  4353. }
  4354. return true;
  4355. }
  4356. public void WriteXmlSchema(XmlWriter writer) {
  4357. WriteXmlSchema(writer, false);
  4358. }
  4359. public void WriteXmlSchema(XmlWriter writer, bool writeHierarchy)
  4360. {
  4361. IntPtr hscp;
  4362. Bid.ScopeEnter(out hscp, "<ds.DataTable.WriteXmlSchema|API> %d#\n", ObjectID);
  4363. try{
  4364. if (this.tableName.Length == 0) {
  4365. throw ExceptionBuilder.CanNotSerializeDataTableWithEmptyName();
  4366. }
  4367. if (!CheckForClosureOnExpressions(this, writeHierarchy)) {
  4368. throw ExceptionBuilder.CanNotSerializeDataTableHierarchy();
  4369. }
  4370. DataSet ds = null;
  4371. string tablenamespace = this.tableNamespace;//SQL BU Defect Tracking 286968
  4372. // Generate SchemaTree and write it out
  4373. if (null == this.DataSet) {
  4374. ds = new DataSet();
  4375. // if user set values on DataTable, it isn't necessary
  4376. // to set them on the DataSet because they won't be inherited
  4377. // but it is simpler to set them in both places
  4378. // if user did not set values on DataTable, it is required
  4379. // to set them on the DataSet so the table will inherit
  4380. // the value already on the Datatable
  4381. ds.SetLocaleValue(_culture, _cultureUserSet);
  4382. ds.CaseSensitive = this.CaseSensitive;
  4383. ds.Namespace = this.Namespace;
  4384. ds.RemotingFormat = this.RemotingFormat;
  4385. ds.Tables.Add(this);
  4386. }
  4387. if (writer != null) {
  4388. XmlTreeGen treeGen = new XmlTreeGen(SchemaFormat.Public);
  4389. treeGen.Save(null, this, writer, writeHierarchy);
  4390. }
  4391. if (null != ds) {
  4392. ds.Tables.Remove(this);
  4393. this.tableNamespace = tablenamespace;
  4394. }
  4395. }
  4396. finally {
  4397. Bid.ScopeLeave(ref hscp);
  4398. }
  4399. }
  4400. [ResourceExposure(ResourceScope.Machine)]
  4401. [ResourceConsumption(ResourceScope.Machine)]
  4402. public void WriteXmlSchema(String fileName) {
  4403. WriteXmlSchema(fileName, false);
  4404. }
  4405. [ResourceExposure(ResourceScope.Machine)]
  4406. [ResourceConsumption(ResourceScope.Machine)]
  4407. public void WriteXmlSchema(String fileName, bool writeHierarchy)
  4408. {
  4409. XmlTextWriter xw = new XmlTextWriter( fileName, null );
  4410. try {
  4411. xw.Formatting = Formatting.Indented;
  4412. xw.WriteStartDocument(true);
  4413. WriteXmlSchema(xw, writeHierarchy);
  4414. xw.WriteEndDocument();
  4415. }
  4416. finally {
  4417. xw.Close();
  4418. }
  4419. }
  4420. public XmlReadMode ReadXml(Stream stream)
  4421. {
  4422. if (stream == null)
  4423. return XmlReadMode.Auto;
  4424. return ReadXml( new XmlTextReader(stream), false);
  4425. }
  4426. public XmlReadMode ReadXml(TextReader reader)
  4427. {
  4428. if (reader == null)
  4429. return XmlReadMode.Auto;
  4430. return ReadXml( new XmlTextReader(reader), false);
  4431. }
  4432. [ResourceExposure(ResourceScope.Machine)]
  4433. [ResourceConsumption(ResourceScope.Machine)]
  4434. public XmlReadMode ReadXml(string fileName)
  4435. {
  4436. XmlTextReader xr = new XmlTextReader(fileName);
  4437. try {
  4438. return ReadXml( xr , false);
  4439. }
  4440. finally {
  4441. xr.Close();
  4442. }
  4443. }
  4444. public XmlReadMode ReadXml(XmlReader reader)
  4445. {
  4446. return ReadXml(reader, false);
  4447. }
  4448. private void RestoreConstraint(bool originalEnforceConstraint) {
  4449. if (this.DataSet != null) {
  4450. this.DataSet.EnforceConstraints = originalEnforceConstraint;
  4451. }
  4452. else {
  4453. this.EnforceConstraints = originalEnforceConstraint;
  4454. }
  4455. }
  4456. private bool IsEmptyXml(XmlReader reader) {
  4457. if (reader.IsEmptyElement) {
  4458. if (reader.AttributeCount == 0 || (reader.LocalName == Keywords.DIFFGRAM && reader.NamespaceURI == Keywords.DFFNS)) {
  4459. return true;
  4460. }
  4461. if (reader.AttributeCount == 1) {
  4462. reader.MoveToAttribute(0);
  4463. if ((this.Namespace == reader.Value) &&
  4464. (this.Prefix == reader.LocalName) &&
  4465. (reader.Prefix == Keywords.XMLNS) &&
  4466. (reader.NamespaceURI == Keywords.XSD_XMLNS_NS))
  4467. return true;
  4468. }
  4469. }
  4470. return false;
  4471. }
  4472. internal XmlReadMode ReadXml(XmlReader reader, bool denyResolving)
  4473. {
  4474. IntPtr hscp;
  4475. Bid.ScopeEnter(out hscp, "<ds.DataTable.ReadXml|INFO> %d#, denyResolving=%d{bool}\n", ObjectID, denyResolving);
  4476. try {
  4477. DataTable.RowDiffIdUsageSection rowDiffIdUsage = new DataTable.RowDiffIdUsageSection();
  4478. try {
  4479. bool fDataFound = false;
  4480. bool fSchemaFound = false;
  4481. bool fDiffsFound = false;
  4482. bool fIsXdr = false;
  4483. int iCurrentDepth = -1;
  4484. XmlReadMode ret = XmlReadMode.Auto;
  4485. // clear the hashtable to avoid conflicts between diffgrams, SqlHotFix 782
  4486. rowDiffIdUsage.Prepare(this);
  4487. if (reader == null)
  4488. return ret;
  4489. bool originalEnforceConstraint = false;
  4490. if (this.DataSet != null) {
  4491. originalEnforceConstraint = this.DataSet.EnforceConstraints;
  4492. this.DataSet.EnforceConstraints = false;
  4493. }
  4494. else {
  4495. originalEnforceConstraint = this.EnforceConstraints;
  4496. this.EnforceConstraints = false;
  4497. }
  4498. if (reader is XmlTextReader)
  4499. ((XmlTextReader) reader).WhitespaceHandling = WhitespaceHandling.Significant;
  4500. XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema
  4501. XmlDataLoader xmlload = null;
  4502. reader.MoveToContent();
  4503. if (Columns.Count == 0) {
  4504. if (IsEmptyXml(reader)) {
  4505. reader.Read();
  4506. return ret;
  4507. }
  4508. }
  4509. if (reader.NodeType == XmlNodeType.Element) {
  4510. iCurrentDepth = reader.Depth;
  4511. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  4512. if (Columns.Count == 0) {
  4513. if (reader.IsEmptyElement) {
  4514. reader.Read();
  4515. return XmlReadMode.DiffGram;
  4516. }
  4517. throw ExceptionBuilder.DataTableInferenceNotSupported();
  4518. }
  4519. this.ReadXmlDiffgram(reader);
  4520. // read the closing tag of the current element
  4521. ReadEndElement(reader);
  4522. RestoreConstraint(originalEnforceConstraint);
  4523. return XmlReadMode.DiffGram;
  4524. }
  4525. // if reader points to the schema load it
  4526. if (reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI==Keywords.XDRNS) {
  4527. // load XDR schema and exit
  4528. ReadXDRSchema(reader);
  4529. RestoreConstraint(originalEnforceConstraint);
  4530. return XmlReadMode.ReadSchema; //since the top level element is a schema return
  4531. }
  4532. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI==Keywords.XSDNS) {
  4533. // load XSD schema and exit
  4534. ReadXmlSchema(reader, denyResolving);
  4535. RestoreConstraint(originalEnforceConstraint);
  4536. return XmlReadMode.ReadSchema; //since the top level element is a schema return
  4537. }
  4538. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal)) {
  4539. if (this.DataSet != null) { // we should not throw for constraint, we already will throw for unsupported schema, so restore enforce cost, but not via property
  4540. this.DataSet.RestoreEnforceConstraints(originalEnforceConstraint);
  4541. }
  4542. else {
  4543. this.enforceConstraints = originalEnforceConstraint;
  4544. }
  4545. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  4546. }
  4547. // now either the top level node is a table and we load it through dataReader...
  4548. // ... or backup the top node and all its attributes because we may need to InferSchema
  4549. XmlElement topNode = xdoc.CreateElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  4550. if (reader.HasAttributes) {
  4551. int attrCount = reader.AttributeCount;
  4552. for (int i=0;i<attrCount;i++) {
  4553. reader.MoveToAttribute(i);
  4554. if (reader.NamespaceURI.Equals(Keywords.XSD_XMLNS_NS))
  4555. topNode.SetAttribute(reader.Name, reader.GetAttribute(i));
  4556. else {
  4557. XmlAttribute attr = topNode.SetAttributeNode(reader.LocalName, reader.NamespaceURI);
  4558. attr.Prefix = reader.Prefix;
  4559. attr.Value = reader.GetAttribute(i);
  4560. }
  4561. }
  4562. }
  4563. reader.Read();
  4564. while(MoveToElement(reader, iCurrentDepth)) {
  4565. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  4566. this.ReadXmlDiffgram(reader);
  4567. // read the closing tag of the current element
  4568. ReadEndElement(reader);
  4569. RestoreConstraint(originalEnforceConstraint);
  4570. return XmlReadMode.DiffGram;
  4571. }
  4572. // if reader points to the schema load it...
  4573. if (!fSchemaFound && !fDataFound && reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI==Keywords.XDRNS) {
  4574. // load XDR schema and exit
  4575. ReadXDRSchema(reader);
  4576. fSchemaFound = true;
  4577. fIsXdr = true;
  4578. continue;
  4579. }
  4580. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI==Keywords.XSDNS) {
  4581. // load XSD schema and exit
  4582. ReadXmlSchema(reader, denyResolving);
  4583. fSchemaFound = true;
  4584. continue;
  4585. }
  4586. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal)) {
  4587. if (this.DataSet != null) { // we should not throw for constraint, we already will throw for unsupported schema, so restore enforce cost, but not via property
  4588. this.DataSet.RestoreEnforceConstraints(originalEnforceConstraint);
  4589. }
  4590. else {
  4591. this.enforceConstraints = originalEnforceConstraint;
  4592. }
  4593. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  4594. }
  4595. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  4596. this.ReadXmlDiffgram(reader);
  4597. fDiffsFound = true;
  4598. ret = XmlReadMode.DiffGram;
  4599. }
  4600. else {
  4601. // we found data here
  4602. fDataFound = true;
  4603. if (!fSchemaFound && Columns.Count == 0) {
  4604. XmlNode node = xdoc.ReadNode(reader);
  4605. topNode.AppendChild(node);
  4606. }
  4607. else {
  4608. if (xmlload == null)
  4609. xmlload = new XmlDataLoader(this, fIsXdr, topNode, false);
  4610. xmlload.LoadData(reader);
  4611. if (fSchemaFound)
  4612. ret = XmlReadMode.ReadSchema;
  4613. else
  4614. ret = XmlReadMode.IgnoreSchema;
  4615. }
  4616. }
  4617. }
  4618. // read the closing tag of the current element
  4619. ReadEndElement(reader);
  4620. // now top node contains the data part
  4621. xdoc.AppendChild(topNode);
  4622. if (!fSchemaFound && Columns.Count == 0) {
  4623. if (IsEmptyXml(reader)) {
  4624. reader.Read();
  4625. return ret;
  4626. }
  4627. throw ExceptionBuilder.DataTableInferenceNotSupported();
  4628. }
  4629. if (xmlload == null)
  4630. xmlload = new XmlDataLoader(this, fIsXdr, false);
  4631. // so we InferSchema
  4632. if (!fDiffsFound) {// we need to add support for inference here
  4633. }
  4634. }
  4635. RestoreConstraint(originalEnforceConstraint);
  4636. return ret;
  4637. }
  4638. finally {
  4639. rowDiffIdUsage.Cleanup();
  4640. }
  4641. }
  4642. finally{
  4643. Bid.ScopeLeave(ref hscp);
  4644. }
  4645. }
  4646. internal XmlReadMode ReadXml(XmlReader reader, XmlReadMode mode, bool denyResolving)
  4647. {
  4648. DataTable.RowDiffIdUsageSection rowDiffIdUsage = new DataTable.RowDiffIdUsageSection();
  4649. try {
  4650. bool fSchemaFound = false;
  4651. bool fDataFound = false;
  4652. bool fIsXdr = false;
  4653. int iCurrentDepth = -1;
  4654. XmlReadMode ret = mode;
  4655. // Dev11 904428: prepare and cleanup rowDiffId hashtable
  4656. rowDiffIdUsage.Prepare(this);
  4657. if (reader == null)
  4658. return ret;
  4659. bool originalEnforceConstraint = false;
  4660. if (this.DataSet != null) {
  4661. originalEnforceConstraint = this.DataSet.EnforceConstraints;
  4662. this.DataSet.EnforceConstraints = false;
  4663. }
  4664. else {
  4665. originalEnforceConstraint = this.EnforceConstraints;
  4666. this.EnforceConstraints = false;
  4667. }
  4668. if (reader is XmlTextReader)
  4669. ((XmlTextReader) reader).WhitespaceHandling = WhitespaceHandling.Significant;
  4670. XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema
  4671. if ((mode != XmlReadMode.Fragment) && (reader.NodeType == XmlNodeType.Element))
  4672. iCurrentDepth = reader.Depth;
  4673. reader.MoveToContent();
  4674. if (Columns.Count == 0) {
  4675. if (IsEmptyXml(reader)) {
  4676. reader.Read();
  4677. return ret;
  4678. }
  4679. }
  4680. XmlDataLoader xmlload = null;
  4681. if (reader.NodeType == XmlNodeType.Element) {
  4682. XmlElement topNode = null;
  4683. if (mode == XmlReadMode.Fragment) {
  4684. xdoc.AppendChild(xdoc.CreateElement("ds_sqlXmlWraPPeR"));
  4685. topNode = xdoc.DocumentElement;
  4686. }
  4687. else { //handle the top node
  4688. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  4689. if ((mode == XmlReadMode.DiffGram) || (mode == XmlReadMode.IgnoreSchema)) {
  4690. if (Columns.Count == 0) {
  4691. if(reader.IsEmptyElement) {
  4692. reader.Read();
  4693. return XmlReadMode.DiffGram;
  4694. }
  4695. throw ExceptionBuilder.DataTableInferenceNotSupported();
  4696. }
  4697. this.ReadXmlDiffgram(reader);
  4698. // read the closing tag of the current element
  4699. ReadEndElement(reader);
  4700. }
  4701. else {
  4702. reader.Skip();
  4703. }
  4704. RestoreConstraint(originalEnforceConstraint);
  4705. return ret;
  4706. }
  4707. if (reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI==Keywords.XDRNS) {
  4708. // load XDR schema and exit
  4709. if ((mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema)) {
  4710. ReadXDRSchema(reader);
  4711. }
  4712. else {
  4713. reader.Skip();
  4714. }
  4715. RestoreConstraint(originalEnforceConstraint);
  4716. return ret; //since the top level element is a schema return
  4717. }
  4718. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI==Keywords.XSDNS) {
  4719. // load XSD schema and exit
  4720. if ((mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema)) {
  4721. ReadXmlSchema(reader, denyResolving);
  4722. }
  4723. else
  4724. reader.Skip();
  4725. RestoreConstraint(originalEnforceConstraint);
  4726. return ret; //since the top level element is a schema return
  4727. }
  4728. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal)) {
  4729. if (this.DataSet != null) { // we should not throw for constraint, we already will throw for unsupported schema, so restore enforce cost, but not via property
  4730. this.DataSet.RestoreEnforceConstraints(originalEnforceConstraint);
  4731. }
  4732. else {
  4733. this.enforceConstraints = originalEnforceConstraint;
  4734. }
  4735. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  4736. }
  4737. // now either the top level node is a table and we load it through dataReader...
  4738. // ... or backup the top node and all its attributes
  4739. topNode = xdoc.CreateElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  4740. if (reader.HasAttributes) {
  4741. int attrCount = reader.AttributeCount;
  4742. for (int i=0;i<attrCount;i++) {
  4743. reader.MoveToAttribute(i);
  4744. if (reader.NamespaceURI.Equals(Keywords.XSD_XMLNS_NS))
  4745. topNode.SetAttribute(reader.Name, reader.GetAttribute(i));
  4746. else {
  4747. XmlAttribute attr = topNode.SetAttributeNode(reader.LocalName, reader.NamespaceURI);
  4748. attr.Prefix = reader.Prefix;
  4749. attr.Value = reader.GetAttribute(i);
  4750. }
  4751. }
  4752. }
  4753. reader.Read();
  4754. }
  4755. while(MoveToElement(reader, iCurrentDepth)) {
  4756. if (reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI==Keywords.XDRNS) {
  4757. // load XDR schema
  4758. if (!fSchemaFound && !fDataFound && (mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema)) {
  4759. ReadXDRSchema(reader);
  4760. fSchemaFound = true;
  4761. fIsXdr = true;
  4762. }
  4763. else {
  4764. reader.Skip();
  4765. }
  4766. continue;
  4767. }
  4768. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI==Keywords.XSDNS) {
  4769. // load XSD schema and exit
  4770. if ((mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema)) {
  4771. ReadXmlSchema(reader, denyResolving);
  4772. fSchemaFound = true;
  4773. }
  4774. else {
  4775. reader.Skip();
  4776. }
  4777. continue;
  4778. }
  4779. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  4780. if ((mode == XmlReadMode.DiffGram) || (mode == XmlReadMode.IgnoreSchema)) {
  4781. if (Columns.Count == 0) {
  4782. if(reader.IsEmptyElement) {
  4783. reader.Read();
  4784. return XmlReadMode.DiffGram;
  4785. }
  4786. throw ExceptionBuilder.DataTableInferenceNotSupported();
  4787. }
  4788. this.ReadXmlDiffgram(reader);
  4789. ret = XmlReadMode.DiffGram;
  4790. }
  4791. else {
  4792. reader.Skip();
  4793. }
  4794. continue;
  4795. }
  4796. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal)) {
  4797. if (this.DataSet != null) { // we should not throw for constraint, we already will throw for unsupported schema, so restore enforce cost, but not via property
  4798. this.DataSet.RestoreEnforceConstraints(originalEnforceConstraint);
  4799. }
  4800. else {
  4801. this.enforceConstraints = originalEnforceConstraint;
  4802. }
  4803. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  4804. }
  4805. if (mode == XmlReadMode.DiffGram) {
  4806. reader.Skip();
  4807. continue; // we do not read data in diffgram mode
  4808. }
  4809. // if we are here we found some data
  4810. fDataFound = true;
  4811. if (mode == XmlReadMode.InferSchema) { //save the node in DOM until the end;
  4812. XmlNode node = xdoc.ReadNode(reader);
  4813. topNode.AppendChild(node);
  4814. }
  4815. else {
  4816. if (Columns.Count == 0) {
  4817. throw ExceptionBuilder.DataTableInferenceNotSupported();
  4818. }
  4819. if (xmlload == null)
  4820. xmlload = new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema);
  4821. xmlload.LoadData(reader);
  4822. }
  4823. } //end of the while
  4824. // read the closing tag of the current element
  4825. ReadEndElement(reader);
  4826. // now top node contains the data part
  4827. xdoc.AppendChild(topNode);
  4828. if (xmlload == null)
  4829. xmlload = new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema);
  4830. if (mode == XmlReadMode.DiffGram) {
  4831. // we already got the diffs through XmlReader interface
  4832. RestoreConstraint(originalEnforceConstraint);
  4833. return ret;
  4834. }
  4835. //todo
  4836. // Load Data
  4837. if (mode == XmlReadMode.InferSchema) {
  4838. if (Columns.Count == 0) {
  4839. throw ExceptionBuilder.DataTableInferenceNotSupported();
  4840. }
  4841. // [....] xmlload.InferSchema(xdoc, null);
  4842. // [....] xmlload.LoadData(xdoc);
  4843. }
  4844. }
  4845. RestoreConstraint(originalEnforceConstraint);
  4846. return ret;
  4847. }
  4848. finally {
  4849. // Dev11 904428: prepare and cleanup rowDiffId hashtable
  4850. rowDiffIdUsage.Cleanup();
  4851. }
  4852. }
  4853. internal void ReadEndElement(XmlReader reader) {
  4854. while (reader.NodeType == XmlNodeType.Whitespace) {
  4855. reader.Skip();
  4856. }
  4857. if (reader.NodeType == XmlNodeType.None) {
  4858. reader.Skip();
  4859. }
  4860. else if (reader.NodeType == XmlNodeType.EndElement) {
  4861. reader.ReadEndElement();
  4862. }
  4863. }
  4864. internal void ReadXDRSchema(XmlReader reader) {
  4865. XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema
  4866. XmlNode schNode = xdoc.ReadNode(reader);;
  4867. //consume and ignore it - No support
  4868. }
  4869. internal bool MoveToElement(XmlReader reader, int depth) {
  4870. while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && reader.NodeType != XmlNodeType.Element && reader.Depth > depth) {
  4871. reader.Read();
  4872. }
  4873. return (reader.NodeType == XmlNodeType.Element);
  4874. }
  4875. private void ReadXmlDiffgram(XmlReader reader) { // fill correctly
  4876. int d = reader.Depth;
  4877. bool fEnforce = this.EnforceConstraints;
  4878. this.EnforceConstraints =false;
  4879. DataTable newDt;
  4880. bool isEmpty;
  4881. if (this.Rows.Count == 0) {
  4882. isEmpty = true;
  4883. newDt = this;
  4884. }
  4885. else {
  4886. isEmpty = false;
  4887. newDt = this.Clone();
  4888. newDt.EnforceConstraints = false;
  4889. }
  4890. newDt.Rows.nullInList = 0;
  4891. reader.MoveToContent();
  4892. if ((reader.LocalName != Keywords.DIFFGRAM) && (reader.NamespaceURI != Keywords.DFFNS))
  4893. return;
  4894. reader.Read();
  4895. if (reader.NodeType == XmlNodeType.Whitespace) {
  4896. MoveToElement(reader, reader.Depth - 1 /*iCurrentDepth*/); // skip over whitespaces.
  4897. }
  4898. newDt.fInLoadDiffgram = true;
  4899. if (reader.Depth > d) {
  4900. if ((reader.NamespaceURI != Keywords.DFFNS) && (reader.NamespaceURI != Keywords.MSDNS)) {
  4901. //we should be inside the dataset part
  4902. XmlDocument xdoc = new XmlDocument();
  4903. XmlElement node = xdoc.CreateElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  4904. reader.Read();
  4905. if (reader.Depth-1 > d) {
  4906. XmlDataLoader xmlload = new XmlDataLoader(newDt, false, node, false);
  4907. xmlload.isDiffgram = true; // turn on the special processing
  4908. xmlload.LoadData(reader);
  4909. }
  4910. ReadEndElement(reader);
  4911. }
  4912. if (((reader.LocalName == Keywords.SQL_BEFORE) && (reader.NamespaceURI == Keywords.DFFNS)) ||
  4913. ((reader.LocalName == Keywords.MSD_ERRORS) && (reader.NamespaceURI == Keywords.DFFNS)))
  4914. {
  4915. //this will consume the changes and the errors part
  4916. XMLDiffLoader diffLoader = new XMLDiffLoader();
  4917. diffLoader.LoadDiffGram(newDt, reader);
  4918. }
  4919. // get to the closing diff tag
  4920. while(reader.Depth > d) {
  4921. reader.Read();
  4922. }
  4923. // read the closing tag
  4924. ReadEndElement(reader);
  4925. }
  4926. if (newDt.Rows.nullInList > 0)
  4927. throw ExceptionBuilder.RowInsertMissing(newDt.TableName);
  4928. newDt.fInLoadDiffgram = false;
  4929. List<DataTable> tableList = new List<DataTable>();
  4930. tableList.Add(this);
  4931. CreateTableList(this, tableList);
  4932. // this is terrible, optimize it
  4933. for (int i = 0; i < tableList.Count ; i++) {
  4934. DataRelation[] relations = tableList[i].NestedParentRelations;
  4935. foreach(DataRelation rel in relations) {
  4936. if (rel != null && rel.ParentTable == tableList[i]) {
  4937. foreach (DataRow r in tableList[i].Rows) {
  4938. foreach (DataRelation rel2 in relations) {
  4939. r.CheckForLoops(rel2);
  4940. }
  4941. }
  4942. }
  4943. }
  4944. }
  4945. if (!isEmpty) {
  4946. this.Merge(newDt);
  4947. }
  4948. this.EnforceConstraints = fEnforce;
  4949. }
  4950. internal void ReadXSDSchema(XmlReader reader, bool denyResolving) {
  4951. XmlSchemaSet sSet = new XmlSchemaSet();
  4952. while (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI==Keywords.XSDNS) {
  4953. XmlSchema s = XmlSchema.Read(reader, null);
  4954. sSet.Add(s);
  4955. //read the end tag
  4956. ReadEndElement(reader);
  4957. }
  4958. sSet.Compile();
  4959. XSDSchema schema = new XSDSchema();
  4960. schema.LoadSchema(sSet, this);
  4961. }
  4962. public void ReadXmlSchema(Stream stream)
  4963. {
  4964. if (stream == null)
  4965. return;
  4966. ReadXmlSchema( new XmlTextReader( stream ), false );
  4967. }
  4968. public void ReadXmlSchema(TextReader reader)
  4969. {
  4970. if (reader == null)
  4971. return;
  4972. ReadXmlSchema( new XmlTextReader( reader ), false );
  4973. }
  4974. [ResourceExposure(ResourceScope.Machine)]
  4975. [ResourceConsumption(ResourceScope.Machine)]
  4976. public void ReadXmlSchema(String fileName)
  4977. {
  4978. XmlTextReader xr = new XmlTextReader(fileName);
  4979. try {
  4980. ReadXmlSchema( xr, false );
  4981. }
  4982. finally {
  4983. xr.Close();
  4984. }
  4985. }
  4986. public void ReadXmlSchema(XmlReader reader)
  4987. {
  4988. ReadXmlSchema(reader, false);
  4989. }
  4990. internal void ReadXmlSchema(XmlReader reader, bool denyResolving)
  4991. {
  4992. IntPtr hscp;
  4993. Bid.ScopeEnter(out hscp, "<ds.DataTable.ReadXmlSchema|INFO> %d#, denyResolving=%d{bool}\n", ObjectID, denyResolving);
  4994. try{
  4995. DataSet ds = new DataSet();
  4996. SerializationFormat cachedRemotingFormat = this.RemotingFormat;
  4997. // fxcop: ReadXmlSchema will provide the CaseSensitive, Locale, Namespace information
  4998. ds.ReadXmlSchema(reader, denyResolving);
  4999. string CurrentTableFullName = ds.MainTableName;
  5000. if (Common.ADP.IsEmpty(this.tableName) && Common.ADP.IsEmpty(CurrentTableFullName))
  5001. return;
  5002. DataTable currentTable = null;
  5003. if (!Common.ADP.IsEmpty(this.tableName)) {
  5004. if (!Common.ADP.IsEmpty(this.Namespace)) {
  5005. currentTable = ds.Tables[this.tableName, this.Namespace];
  5006. }
  5007. else {//SQL BU defect tracking 240293
  5008. int tableIndex = ds.Tables.InternalIndexOf(this.tableName);
  5009. if (tableIndex > -1) {
  5010. currentTable = ds.Tables[tableIndex];
  5011. }
  5012. }
  5013. }
  5014. else{ //!Common.ADP.IsEmpty(CurrentTableFullName)
  5015. string CurrentTableNamespace = "";
  5016. int nsSeperator = CurrentTableFullName.IndexOf(':');
  5017. if (nsSeperator > -1) {
  5018. CurrentTableNamespace = CurrentTableFullName.Substring(0, nsSeperator);
  5019. }
  5020. string CurrentTableName = CurrentTableFullName.Substring(nsSeperator + 1, CurrentTableFullName.Length - nsSeperator -1);
  5021. currentTable = ds.Tables[CurrentTableName, CurrentTableNamespace];
  5022. }
  5023. if (currentTable == null) { // bug fix :99186
  5024. string qTableName = string.Empty;
  5025. if (!Common.ADP.IsEmpty(this.tableName)) {
  5026. qTableName = (this.Namespace.Length > 0)? (this.Namespace + ":" + this.tableName):this.tableName;
  5027. }
  5028. else {
  5029. qTableName = CurrentTableFullName ;
  5030. }
  5031. throw ExceptionBuilder.TableNotFound(qTableName);
  5032. }
  5033. currentTable._remotingFormat = cachedRemotingFormat;
  5034. List<DataTable> tableList = new List<DataTable>();
  5035. tableList.Add(currentTable);
  5036. CreateTableList(currentTable, tableList);
  5037. List<DataRelation> relationList = new List<DataRelation>();
  5038. CreateRelationList(tableList, relationList);
  5039. if (relationList.Count == 0) {
  5040. if (this.Columns.Count == 0) {
  5041. DataTable tempTable = currentTable;
  5042. if (tempTable != null)
  5043. tempTable.CloneTo(this, null, false); // we may have issue Amir
  5044. if (this.DataSet == null && this.tableNamespace == null) { // webdata 105506
  5045. // for standalone table, clone wont get these correctly, since they may come with inheritance
  5046. this.tableNamespace = tempTable.Namespace;
  5047. }
  5048. }
  5049. return;
  5050. }
  5051. else {
  5052. if (Common.ADP.IsEmpty(this.TableName)) {
  5053. this.TableName = currentTable.TableName;
  5054. if (!Common.ADP.IsEmpty(currentTable.Namespace)) {
  5055. this.Namespace = currentTable.Namespace;
  5056. }
  5057. }
  5058. if (this.DataSet == null) {
  5059. DataSet dataset = new DataSet(ds.DataSetName);
  5060. // webdata 105506
  5061. // if user set values on DataTable, it isn't necessary
  5062. // to set them on the DataSet because they won't be inherited
  5063. // but it is simpler to set them in both places
  5064. // if user did not set values on DataTable, it is required
  5065. // to set them on the DataSet so the table will inherit
  5066. // the value already on the Datatable
  5067. dataset.SetLocaleValue(ds.Locale, ds.ShouldSerializeLocale());
  5068. dataset.CaseSensitive = ds.CaseSensitive;
  5069. dataset.Namespace = ds.Namespace;
  5070. dataset.mainTableName = ds.mainTableName;
  5071. dataset.RemotingFormat = ds.RemotingFormat;
  5072. dataset.Tables.Add(this);
  5073. }
  5074. DataTable targetTable = CloneHierarchy(currentTable, this.DataSet, null);
  5075. foreach(DataTable tempTable in tableList) {
  5076. DataTable destinationTable = this.DataSet.Tables[tempTable.tableName, tempTable.Namespace];
  5077. DataTable sourceTable = ds.Tables[tempTable.tableName, tempTable.Namespace];
  5078. foreach(Constraint tempConstrain in sourceTable.Constraints) {
  5079. ForeignKeyConstraint fkc = tempConstrain as ForeignKeyConstraint; // we have already cloned the UKC when cloning the datatable
  5080. if (fkc != null) {
  5081. if (fkc.Table != fkc.RelatedTable) {
  5082. if (tableList.Contains(fkc.Table) && tableList.Contains(fkc.RelatedTable)) {
  5083. ForeignKeyConstraint newFKC = (ForeignKeyConstraint)fkc.Clone(destinationTable.DataSet);
  5084. if (!destinationTable.Constraints.Contains(newFKC.ConstraintName))
  5085. destinationTable.Constraints.Add(newFKC); // we know that the dest table is already in the table
  5086. }
  5087. }
  5088. }
  5089. }
  5090. }
  5091. foreach(DataRelation rel in relationList) {
  5092. if (!this.DataSet.Relations.Contains(rel.RelationName))
  5093. this.DataSet.Relations.Add(rel.Clone(this.DataSet));
  5094. }
  5095. bool hasExternaldependency = false;
  5096. foreach(DataTable tempTable in tableList) {
  5097. foreach(DataColumn dc in tempTable.Columns) {
  5098. hasExternaldependency = false;
  5099. if (dc.Expression.Length != 0) {
  5100. DataColumn[] dependency = dc.DataExpression.GetDependency();
  5101. for (int j = 0; j < dependency.Length; j++) {
  5102. if (!tableList.Contains(dependency[j].Table)) {
  5103. hasExternaldependency = true;
  5104. break;
  5105. }
  5106. }
  5107. }
  5108. if (!hasExternaldependency) {
  5109. this.DataSet.Tables[tempTable.TableName, tempTable.Namespace].Columns[dc.ColumnName].Expression = dc.Expression;
  5110. }
  5111. }
  5112. hasExternaldependency = false;
  5113. }
  5114. }
  5115. }
  5116. finally{
  5117. Bid.ScopeLeave(ref hscp);
  5118. }
  5119. }
  5120. private void CreateTableList(DataTable currentTable, List<DataTable> tableList) {
  5121. foreach( DataRelation r in currentTable.ChildRelations ) {
  5122. if (! tableList.Contains(r.ChildTable)) {
  5123. tableList.Add(r.ChildTable);
  5124. CreateTableList(r.ChildTable, tableList);
  5125. }
  5126. }
  5127. }
  5128. private void CreateRelationList(List<DataTable> tableList, List<DataRelation> relationList) {
  5129. foreach(DataTable table in tableList) {
  5130. foreach( DataRelation r in table.ChildRelations) {
  5131. if (tableList.Contains(r.ChildTable) && tableList.Contains(r.ParentTable)) {
  5132. relationList.Add(r);
  5133. }
  5134. }
  5135. }
  5136. }
  5137. /**************************************************************************
  5138. The V2.0 (no V1.0 or V1.1) WSDL for Untyped DataTable being returned as a result (no parameters)
  5139. <s:element name="anyUserSpecifiedMethodName">
  5140. <!-- This is where parameters go -->
  5141. <s:complexType />
  5142. </s:element>
  5143. <s:element name="anyUserSpecifiedMethodName"+"Response">
  5144. <s:complexType>
  5145. <s:sequence>
  5146. <s:element minOccurs="0" maxOccurs="1" name="anyUserSpecifiedMethodName"+"Result">
  5147. <s:complexType>
  5148. <s:sequence>
  5149. <s:any minOccurs="0" maxOccurs="unbounded" namespace="http://www.w3.org/2001/XMLSchema" processContents="lax" />
  5150. <s:any minOccurs="1" namespace="urn:schemas-microsoft-com:xml-diffgram-v1" processContents="lax" />
  5151. </s:sequence>
  5152. </s:complexType>
  5153. </s:element>
  5154. </s:sequence>
  5155. </s:complexType>
  5156. </s:element>
  5157. Typed DataTable is not supported in WSDL (SQLBU 444636)
  5158. either fails because xsd generates its typed DataTable with an internal parameterless ctor
  5159. or System.NullReferenceException: Object reference not set to an instance of an object. (if namespace of StronglyTyped DataTable is not set)
  5160. at System.Data.XmlTreeGen.FindTargetNamespace(DataTable table)
  5161. or System.InvalidOperationException: Schema Id is missing. The schema returned from WebServiceDataSetServer.Service+StudentsDataTable.GetSchema() must have an Id.
  5162. at System.Xml.Serialization.SerializableMapping.RetrieveSerializableSchema()
  5163. *****************************************************************************/
  5164. public static XmlSchemaComplexType GetDataTableSchema(XmlSchemaSet schemaSet) {
  5165. XmlSchemaComplexType type = new XmlSchemaComplexType();
  5166. XmlSchemaSequence sequence = new XmlSchemaSequence();
  5167. XmlSchemaAny any = new XmlSchemaAny();
  5168. any.Namespace = XmlSchema.Namespace;
  5169. any.MinOccurs = 0;
  5170. any.MaxOccurs = Decimal.MaxValue;
  5171. any.ProcessContents = XmlSchemaContentProcessing.Lax;
  5172. sequence.Items.Add(any);
  5173. any = new XmlSchemaAny();
  5174. any.Namespace = Keywords.DFFNS;
  5175. any.MinOccurs = 1; // when recognizing WSDL - MinOccurs="0" denotes DataSet, a MinOccurs="1" for DataTable
  5176. any.ProcessContents = XmlSchemaContentProcessing.Lax;
  5177. sequence.Items.Add(any);
  5178. type.Particle = sequence;
  5179. return type;
  5180. }
  5181. XmlSchema IXmlSerializable.GetSchema() {
  5182. return GetSchema();
  5183. }
  5184. protected virtual XmlSchema GetSchema() {
  5185. if (GetType() == typeof(DataTable)) {
  5186. return null;
  5187. }
  5188. MemoryStream stream = new MemoryStream();
  5189. XmlWriter writer = new XmlTextWriter(stream, null);
  5190. if (writer != null) {
  5191. (new XmlTreeGen(SchemaFormat.WebService)).Save(this, writer);
  5192. }
  5193. stream.Position = 0;
  5194. return XmlSchema.Read(new XmlTextReader(stream), null);
  5195. }
  5196. void IXmlSerializable.ReadXml(XmlReader reader) {
  5197. IXmlTextParser textReader = reader as IXmlTextParser;
  5198. bool fNormalization = true;
  5199. if (textReader != null) {
  5200. fNormalization = textReader.Normalized;
  5201. textReader.Normalized = false;
  5202. }
  5203. ReadXmlSerializable(reader);
  5204. if (textReader != null) {
  5205. textReader.Normalized = fNormalization;
  5206. }
  5207. }
  5208. void IXmlSerializable.WriteXml(XmlWriter writer) {
  5209. WriteXmlSchema(writer, false);
  5210. WriteXml(writer, XmlWriteMode.DiffGram, false);
  5211. }
  5212. protected virtual void ReadXmlSerializable(XmlReader reader) {
  5213. ReadXml(reader, XmlReadMode.DiffGram, true);
  5214. }
  5215. /*
  5216. [
  5217. DefaultValue(false),
  5218. ResCategoryAttribute(Res.DataCategory_Data),
  5219. ResDescriptionAttribute(Res.DataTableSerializeHierarchy)
  5220. ]
  5221. public bool SerializeHierarchy {
  5222. get {
  5223. return this.serializeHierarchy;
  5224. }
  5225. set {
  5226. this.serializeHierarchy = value;
  5227. }
  5228. }
  5229. */
  5230. // RowDiffIdUsageSection & DSRowDiffIdUsageSection Usage:
  5231. //
  5232. // DataTable.[DS]RowDiffIdUsageSection rowDiffIdUsage = new DataTable.[DS]RowDiffIdUsageSection();
  5233. // try {
  5234. // rowDiffIdUsage.Prepare(DataTable or DataSet, depending on type);
  5235. //
  5236. // // code that requires RowDiffId usage
  5237. //
  5238. // }
  5239. // finally {
  5240. // rowDiffIdUsage.Cleanup();
  5241. // }
  5242. //
  5243. // Nested calls are allowed on different tables. For example, user can register to row change events and trigger
  5244. // ReadXml on different table/ds). But, if user code will try to call ReadXml on table that is already in the scope,
  5245. // this code will assert since nested calls on same table are unsupported.
  5246. internal struct RowDiffIdUsageSection
  5247. {
  5248. #if DEBUG
  5249. // This list contains tables currently used in diffgram processing, not including new tables that might be added later during.
  5250. // if diffgram processing is not started, this value must be null. when it starts, relevant method should call Prepare.
  5251. // Notes:
  5252. // * in case of ReadXml on empty DataSet, this list can be initialized as empty (so empty list != null).
  5253. // * only one scope is allowed on single thread, either for datatable or dataset
  5254. // * assert is triggered if same table is added to this list twice
  5255. //
  5256. // do not allocate TLS data in RETAIL bits!
  5257. [ThreadStatic]
  5258. internal static List<DataTable> s_usedTables;
  5259. #endif //DEBUG
  5260. DataTable _targetTable;
  5261. internal void Prepare(DataTable table)
  5262. {
  5263. Debug.Assert(_targetTable == null, "do not reuse this section");
  5264. Debug.Assert(table != null);
  5265. Debug.Assert(table.rowDiffId == null, "rowDiffId wasn't previously cleared");
  5266. #if DEBUG
  5267. Debug.Assert(s_usedTables == null || !s_usedTables.Contains(table),
  5268. "Nested call with same table can cause data corruption!");
  5269. #endif //DEBUG
  5270. #if DEBUG
  5271. if (s_usedTables == null)
  5272. s_usedTables = new List<DataTable>();
  5273. s_usedTables.Add(table);
  5274. #endif //DEBUG
  5275. _targetTable = table;
  5276. table.rowDiffId = null;
  5277. }
  5278. [Conditional("DEBUG")]
  5279. internal void Cleanup()
  5280. {
  5281. // cannot assume target table was set - ThreadAbortException can be raised before Start is called
  5282. if (_targetTable != null)
  5283. {
  5284. #if DEBUG
  5285. Debug.Assert(s_usedTables != null && s_usedTables.Contains(_targetTable), "missing Prepare before Cleanup");
  5286. if (s_usedTables != null)
  5287. {
  5288. s_usedTables.Remove(_targetTable);
  5289. if (s_usedTables.Count == 0)
  5290. s_usedTables = null;
  5291. }
  5292. #endif //DEBUG
  5293. _targetTable.rowDiffId = null;
  5294. }
  5295. }
  5296. [Conditional("DEBUG")]
  5297. internal static void Assert(string message)
  5298. {
  5299. #if DEBUG
  5300. // this code asserts scope was created, but it does not assert that the table was included in it
  5301. // note that in case of DataSet, new tables might be added to the list in which case they won't appear in s_usedTables.
  5302. Debug.Assert(s_usedTables != null, message);
  5303. #endif //DEBUG
  5304. }
  5305. }
  5306. internal struct DSRowDiffIdUsageSection
  5307. {
  5308. DataSet _targetDS;
  5309. internal void Prepare(DataSet ds)
  5310. {
  5311. Debug.Assert(_targetDS == null, "do not reuse this section");
  5312. Debug.Assert(ds != null);
  5313. _targetDS = ds;
  5314. #if DEBUG
  5315. // initialize list of tables out of current tables
  5316. // note: it might remain empty (still initialization is needed for assert to operate)
  5317. if (RowDiffIdUsageSection.s_usedTables == null)
  5318. RowDiffIdUsageSection.s_usedTables = new List<DataTable>();
  5319. #endif //DEBUG
  5320. for (int tableIndex = 0; tableIndex < ds.Tables.Count; ++tableIndex)
  5321. {
  5322. DataTable table = ds.Tables[tableIndex];
  5323. #if DEBUG
  5324. Debug.Assert(!RowDiffIdUsageSection.s_usedTables.Contains(table), "Nested call with same table can cause data corruption!");
  5325. RowDiffIdUsageSection.s_usedTables.Add(table);
  5326. #endif //DEBUG
  5327. Debug.Assert(table.rowDiffId == null, "rowDiffId wasn't previously cleared");
  5328. table.rowDiffId = null;
  5329. }
  5330. }
  5331. [Conditional("DEBUG")]
  5332. internal void Cleanup()
  5333. {
  5334. // cannot assume target was set - ThreadAbortException can be raised before Start is called
  5335. if (_targetDS != null)
  5336. {
  5337. #if DEBUG
  5338. Debug.Assert(RowDiffIdUsageSection.s_usedTables != null, "missing Prepare before Cleanup");
  5339. #endif //DEBUG
  5340. for (int tableIndex = 0; tableIndex < _targetDS.Tables.Count; ++tableIndex)
  5341. {
  5342. DataTable table = _targetDS.Tables[tableIndex];
  5343. #if DEBUG
  5344. // cannot assert that table exists in the usedTables - new tables might be
  5345. // created during diffgram processing in DataSet.ReadXml.
  5346. if (RowDiffIdUsageSection.s_usedTables != null)
  5347. RowDiffIdUsageSection.s_usedTables.Remove(table);
  5348. #endif //DEBUG
  5349. table.rowDiffId = null;
  5350. }
  5351. #if DEBUG
  5352. if (RowDiffIdUsageSection.s_usedTables != null && RowDiffIdUsageSection.s_usedTables.Count == 0)
  5353. RowDiffIdUsageSection.s_usedTables = null; // out-of-scope
  5354. #endif //DEBUG
  5355. }
  5356. }
  5357. }
  5358. internal Hashtable RowDiffId {
  5359. get {
  5360. // assert scope has been created either with RowDiffIdUsageSection.Prepare or DSRowDiffIdUsageSection.Prepare
  5361. RowDiffIdUsageSection.Assert("missing call to RowDiffIdUsageSection.Prepare or DSRowDiffIdUsageSection.Prepare");
  5362. if (rowDiffId == null)
  5363. rowDiffId = new Hashtable();
  5364. return rowDiffId;
  5365. }
  5366. }
  5367. internal int ObjectID {
  5368. get {
  5369. return _objectID;
  5370. }
  5371. }
  5372. internal void AddDependentColumn(DataColumn expressionColumn) {
  5373. if (dependentColumns == null)
  5374. dependentColumns = new List<DataColumn>();
  5375. if (!dependentColumns.Contains(expressionColumn)) {
  5376. // only remember unique columns but expect non-unique columns to be added
  5377. dependentColumns.Add(expressionColumn);
  5378. }
  5379. }
  5380. internal void RemoveDependentColumn(DataColumn expressionColumn) {
  5381. if (dependentColumns != null && dependentColumns.Contains(expressionColumn)) {
  5382. dependentColumns.Remove(expressionColumn);
  5383. }
  5384. }
  5385. internal void EvaluateExpressions() {
  5386. //evaluates all expressions for all rows in table
  5387. // SQLBU 414992: Serious performance issue when calling Merge
  5388. // this improves performance by only computing expressions when they are present
  5389. // and iterating over the rows instead of computing their position multiple times
  5390. if ((null != dependentColumns) && (0 < dependentColumns.Count)) {
  5391. foreach(DataRow row in Rows) {
  5392. // only evaluate original values if different from current.
  5393. if (row.oldRecord != -1 && row.oldRecord != row.newRecord) {
  5394. EvaluateDependentExpressions(dependentColumns, row, DataRowVersion.Original, null);
  5395. }
  5396. if (row.newRecord != -1) {
  5397. EvaluateDependentExpressions(dependentColumns, row, DataRowVersion.Current, null);
  5398. }
  5399. if (row.tempRecord != -1) {
  5400. EvaluateDependentExpressions(dependentColumns, row, DataRowVersion.Proposed, null);
  5401. }
  5402. }
  5403. }
  5404. }
  5405. internal void EvaluateExpressions(DataRow row, DataRowAction action, List<DataRow> cachedRows) {
  5406. // evaluate all expressions for specified row
  5407. if (action == DataRowAction.Add ||
  5408. action == DataRowAction.Change||
  5409. (action == DataRowAction.Rollback && (row.oldRecord!=-1 || row.newRecord!=-1))) {
  5410. // only evaluate original values if different from current.
  5411. if (row.oldRecord != -1 && row.oldRecord != row.newRecord) {
  5412. EvaluateDependentExpressions(dependentColumns, row, DataRowVersion.Original, cachedRows);
  5413. }
  5414. if (row.newRecord != -1) {
  5415. EvaluateDependentExpressions(dependentColumns, row, DataRowVersion.Current, cachedRows);
  5416. }
  5417. if (row.tempRecord != -1) {
  5418. EvaluateDependentExpressions(dependentColumns, row, DataRowVersion.Proposed, cachedRows);
  5419. }
  5420. return;
  5421. }
  5422. else if ((action == DataRowAction.Delete || (action==DataRowAction.Rollback && row.oldRecord==-1 && row.newRecord==-1)) && dependentColumns != null) {
  5423. foreach(DataColumn col in dependentColumns) {
  5424. if (col.DataExpression != null && col.DataExpression.HasLocalAggregate() && col.Table == this) {
  5425. for (int j = 0; j < Rows.Count; j++) {
  5426. DataRow tableRow = Rows[j];
  5427. if (tableRow.oldRecord != -1 && tableRow.oldRecord != tableRow.newRecord) {
  5428. EvaluateDependentExpressions(dependentColumns, tableRow, DataRowVersion.Original, null);
  5429. }
  5430. }
  5431. for (int j = 0; j < Rows.Count; j++)
  5432. {
  5433. DataRow tableRow = Rows[j];
  5434. if (tableRow.tempRecord != -1)
  5435. {
  5436. EvaluateDependentExpressions(dependentColumns, tableRow, DataRowVersion.Proposed, null);
  5437. }
  5438. }
  5439. // VSTFDEVDIV911434: Order is important here - we need to update proposed before current
  5440. // Oherwise rows that are in edit state will get ListChanged/PropertyChanged event before default value is changed
  5441. // It is also the reason why we are not doping it in the single loop: EvaluateDependentExpression can update the
  5442. // whole table, if it happens, current for all but first row is updated before proposed value
  5443. for (int j = 0; j < Rows.Count; j++)
  5444. {
  5445. DataRow tableRow = Rows[j];
  5446. if (tableRow.newRecord != -1)
  5447. {
  5448. EvaluateDependentExpressions(dependentColumns, tableRow, DataRowVersion.Current, null);
  5449. }
  5450. }
  5451. break;
  5452. }
  5453. }
  5454. if (cachedRows != null) {
  5455. foreach (DataRow relatedRow in cachedRows) {
  5456. if (relatedRow.oldRecord != -1 && relatedRow.oldRecord != relatedRow.newRecord) {
  5457. relatedRow.Table.EvaluateDependentExpressions(relatedRow.Table.dependentColumns, relatedRow, DataRowVersion.Original, null);
  5458. }
  5459. if (relatedRow.newRecord != -1) {
  5460. relatedRow.Table.EvaluateDependentExpressions(relatedRow.Table.dependentColumns, relatedRow, DataRowVersion.Current, null);
  5461. }
  5462. if (relatedRow.tempRecord != -1) {
  5463. relatedRow.Table.EvaluateDependentExpressions(relatedRow.Table.dependentColumns, relatedRow, DataRowVersion.Proposed, null);
  5464. }
  5465. }
  5466. }
  5467. }
  5468. }
  5469. internal void EvaluateExpressions(DataColumn column) {
  5470. // evaluates all rows for expression from specified column
  5471. Debug.Assert(column.Computed, "Only computed columns should be re-evaluated.");
  5472. int count = column.table.Rows.Count;
  5473. if (column.DataExpression.IsTableAggregate() && count > 0) {
  5474. // this value is a constant across the table.
  5475. object aggCurrent = column.DataExpression.Evaluate();
  5476. for (int j = 0; j < count; j++) {
  5477. DataRow row = column.table.Rows[j];
  5478. // only evaluate original values if different from current.
  5479. if (row.oldRecord != -1 && row.oldRecord != row.newRecord) {
  5480. column[row.oldRecord] = aggCurrent;
  5481. }
  5482. if (row.newRecord != -1) {
  5483. column[row.newRecord] = aggCurrent;
  5484. }
  5485. if (row.tempRecord != -1) {
  5486. column[row.tempRecord] = aggCurrent;
  5487. }
  5488. }
  5489. }
  5490. else {
  5491. for (int j = 0; j < count; j++) {
  5492. DataRow row = column.table.Rows[j];
  5493. if (row.oldRecord != -1 && row.oldRecord != row.newRecord) {
  5494. column[row.oldRecord] = column.DataExpression.Evaluate(row, DataRowVersion.Original);
  5495. }
  5496. if (row.newRecord != -1) {
  5497. column[row.newRecord] = column.DataExpression.Evaluate(row, DataRowVersion.Current);
  5498. }
  5499. if (row.tempRecord != -1) {
  5500. column[row.tempRecord] = column.DataExpression.Evaluate(row, DataRowVersion.Proposed);
  5501. }
  5502. }
  5503. }
  5504. // SQLBU 501916 - DataTable internal index is corrupted:'5'
  5505. column.Table.ResetInternalIndexes(column);
  5506. EvaluateDependentExpressions(column);
  5507. }
  5508. internal void EvaluateDependentExpressions(DataColumn column) {
  5509. // DataTable.Clear(), DataRowCollection.Clear() & DataColumn.set_Expression
  5510. if (column.dependentColumns != null) {
  5511. foreach (DataColumn dc in column.dependentColumns) {
  5512. if ((dc.table != null) && !Object.ReferenceEquals(column, dc)) { // SQLBU 502736
  5513. EvaluateExpressions(dc);
  5514. }
  5515. }
  5516. }
  5517. }
  5518. internal void EvaluateDependentExpressions(List<DataColumn> columns, DataRow row, DataRowVersion version, List<DataRow> cachedRows) {
  5519. if (columns == null)
  5520. return;
  5521. //Expression evaluation is done first over same table expressions.
  5522. int count = columns.Count;
  5523. for(int i = 0; i < count; i++) {
  5524. if (columns[i].Table == this) {// if this column is in my table
  5525. DataColumn dc = columns[i];
  5526. if (dc.DataExpression != null && dc.DataExpression.HasLocalAggregate()) {
  5527. // if column expression references a local Table aggregate we need to recalc it for the each row in the local table
  5528. DataRowVersion expressionVersion = (version == DataRowVersion.Proposed) ? DataRowVersion.Default : version;
  5529. bool isConst = dc.DataExpression.IsTableAggregate(); //is expression constant for entire table?
  5530. object newValue = null;
  5531. if (isConst) { //if new value, just compute once
  5532. newValue = dc.DataExpression.Evaluate(row, expressionVersion);
  5533. }
  5534. for (int j = 0; j < Rows.Count; j++) { //evaluate for all rows in the table
  5535. DataRow dr = Rows[j];
  5536. if (dr.RowState == DataRowState.Deleted) {
  5537. continue;
  5538. }
  5539. else if (expressionVersion == DataRowVersion.Original && (dr.oldRecord == -1 || dr.oldRecord == dr.newRecord)) {
  5540. continue;
  5541. }
  5542. if (!isConst) {
  5543. newValue = dc.DataExpression.Evaluate(dr, expressionVersion);
  5544. }
  5545. SilentlySetValue(dr, dc, expressionVersion, newValue);
  5546. }
  5547. }
  5548. else {
  5549. if (row.RowState == DataRowState.Deleted) {
  5550. continue;
  5551. }
  5552. else if (version == DataRowVersion.Original && (row.oldRecord == -1 || row.oldRecord == row.newRecord)) {
  5553. continue;
  5554. }
  5555. SilentlySetValue(row, dc, version, dc.DataExpression == null ? dc.DefaultValue : dc.DataExpression.Evaluate(row, version));
  5556. }
  5557. }
  5558. }
  5559. // now do expression evaluation for expression columns other tables.
  5560. count = columns.Count;
  5561. for(int i = 0; i < count; i++) {
  5562. DataColumn dc = columns[i];
  5563. // if this column is NOT in my table or it is in the table and is not a local aggregate (self refs)
  5564. if (dc.Table != this || (dc.DataExpression != null && !dc.DataExpression.HasLocalAggregate())) {
  5565. DataRowVersion foreignVer = (version == DataRowVersion.Proposed) ? DataRowVersion.Default : version;
  5566. // first - evaluate expressions for cachedRows (deletes & updates)
  5567. if (cachedRows != null) {
  5568. foreach (DataRow cachedRow in cachedRows) {
  5569. if (cachedRow.Table != dc.Table)
  5570. continue;
  5571. // don't update original version if child row doesn't have an oldRecord.
  5572. if (foreignVer == DataRowVersion.Original && cachedRow.newRecord == cachedRow.oldRecord)
  5573. continue;
  5574. if (cachedRow != null && ((cachedRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || cachedRow.oldRecord != -1))) {// if deleted GetRecordFromVersion will throw
  5575. object newValue = dc.DataExpression.Evaluate(cachedRow, foreignVer);
  5576. SilentlySetValue(cachedRow, dc, foreignVer, newValue);
  5577. }
  5578. }
  5579. }
  5580. // next check parent relations
  5581. for (int j = 0; j < ParentRelations.Count; j++) {
  5582. DataRelation relation = ParentRelations[j];
  5583. if (relation.ParentTable != dc.Table)
  5584. continue;
  5585. foreach (DataRow parentRow in row.GetParentRows(relation, version)) {
  5586. if (cachedRows != null && cachedRows.Contains(parentRow))
  5587. continue;
  5588. // don't update original version if child row doesn't have an oldRecord.
  5589. if (foreignVer == DataRowVersion.Original && parentRow.newRecord == parentRow.oldRecord)
  5590. continue;
  5591. if (parentRow != null && ((parentRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || parentRow.oldRecord != -1))) {// if deleted GetRecordFromVersion will throw
  5592. object newValue = dc.DataExpression.Evaluate(parentRow, foreignVer);
  5593. SilentlySetValue(parentRow, dc, foreignVer, newValue);
  5594. }
  5595. }
  5596. }
  5597. // next check child relations
  5598. for (int j = 0; j < ChildRelations.Count; j++) {
  5599. DataRelation relation = ChildRelations[j];
  5600. if (relation.ChildTable != dc.Table)
  5601. continue;
  5602. foreach (DataRow childRow in row.GetChildRows(relation, version)) {
  5603. // don't update original version if child row doesn't have an oldRecord.
  5604. if (cachedRows != null && cachedRows.Contains(childRow))
  5605. continue;
  5606. if (foreignVer == DataRowVersion.Original && childRow.newRecord == childRow.oldRecord)
  5607. continue;
  5608. if (childRow != null && ((childRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || childRow.oldRecord != -1))) { // if deleted GetRecordFromVersion will throw
  5609. object newValue = dc.DataExpression.Evaluate(childRow, foreignVer);
  5610. SilentlySetValue(childRow, dc, foreignVer, newValue);
  5611. }
  5612. }
  5613. }
  5614. }
  5615. }
  5616. }
  5617. }
  5618. }