SqlCommand.cs 282 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911
  1. //------------------------------------------------------------------------------
  2. // <copyright file="SqlCommand.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.SqlClient {
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using System.Collections.ObjectModel;
  13. using System.ComponentModel;
  14. using System.Configuration.Assemblies;
  15. using System.Data;
  16. using System.Data.Common;
  17. using System.Data.ProviderBase;
  18. using System.Data.Sql;
  19. using System.Data.SqlTypes;
  20. using System.Diagnostics;
  21. using System.Diagnostics.Tracing;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Linq;
  25. using System.Reflection;
  26. using System.Runtime.CompilerServices;
  27. using System.Runtime.ConstrainedExecution;
  28. using System.Runtime.Serialization.Formatters;
  29. using System.Security.Permissions;
  30. using System.Text;
  31. using System.Threading;
  32. using System.Threading.Tasks;
  33. using SysTx = System.Transactions;
  34. using System.Xml;
  35. using Microsoft.SqlServer.Server;
  36. [
  37. DefaultEvent("RecordsAffected"),
  38. ToolboxItem(true),
  39. Designer("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, " + AssemblyRef.MicrosoftVSDesigner)
  40. ]
  41. public sealed class SqlCommand : DbCommand, ICloneable {
  42. private static int _objectTypeCount; // Bid counter
  43. internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
  44. private string _commandText;
  45. private CommandType _commandType;
  46. private int _commandTimeout = ADP.DefaultCommandTimeout;
  47. private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
  48. private bool _designTimeInvisible;
  49. /// <summary>
  50. /// Indicates if the column encryption setting was set at-least once in the batch rpc mode, when using AddBatchCommand.
  51. /// </summary>
  52. private bool _wasBatchModeColumnEncryptionSettingSetOnce;
  53. /// <summary>
  54. /// Column Encryption Override. Defaults to SqlConnectionSetting, in which case
  55. /// it will be Enabled if SqlConnectionOptions.IsColumnEncryptionSettingEnabled = true, Disabled if false.
  56. /// This may also be used to set other behavior which overrides connection level setting.
  57. /// </summary>
  58. private SqlCommandColumnEncryptionSetting _columnEncryptionSetting = SqlCommandColumnEncryptionSetting.UseConnectionSetting;
  59. internal SqlDependency _sqlDep;
  60. #if DEBUG
  61. /// <summary>
  62. /// Force the client to sleep during sp_describe_parameter_encryption in the function TryFetchInputParameterEncryptionInfo.
  63. /// </summary>
  64. private static bool _sleepDuringTryFetchInputParameterEncryptionInfo = false;
  65. /// <summary>
  66. /// Force the client to sleep during sp_describe_parameter_encryption in the function RunExecuteReaderTds.
  67. /// </summary>
  68. private static bool _sleepDuringRunExecuteReaderTdsForSpDescribeParameterEncryption = false;
  69. /// <summary>
  70. /// Force the client to sleep during sp_describe_parameter_encryption after ReadDescribeEncryptionParameterResults.
  71. /// </summary>
  72. private static bool _sleepAfterReadDescribeEncryptionParameterResults = false;
  73. #endif
  74. // devnote: Prepare
  75. // Against 7.0 Server (Sphinx) a prepare/unprepare requires an extra roundtrip to the server.
  76. //
  77. // From 8.0 (Shiloh) and above (Yukon) the preparation can be done as part of the command execution.
  78. //
  79. private enum EXECTYPE {
  80. UNPREPARED, // execute unprepared commands, all server versions (results in sp_execsql call)
  81. PREPAREPENDING, // prepare and execute command, 8.0 and above only (results in sp_prepexec call)
  82. PREPARED, // execute prepared commands, all server versions (results in sp_exec call)
  83. }
  84. // devnotes
  85. //
  86. // _hiddenPrepare
  87. // On 8.0 and above the Prepared state cannot be left. Once a command is prepared it will always be prepared.
  88. // A change in parameters, commandtext etc (IsDirty) automatically causes a hidden prepare
  89. //
  90. // _inPrepare will be set immediately before the actual prepare is done.
  91. // The OnReturnValue function will test this flag to determine whether the returned value is a _prepareHandle or something else.
  92. //
  93. // _prepareHandle - the handle of a prepared command. Apparently there can be multiple prepared commands at a time - a feature that we do not support yet.
  94. private bool _inPrepare = false;
  95. private int _prepareHandle = -1;
  96. private bool _hiddenPrepare = false;
  97. private int _preparedConnectionCloseCount = -1;
  98. private int _preparedConnectionReconnectCount = -1;
  99. private SqlParameterCollection _parameters;
  100. private SqlConnection _activeConnection;
  101. private bool _dirty = false; // true if the user changes the commandtext or number of parameters after the command is already prepared
  102. private EXECTYPE _execType = EXECTYPE.UNPREPARED; // by default, assume the user is not sharing a connection so the command has not been prepared
  103. private _SqlRPC[] _rpcArrayOf1 = null; // Used for RPC executes
  104. private _SqlRPC _rpcForEncryption = null; // Used for sp_describe_parameter_encryption RPC executes
  105. // cut down on object creation and cache all these
  106. // cached metadata
  107. private _SqlMetaDataSet _cachedMetaData;
  108. // Last TaskCompletionSource for reconnect task - use for cancellation only
  109. TaskCompletionSource<object> _reconnectionCompletionSource = null;
  110. #if DEBUG
  111. static internal int DebugForceAsyncWriteDelay { get; set; }
  112. #endif
  113. internal bool InPrepare {
  114. get {
  115. return _inPrepare;
  116. }
  117. }
  118. /// <summary>
  119. /// Return if column encryption setting is enabled.
  120. /// The order in the below if is important since _activeConnection.Parser can throw if the
  121. /// underlying tds connection is closed and we don't want to change the behavior for folks
  122. /// not trying to use transparent parameter encryption i.e. who don't use (SqlCommandColumnEncryptionSetting.Enabled or _activeConnection.IsColumnEncryptionSettingEnabled) here.
  123. /// </summary>
  124. internal bool IsColumnEncryptionEnabled {
  125. get {
  126. return (_columnEncryptionSetting == SqlCommandColumnEncryptionSetting.Enabled
  127. || (_columnEncryptionSetting == SqlCommandColumnEncryptionSetting.UseConnectionSetting && _activeConnection.IsColumnEncryptionSettingEnabled))
  128. && _activeConnection.Parser != null
  129. && _activeConnection.Parser.IsColumnEncryptionSupported;
  130. }
  131. }
  132. // Cached info for async executions
  133. private class CachedAsyncState {
  134. private int _cachedAsyncCloseCount = -1; // value of the connection's CloseCount property when the asyncResult was set; tracks when connections are closed after an async operation
  135. private TaskCompletionSource<object> _cachedAsyncResult = null;
  136. private SqlConnection _cachedAsyncConnection = null; // Used to validate that the connection hasn't changed when end the connection;
  137. private SqlDataReader _cachedAsyncReader = null;
  138. private RunBehavior _cachedRunBehavior = RunBehavior.ReturnImmediately;
  139. private string _cachedSetOptions = null;
  140. private string _cachedEndMethod = null;
  141. internal CachedAsyncState () {
  142. }
  143. internal SqlDataReader CachedAsyncReader {
  144. get {return _cachedAsyncReader;}
  145. }
  146. internal RunBehavior CachedRunBehavior {
  147. get {return _cachedRunBehavior;}
  148. }
  149. internal string CachedSetOptions {
  150. get {return _cachedSetOptions;}
  151. }
  152. internal bool PendingAsyncOperation {
  153. get {return (null != _cachedAsyncResult);}
  154. }
  155. internal string EndMethodName {
  156. get { return _cachedEndMethod; }
  157. }
  158. internal bool IsActiveConnectionValid(SqlConnection activeConnection) {
  159. return (_cachedAsyncConnection == activeConnection && _cachedAsyncCloseCount == activeConnection.CloseCount);
  160. }
  161. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  162. internal void ResetAsyncState() {
  163. _cachedAsyncCloseCount = -1;
  164. _cachedAsyncResult = null;
  165. if (_cachedAsyncConnection != null) {
  166. _cachedAsyncConnection.AsyncCommandInProgress = false;
  167. _cachedAsyncConnection = null;
  168. }
  169. _cachedAsyncReader = null;
  170. _cachedRunBehavior = RunBehavior.ReturnImmediately;
  171. _cachedSetOptions = null;
  172. _cachedEndMethod = null;
  173. }
  174. internal void SetActiveConnectionAndResult(TaskCompletionSource<object> completion, string endMethod, SqlConnection activeConnection) {
  175. Debug.Assert(activeConnection != null, "Unexpected null connection argument on SetActiveConnectionAndResult!");
  176. TdsParser parser = activeConnection.Parser;
  177. if ((parser == null) || (parser.State == TdsParserState.Closed) || (parser.State == TdsParserState.Broken)) {
  178. throw ADP.ClosedConnectionError();
  179. }
  180. _cachedAsyncCloseCount = activeConnection.CloseCount;
  181. _cachedAsyncResult = completion;
  182. if (null != activeConnection && !parser.MARSOn) {
  183. if (activeConnection.AsyncCommandInProgress)
  184. throw SQL.MARSUnspportedOnConnection();
  185. }
  186. _cachedAsyncConnection = activeConnection;
  187. // Should only be needed for non-MARS, but set anyways.
  188. _cachedAsyncConnection.AsyncCommandInProgress = true;
  189. _cachedEndMethod = endMethod;
  190. }
  191. internal void SetAsyncReaderState (SqlDataReader ds, RunBehavior runBehavior, string optionSettings) {
  192. _cachedAsyncReader = ds;
  193. _cachedRunBehavior = runBehavior;
  194. _cachedSetOptions = optionSettings;
  195. }
  196. }
  197. CachedAsyncState _cachedAsyncState = null;
  198. private CachedAsyncState cachedAsyncState {
  199. get {
  200. if (_cachedAsyncState == null) {
  201. _cachedAsyncState = new CachedAsyncState ();
  202. }
  203. return _cachedAsyncState;
  204. }
  205. }
  206. // sql reader will pull this value out for each NextResult call. It is not cumulative
  207. // _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches
  208. internal int _rowsAffected = -1; // rows affected by the command
  209. // number of rows affected by sp_describe_parameter_encryption.
  210. // The below line is used only for debug asserts and not exposed publicly or impacts functionality otherwise.
  211. private int _rowsAffectedBySpDescribeParameterEncryption = -1;
  212. private SqlNotificationRequest _notification;
  213. private bool _notificationAutoEnlist = true; // Notifications auto enlistment is turned on by default
  214. // transaction support
  215. private SqlTransaction _transaction;
  216. private StatementCompletedEventHandler _statementCompletedEventHandler;
  217. private TdsParserStateObject _stateObj; // this is the TDS session we're using.
  218. // Volatile bool used to synchronize with cancel thread the state change of an executing
  219. // command going from pre-processing to obtaining a stateObject. The cancel synchronization
  220. // we require in the command is only from entering an Execute* API to obtaining a
  221. // stateObj. Once a stateObj is successfully obtained, cancel synchronization is handled
  222. // by the stateObject.
  223. private volatile bool _pendingCancel;
  224. private bool _batchRPCMode;
  225. private List<_SqlRPC> _RPCList;
  226. private _SqlRPC[] _SqlRPCBatchArray;
  227. private _SqlRPC[] _sqlRPCParameterEncryptionReqArray;
  228. private List<SqlParameterCollection> _parameterCollectionList;
  229. private int _currentlyExecutingBatch;
  230. /// <summary>
  231. /// This variable is used to keep track of which RPC batch's results are being read when reading the results of
  232. /// describe parameter encryption RPC requests in BatchRPCMode.
  233. /// </summary>
  234. private int _currentlyExecutingDescribeParameterEncryptionRPC;
  235. /// <summary>
  236. /// A flag to indicate if we have in-progress describe parameter encryption RPC requests.
  237. /// Reset to false when completed.
  238. /// </summary>
  239. private bool _isDescribeParameterEncryptionRPCCurrentlyInProgress;
  240. /// <summary>
  241. /// Return the flag that indicates if describe parameter encryption RPC requests are in-progress.
  242. /// </summary>
  243. internal bool IsDescribeParameterEncryptionRPCCurrentlyInProgress {
  244. get {
  245. return _isDescribeParameterEncryptionRPCCurrentlyInProgress;
  246. }
  247. }
  248. //
  249. // Smi execution-specific stuff
  250. //
  251. sealed private class CommandEventSink : SmiEventSink_Default {
  252. private SqlCommand _command;
  253. internal CommandEventSink( SqlCommand command ) : base( ) {
  254. _command = command;
  255. }
  256. internal override void StatementCompleted( int rowsAffected ) {
  257. if (Bid.AdvancedOn) {
  258. Bid.Trace("<sc.SqlCommand.CommandEventSink.StatementCompleted|ADV> %d#, rowsAffected=%d.\n", _command.ObjectID, rowsAffected);
  259. }
  260. _command.InternalRecordsAffected = rowsAffected;
  261. //
  262. }
  263. internal override void BatchCompleted() {
  264. if (Bid.AdvancedOn) {
  265. Bid.Trace("<sc.SqlCommand.CommandEventSink.BatchCompleted|ADV> %d#.\n", _command.ObjectID);
  266. }
  267. }
  268. internal override void ParametersAvailable( SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues ) {
  269. if (Bid.AdvancedOn) {
  270. Bid.Trace("<sc.SqlCommand.CommandEventSink.ParametersAvailable|ADV> %d# metaData.Length=%d.\n", _command.ObjectID, (null!=metaData)?metaData.Length:-1);
  271. if (null != metaData) {
  272. for (int i=0; i < metaData.Length; i++) {
  273. Bid.Trace("<sc.SqlCommand.CommandEventSink.ParametersAvailable|ADV> %d#, metaData[%d] is %ls%ls\n",
  274. _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString());
  275. }
  276. }
  277. }
  278. Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.YukonVersion);
  279. _command.OnParametersAvailableSmi( metaData, parameterValues );
  280. }
  281. internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal)
  282. {
  283. if (Bid.AdvancedOn) {
  284. if (null != metaData) {
  285. Bid.Trace("<sc.SqlCommand.CommandEventSink.ParameterAvailable|ADV> %d#, metaData[%d] is %ls%ls\n",
  286. _command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString());
  287. }
  288. }
  289. Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion);
  290. _command.OnParameterAvailableSmi(metaData, parameterValues, ordinal);
  291. }
  292. }
  293. private SmiContext _smiRequestContext; // context that _smiRequest came from
  294. private CommandEventSink _smiEventSink;
  295. private SmiEventSink_DeferedProcessing _outParamEventSink;
  296. private CommandEventSink EventSink {
  297. get {
  298. if ( null == _smiEventSink ) {
  299. _smiEventSink = new CommandEventSink( this );
  300. }
  301. _smiEventSink.Parent = InternalSmiConnection.CurrentEventSink;
  302. return _smiEventSink;
  303. }
  304. }
  305. private SmiEventSink_DeferedProcessing OutParamEventSink {
  306. get {
  307. if (null == _outParamEventSink) {
  308. _outParamEventSink = new SmiEventSink_DeferedProcessing(EventSink);
  309. }
  310. else {
  311. _outParamEventSink.Parent = EventSink;
  312. }
  313. return _outParamEventSink;
  314. }
  315. }
  316. public SqlCommand() : base() {
  317. GC.SuppressFinalize(this);
  318. }
  319. public SqlCommand(string cmdText) : this() {
  320. CommandText = cmdText;
  321. }
  322. public SqlCommand(string cmdText, SqlConnection connection) : this() {
  323. CommandText = cmdText;
  324. Connection = connection;
  325. }
  326. public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction) : this() {
  327. CommandText = cmdText;
  328. Connection = connection;
  329. Transaction = transaction;
  330. }
  331. public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction, SqlCommandColumnEncryptionSetting columnEncryptionSetting) : this() {
  332. CommandText = cmdText;
  333. Connection = connection;
  334. Transaction = transaction;
  335. _columnEncryptionSetting = columnEncryptionSetting;
  336. }
  337. private SqlCommand(SqlCommand from) : this() { // Clone
  338. CommandText = from.CommandText;
  339. CommandTimeout = from.CommandTimeout;
  340. CommandType = from.CommandType;
  341. Connection = from.Connection;
  342. DesignTimeVisible = from.DesignTimeVisible;
  343. Transaction = from.Transaction;
  344. UpdatedRowSource = from.UpdatedRowSource;
  345. _columnEncryptionSetting = from.ColumnEncryptionSetting;
  346. SqlParameterCollection parameters = Parameters;
  347. foreach(object parameter in from.Parameters) {
  348. parameters.Add((parameter is ICloneable) ? (parameter as ICloneable).Clone() : parameter);
  349. }
  350. }
  351. [
  352. DefaultValue(null),
  353. Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
  354. ResCategoryAttribute(Res.DataCategory_Data),
  355. ResDescriptionAttribute(Res.DbCommand_Connection),
  356. ]
  357. new public SqlConnection Connection {
  358. get {
  359. return _activeConnection;
  360. }
  361. set {
  362. // Don't allow the connection to be changed while in a async opperation.
  363. if (_activeConnection != value && _activeConnection != null) { // If new value...
  364. if (cachedAsyncState.PendingAsyncOperation) { // If in pending async state, throw.
  365. throw SQL.CannotModifyPropertyAsyncOperationInProgress(SQL.Connection);
  366. }
  367. }
  368. // Check to see if the currently set transaction has completed. If so,
  369. // null out our local reference.
  370. if (null != _transaction && _transaction.Connection == null) {
  371. _transaction = null;
  372. }
  373. // If the connection has changes, then the request context may have changed as well
  374. _smiRequestContext = null;
  375. // Command is no longer prepared on new connection, cleanup prepare status
  376. if (IsPrepared) {
  377. if (_activeConnection != value && _activeConnection != null) {
  378. RuntimeHelpers.PrepareConstrainedRegions();
  379. try {
  380. #if DEBUG
  381. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  382. RuntimeHelpers.PrepareConstrainedRegions();
  383. try {
  384. tdsReliabilitySection.Start();
  385. #endif //DEBUG
  386. // cleanup
  387. Unprepare();
  388. #if DEBUG
  389. }
  390. finally {
  391. tdsReliabilitySection.Stop();
  392. }
  393. #endif //DEBUG
  394. }
  395. catch (System.OutOfMemoryException) {
  396. _activeConnection.InnerConnection.DoomThisConnection();
  397. throw;
  398. }
  399. catch (System.StackOverflowException) {
  400. _activeConnection.InnerConnection.DoomThisConnection();
  401. throw;
  402. }
  403. catch (System.Threading.ThreadAbortException) {
  404. _activeConnection.InnerConnection.DoomThisConnection();
  405. throw;
  406. }
  407. catch (Exception) {
  408. // we do not really care about errors in unprepare (may be the old connection went bad)
  409. }
  410. finally {
  411. // clean prepare status (even successfull Unprepare does not do that)
  412. _prepareHandle = -1;
  413. _execType = EXECTYPE.UNPREPARED;
  414. }
  415. }
  416. }
  417. _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios?
  418. Bid.Trace("<sc.SqlCommand.set_Connection|API> %d#, %d#\n", ObjectID, ((null != value) ? value.ObjectID : -1));
  419. }
  420. }
  421. override protected DbConnection DbConnection { // V1.2.3300
  422. get {
  423. return Connection;
  424. }
  425. set {
  426. Connection = (SqlConnection)value;
  427. }
  428. }
  429. private SqlInternalConnectionSmi InternalSmiConnection {
  430. get {
  431. return (SqlInternalConnectionSmi)_activeConnection.InnerConnection;
  432. }
  433. }
  434. private SqlInternalConnectionTds InternalTdsConnection {
  435. get {
  436. return (SqlInternalConnectionTds)_activeConnection.InnerConnection;
  437. }
  438. }
  439. private bool IsShiloh {
  440. get {
  441. Debug.Assert(_activeConnection != null, "The active connection is null!");
  442. if (_activeConnection == null)
  443. return false;
  444. return _activeConnection.IsShiloh;
  445. }
  446. }
  447. [
  448. DefaultValue(true),
  449. ResCategoryAttribute(Res.DataCategory_Notification),
  450. ResDescriptionAttribute(Res.SqlCommand_NotificationAutoEnlist),
  451. ]
  452. public bool NotificationAutoEnlist {
  453. get {
  454. return _notificationAutoEnlist;
  455. }
  456. set {
  457. _notificationAutoEnlist = value;
  458. }
  459. }
  460. [
  461. Browsable(false),
  462. DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), // MDAC 90471
  463. ResCategoryAttribute(Res.DataCategory_Notification),
  464. ResDescriptionAttribute(Res.SqlCommand_Notification),
  465. ]
  466. public SqlNotificationRequest Notification {
  467. get {
  468. return _notification;
  469. }
  470. set {
  471. Bid.Trace("<sc.SqlCommand.set_Notification|API> %d#\n", ObjectID);
  472. _sqlDep = null;
  473. _notification = value;
  474. }
  475. }
  476. internal SqlStatistics Statistics {
  477. get {
  478. if (null != _activeConnection) {
  479. if (_activeConnection.StatisticsEnabled) {
  480. return _activeConnection.Statistics;
  481. }
  482. }
  483. return null;
  484. }
  485. }
  486. [
  487. Browsable(false),
  488. DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
  489. ResDescriptionAttribute(Res.DbCommand_Transaction),
  490. ]
  491. new public SqlTransaction Transaction {
  492. get {
  493. // if the transaction object has been zombied, just return null
  494. if ((null != _transaction) && (null == _transaction.Connection)) { // MDAC 72720
  495. _transaction = null;
  496. }
  497. return _transaction;
  498. }
  499. set {
  500. // Don't allow the transaction to be changed while in a async opperation.
  501. if (_transaction != value && _activeConnection != null) { // If new value...
  502. if (cachedAsyncState.PendingAsyncOperation) { // If in pending async state, throw
  503. throw SQL.CannotModifyPropertyAsyncOperationInProgress(SQL.Transaction);
  504. }
  505. }
  506. //
  507. Bid.Trace("<sc.SqlCommand.set_Transaction|API> %d#\n", ObjectID);
  508. _transaction = value;
  509. }
  510. }
  511. override protected DbTransaction DbTransaction { // V1.2.3300
  512. get {
  513. return Transaction;
  514. }
  515. set {
  516. Transaction = (SqlTransaction)value;
  517. }
  518. }
  519. [
  520. DefaultValue(""),
  521. Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
  522. RefreshProperties(RefreshProperties.All), // MDAC 67707
  523. ResCategoryAttribute(Res.DataCategory_Data),
  524. ResDescriptionAttribute(Res.DbCommand_CommandText),
  525. ]
  526. override public string CommandText { // V1.2.3300, XXXCommand V1.0.5000
  527. get {
  528. string value = _commandText;
  529. return ((null != value) ? value : ADP.StrEmpty);
  530. }
  531. set {
  532. if (Bid.TraceOn) {
  533. Bid.Trace("<sc.SqlCommand.set_CommandText|API> %d#, '", ObjectID);
  534. Bid.PutStr(value); // Use PutStr to write out entire string
  535. Bid.Trace("'\n");
  536. }
  537. if (0 != ADP.SrcCompare(_commandText, value)) {
  538. PropertyChanging();
  539. _commandText = value;
  540. }
  541. }
  542. }
  543. [
  544. Browsable(false),
  545. DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
  546. ResCategoryAttribute(Res.DataCategory_Data),
  547. ResDescriptionAttribute(Res.TCE_SqlCommand_ColumnEncryptionSetting),
  548. ]
  549. public SqlCommandColumnEncryptionSetting ColumnEncryptionSetting {
  550. get {
  551. return _columnEncryptionSetting;
  552. }
  553. }
  554. [
  555. ResCategoryAttribute(Res.DataCategory_Data),
  556. ResDescriptionAttribute(Res.DbCommand_CommandTimeout),
  557. ]
  558. override public int CommandTimeout { // V1.2.3300, XXXCommand V1.0.5000
  559. get {
  560. return _commandTimeout;
  561. }
  562. set {
  563. Bid.Trace("<sc.SqlCommand.set_CommandTimeout|API> %d#, %d\n", ObjectID, value);
  564. if (value < 0) {
  565. throw ADP.InvalidCommandTimeout(value);
  566. }
  567. if (value != _commandTimeout) {
  568. PropertyChanging();
  569. _commandTimeout = value;
  570. }
  571. }
  572. }
  573. public void ResetCommandTimeout() { // V1.2.3300
  574. if (ADP.DefaultCommandTimeout != _commandTimeout) {
  575. PropertyChanging();
  576. _commandTimeout = ADP.DefaultCommandTimeout;
  577. }
  578. }
  579. private bool ShouldSerializeCommandTimeout() { // V1.2.3300
  580. return (ADP.DefaultCommandTimeout != _commandTimeout);
  581. }
  582. [
  583. DefaultValue(System.Data.CommandType.Text),
  584. RefreshProperties(RefreshProperties.All),
  585. ResCategoryAttribute(Res.DataCategory_Data),
  586. ResDescriptionAttribute(Res.DbCommand_CommandType),
  587. ]
  588. override public CommandType CommandType { // V1.2.3300, XXXCommand V1.0.5000
  589. get {
  590. CommandType cmdType = _commandType;
  591. return ((0 != cmdType) ? cmdType : CommandType.Text);
  592. }
  593. set {
  594. Bid.Trace("<sc.SqlCommand.set_CommandType|API> %d#, %d{ds.CommandType}\n", ObjectID, (int)value);
  595. if (_commandType != value) {
  596. switch(value) { // @perfnote: Enum.IsDefined
  597. case CommandType.Text:
  598. case CommandType.StoredProcedure:
  599. PropertyChanging();
  600. _commandType = value;
  601. break;
  602. case System.Data.CommandType.TableDirect:
  603. throw SQL.NotSupportedCommandType(value);
  604. default:
  605. throw ADP.InvalidCommandType(value);
  606. }
  607. }
  608. }
  609. }
  610. // @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
  611. // to limit the number of components that clutter the design surface,
  612. // when the DataAdapter design wizard generates the insert/update/delete commands it will
  613. // set the DesignTimeVisible property to false so that cmds won't appear as individual objects
  614. [
  615. DefaultValue(true),
  616. DesignOnly(true),
  617. Browsable(false),
  618. EditorBrowsableAttribute(EditorBrowsableState.Never),
  619. ]
  620. public override bool DesignTimeVisible { // V1.2.3300, XXXCommand V1.0.5000
  621. get {
  622. return !_designTimeInvisible;
  623. }
  624. set {
  625. _designTimeInvisible = !value;
  626. TypeDescriptor.Refresh(this); // VS7 208845
  627. }
  628. }
  629. [
  630. DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
  631. ResCategoryAttribute(Res.DataCategory_Data),
  632. ResDescriptionAttribute(Res.DbCommand_Parameters),
  633. ]
  634. new public SqlParameterCollection Parameters {
  635. get {
  636. if (null == this._parameters) {
  637. // delay the creation of the SqlParameterCollection
  638. // until user actually uses the Parameters property
  639. this._parameters = new SqlParameterCollection();
  640. }
  641. return this._parameters;
  642. }
  643. }
  644. override protected DbParameterCollection DbParameterCollection { // V1.2.3300
  645. get {
  646. return Parameters;
  647. }
  648. }
  649. [
  650. DefaultValue(System.Data.UpdateRowSource.Both),
  651. ResCategoryAttribute(Res.DataCategory_Update),
  652. ResDescriptionAttribute(Res.DbCommand_UpdatedRowSource),
  653. ]
  654. override public UpdateRowSource UpdatedRowSource { // V1.2.3300, XXXCommand V1.0.5000
  655. get {
  656. return _updatedRowSource;
  657. }
  658. set {
  659. switch(value) { // @perfnote: Enum.IsDefined
  660. case UpdateRowSource.None:
  661. case UpdateRowSource.OutputParameters:
  662. case UpdateRowSource.FirstReturnedRecord:
  663. case UpdateRowSource.Both:
  664. _updatedRowSource = value;
  665. break;
  666. default:
  667. throw ADP.InvalidUpdateRowSource(value);
  668. }
  669. }
  670. }
  671. [
  672. ResCategoryAttribute(Res.DataCategory_StatementCompleted),
  673. ResDescriptionAttribute(Res.DbCommand_StatementCompleted),
  674. ]
  675. public event StatementCompletedEventHandler StatementCompleted {
  676. add {
  677. _statementCompletedEventHandler += value;
  678. }
  679. remove {
  680. _statementCompletedEventHandler -= value;
  681. }
  682. }
  683. internal void OnStatementCompleted(int recordCount) { // V1.2.3300
  684. if (0 <= recordCount) {
  685. StatementCompletedEventHandler handler = _statementCompletedEventHandler;
  686. if (null != handler) {
  687. try {
  688. Bid.Trace("<sc.SqlCommand.OnStatementCompleted|INFO> %d#, recordCount=%d\n", ObjectID, recordCount);
  689. handler(this, new StatementCompletedEventArgs(recordCount));
  690. }
  691. catch(Exception e) {
  692. //
  693. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  694. throw;
  695. }
  696. ADP.TraceExceptionWithoutRethrow(e);
  697. }
  698. }
  699. }
  700. }
  701. private void PropertyChanging() { // also called from SqlParameterCollection
  702. this.IsDirty = true;
  703. }
  704. override public void Prepare() {
  705. SqlConnection.ExecutePermission.Demand();
  706. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  707. // between entry into Execute* API and the thread obtaining the stateObject.
  708. _pendingCancel = false;
  709. // Context connection's prepare is a no-op
  710. if (null != _activeConnection && _activeConnection.IsContextConnection) {
  711. return;
  712. }
  713. SqlStatistics statistics = null;
  714. IntPtr hscp;
  715. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.Prepare|API> %d#", ObjectID);
  716. Bid.CorrelationTrace("<sc.SqlCommand.Prepare|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  717. statistics = SqlStatistics.StartTimer(Statistics);
  718. // only prepare if batch with parameters
  719. // MDAC
  720. if (
  721. this.IsPrepared && !this.IsDirty
  722. || (this.CommandType == CommandType.StoredProcedure)
  723. || (
  724. (System.Data.CommandType.Text == this.CommandType)
  725. && (0 == GetParameterCount (_parameters))
  726. )
  727. ) {
  728. if (null != Statistics) {
  729. Statistics.SafeIncrement (ref Statistics._prepares);
  730. }
  731. _hiddenPrepare = false;
  732. }
  733. else {
  734. // Validate the command outside of the try\catch to avoid putting the _stateObj on error
  735. ValidateCommand(ADP.Prepare, false /*not async*/);
  736. bool processFinallyBlock = true;
  737. TdsParser bestEffortCleanupTarget = null;
  738. RuntimeHelpers.PrepareConstrainedRegions();
  739. try {
  740. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  741. // NOTE: The state object isn't actually needed for this, but it is still here for back-compat (since it does a bunch of checks)
  742. GetStateObject();
  743. // Loop through parameters ensuring that we do not have unspecified types, sizes, scales, or precisions
  744. if (null != _parameters) {
  745. int count = _parameters.Count;
  746. for (int i = 0; i < count; ++i) {
  747. _parameters[i].Prepare(this); // MDAC 67063
  748. }
  749. }
  750. #if DEBUG
  751. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  752. RuntimeHelpers.PrepareConstrainedRegions();
  753. try {
  754. tdsReliabilitySection.Start();
  755. #else
  756. {
  757. #endif //DEBUG
  758. InternalPrepare();
  759. }
  760. #if DEBUG
  761. finally {
  762. tdsReliabilitySection.Stop();
  763. }
  764. #endif //DEBUG
  765. }
  766. catch (System.OutOfMemoryException e) {
  767. processFinallyBlock = false;
  768. _activeConnection.Abort(e);
  769. throw;
  770. }
  771. catch (System.StackOverflowException e) {
  772. processFinallyBlock = false;
  773. _activeConnection.Abort(e);
  774. throw;
  775. }
  776. catch (System.Threading.ThreadAbortException e) {
  777. processFinallyBlock = false;
  778. _activeConnection.Abort(e);
  779. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  780. throw;
  781. }
  782. catch (Exception e) {
  783. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  784. throw;
  785. }
  786. finally {
  787. if (processFinallyBlock) {
  788. _hiddenPrepare = false; // The command is now officially prepared
  789. ReliablePutStateObject();
  790. }
  791. }
  792. }
  793. SqlStatistics.StopTimer(statistics);
  794. Bid.ScopeLeave(ref hscp);
  795. }
  796. private void InternalPrepare() {
  797. if (this.IsDirty) {
  798. Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters
  799. //
  800. // someone changed the command text or the parameter schema so we must unprepare the command
  801. //
  802. this.Unprepare();
  803. this.IsDirty = false;
  804. }
  805. Debug.Assert(_execType != EXECTYPE.PREPARED, "Invalid attempt to Prepare already Prepared command!");
  806. Debug.Assert(_activeConnection != null, "must have an open connection to Prepare");
  807. Debug.Assert(null != _stateObj, "TdsParserStateObject should not be null");
  808. Debug.Assert(null != _stateObj.Parser, "TdsParser class should not be null in Command.Execute!");
  809. Debug.Assert(_stateObj.Parser == _activeConnection.Parser, "stateobject parser not same as connection parser");
  810. Debug.Assert(false == _inPrepare, "Already in Prepare cycle, this.inPrepare should be false!");
  811. // remember that the user wants to do a prepare but don't actually do an rpc
  812. _execType = EXECTYPE.PREPAREPENDING;
  813. // Note the current close count of the connection - this will tell us if the connection has been closed between calls to Prepare() and Execute
  814. _preparedConnectionCloseCount = _activeConnection.CloseCount;
  815. _preparedConnectionReconnectCount = _activeConnection.ReconnectCount;
  816. if (null != Statistics) {
  817. Statistics.SafeIncrement(ref Statistics._prepares);
  818. }
  819. }
  820. // SqlInternalConnectionTds needs to be able to unprepare a statement
  821. internal void Unprepare() {
  822. // Context connection's prepare is a no-op
  823. if (_activeConnection.IsContextConnection) {
  824. return;
  825. }
  826. Debug.Assert(true == IsPrepared, "Invalid attempt to Unprepare a non-prepared command!");
  827. Debug.Assert(_activeConnection != null, "must have an open connection to UnPrepare");
  828. Debug.Assert(false == _inPrepare, "_inPrepare should be false!");
  829. // @devnote: we're always falling back to Prepare pending
  830. // @devnote: This seems broken because once the command is prepared it will - always - be a
  831. // @devnote: prepared execution.
  832. // @devnote: Even replacing the parameterlist with something completely different or
  833. // @devnote: changing the commandtext to a non-parameterized query will result in prepared execution
  834. // @devnote:
  835. // @devnote: We need to keep the behavior for backward compatibility though (non-breaking change)
  836. //
  837. _execType = EXECTYPE.PREPAREPENDING;
  838. // Don't zero out the handle because we'll pass it in to sp_prepexec on the next prepare
  839. // Unless the close count isn't the same as when we last prepared
  840. if ((_activeConnection.CloseCount != _preparedConnectionCloseCount) || (_activeConnection.ReconnectCount != _preparedConnectionReconnectCount)) {
  841. // reset our handle
  842. _prepareHandle = -1;
  843. }
  844. _cachedMetaData = null;
  845. Bid.Trace("<sc.SqlCommand.Prepare|INFO> %d#, Command unprepared.\n", ObjectID);
  846. }
  847. // Cancel is supposed to be multi-thread safe.
  848. // It doesn't make sense to verify the connection exists or that it is open during cancel
  849. // because immediately after checkin the connection can be closed or removed via another thread.
  850. //
  851. override public void Cancel() {
  852. IntPtr hscp;
  853. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.Cancel|API> %d#", ObjectID);
  854. Bid.CorrelationTrace("<sc.SqlCommand.Cancel|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  855. SqlStatistics statistics = null;
  856. try {
  857. statistics = SqlStatistics.StartTimer(Statistics);
  858. // If we are in reconnect phase simply cancel the waiting task
  859. var reconnectCompletionSource = _reconnectionCompletionSource;
  860. if (reconnectCompletionSource != null) {
  861. if (reconnectCompletionSource.TrySetCanceled()) {
  862. return;
  863. }
  864. }
  865. // the pending data flag means that we are awaiting a response or are in the middle of proccessing a response
  866. // if we have no pending data, then there is nothing to cancel
  867. // if we have pending data, but it is not a result of this command, then we don't cancel either. Note that
  868. // this model is implementable because we only allow one active command at any one time. This code
  869. // will have to change we allow multiple outstanding batches
  870. //
  871. if (null == _activeConnection) {
  872. return;
  873. }
  874. SqlInternalConnectionTds connection = (_activeConnection.InnerConnection as SqlInternalConnectionTds);
  875. if (null == connection) { // Fail with out locking
  876. return;
  877. }
  878. // The lock here is to protect against the command.cancel / connection.close race condition
  879. // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
  880. // the command will no longer be cancelable. It might be desirable to be able to cancel the close opperation, but this is
  881. // outside of the scope of Whidbey RTM. See (SqlConnection::Close) for other lock.
  882. lock (connection) {
  883. if (connection != (_activeConnection.InnerConnection as SqlInternalConnectionTds)) { // make sure the connection held on the active connection is what we have stored in our temp connection variable, if not between getting "connection" and takeing the lock, the connection has been closed
  884. return;
  885. }
  886. TdsParser parser = connection.Parser;
  887. if (null == parser) {
  888. return;
  889. }
  890. TdsParser bestEffortCleanupTarget = null;
  891. RuntimeHelpers.PrepareConstrainedRegions();
  892. try {
  893. #if DEBUG
  894. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  895. RuntimeHelpers.PrepareConstrainedRegions();
  896. try {
  897. tdsReliabilitySection.Start();
  898. #else
  899. {
  900. #endif //DEBUG
  901. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  902. if (!_pendingCancel) { // Do nothing if aleady pending.
  903. // Before attempting actual cancel, set the _pendingCancel flag to false.
  904. // This denotes to other thread before obtaining stateObject from the
  905. // session pool that there is another thread wishing to cancel.
  906. // The period in question is between entering the ExecuteAPI and obtaining
  907. // a stateObject.
  908. _pendingCancel = true;
  909. TdsParserStateObject stateObj = _stateObj;
  910. if (null != stateObj) {
  911. stateObj.Cancel(ObjectID);
  912. }
  913. else {
  914. SqlDataReader reader = connection.FindLiveReader(this);
  915. if (reader != null) {
  916. reader.Cancel(ObjectID);
  917. }
  918. }
  919. }
  920. }
  921. #if DEBUG
  922. finally {
  923. tdsReliabilitySection.Stop();
  924. }
  925. #endif //DEBUG
  926. }
  927. catch (System.OutOfMemoryException e) {
  928. _activeConnection.Abort(e);
  929. throw;
  930. }
  931. catch (System.StackOverflowException e) {
  932. _activeConnection.Abort(e);
  933. throw;
  934. }
  935. catch (System.Threading.ThreadAbortException e) {
  936. _activeConnection.Abort(e);
  937. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  938. throw;
  939. }
  940. }
  941. }
  942. finally {
  943. SqlStatistics.StopTimer(statistics);
  944. Bid.ScopeLeave(ref hscp);
  945. }
  946. }
  947. new public SqlParameter CreateParameter() {
  948. return new SqlParameter();
  949. }
  950. override protected DbParameter CreateDbParameter() {
  951. return CreateParameter();
  952. }
  953. override protected void Dispose(bool disposing) {
  954. if (disposing) { // release mananged objects
  955. // V1.0, V1.1 did not reset the Connection, Parameters, CommandText, WebData 100524
  956. //_parameters = null;
  957. //_activeConnection = null;
  958. //_statistics = null;
  959. //CommandText = null;
  960. _cachedMetaData = null;
  961. }
  962. // release unmanaged objects
  963. base.Dispose(disposing);
  964. }
  965. override public object ExecuteScalar() {
  966. SqlConnection.ExecutePermission.Demand();
  967. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  968. // between entry into Execute* API and the thread obtaining the stateObject.
  969. _pendingCancel = false;
  970. SqlStatistics statistics = null;
  971. IntPtr hscp;
  972. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteScalar|API> %d#", ObjectID);
  973. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteScalar|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  974. bool success = false;
  975. int? sqlExceptionNumber = null;
  976. try {
  977. statistics = SqlStatistics.StartTimer(Statistics);
  978. WriteBeginExecuteEvent();
  979. SqlDataReader ds;
  980. ds = RunExecuteReader(0, RunBehavior.ReturnImmediately, true, ADP.ExecuteScalar);
  981. object result = CompleteExecuteScalar(ds, false);
  982. success = true;
  983. return result;
  984. }
  985. catch (SqlException ex) {
  986. sqlExceptionNumber = ex.Number;
  987. throw;
  988. }
  989. finally {
  990. SqlStatistics.StopTimer(statistics);
  991. Bid.ScopeLeave(ref hscp);
  992. WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true);
  993. }
  994. }
  995. private object CompleteExecuteScalar(SqlDataReader ds, bool returnSqlValue) {
  996. object retResult = null;
  997. try {
  998. if (ds.Read()) {
  999. if (ds.FieldCount > 0) {
  1000. if (returnSqlValue) {
  1001. retResult = ds.GetSqlValue(0);
  1002. }
  1003. else {
  1004. retResult = ds.GetValue(0);
  1005. }
  1006. }
  1007. }
  1008. }
  1009. finally {
  1010. // clean off the wire
  1011. ds.Close();
  1012. }
  1013. return retResult;
  1014. }
  1015. override public int ExecuteNonQuery() {
  1016. SqlConnection.ExecutePermission.Demand();
  1017. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1018. // between entry into Execute* API and the thread obtaining the stateObject.
  1019. _pendingCancel = false;
  1020. SqlStatistics statistics = null;
  1021. IntPtr hscp;
  1022. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteNonQuery|API> %d#", ObjectID);
  1023. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1024. bool success = false;
  1025. int? sqlExceptionNumber = null;
  1026. try {
  1027. statistics = SqlStatistics.StartTimer(Statistics);
  1028. WriteBeginExecuteEvent();
  1029. InternalExecuteNonQuery(null, ADP.ExecuteNonQuery, false, CommandTimeout);
  1030. success = true;
  1031. return _rowsAffected;
  1032. }
  1033. catch (SqlException ex) {
  1034. sqlExceptionNumber = ex.Number;
  1035. throw;
  1036. }
  1037. finally {
  1038. SqlStatistics.StopTimer(statistics);
  1039. Bid.ScopeLeave(ref hscp);
  1040. WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous : true);
  1041. }
  1042. }
  1043. // Handles in-proc execute-to-pipe functionality
  1044. // Identical to ExecuteNonQuery
  1045. internal void ExecuteToPipe( SmiContext pipeContext ) {
  1046. SqlConnection.ExecutePermission.Demand();
  1047. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1048. // between entry into Execute* API and the thread obtaining the stateObject.
  1049. _pendingCancel = false;
  1050. SqlStatistics statistics = null;
  1051. IntPtr hscp;
  1052. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteToPipe|INFO> %d#", ObjectID);
  1053. try {
  1054. statistics = SqlStatistics.StartTimer(Statistics);
  1055. InternalExecuteNonQuery(null, ADP.ExecuteNonQuery, true, CommandTimeout);
  1056. }
  1057. finally {
  1058. SqlStatistics.StopTimer(statistics);
  1059. Bid.ScopeLeave(ref hscp);
  1060. }
  1061. }
  1062. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1063. public IAsyncResult BeginExecuteNonQuery() {
  1064. // BeginExecuteNonQuery will track ExecutionTime for us
  1065. return BeginExecuteNonQuery(null, null);
  1066. }
  1067. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1068. public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) {
  1069. Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1070. SqlConnection.ExecutePermission.Demand();
  1071. return BeginExecuteNonQueryInternal(callback, stateObject, 0);
  1072. }
  1073. private IAsyncResult BeginExecuteNonQueryAsync(AsyncCallback callback, object stateObject) {
  1074. return BeginExecuteNonQueryInternal(callback, stateObject, CommandTimeout, asyncWrite:true);
  1075. }
  1076. private IAsyncResult BeginExecuteNonQueryInternal(AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false) {
  1077. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1078. // between entry into Execute* API and the thread obtaining the stateObject.
  1079. _pendingCancel = false;
  1080. ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
  1081. // back into pool when we should not.
  1082. SqlStatistics statistics = null;
  1083. try {
  1084. statistics = SqlStatistics.StartTimer(Statistics);
  1085. WriteBeginExecuteEvent();
  1086. TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
  1087. try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
  1088. Task execNQ = InternalExecuteNonQuery(completion, ADP.BeginExecuteNonQuery, false, timeout, asyncWrite);
  1089. if (execNQ != null) {
  1090. AsyncHelper.ContinueTask(execNQ, completion, () => BeginExecuteNonQueryInternalReadStage(completion));
  1091. }
  1092. else {
  1093. BeginExecuteNonQueryInternalReadStage(completion);
  1094. }
  1095. }
  1096. catch (Exception e) {
  1097. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  1098. // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
  1099. throw;
  1100. }
  1101. // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
  1102. ReliablePutStateObject();
  1103. throw;
  1104. }
  1105. // Add callback after work is done to avoid overlapping Begin\End methods
  1106. if (callback != null) {
  1107. completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default);
  1108. }
  1109. return completion.Task;
  1110. }
  1111. finally {
  1112. SqlStatistics.StopTimer(statistics);
  1113. }
  1114. }
  1115. private void BeginExecuteNonQueryInternalReadStage(TaskCompletionSource<object> completion) {
  1116. // Read SNI does not have catches for async exceptions, handle here.
  1117. TdsParser bestEffortCleanupTarget = null;
  1118. RuntimeHelpers.PrepareConstrainedRegions();
  1119. try {
  1120. #if DEBUG
  1121. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1122. RuntimeHelpers.PrepareConstrainedRegions();
  1123. try {
  1124. tdsReliabilitySection.Start();
  1125. #else
  1126. {
  1127. #endif //DEBUG
  1128. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1129. // must finish caching information before ReadSni which can activate the callback before returning
  1130. cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteNonQuery, _activeConnection);
  1131. _stateObj.ReadSni(completion);
  1132. }
  1133. #if DEBUG
  1134. finally {
  1135. tdsReliabilitySection.Stop();
  1136. }
  1137. #endif //DEBUG
  1138. }
  1139. catch (System.OutOfMemoryException e) {
  1140. _activeConnection.Abort(e);
  1141. throw;
  1142. }
  1143. catch (System.StackOverflowException e) {
  1144. _activeConnection.Abort(e);
  1145. throw;
  1146. }
  1147. catch (System.Threading.ThreadAbortException e) {
  1148. _activeConnection.Abort(e);
  1149. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1150. throw;
  1151. }
  1152. catch (Exception) {
  1153. // Similarly, if an exception occurs put the stateObj back into the pool.
  1154. // and reset async cache information to allow a second async execute
  1155. if (null != _cachedAsyncState) {
  1156. _cachedAsyncState.ResetAsyncState();
  1157. }
  1158. ReliablePutStateObject();
  1159. throw;
  1160. }
  1161. }
  1162. private void VerifyEndExecuteState(Task completionTask, String endMethod) {
  1163. if (null == completionTask) {
  1164. throw ADP.ArgumentNull("asyncResult");
  1165. }
  1166. if (completionTask.IsCanceled) {
  1167. if (_stateObj != null) {
  1168. _stateObj.Parser.State = TdsParserState.Broken; // We failed to respond to attention, we have to quit!
  1169. _stateObj.Parser.Connection.BreakConnection();
  1170. _stateObj.Parser.ThrowExceptionAndWarning(_stateObj);
  1171. }
  1172. else {
  1173. Debug.Assert(_reconnectionCompletionSource == null || _reconnectionCompletionSource.Task.IsCanceled, "ReconnectCompletionSource should be null or cancelled");
  1174. throw SQL.CR_ReconnectionCancelled();
  1175. }
  1176. }
  1177. else if (completionTask.IsFaulted) {
  1178. throw completionTask.Exception.InnerException;
  1179. }
  1180. // If transparent parameter encryption was attempted, then we need to skip other checks like those on EndMethodName
  1181. // since we want to wait for async results before checking those fields.
  1182. if (IsColumnEncryptionEnabled) {
  1183. if (_activeConnection.State != ConnectionState.Open) {
  1184. // If the connection is not 'valid' then it was closed while we were executing
  1185. throw ADP.ClosedConnectionError();
  1186. }
  1187. return;
  1188. }
  1189. if (cachedAsyncState.EndMethodName == null) {
  1190. throw ADP.MethodCalledTwice(endMethod);
  1191. }
  1192. if (endMethod != cachedAsyncState.EndMethodName) {
  1193. throw ADP.MismatchedAsyncResult(cachedAsyncState.EndMethodName, endMethod);
  1194. }
  1195. if ((_activeConnection.State != ConnectionState.Open) || (!cachedAsyncState.IsActiveConnectionValid(_activeConnection))) {
  1196. // If the connection is not 'valid' then it was closed while we were executing
  1197. throw ADP.ClosedConnectionError();
  1198. }
  1199. }
  1200. private void WaitForAsyncResults(IAsyncResult asyncResult) {
  1201. Task completionTask = (Task) asyncResult;
  1202. if (!asyncResult.IsCompleted) {
  1203. asyncResult.AsyncWaitHandle.WaitOne();
  1204. }
  1205. _stateObj._networkPacketTaskSource = null;
  1206. _activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
  1207. }
  1208. public int EndExecuteNonQuery(IAsyncResult asyncResult) {
  1209. try {
  1210. return EndExecuteNonQueryInternal(asyncResult);
  1211. }
  1212. finally {
  1213. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1214. }
  1215. }
  1216. private void ThrowIfReconnectionHasBeenCanceled() {
  1217. if (_stateObj == null) {
  1218. var reconnectionCompletionSource = _reconnectionCompletionSource;
  1219. if (reconnectionCompletionSource != null && reconnectionCompletionSource.Task.IsCanceled) {
  1220. throw SQL.CR_ReconnectionCancelled();
  1221. }
  1222. }
  1223. }
  1224. private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) {
  1225. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteNonQueryAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1226. Exception asyncException = ((Task)asyncResult).Exception;
  1227. if (asyncException != null) {
  1228. // Leftover exception from the Begin...InternalReadStage
  1229. ReliablePutStateObject();
  1230. throw asyncException.InnerException;
  1231. }
  1232. else {
  1233. ThrowIfReconnectionHasBeenCanceled();
  1234. // lock on _stateObj prevents ----s with close/cancel.
  1235. lock (_stateObj) {
  1236. return EndExecuteNonQueryInternal(asyncResult);
  1237. }
  1238. }
  1239. }
  1240. private int EndExecuteNonQueryInternal(IAsyncResult asyncResult) {
  1241. SqlStatistics statistics = null;
  1242. TdsParser bestEffortCleanupTarget = null;
  1243. RuntimeHelpers.PrepareConstrainedRegions();
  1244. bool success = false;
  1245. int? sqlExceptionNumber = null;
  1246. try {
  1247. #if DEBUG
  1248. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1249. RuntimeHelpers.PrepareConstrainedRegions();
  1250. try {
  1251. tdsReliabilitySection.Start();
  1252. #else
  1253. {
  1254. #endif //DEBUG
  1255. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1256. statistics = SqlStatistics.StartTimer(Statistics);
  1257. VerifyEndExecuteState((Task)asyncResult, ADP.EndExecuteNonQuery);
  1258. WaitForAsyncResults(asyncResult);
  1259. // If Transparent parameter encryption was attempted, then we would have skipped the below
  1260. // checks in VerifyEndExecuteState since we wanted to wait for WaitForAsyncResults to complete.
  1261. if (IsColumnEncryptionEnabled) {
  1262. if (cachedAsyncState.EndMethodName == null) {
  1263. throw ADP.MethodCalledTwice(ADP.EndExecuteNonQuery);
  1264. }
  1265. if (ADP.EndExecuteNonQuery != cachedAsyncState.EndMethodName) {
  1266. throw ADP.MismatchedAsyncResult(cachedAsyncState.EndMethodName, ADP.EndExecuteNonQuery);
  1267. }
  1268. if (!cachedAsyncState.IsActiveConnectionValid(_activeConnection)) {
  1269. // If the connection is not 'valid' then it was closed while we were executing
  1270. throw ADP.ClosedConnectionError();
  1271. }
  1272. }
  1273. bool processFinallyBlock = true;
  1274. try {
  1275. NotifyDependency();
  1276. CheckThrowSNIException();
  1277. // only send over SQL Batch command if we are not a stored proc and have no parameters
  1278. if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) {
  1279. try {
  1280. bool dataReady;
  1281. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  1282. bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady);
  1283. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  1284. }
  1285. finally {
  1286. cachedAsyncState.ResetAsyncState();
  1287. }
  1288. }
  1289. else { // otherwise, use a full-fledged execute that can handle params and stored procs
  1290. SqlDataReader reader = CompleteAsyncExecuteReader();
  1291. if (null != reader) {
  1292. reader.Close();
  1293. }
  1294. }
  1295. }
  1296. catch (SqlException e) {
  1297. sqlExceptionNumber = e.Number;
  1298. throw;
  1299. }
  1300. catch (Exception e) {
  1301. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  1302. throw;
  1303. }
  1304. finally {
  1305. if (processFinallyBlock) {
  1306. PutStateObject();
  1307. }
  1308. }
  1309. Debug.Assert(null == _stateObj, "non-null state object in EndExecuteNonQuery");
  1310. success = true;
  1311. return _rowsAffected;
  1312. }
  1313. #if DEBUG
  1314. finally {
  1315. tdsReliabilitySection.Stop();
  1316. }
  1317. #endif //DEBUG
  1318. }
  1319. catch (System.OutOfMemoryException e) {
  1320. _activeConnection.Abort(e);
  1321. throw;
  1322. }
  1323. catch (System.StackOverflowException e) {
  1324. _activeConnection.Abort(e);
  1325. throw;
  1326. }
  1327. catch (System.Threading.ThreadAbortException e) {
  1328. _activeConnection.Abort(e);
  1329. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1330. throw;
  1331. }
  1332. catch (Exception e) {
  1333. if (cachedAsyncState != null) {
  1334. cachedAsyncState.ResetAsyncState();
  1335. };
  1336. if (ADP.IsCatchableExceptionType(e)) {
  1337. ReliablePutStateObject();
  1338. };
  1339. throw;
  1340. }
  1341. finally {
  1342. SqlStatistics.StopTimer(statistics);
  1343. WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: false);
  1344. }
  1345. }
  1346. private Task InternalExecuteNonQuery(TaskCompletionSource<object> completion, string methodName, bool sendToPipe, int timeout, bool asyncWrite = false) {
  1347. bool async = (null != completion);
  1348. SqlStatistics statistics = Statistics;
  1349. _rowsAffected = -1;
  1350. TdsParser bestEffortCleanupTarget = null;
  1351. RuntimeHelpers.PrepareConstrainedRegions();
  1352. try {
  1353. #if DEBUG
  1354. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1355. RuntimeHelpers.PrepareConstrainedRegions();
  1356. try {
  1357. tdsReliabilitySection.Start();
  1358. #else
  1359. {
  1360. #endif //DEBUG
  1361. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1362. // @devnote: this function may throw for an invalid connection
  1363. // @devnote: returns false for empty command text
  1364. ValidateCommand(methodName, async);
  1365. CheckNotificationStateAndAutoEnlist(); // Only call after validate - requires non null connection!
  1366. Task task = null;
  1367. // only send over SQL Batch command if we are not a stored proc and have no parameters and not in batch RPC mode
  1368. if ( _activeConnection.IsContextConnection ) {
  1369. if (null != statistics) {
  1370. statistics.SafeIncrement(ref statistics._unpreparedExecs);
  1371. }
  1372. RunExecuteNonQuerySmi( sendToPipe );
  1373. }
  1374. else if (!BatchRPCMode && (System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) {
  1375. Debug.Assert( !sendToPipe, "trying to send non-context command to pipe" );
  1376. if (null != statistics) {
  1377. if (!this.IsDirty && this.IsPrepared) {
  1378. statistics.SafeIncrement(ref statistics._preparedExecs);
  1379. }
  1380. else {
  1381. statistics.SafeIncrement(ref statistics._unpreparedExecs);
  1382. }
  1383. }
  1384. task = RunExecuteNonQueryTds(methodName, async, timeout, asyncWrite);
  1385. }
  1386. else { // otherwise, use a full-fledged execute that can handle params and stored procs
  1387. Debug.Assert( !sendToPipe, "trying to send non-context command to pipe" );
  1388. Bid.Trace("<sc.SqlCommand.ExecuteNonQuery|INFO> %d#, Command executed as RPC.\n", ObjectID);
  1389. SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, asyncWrite);
  1390. if (null!=reader) {
  1391. if (task != null) {
  1392. task = AsyncHelper.CreateContinuationTask(task, () => reader.Close());
  1393. }
  1394. else {
  1395. reader.Close();
  1396. }
  1397. }
  1398. }
  1399. Debug.Assert(async || null == _stateObj, "non-null state object in InternalExecuteNonQuery");
  1400. return task;
  1401. }
  1402. #if DEBUG
  1403. finally {
  1404. tdsReliabilitySection.Stop();
  1405. }
  1406. #endif //DEBUG
  1407. }
  1408. catch (System.OutOfMemoryException e) {
  1409. _activeConnection.Abort(e);
  1410. throw;
  1411. }
  1412. catch (System.StackOverflowException e) {
  1413. _activeConnection.Abort(e);
  1414. throw;
  1415. }
  1416. catch (System.Threading.ThreadAbortException e) {
  1417. _activeConnection.Abort(e);
  1418. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1419. throw;
  1420. }
  1421. }
  1422. public XmlReader ExecuteXmlReader() {
  1423. SqlConnection.ExecutePermission.Demand();
  1424. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1425. // between entry into Execute* API and the thread obtaining the stateObject.
  1426. _pendingCancel = false;
  1427. SqlStatistics statistics = null;
  1428. IntPtr hscp;
  1429. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteXmlReader|API> %d#", ObjectID);
  1430. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1431. bool success = false;
  1432. int? sqlExceptionNumber = null;
  1433. try {
  1434. statistics = SqlStatistics.StartTimer(Statistics);
  1435. WriteBeginExecuteEvent();
  1436. // use the reader to consume metadata
  1437. SqlDataReader ds;
  1438. ds = RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, ADP.ExecuteXmlReader);
  1439. XmlReader result = CompleteXmlReader(ds);
  1440. success = true;
  1441. return result;
  1442. }
  1443. catch (SqlException ex) {
  1444. sqlExceptionNumber = ex.Number;
  1445. throw;
  1446. }
  1447. finally {
  1448. SqlStatistics.StopTimer(statistics);
  1449. Bid.ScopeLeave(ref hscp);
  1450. WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous : true);
  1451. }
  1452. }
  1453. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1454. public IAsyncResult BeginExecuteXmlReader() {
  1455. // BeginExecuteXmlReader will track executiontime
  1456. return BeginExecuteXmlReader(null, null);
  1457. }
  1458. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1459. public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) {
  1460. Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1461. SqlConnection.ExecutePermission.Demand();
  1462. return BeginExecuteXmlReaderInternal(callback, stateObject, 0);
  1463. }
  1464. private IAsyncResult BeginExecuteXmlReaderAsync(AsyncCallback callback, object stateObject) {
  1465. return BeginExecuteXmlReaderInternal(callback, stateObject, CommandTimeout, asyncWrite:true);
  1466. }
  1467. private IAsyncResult BeginExecuteXmlReaderInternal(AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false) {
  1468. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1469. // between entry into Execute* API and the thread obtaining the stateObject.
  1470. _pendingCancel = false;
  1471. ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
  1472. // back into pool when we should not.
  1473. SqlStatistics statistics = null;
  1474. try {
  1475. statistics = SqlStatistics.StartTimer(Statistics);
  1476. WriteBeginExecuteEvent();
  1477. TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
  1478. Task writeTask;
  1479. try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
  1480. RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, ADP.BeginExecuteXmlReader, completion, timeout, out writeTask, asyncWrite);
  1481. }
  1482. catch (Exception e) {
  1483. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  1484. // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
  1485. throw;
  1486. }
  1487. // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
  1488. ReliablePutStateObject();
  1489. throw;
  1490. }
  1491. if (writeTask != null) {
  1492. AsyncHelper.ContinueTask(writeTask, completion, () => BeginExecuteXmlReaderInternalReadStage(completion));
  1493. }
  1494. else {
  1495. BeginExecuteXmlReaderInternalReadStage(completion);
  1496. }
  1497. // Add callback after work is done to avoid overlapping Begin\End methods
  1498. if (callback != null) {
  1499. completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default);
  1500. }
  1501. return completion.Task;
  1502. }
  1503. finally {
  1504. SqlStatistics.StopTimer(statistics);
  1505. }
  1506. }
  1507. private void BeginExecuteXmlReaderInternalReadStage(TaskCompletionSource<object> completion) {
  1508. Debug.Assert(completion != null,"Completion source should not be null");
  1509. // Read SNI does not have catches for async exceptions, handle here.
  1510. TdsParser bestEffortCleanupTarget = null;
  1511. RuntimeHelpers.PrepareConstrainedRegions();
  1512. try {
  1513. #if DEBUG
  1514. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1515. RuntimeHelpers.PrepareConstrainedRegions();
  1516. try {
  1517. tdsReliabilitySection.Start();
  1518. #else
  1519. {
  1520. #endif //DEBUG
  1521. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1522. // must finish caching information before ReadSni which can activate the callback before returning
  1523. cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteXmlReader, _activeConnection);
  1524. _stateObj.ReadSni(completion);
  1525. }
  1526. #if DEBUG
  1527. finally {
  1528. tdsReliabilitySection.Stop();
  1529. }
  1530. #endif //DEBUG
  1531. }
  1532. catch (System.OutOfMemoryException e) {
  1533. _activeConnection.Abort(e);
  1534. completion.TrySetException(e);
  1535. throw;
  1536. }
  1537. catch (System.StackOverflowException e) {
  1538. _activeConnection.Abort(e);
  1539. completion.TrySetException(e);
  1540. throw;
  1541. }
  1542. catch (System.Threading.ThreadAbortException e) {
  1543. _activeConnection.Abort(e);
  1544. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1545. completion.TrySetException(e);
  1546. throw;
  1547. }
  1548. catch (Exception e) {
  1549. // Similarly, if an exception occurs put the stateObj back into the pool.
  1550. // and reset async cache information to allow a second async execute
  1551. if (null != _cachedAsyncState) {
  1552. _cachedAsyncState.ResetAsyncState();
  1553. }
  1554. ReliablePutStateObject();
  1555. completion.TrySetException(e);
  1556. }
  1557. }
  1558. public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) {
  1559. try {
  1560. return EndExecuteXmlReaderInternal(asyncResult);
  1561. }
  1562. finally {
  1563. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1564. }
  1565. }
  1566. private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) {
  1567. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteXmlReaderAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1568. Exception asyncException = ((Task)asyncResult).Exception;
  1569. if (asyncException != null) {
  1570. // Leftover exception from the Begin...InternalReadStage
  1571. ReliablePutStateObject();
  1572. throw asyncException.InnerException;
  1573. }
  1574. else {
  1575. ThrowIfReconnectionHasBeenCanceled();
  1576. // lock on _stateObj prevents ----s with close/cancel.
  1577. lock (_stateObj) {
  1578. return EndExecuteXmlReaderInternal(asyncResult);
  1579. }
  1580. }
  1581. }
  1582. private XmlReader EndExecuteXmlReaderInternal(IAsyncResult asyncResult) {
  1583. bool success = false;
  1584. int? sqlExceptionNumber = null;
  1585. try {
  1586. XmlReader result = CompleteXmlReader(InternalEndExecuteReader(asyncResult, ADP.EndExecuteXmlReader));
  1587. success = true;
  1588. return result;
  1589. }
  1590. catch (SqlException e){
  1591. sqlExceptionNumber = e.Number;
  1592. if (cachedAsyncState != null) {
  1593. cachedAsyncState.ResetAsyncState();
  1594. };
  1595. // SqlException is always catchable
  1596. ReliablePutStateObject();
  1597. throw;
  1598. }
  1599. catch (Exception e) {
  1600. if (cachedAsyncState != null) {
  1601. cachedAsyncState.ResetAsyncState();
  1602. };
  1603. if (ADP.IsCatchableExceptionType(e)) {
  1604. ReliablePutStateObject();
  1605. };
  1606. throw;
  1607. }
  1608. finally {
  1609. WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous : false);
  1610. }
  1611. }
  1612. private XmlReader CompleteXmlReader(SqlDataReader ds) {
  1613. XmlReader xr = null;
  1614. SmiExtendedMetaData[] md = ds.GetInternalSmiMetaData();
  1615. bool isXmlCapable = (null != md && md.Length == 1 && (md[0].SqlDbType == SqlDbType.NText
  1616. || md[0].SqlDbType == SqlDbType.NVarChar
  1617. || md[0].SqlDbType == SqlDbType.Xml));
  1618. if (isXmlCapable) {
  1619. try {
  1620. SqlStream sqlBuf = new SqlStream(ds, true /*addByteOrderMark*/, (md[0].SqlDbType == SqlDbType.Xml) ? false : true /*process all rows*/);
  1621. xr = sqlBuf.ToXmlReader();
  1622. }
  1623. catch (Exception e) {
  1624. if (ADP.IsCatchableExceptionType(e)) {
  1625. ds.Close();
  1626. }
  1627. throw;
  1628. }
  1629. }
  1630. if (xr == null) {
  1631. ds.Close();
  1632. throw SQL.NonXmlResult();
  1633. }
  1634. return xr;
  1635. }
  1636. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1637. public IAsyncResult BeginExecuteReader() {
  1638. return BeginExecuteReader(null, null, CommandBehavior.Default);
  1639. }
  1640. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1641. public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject) {
  1642. return BeginExecuteReader(callback, stateObject, CommandBehavior.Default);
  1643. }
  1644. override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) {
  1645. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteDbDataReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1646. return ExecuteReader(behavior, ADP.ExecuteReader);
  1647. }
  1648. new public SqlDataReader ExecuteReader() {
  1649. SqlStatistics statistics = null;
  1650. IntPtr hscp;
  1651. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteReader|API> %d#", ObjectID);
  1652. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1653. try {
  1654. statistics = SqlStatistics.StartTimer(Statistics);
  1655. return ExecuteReader(CommandBehavior.Default, ADP.ExecuteReader);
  1656. }
  1657. finally {
  1658. SqlStatistics.StopTimer(statistics);
  1659. Bid.ScopeLeave(ref hscp);
  1660. }
  1661. }
  1662. new public SqlDataReader ExecuteReader(CommandBehavior behavior) {
  1663. IntPtr hscp;
  1664. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteReader|API> %d#, behavior=%d{ds.CommandBehavior}", ObjectID, (int)behavior);
  1665. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReader|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior);
  1666. try {
  1667. return ExecuteReader(behavior, ADP.ExecuteReader);
  1668. }
  1669. finally {
  1670. Bid.ScopeLeave(ref hscp);
  1671. }
  1672. }
  1673. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1674. public IAsyncResult BeginExecuteReader(CommandBehavior behavior) {
  1675. return BeginExecuteReader(null, null, behavior);
  1676. }
  1677. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1678. public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) {
  1679. Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteReader|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior);
  1680. SqlConnection.ExecutePermission.Demand();
  1681. return BeginExecuteReaderInternal(behavior, callback, stateObject, 0);
  1682. }
  1683. internal SqlDataReader ExecuteReader(CommandBehavior behavior, string method) {
  1684. SqlConnection.ExecutePermission.Demand(); // TODO: Need to move this to public methods...
  1685. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1686. // between entry into Execute* API and the thread obtaining the stateObject.
  1687. _pendingCancel = false;
  1688. SqlStatistics statistics = null;
  1689. TdsParser bestEffortCleanupTarget = null;
  1690. RuntimeHelpers.PrepareConstrainedRegions();
  1691. bool success = false;
  1692. int? sqlExceptionNumber = null;
  1693. try {
  1694. WriteBeginExecuteEvent();
  1695. #if DEBUG
  1696. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1697. RuntimeHelpers.PrepareConstrainedRegions();
  1698. try {
  1699. tdsReliabilitySection.Start();
  1700. #else
  1701. {
  1702. #endif //DEBUG
  1703. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1704. statistics = SqlStatistics.StartTimer(Statistics);
  1705. SqlDataReader result = RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, method);
  1706. success = true;
  1707. return result;
  1708. }
  1709. #if DEBUG
  1710. finally {
  1711. tdsReliabilitySection.Stop();
  1712. }
  1713. #endif //DEBUG
  1714. }
  1715. catch (SqlException e) {
  1716. sqlExceptionNumber = e.Number;
  1717. throw;
  1718. }
  1719. catch (System.OutOfMemoryException e) {
  1720. _activeConnection.Abort(e);
  1721. throw;
  1722. }
  1723. catch (System.StackOverflowException e) {
  1724. _activeConnection.Abort(e);
  1725. throw;
  1726. }
  1727. catch (System.Threading.ThreadAbortException e) {
  1728. _activeConnection.Abort(e);
  1729. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1730. throw;
  1731. }
  1732. finally {
  1733. SqlStatistics.StopTimer(statistics);
  1734. WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous : true);
  1735. }
  1736. }
  1737. public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) {
  1738. try {
  1739. return EndExecuteReaderInternal(asyncResult);
  1740. }
  1741. finally {
  1742. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1743. }
  1744. }
  1745. private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) {
  1746. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteReaderAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1747. Exception asyncException = ((Task)asyncResult).Exception;
  1748. if (asyncException != null) {
  1749. // Leftover exception from the Begin...InternalReadStage
  1750. ReliablePutStateObject();
  1751. throw asyncException.InnerException;
  1752. }
  1753. else {
  1754. ThrowIfReconnectionHasBeenCanceled();
  1755. // lock on _stateObj prevents ----s with close/cancel.
  1756. lock (_stateObj) {
  1757. return EndExecuteReaderInternal(asyncResult);
  1758. }
  1759. }
  1760. }
  1761. private SqlDataReader EndExecuteReaderInternal(IAsyncResult asyncResult) {
  1762. SqlStatistics statistics = null;
  1763. bool success = false;
  1764. int? sqlExceptionNumber = null;
  1765. try {
  1766. statistics = SqlStatistics.StartTimer(Statistics);
  1767. SqlDataReader result = InternalEndExecuteReader(asyncResult, ADP.EndExecuteReader);
  1768. success = true;
  1769. return result;
  1770. }
  1771. catch (SqlException e) {
  1772. sqlExceptionNumber = e.Number;
  1773. if (cachedAsyncState != null)
  1774. {
  1775. cachedAsyncState.ResetAsyncState();
  1776. };
  1777. // SqlException is always catchable
  1778. ReliablePutStateObject();
  1779. throw;
  1780. }
  1781. catch (Exception e) {
  1782. if (cachedAsyncState != null) {
  1783. cachedAsyncState.ResetAsyncState();
  1784. };
  1785. if (ADP.IsCatchableExceptionType(e)) {
  1786. ReliablePutStateObject();
  1787. };
  1788. throw;
  1789. }
  1790. finally {
  1791. SqlStatistics.StopTimer(statistics);
  1792. WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous : false);
  1793. }
  1794. }
  1795. private IAsyncResult BeginExecuteReaderAsync(CommandBehavior behavior, AsyncCallback callback, object stateObject) {
  1796. return BeginExecuteReaderInternal(behavior, callback, stateObject, CommandTimeout, asyncWrite:true);
  1797. }
  1798. private IAsyncResult BeginExecuteReaderInternal(CommandBehavior behavior, AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false) {
  1799. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1800. // between entry into Execute* API and the thread obtaining the stateObject.
  1801. _pendingCancel = false;
  1802. SqlStatistics statistics = null;
  1803. try {
  1804. statistics = SqlStatistics.StartTimer(Statistics);
  1805. WriteBeginExecuteEvent();
  1806. TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
  1807. ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
  1808. // back into pool when we should not.
  1809. Task writeTask = null;
  1810. try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
  1811. RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, ADP.BeginExecuteReader, completion, timeout, out writeTask, asyncWrite);
  1812. }
  1813. catch (Exception e) {
  1814. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  1815. // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
  1816. throw;
  1817. }
  1818. // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
  1819. ReliablePutStateObject();
  1820. throw;
  1821. }
  1822. if (writeTask != null ) {
  1823. AsyncHelper.ContinueTask(writeTask,completion,()=> BeginExecuteReaderInternalReadStage(completion));
  1824. }
  1825. else {
  1826. BeginExecuteReaderInternalReadStage(completion);
  1827. }
  1828. // Add callback after work is done to avoid overlapping Begin\End methods
  1829. if (callback != null) {
  1830. completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default);
  1831. }
  1832. return completion.Task;
  1833. }
  1834. finally {
  1835. SqlStatistics.StopTimer(statistics);
  1836. }
  1837. }
  1838. private void BeginExecuteReaderInternalReadStage(TaskCompletionSource<object> completion) {
  1839. Debug.Assert(completion != null,"CompletionSource should not be null");
  1840. // Read SNI does not have catches for async exceptions, handle here.
  1841. TdsParser bestEffortCleanupTarget = null;
  1842. RuntimeHelpers.PrepareConstrainedRegions();
  1843. try {
  1844. #if DEBUG
  1845. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1846. RuntimeHelpers.PrepareConstrainedRegions();
  1847. try {
  1848. tdsReliabilitySection.Start();
  1849. #else
  1850. {
  1851. #endif //DEBUG
  1852. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1853. // must finish caching information before ReadSni which can activate the callback before returning
  1854. cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteReader, _activeConnection);
  1855. _stateObj.ReadSni(completion);
  1856. }
  1857. #if DEBUG
  1858. finally {
  1859. tdsReliabilitySection.Stop();
  1860. }
  1861. #endif //DEBUG
  1862. }
  1863. catch (System.OutOfMemoryException e) {
  1864. _activeConnection.Abort(e);
  1865. completion.TrySetException(e);
  1866. throw;
  1867. }
  1868. catch (System.StackOverflowException e) {
  1869. _activeConnection.Abort(e);
  1870. completion.TrySetException(e);
  1871. throw;
  1872. }
  1873. catch (System.Threading.ThreadAbortException e) {
  1874. _activeConnection.Abort(e);
  1875. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1876. completion.TrySetException(e);
  1877. throw;
  1878. }
  1879. catch (Exception e) {
  1880. // Similarly, if an exception occurs put the stateObj back into the pool.
  1881. // and reset async cache information to allow a second async execute
  1882. if (null != _cachedAsyncState) {
  1883. _cachedAsyncState.ResetAsyncState();
  1884. }
  1885. ReliablePutStateObject();
  1886. completion.TrySetException(e);
  1887. }
  1888. }
  1889. private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string endMethod) {
  1890. VerifyEndExecuteState((Task) asyncResult, endMethod);
  1891. WaitForAsyncResults(asyncResult);
  1892. // If Transparent parameter encryption was attempted, then we would have skipped the below
  1893. // checks in VerifyEndExecuteState since we wanted to wait for WaitForAsyncResults to complete.
  1894. if (IsColumnEncryptionEnabled) {
  1895. if (cachedAsyncState.EndMethodName == null) {
  1896. throw ADP.MethodCalledTwice(endMethod);
  1897. }
  1898. if (endMethod != cachedAsyncState.EndMethodName) {
  1899. throw ADP.MismatchedAsyncResult(cachedAsyncState.EndMethodName, endMethod);
  1900. }
  1901. if (!cachedAsyncState.IsActiveConnectionValid(_activeConnection)) {
  1902. // If the connection is not 'valid' then it was closed while we were executing
  1903. throw ADP.ClosedConnectionError();
  1904. }
  1905. }
  1906. CheckThrowSNIException();
  1907. TdsParser bestEffortCleanupTarget = null;
  1908. RuntimeHelpers.PrepareConstrainedRegions();
  1909. try {
  1910. #if DEBUG
  1911. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1912. RuntimeHelpers.PrepareConstrainedRegions();
  1913. try {
  1914. tdsReliabilitySection.Start();
  1915. #else
  1916. {
  1917. #endif //DEBUG
  1918. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1919. SqlDataReader reader = CompleteAsyncExecuteReader();
  1920. Debug.Assert(null == _stateObj, "non-null state object in InternalEndExecuteReader");
  1921. return reader;
  1922. }
  1923. #if DEBUG
  1924. finally {
  1925. tdsReliabilitySection.Stop();
  1926. }
  1927. #endif //DEBUG
  1928. }
  1929. catch (System.OutOfMemoryException e) {
  1930. _activeConnection.Abort(e);
  1931. throw;
  1932. }
  1933. catch (System.StackOverflowException e) {
  1934. _activeConnection.Abort(e);
  1935. throw;
  1936. }
  1937. catch (System.Threading.ThreadAbortException e) {
  1938. _activeConnection.Abort(e);
  1939. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1940. throw;
  1941. }
  1942. }
  1943. public override Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) {
  1944. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteNonQueryAsync|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1945. SqlConnection.ExecutePermission.Demand();
  1946. TaskCompletionSource<int> source = new TaskCompletionSource<int>();
  1947. CancellationTokenRegistration registration = new CancellationTokenRegistration();
  1948. if (cancellationToken.CanBeCanceled) {
  1949. if (cancellationToken.IsCancellationRequested) {
  1950. source.SetCanceled();
  1951. return source.Task;
  1952. }
  1953. registration = cancellationToken.Register(CancelIgnoreFailure);
  1954. }
  1955. Task<int> returnedTask = source.Task;
  1956. try {
  1957. RegisterForConnectionCloseNotification(ref returnedTask);
  1958. Task<int>.Factory.FromAsync(BeginExecuteNonQueryAsync, EndExecuteNonQueryAsync, null).ContinueWith((t) => {
  1959. registration.Dispose();
  1960. if (t.IsFaulted) {
  1961. Exception e = t.Exception.InnerException;
  1962. source.SetException(e);
  1963. }
  1964. else {
  1965. if (t.IsCanceled) {
  1966. source.SetCanceled();
  1967. }
  1968. else {
  1969. source.SetResult(t.Result);
  1970. }
  1971. }
  1972. }, TaskScheduler.Default);
  1973. }
  1974. catch (Exception e) {
  1975. source.SetException(e);
  1976. }
  1977. return returnedTask;
  1978. }
  1979. protected override Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) {
  1980. return ExecuteReaderAsync(behavior, cancellationToken).ContinueWith<DbDataReader>((result) => {
  1981. if (result.IsFaulted) {
  1982. throw result.Exception.InnerException;
  1983. }
  1984. return result.Result;
  1985. }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default);
  1986. }
  1987. new public Task<SqlDataReader> ExecuteReaderAsync() {
  1988. return ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None);
  1989. }
  1990. new public Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior) {
  1991. return ExecuteReaderAsync(behavior, CancellationToken.None);
  1992. }
  1993. new public Task<SqlDataReader> ExecuteReaderAsync(CancellationToken cancellationToken) {
  1994. return ExecuteReaderAsync(CommandBehavior.Default, cancellationToken);
  1995. }
  1996. new public Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) {
  1997. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReaderAsync|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior);
  1998. SqlConnection.ExecutePermission.Demand();
  1999. TaskCompletionSource<SqlDataReader> source = new TaskCompletionSource<SqlDataReader>();
  2000. CancellationTokenRegistration registration = new CancellationTokenRegistration();
  2001. if (cancellationToken.CanBeCanceled) {
  2002. if (cancellationToken.IsCancellationRequested) {
  2003. source.SetCanceled();
  2004. return source.Task;
  2005. }
  2006. registration = cancellationToken.Register(CancelIgnoreFailure);
  2007. }
  2008. Task<SqlDataReader> returnedTask = source.Task;
  2009. try {
  2010. RegisterForConnectionCloseNotification(ref returnedTask);
  2011. Task<SqlDataReader>.Factory.FromAsync(BeginExecuteReaderAsync, EndExecuteReaderAsync, behavior, null).ContinueWith((t) => {
  2012. registration.Dispose();
  2013. if (t.IsFaulted) {
  2014. Exception e = t.Exception.InnerException;
  2015. source.SetException(e);
  2016. }
  2017. else {
  2018. if (t.IsCanceled) {
  2019. source.SetCanceled();
  2020. }
  2021. else {
  2022. source.SetResult(t.Result);
  2023. }
  2024. }
  2025. }, TaskScheduler.Default);
  2026. }
  2027. catch (Exception e) {
  2028. source.SetException(e);
  2029. }
  2030. return returnedTask;
  2031. }
  2032. public override Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
  2033. {
  2034. return ExecuteReaderAsync(cancellationToken).ContinueWith((executeTask) => {
  2035. TaskCompletionSource<object> source = new TaskCompletionSource<object>();
  2036. if (executeTask.IsCanceled) {
  2037. source.SetCanceled();
  2038. }
  2039. else if (executeTask.IsFaulted) {
  2040. source.SetException(executeTask.Exception.InnerException);
  2041. }
  2042. else {
  2043. SqlDataReader reader = executeTask.Result;
  2044. reader.ReadAsync(cancellationToken).ContinueWith((readTask) => {
  2045. try {
  2046. if (readTask.IsCanceled) {
  2047. reader.Dispose();
  2048. source.SetCanceled();
  2049. }
  2050. else if (readTask.IsFaulted) {
  2051. reader.Dispose();
  2052. source.SetException(readTask.Exception.InnerException);
  2053. }
  2054. else {
  2055. Exception exception = null;
  2056. object result = null;
  2057. try {
  2058. bool more = readTask.Result;
  2059. if (more && reader.FieldCount > 0) {
  2060. try {
  2061. result = reader.GetValue(0);
  2062. }
  2063. catch (Exception e) {
  2064. exception = e;
  2065. }
  2066. }
  2067. }
  2068. finally {
  2069. reader.Dispose();
  2070. }
  2071. if (exception != null) {
  2072. source.SetException(exception);
  2073. }
  2074. else {
  2075. source.SetResult(result);
  2076. }
  2077. }
  2078. }
  2079. catch (Exception e) {
  2080. // exception thrown by Dispose...
  2081. source.SetException(e);
  2082. }
  2083. }, TaskScheduler.Default);
  2084. }
  2085. return source.Task;
  2086. }, TaskScheduler.Default).Unwrap();
  2087. }
  2088. public Task<XmlReader> ExecuteXmlReaderAsync() {
  2089. return ExecuteXmlReaderAsync(CancellationToken.None);
  2090. }
  2091. public Task<XmlReader> ExecuteXmlReaderAsync(CancellationToken cancellationToken) {
  2092. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteXmlReaderAsync|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  2093. SqlConnection.ExecutePermission.Demand();
  2094. TaskCompletionSource<XmlReader> source = new TaskCompletionSource<XmlReader>();
  2095. CancellationTokenRegistration registration = new CancellationTokenRegistration();
  2096. if (cancellationToken.CanBeCanceled) {
  2097. if (cancellationToken.IsCancellationRequested) {
  2098. source.SetCanceled();
  2099. return source.Task;
  2100. }
  2101. registration = cancellationToken.Register(CancelIgnoreFailure);
  2102. }
  2103. Task<XmlReader> returnedTask = source.Task;
  2104. try {
  2105. RegisterForConnectionCloseNotification(ref returnedTask);
  2106. Task<XmlReader>.Factory.FromAsync(BeginExecuteXmlReaderAsync, EndExecuteXmlReaderAsync, null).ContinueWith((t) => {
  2107. registration.Dispose();
  2108. if (t.IsFaulted) {
  2109. Exception e = t.Exception.InnerException;
  2110. source.SetException(e);
  2111. }
  2112. else {
  2113. if (t.IsCanceled) {
  2114. source.SetCanceled();
  2115. }
  2116. else {
  2117. source.SetResult(t.Result);
  2118. }
  2119. }
  2120. }, TaskScheduler.Default);
  2121. }
  2122. catch (Exception e) {
  2123. source.SetException(e);
  2124. }
  2125. return returnedTask;
  2126. }
  2127. // If the user part is quoted, remove first and last brackets and then unquote any right square
  2128. // brackets in the procedure. This is a very simple parser that performs no validation. As
  2129. // with the function below, ideally we should have support from the server for this.
  2130. private static string UnquoteProcedurePart(string part) {
  2131. if ((null != part) && (2 <= part.Length)) {
  2132. if ('[' == part[0] && ']' == part[part.Length-1]) {
  2133. part = part.Substring(1, part.Length-2); // strip outer '[' & ']'
  2134. part = part.Replace("]]", "]"); // undo quoted "]" from "]]" to "]"
  2135. }
  2136. }
  2137. return part;
  2138. }
  2139. // User value in this format: [server].[database].[schema].[sp_foo];1
  2140. // This function should only be passed "[sp_foo];1".
  2141. // This function uses a pretty simple parser that doesn't do any validation.
  2142. // Ideally, we would have support from the server rather than us having to do this.
  2143. private static string UnquoteProcedureName(string name, out object groupNumber) {
  2144. groupNumber = null; // Out param - initialize value to no value.
  2145. string sproc = name;
  2146. if (null != sproc) {
  2147. if (Char.IsDigit(sproc[sproc.Length-1])) { // If last char is a digit, parse.
  2148. int semicolon = sproc.LastIndexOf(';');
  2149. if (semicolon != -1) { // If we found a semicolon, obtain the integer.
  2150. string part = sproc.Substring(semicolon+1);
  2151. int number = 0;
  2152. if (Int32.TryParse(part, out number)) { // No checking, just fail if this doesn't work.
  2153. groupNumber = number;
  2154. sproc = sproc.Substring(0, semicolon);
  2155. }
  2156. }
  2157. }
  2158. sproc = UnquoteProcedurePart(sproc);
  2159. }
  2160. return sproc;
  2161. }
  2162. //index into indirection arrays for columns of interest to DeriveParameters
  2163. private enum ProcParamsColIndex {
  2164. ParameterName = 0,
  2165. ParameterType,
  2166. DataType, // obsolete in katmai, use ManagedDataType instead
  2167. ManagedDataType, // new in katmai
  2168. CharacterMaximumLength,
  2169. NumericPrecision,
  2170. NumericScale,
  2171. TypeCatalogName,
  2172. TypeSchemaName,
  2173. TypeName,
  2174. XmlSchemaCollectionCatalogName,
  2175. XmlSchemaCollectionSchemaName,
  2176. XmlSchemaCollectionName,
  2177. UdtTypeName, // obsolete in Katmai. Holds the actual typename if UDT, since TypeName didn't back then.
  2178. DateTimeScale // new in Katmai
  2179. };
  2180. // Yukon- column ordinals (this array indexed by ProcParamsColIndex
  2181. static readonly internal string[] PreKatmaiProcParamsNames = new string[] {
  2182. "PARAMETER_NAME", // ParameterName,
  2183. "PARAMETER_TYPE", // ParameterType,
  2184. "DATA_TYPE", // DataType
  2185. null, // ManagedDataType, introduced in Katmai
  2186. "CHARACTER_MAXIMUM_LENGTH", // CharacterMaximumLength,
  2187. "NUMERIC_PRECISION", // NumericPrecision,
  2188. "NUMERIC_SCALE", // NumericScale,
  2189. "UDT_CATALOG", // TypeCatalogName,
  2190. "UDT_SCHEMA", // TypeSchemaName,
  2191. "TYPE_NAME", // TypeName,
  2192. "XML_CATALOGNAME", // XmlSchemaCollectionCatalogName,
  2193. "XML_SCHEMANAME", // XmlSchemaCollectionSchemaName,
  2194. "XML_SCHEMACOLLECTIONNAME", // XmlSchemaCollectionName
  2195. "UDT_NAME", // UdtTypeName
  2196. null, // Scale for datetime types with scale, introduced in Katmai
  2197. };
  2198. // Katmai+ column ordinals (this array indexed by ProcParamsColIndex
  2199. static readonly internal string[] KatmaiProcParamsNames = new string[] {
  2200. "PARAMETER_NAME", // ParameterName,
  2201. "PARAMETER_TYPE", // ParameterType,
  2202. null, // DataType, removed from Katmai+
  2203. "MANAGED_DATA_TYPE", // ManagedDataType,
  2204. "CHARACTER_MAXIMUM_LENGTH", // CharacterMaximumLength,
  2205. "NUMERIC_PRECISION", // NumericPrecision,
  2206. "NUMERIC_SCALE", // NumericScale,
  2207. "TYPE_CATALOG_NAME", // TypeCatalogName,
  2208. "TYPE_SCHEMA_NAME", // TypeSchemaName,
  2209. "TYPE_NAME", // TypeName,
  2210. "XML_CATALOGNAME", // XmlSchemaCollectionCatalogName,
  2211. "XML_SCHEMANAME", // XmlSchemaCollectionSchemaName,
  2212. "XML_SCHEMACOLLECTIONNAME", // XmlSchemaCollectionName
  2213. null, // UdtTypeName, removed from Katmai+
  2214. "SS_DATETIME_PRECISION", // Scale for datetime types with scale
  2215. };
  2216. internal void DeriveParameters() {
  2217. switch (this.CommandType) {
  2218. case System.Data.CommandType.Text:
  2219. throw ADP.DeriveParametersNotSupported(this);
  2220. case System.Data.CommandType.StoredProcedure:
  2221. break;
  2222. case System.Data.CommandType.TableDirect:
  2223. // CommandType.TableDirect - do nothing, parameters are not supported
  2224. throw ADP.DeriveParametersNotSupported(this);
  2225. default:
  2226. throw ADP.InvalidCommandType(this.CommandType);
  2227. }
  2228. // validate that we have a valid connection
  2229. ValidateCommand(ADP.DeriveParameters, false /*not async*/);
  2230. // Use common parser for SqlClient and OleDb - parse into 4 parts - Server, Catalog, Schema, ProcedureName
  2231. string[] parsedSProc = MultipartIdentifier.ParseMultipartIdentifier(this.CommandText, "[\"", "]\"", Res.SQL_SqlCommandCommandText, false);
  2232. if (null == parsedSProc[3] || ADP.IsEmpty(parsedSProc[3]))
  2233. {
  2234. throw ADP.NoStoredProcedureExists(this.CommandText);
  2235. }
  2236. Debug.Assert(parsedSProc.Length == 4, "Invalid array length result from SqlCommandBuilder.ParseProcedureName");
  2237. SqlCommand paramsCmd = null;
  2238. StringBuilder cmdText = new StringBuilder();
  2239. // Build call for sp_procedure_params_rowset built of unquoted values from user:
  2240. // [user server, if provided].[user catalog, else current database].[sys if Yukon, else blank].[sp_procedure_params_rowset]
  2241. // Server - pass only if user provided.
  2242. if (!ADP.IsEmpty(parsedSProc[0])) {
  2243. SqlCommandSet.BuildStoredProcedureName(cmdText, parsedSProc[0]);
  2244. cmdText.Append(".");
  2245. }
  2246. // Catalog - pass user provided, otherwise use current database.
  2247. if (ADP.IsEmpty(parsedSProc[1])) {
  2248. parsedSProc[1] = this.Connection.Database;
  2249. }
  2250. SqlCommandSet.BuildStoredProcedureName(cmdText, parsedSProc[1]);
  2251. cmdText.Append(".");
  2252. // Schema - only if Yukon, and then only pass sys. Also - pass managed version of sproc
  2253. // for Yukon, else older sproc.
  2254. string[] colNames;
  2255. bool useManagedDataType;
  2256. if (this.Connection.IsKatmaiOrNewer) {
  2257. // Procedure - [sp_procedure_params_managed]
  2258. cmdText.Append("[sys].[").Append(TdsEnums.SP_PARAMS_MGD10).Append("]");
  2259. colNames = KatmaiProcParamsNames;
  2260. useManagedDataType = true;
  2261. }
  2262. else {
  2263. if (this.Connection.IsYukonOrNewer) {
  2264. // Procedure - [sp_procedure_params_managed]
  2265. cmdText.Append("[sys].[").Append(TdsEnums.SP_PARAMS_MANAGED).Append("]");
  2266. }
  2267. else {
  2268. // Procedure - [sp_procedure_params_rowset]
  2269. cmdText.Append(".[").Append(TdsEnums.SP_PARAMS).Append("]");
  2270. }
  2271. colNames = PreKatmaiProcParamsNames;
  2272. useManagedDataType = false;
  2273. }
  2274. paramsCmd = new SqlCommand(cmdText.ToString(), this.Connection, this.Transaction);
  2275. paramsCmd.CommandType = CommandType.StoredProcedure;
  2276. object groupNumber;
  2277. // Prepare parameters for sp_procedure_params_rowset:
  2278. // 1) procedure name - unquote user value
  2279. // 2) group number - parsed at the time we unquoted procedure name
  2280. // 3) procedure schema - unquote user value
  2281. //
  2282. paramsCmd.Parameters.Add(new SqlParameter("@procedure_name", SqlDbType.NVarChar, 255));
  2283. paramsCmd.Parameters[0].Value = UnquoteProcedureName(parsedSProc[3], out groupNumber); // ProcedureName is 4rd element in parsed array
  2284. if (null != groupNumber) {
  2285. SqlParameter param = paramsCmd.Parameters.Add(new SqlParameter("@group_number", SqlDbType.Int));
  2286. param.Value = groupNumber;
  2287. }
  2288. if (!ADP.IsEmpty(parsedSProc[2])) { // SchemaName is 3rd element in parsed array
  2289. SqlParameter param = paramsCmd.Parameters.Add(new SqlParameter("@procedure_schema", SqlDbType.NVarChar, 255));
  2290. param.Value = UnquoteProcedurePart(parsedSProc[2]);
  2291. }
  2292. SqlDataReader r = null;
  2293. List<SqlParameter> parameters = new List<SqlParameter>();
  2294. bool processFinallyBlock = true;
  2295. try {
  2296. r = paramsCmd.ExecuteReader();
  2297. SqlParameter p = null;
  2298. while (r.Read()) {
  2299. // each row corresponds to a parameter of the stored proc. Fill in all the info
  2300. p = new SqlParameter();
  2301. // name
  2302. p.ParameterName = (string) r[colNames[(int)ProcParamsColIndex.ParameterName]];
  2303. // type
  2304. if (useManagedDataType) {
  2305. p.SqlDbType = (SqlDbType)(short)r[colNames[(int)ProcParamsColIndex.ManagedDataType]];
  2306. // Yukon didn't have as accurate of information as we're getting for Katmai, so re-map a couple of
  2307. // types for backward compatability.
  2308. switch (p.SqlDbType) {
  2309. case SqlDbType.Image:
  2310. case SqlDbType.Timestamp:
  2311. p.SqlDbType = SqlDbType.VarBinary;
  2312. break;
  2313. case SqlDbType.NText:
  2314. p.SqlDbType = SqlDbType.NVarChar;
  2315. break;
  2316. case SqlDbType.Text:
  2317. p.SqlDbType = SqlDbType.VarChar;
  2318. break;
  2319. default:
  2320. break;
  2321. }
  2322. }
  2323. else {
  2324. p.SqlDbType = MetaType.GetSqlDbTypeFromOleDbType((short)r[colNames[(int)ProcParamsColIndex.DataType]],
  2325. ADP.IsNull(r[colNames[(int)ProcParamsColIndex.TypeName]]) ?
  2326. ADP.StrEmpty :
  2327. (string)r[colNames[(int)ProcParamsColIndex.TypeName]]);
  2328. }
  2329. // size
  2330. object a = r[colNames[(int)ProcParamsColIndex.CharacterMaximumLength]];
  2331. if (a is int) {
  2332. int size = (int)a;
  2333. // Map MAX sizes correctly. The Katmai server-side proc sends 0 for these instead of -1.
  2334. // Should be fixed on the Katmai side, but would likely hold up the RI, and is safer to fix here.
  2335. // If we can get the server-side fixed before shipping Katmai, we can remove this mapping.
  2336. if (0 == size &&
  2337. (p.SqlDbType == SqlDbType.NVarChar ||
  2338. p.SqlDbType == SqlDbType.VarBinary ||
  2339. p.SqlDbType == SqlDbType.VarChar)) {
  2340. size = -1;
  2341. }
  2342. p.Size = size;
  2343. }
  2344. // direction
  2345. p.Direction = ParameterDirectionFromOleDbDirection((short)r[colNames[(int)ProcParamsColIndex.ParameterType]]);
  2346. if (p.SqlDbType == SqlDbType.Decimal) {
  2347. p.ScaleInternal = (byte) ((short)r[colNames[(int)ProcParamsColIndex.NumericScale]] & 0xff);
  2348. p.PrecisionInternal = (byte)((short)r[colNames[(int)ProcParamsColIndex.NumericPrecision]] & 0xff);
  2349. }
  2350. // type name for Udt
  2351. if (SqlDbType.Udt == p.SqlDbType) {
  2352. Debug.Assert(this._activeConnection.IsYukonOrNewer,"Invalid datatype token received from pre-yukon server");
  2353. string udtTypeName;
  2354. if (useManagedDataType) {
  2355. udtTypeName = (string)r[colNames[(int)ProcParamsColIndex.TypeName]];
  2356. }
  2357. else {
  2358. udtTypeName = (string)r[colNames[(int)ProcParamsColIndex.UdtTypeName]];
  2359. }
  2360. //read the type name
  2361. p.UdtTypeName = r[colNames[(int)ProcParamsColIndex.TypeCatalogName]]+"."+
  2362. r[colNames[(int)ProcParamsColIndex.TypeSchemaName]]+"."+
  2363. udtTypeName;
  2364. }
  2365. // type name for Structured types (same as for Udt's except assign p.TypeName instead of p.UdtTypeName
  2366. if (SqlDbType.Structured == p.SqlDbType) {
  2367. Debug.Assert(this._activeConnection.IsKatmaiOrNewer,"Invalid datatype token received from pre-katmai server");
  2368. //read the type name
  2369. p.TypeName = r[colNames[(int)ProcParamsColIndex.TypeCatalogName]]+"."+
  2370. r[colNames[(int)ProcParamsColIndex.TypeSchemaName]]+"."+
  2371. r[colNames[(int)ProcParamsColIndex.TypeName]];
  2372. }
  2373. // XmlSchema name for Xml types
  2374. if (SqlDbType.Xml == p.SqlDbType) {
  2375. object value;
  2376. value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionCatalogName]];
  2377. p.XmlSchemaCollectionDatabase = ADP.IsNull(value) ? String.Empty : (string) value;
  2378. value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionSchemaName]];
  2379. p.XmlSchemaCollectionOwningSchema = ADP.IsNull(value) ? String.Empty : (string) value;
  2380. value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionName]];
  2381. p.XmlSchemaCollectionName = ADP.IsNull(value) ? String.Empty : (string) value;
  2382. }
  2383. if (MetaType._IsVarTime(p.SqlDbType)) {
  2384. object value = r[colNames[(int)ProcParamsColIndex.DateTimeScale]];
  2385. if (value is int) {
  2386. p.ScaleInternal = (byte)(((int)value) & 0xff);
  2387. }
  2388. }
  2389. parameters.Add(p);
  2390. }
  2391. }
  2392. catch (Exception e) {
  2393. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  2394. throw;
  2395. }
  2396. finally {
  2397. TdsParser.ReliabilitySection.Assert("unreliable call to DeriveParameters"); // you need to setup for a thread abort somewhere before you call this method
  2398. if (processFinallyBlock) {
  2399. if (null != r)
  2400. r.Close();
  2401. // always unhook the user's connection
  2402. paramsCmd.Connection = null;
  2403. }
  2404. }
  2405. if (parameters.Count == 0) {
  2406. throw ADP.NoStoredProcedureExists(this.CommandText);
  2407. }
  2408. this.Parameters.Clear();
  2409. foreach (SqlParameter temp in parameters) {
  2410. this._parameters.Add(temp);
  2411. }
  2412. }
  2413. private ParameterDirection ParameterDirectionFromOleDbDirection(short oledbDirection) {
  2414. Debug.Assert(oledbDirection >= 1 && oledbDirection <= 4, "invalid parameter direction from params_rowset!");
  2415. switch (oledbDirection) {
  2416. case 2:
  2417. return ParameterDirection.InputOutput;
  2418. case 3:
  2419. return ParameterDirection.Output;
  2420. case 4:
  2421. return ParameterDirection.ReturnValue;
  2422. default:
  2423. return ParameterDirection.Input;
  2424. }
  2425. }
  2426. // get cached metadata
  2427. internal _SqlMetaDataSet MetaData {
  2428. get {
  2429. return _cachedMetaData;
  2430. }
  2431. }
  2432. // Check to see if notificactions auto enlistment is turned on. Enlist if so.
  2433. private void CheckNotificationStateAndAutoEnlist() {
  2434. // First, if auto-enlist is on, check server version and then obtain context if
  2435. // present. If so, auto enlist to the dependency ID given in the context data.
  2436. if (NotificationAutoEnlist) {
  2437. if (_activeConnection.IsYukonOrNewer) { // Only supported for Yukon...
  2438. string notifyContext = SqlNotificationContext();
  2439. if (!ADP.IsEmpty(notifyContext)) {
  2440. // Map to dependency by ID set in context data.
  2441. SqlDependency dependency = SqlDependencyPerAppDomainDispatcher.SingletonInstance.LookupDependencyEntry(notifyContext);
  2442. if (null != dependency) {
  2443. // Add this command to the dependency.
  2444. dependency.AddCommandDependency(this);
  2445. }
  2446. }
  2447. }
  2448. }
  2449. // If we have a notification with a dependency, setup the notification options at this time.
  2450. // If user passes options, then we will always have option data at the time the SqlDependency
  2451. // ctor is called. But, if we are using default queue, then we do not have this data until
  2452. // Start(). Due to this, we always delay setting options until execute.
  2453. // There is a variance in order between Start(), SqlDependency(), and Execute. This is the
  2454. // best way to solve that problem.
  2455. if (null != Notification) {
  2456. if (_sqlDep != null) {
  2457. if (null == _sqlDep.Options) {
  2458. // If null, SqlDependency was not created with options, so we need to obtain default options now.
  2459. // GetDefaultOptions can and will throw under certain conditions.
  2460. // In order to match to the appropriate start - we need 3 pieces of info:
  2461. // 1) server 2) user identity (SQL Auth or Int Sec) 3) database
  2462. SqlDependency.IdentityUserNamePair identityUserName = null;
  2463. // Obtain identity from connection.
  2464. SqlInternalConnectionTds internalConnection = _activeConnection.InnerConnection as SqlInternalConnectionTds;
  2465. if (internalConnection.Identity != null) {
  2466. identityUserName = new SqlDependency.IdentityUserNamePair(internalConnection.Identity, null);
  2467. }
  2468. else {
  2469. identityUserName = new SqlDependency.IdentityUserNamePair(null, internalConnection.ConnectionOptions.UserID);
  2470. }
  2471. Notification.Options = SqlDependency.GetDefaultComposedOptions(_activeConnection.DataSource,
  2472. InternalTdsConnection.ServerProvidedFailOverPartner,
  2473. identityUserName, _activeConnection.Database);
  2474. }
  2475. // Set UserData on notifications, as well as adding to the appdomain dispatcher. The value is
  2476. // computed by an algorithm on the dependency - fixed and will always produce the same value
  2477. // given identical commandtext + parameter values.
  2478. Notification.UserData = _sqlDep.ComputeHashAndAddToDispatcher(this);
  2479. // Maintain server list for SqlDependency.
  2480. _sqlDep.AddToServerList(_activeConnection.DataSource);
  2481. }
  2482. }
  2483. }
  2484. [System.Security.Permissions.SecurityPermission(SecurityAction.Assert, Infrastructure=true)]
  2485. static internal string SqlNotificationContext() {
  2486. SqlConnection.VerifyExecutePermission();
  2487. // since this information is protected, follow it so that it is not exposed to the user.
  2488. // SQLBU 329633, SQLBU 329637
  2489. return (System.Runtime.Remoting.Messaging.CallContext.GetData("MS.SqlDependencyCookie") as string);
  2490. }
  2491. // Tds-specific logic for ExecuteNonQuery run handling
  2492. private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, bool asyncWrite ) {
  2493. Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async");
  2494. bool processFinallyBlock = true;
  2495. try {
  2496. Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout);
  2497. if (reconnectTask != null) {
  2498. long reconnectionStart = ADP.TimerCurrent();
  2499. if (async) {
  2500. TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
  2501. _activeConnection.RegisterWaitingForReconnect(completion.Task);
  2502. _reconnectionCompletionSource = completion;
  2503. CancellationTokenSource timeoutCTS = new CancellationTokenSource();
  2504. AsyncHelper.SetTimeoutException(completion, timeout, SQL.CR_ReconnectTimeout, timeoutCTS.Token);
  2505. AsyncHelper.ContinueTask(reconnectTask, completion,
  2506. () => {
  2507. if (completion.Task.IsCompleted) {
  2508. return;
  2509. }
  2510. Interlocked.CompareExchange(ref _reconnectionCompletionSource, null, completion);
  2511. timeoutCTS.Cancel();
  2512. Task subTask = RunExecuteNonQueryTds(methodName, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart), asyncWrite);
  2513. if (subTask == null) {
  2514. completion.SetResult(null);
  2515. }
  2516. else {
  2517. AsyncHelper.ContinueTask(subTask, completion, () => completion.SetResult(null));
  2518. }
  2519. }, connectionToAbort: _activeConnection);
  2520. return completion.Task;
  2521. }
  2522. else {
  2523. AsyncHelper.WaitForCompletion(reconnectTask, timeout, () => { throw SQL.CR_ReconnectTimeout(); });
  2524. timeout = TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart);
  2525. }
  2526. }
  2527. if (asyncWrite) {
  2528. _activeConnection.AddWeakReference(this, SqlReferenceCollection.CommandTag);
  2529. }
  2530. GetStateObject();
  2531. // we just send over the raw text with no annotation
  2532. // no parameters are sent over
  2533. // no data reader is returned
  2534. // use this overload for "batch SQL" tds token type
  2535. Bid.Trace("<sc.SqlCommand.ExecuteNonQuery|INFO> %d#, Command executed as SQLBATCH.\n", ObjectID);
  2536. Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true);
  2537. Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
  2538. NotifyDependency();
  2539. if (async) {
  2540. _activeConnection.GetOpenTdsConnection(methodName).IncrementAsyncCount();
  2541. }
  2542. else {
  2543. bool dataReady;
  2544. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2545. bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady);
  2546. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2547. }
  2548. }
  2549. catch (Exception e) {
  2550. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  2551. throw;
  2552. }
  2553. finally {
  2554. TdsParser.ReliabilitySection.Assert("unreliable call to RunExecuteNonQueryTds"); // you need to setup for a thread abort somewhere before you call this method
  2555. if (processFinallyBlock && !async) {
  2556. // When executing Async, we need to keep the _stateObj alive...
  2557. PutStateObject();
  2558. }
  2559. }
  2560. return null;
  2561. }
  2562. // Smi-specific logic for ExecuteNonQuery
  2563. private void RunExecuteNonQuerySmi( bool sendToPipe ) {
  2564. SqlInternalConnectionSmi innerConnection = InternalSmiConnection;
  2565. // Set it up, process all of the events, and we're done!
  2566. SmiRequestExecutor requestExecutor = null;
  2567. try {
  2568. requestExecutor = SetUpSmiRequest(innerConnection);
  2569. SmiExecuteType execType;
  2570. if ( sendToPipe )
  2571. execType = SmiExecuteType.ToPipe;
  2572. else
  2573. execType = SmiExecuteType.NonQuery;
  2574. SmiEventStream eventStream = null;
  2575. // Don't need a CER here because caller already has one that will doom the
  2576. // connection if it's a finally-skipping type of problem.
  2577. bool processFinallyBlock = true;
  2578. try {
  2579. long transactionId;
  2580. SysTx.Transaction transaction;
  2581. innerConnection.GetCurrentTransactionPair(out transactionId, out transaction);
  2582. if (Bid.AdvancedOn) {
  2583. Bid.Trace("<sc.SqlCommand.RunExecuteNonQuerySmi|ADV> %d#, innerConnection=%d#, transactionId=0x%I64x, cmdBehavior=%d.\n", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default);
  2584. }
  2585. if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) {
  2586. eventStream = requestExecutor.Execute(
  2587. innerConnection.SmiConnection,
  2588. transactionId,
  2589. transaction,
  2590. CommandBehavior.Default,
  2591. execType);
  2592. }
  2593. else {
  2594. eventStream = requestExecutor.Execute(
  2595. innerConnection.SmiConnection,
  2596. transactionId,
  2597. CommandBehavior.Default,
  2598. execType);
  2599. }
  2600. while ( eventStream.HasEvents ) {
  2601. eventStream.ProcessEvent( EventSink );
  2602. }
  2603. }
  2604. catch (Exception e) {
  2605. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  2606. throw;
  2607. }
  2608. finally {
  2609. TdsParser.ReliabilitySection.Assert("unreliable call to RunExecuteNonQuerySmi"); // you need to setup for a thread abort somewhere before you call this method
  2610. if (null != eventStream && processFinallyBlock) {
  2611. eventStream.Close( EventSink );
  2612. }
  2613. }
  2614. EventSink.ProcessMessagesAndThrow();
  2615. }
  2616. finally {
  2617. if (requestExecutor != null) {
  2618. requestExecutor.Close(EventSink);
  2619. EventSink.ProcessMessagesAndThrow(ignoreNonFatalMessages: true);
  2620. }
  2621. }
  2622. }
  2623. /// <summary>
  2624. /// Resets the encryption related state of the command object and each of the parameters.
  2625. /// BatchRPC doesn't need special handling to cleanup the state of each RPC object and its parameters since a new RPC object and
  2626. /// parameters are generated on every execution.
  2627. /// </summary>
  2628. private void ResetEncryptionState() {
  2629. // First reset the command level state.
  2630. ClearDescribeParameterEncryptionRequests();
  2631. // Reset the state of each of the parameters.
  2632. if (_parameters != null) {
  2633. for (int i = 0; i < _parameters.Count; i++) {
  2634. _parameters[i].CipherMetadata = null;
  2635. _parameters[i].HasReceivedMetadata = false;
  2636. }
  2637. }
  2638. }
  2639. /// <summary>
  2640. /// Steps to be executed in the Prepare Transparent Encryption finally block.
  2641. /// </summary>
  2642. private void PrepareTransparentEncryptionFinallyBlock( bool closeDataReader,
  2643. bool clearDataStructures,
  2644. bool decrementAsyncCount,
  2645. bool wasDescribeParameterEncryptionNeeded,
  2646. ReadOnlyDictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcMap,
  2647. SqlDataReader describeParameterEncryptionDataReader) {
  2648. if (clearDataStructures) {
  2649. // Clear some state variables in SqlCommand that reflect in-progress describe parameter encryption requests.
  2650. ClearDescribeParameterEncryptionRequests();
  2651. if (describeParameterEncryptionRpcOriginalRpcMap != null) {
  2652. describeParameterEncryptionRpcOriginalRpcMap = null;
  2653. }
  2654. }
  2655. // Decrement the async count.
  2656. if (decrementAsyncCount) {
  2657. SqlInternalConnectionTds internalConnectionTds = _activeConnection.GetOpenTdsConnection();
  2658. if (internalConnectionTds != null) {
  2659. internalConnectionTds.DecrementAsyncCount();
  2660. }
  2661. }
  2662. if (closeDataReader) {
  2663. // Close the data reader to reset the _stateObj
  2664. if (null != describeParameterEncryptionDataReader) {
  2665. describeParameterEncryptionDataReader.Close();
  2666. }
  2667. }
  2668. }
  2669. /// <summary>
  2670. /// Executes the reader after checking to see if we need to encrypt input parameters and then encrypting it if required.
  2671. /// TryFetchInputParameterEncryptionInfo() -> ReadDescribeEncryptionParameterResults()-> EncryptInputParameters() ->RunExecuteReaderTds()
  2672. /// </summary>
  2673. /// <param name="cmdBehavior"></param>
  2674. /// <param name="returnStream"></param>
  2675. /// <param name="async"></param>
  2676. /// <param name="timeout"></param>
  2677. /// <param name="task"></param>
  2678. /// <param name="asyncWrite"></param>
  2679. /// <returns></returns>
  2680. private void PrepareForTransparentEncryption(CommandBehavior cmdBehavior, bool returnStream, bool async, int timeout, TaskCompletionSource<object> completion, out Task returnTask, bool asyncWrite)
  2681. {
  2682. // Fetch reader with input params
  2683. Task fetchInputParameterEncryptionInfoTask = null;
  2684. bool describeParameterEncryptionNeeded = false;
  2685. SqlDataReader describeParameterEncryptionDataReader = null;
  2686. returnTask = null;
  2687. Debug.Assert(_activeConnection != null, "_activeConnection should not be null in PrepareForTransparentEncryption.");
  2688. Debug.Assert(_activeConnection.Parser != null, "_activeConnection.Parser should not be null in PrepareForTransparentEncryption.");
  2689. Debug.Assert(_activeConnection.Parser.IsColumnEncryptionSupported,
  2690. "_activeConnection.Parser.IsColumnEncryptionSupported should be true in PrepareForTransparentEncryption.");
  2691. Debug.Assert(_columnEncryptionSetting == SqlCommandColumnEncryptionSetting.Enabled
  2692. || (_columnEncryptionSetting == SqlCommandColumnEncryptionSetting.UseConnectionSetting && _activeConnection.IsColumnEncryptionSettingEnabled),
  2693. "ColumnEncryption setting should be enabled for input parameter encryption.");
  2694. Debug.Assert(async == (completion != null), "completion should can be null if and only if mode is async.");
  2695. // A flag to indicate if finallyblock needs to execute.
  2696. bool processFinallyBlock = true;
  2697. // A flag to indicate if we need to decrement async count on the connection in finally block.
  2698. bool decrementAsyncCountInFinallyBlock = async;
  2699. // Flag to indicate if exception is caught during the execution, to govern clean up.
  2700. bool exceptionCaught = false;
  2701. // Used in BatchRPCMode to maintain a map of describe parameter encryption RPC requests (Keys) and their corresponding original RPC requests (Values).
  2702. ReadOnlyDictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcMap = null;
  2703. TdsParser bestEffortCleanupTarget = null;
  2704. RuntimeHelpers.PrepareConstrainedRegions();
  2705. try {
  2706. #if DEBUG
  2707. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  2708. RuntimeHelpers.PrepareConstrainedRegions();
  2709. try {
  2710. tdsReliabilitySection.Start();
  2711. #else
  2712. {
  2713. #endif //DEBUG
  2714. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  2715. try {
  2716. // Fetch the encryption information that applies to any of the input parameters.
  2717. describeParameterEncryptionDataReader = TryFetchInputParameterEncryptionInfo(timeout,
  2718. async,
  2719. asyncWrite,
  2720. out describeParameterEncryptionNeeded,
  2721. out fetchInputParameterEncryptionInfoTask,
  2722. out describeParameterEncryptionRpcOriginalRpcMap);
  2723. Debug.Assert(describeParameterEncryptionNeeded || describeParameterEncryptionDataReader == null,
  2724. "describeParameterEncryptionDataReader should be null if we don't need to request describe parameter encryption request.");
  2725. Debug.Assert(fetchInputParameterEncryptionInfoTask == null || async,
  2726. "Task returned by TryFetchInputParameterEncryptionInfo, when in sync mode, in PrepareForTransparentEncryption.");
  2727. Debug.Assert((describeParameterEncryptionRpcOriginalRpcMap != null) == BatchRPCMode,
  2728. "describeParameterEncryptionRpcOriginalRpcMap can be non-null if and only if it is in BatchRPCMode.");
  2729. // If we didn't have parameters, we can fall back to regular code path, by simply returning.
  2730. if (!describeParameterEncryptionNeeded) {
  2731. Debug.Assert(null == fetchInputParameterEncryptionInfoTask,
  2732. "fetchInputParameterEncryptionInfoTask should not be set if describe parameter encryption is not needed.");
  2733. Debug.Assert(null == describeParameterEncryptionDataReader,
  2734. "SqlDataReader created for describe parameter encryption params when it is not needed.");
  2735. return;
  2736. }
  2737. Debug.Assert(describeParameterEncryptionDataReader != null,
  2738. "describeParameterEncryptionDataReader should not be null, as it is required to get results of describe parameter encryption.");
  2739. // Fire up another task to read the results of describe parameter encryption
  2740. if (fetchInputParameterEncryptionInfoTask != null) {
  2741. // Mark that we should not process the finally block since we have async execution pending.
  2742. // Note that this should be done outside the task's continuation delegate.
  2743. processFinallyBlock = false;
  2744. returnTask = AsyncHelper.CreateContinuationTask(fetchInputParameterEncryptionInfoTask, () => {
  2745. bool processFinallyBlockAsync = true;
  2746. RuntimeHelpers.PrepareConstrainedRegions();
  2747. try {
  2748. #if DEBUG
  2749. TdsParser.ReliabilitySection tdsReliabilitySectionAsync = new TdsParser.ReliabilitySection();
  2750. RuntimeHelpers.PrepareConstrainedRegions();
  2751. try {
  2752. tdsReliabilitySectionAsync.Start();
  2753. #endif //DEBUG
  2754. // Check for any exceptions on network write, before reading.
  2755. CheckThrowSNIException();
  2756. // If it is async, then TryFetchInputParameterEncryptionInfo-> RunExecuteReaderTds would have incremented the async count.
  2757. // Decrement it when we are about to complete async execute reader.
  2758. SqlInternalConnectionTds internalConnectionTds = _activeConnection.GetOpenTdsConnection();
  2759. if (internalConnectionTds != null)
  2760. {
  2761. internalConnectionTds.DecrementAsyncCount();
  2762. decrementAsyncCountInFinallyBlock = false;
  2763. }
  2764. // Complete executereader.
  2765. describeParameterEncryptionDataReader = CompleteAsyncExecuteReader();
  2766. Debug.Assert(null == _stateObj, "non-null state object in PrepareForTransparentEncryption.");
  2767. // Read the results of describe parameter encryption.
  2768. ReadDescribeEncryptionParameterResults(describeParameterEncryptionDataReader, describeParameterEncryptionRpcOriginalRpcMap);
  2769. #if DEBUG
  2770. // Failpoint to force the thread to halt to simulate cancellation of SqlCommand.
  2771. if (_sleepAfterReadDescribeEncryptionParameterResults) {
  2772. Thread.Sleep(10000);
  2773. }
  2774. }
  2775. finally {
  2776. tdsReliabilitySectionAsync.Stop();
  2777. }
  2778. #endif //DEBUG
  2779. }
  2780. catch (Exception e) {
  2781. processFinallyBlockAsync = ADP.IsCatchableExceptionType(e);
  2782. throw;
  2783. }
  2784. finally {
  2785. PrepareTransparentEncryptionFinallyBlock( closeDataReader: processFinallyBlockAsync,
  2786. decrementAsyncCount: decrementAsyncCountInFinallyBlock,
  2787. clearDataStructures: processFinallyBlockAsync,
  2788. wasDescribeParameterEncryptionNeeded: describeParameterEncryptionNeeded,
  2789. describeParameterEncryptionRpcOriginalRpcMap: describeParameterEncryptionRpcOriginalRpcMap,
  2790. describeParameterEncryptionDataReader: describeParameterEncryptionDataReader);
  2791. }
  2792. },
  2793. onFailure: ((exception) => {
  2794. if (_cachedAsyncState != null) {
  2795. _cachedAsyncState.ResetAsyncState();
  2796. }
  2797. if (exception != null) {
  2798. throw exception;
  2799. }}));
  2800. }
  2801. else {
  2802. // If it was async, ending the reader is still pending.
  2803. if (async) {
  2804. // Mark that we should not process the finally block since we have async execution pending.
  2805. // Note that this should be done outside the task's continuation delegate.
  2806. processFinallyBlock = false;
  2807. returnTask = Task.Run(() => {
  2808. bool processFinallyBlockAsync = true;
  2809. RuntimeHelpers.PrepareConstrainedRegions();
  2810. try {
  2811. #if DEBUG
  2812. TdsParser.ReliabilitySection tdsReliabilitySectionAsync = new TdsParser.ReliabilitySection();
  2813. RuntimeHelpers.PrepareConstrainedRegions();
  2814. try {
  2815. tdsReliabilitySectionAsync.Start();
  2816. #endif //DEBUG
  2817. // Check for any exceptions on network write, before reading.
  2818. CheckThrowSNIException();
  2819. // If it is async, then TryFetchInputParameterEncryptionInfo-> RunExecuteReaderTds would have incremented the async count.
  2820. // Decrement it when we are about to complete async execute reader.
  2821. SqlInternalConnectionTds internalConnectionTds = _activeConnection.GetOpenTdsConnection();
  2822. if (internalConnectionTds != null) {
  2823. internalConnectionTds.DecrementAsyncCount();
  2824. decrementAsyncCountInFinallyBlock = false;
  2825. }
  2826. // Complete executereader.
  2827. describeParameterEncryptionDataReader = CompleteAsyncExecuteReader();
  2828. Debug.Assert(null == _stateObj, "non-null state object in PrepareForTransparentEncryption.");
  2829. // Read the results of describe parameter encryption.
  2830. ReadDescribeEncryptionParameterResults(describeParameterEncryptionDataReader, describeParameterEncryptionRpcOriginalRpcMap);
  2831. #if DEBUG
  2832. // Failpoint to force the thread to halt to simulate cancellation of SqlCommand.
  2833. if (_sleepAfterReadDescribeEncryptionParameterResults) {
  2834. Thread.Sleep(10000);
  2835. }
  2836. #endif
  2837. #if DEBUG
  2838. }
  2839. finally {
  2840. tdsReliabilitySectionAsync.Stop();
  2841. }
  2842. #endif //DEBUG
  2843. }
  2844. catch (Exception e) {
  2845. processFinallyBlockAsync = ADP.IsCatchableExceptionType(e);
  2846. throw;
  2847. }
  2848. finally {
  2849. PrepareTransparentEncryptionFinallyBlock( closeDataReader: processFinallyBlockAsync,
  2850. decrementAsyncCount: decrementAsyncCountInFinallyBlock,
  2851. clearDataStructures: processFinallyBlockAsync,
  2852. wasDescribeParameterEncryptionNeeded: describeParameterEncryptionNeeded,
  2853. describeParameterEncryptionRpcOriginalRpcMap: describeParameterEncryptionRpcOriginalRpcMap,
  2854. describeParameterEncryptionDataReader: describeParameterEncryptionDataReader);
  2855. }
  2856. });
  2857. }
  2858. else {
  2859. // For synchronous execution, read the results of describe parameter encryption here.
  2860. ReadDescribeEncryptionParameterResults(describeParameterEncryptionDataReader, describeParameterEncryptionRpcOriginalRpcMap);
  2861. }
  2862. #if DEBUG
  2863. // Failpoint to force the thread to halt to simulate cancellation of SqlCommand.
  2864. if (_sleepAfterReadDescribeEncryptionParameterResults) {
  2865. Thread.Sleep(10000);
  2866. }
  2867. #endif
  2868. }
  2869. }
  2870. catch (Exception e) {
  2871. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  2872. exceptionCaught = true;
  2873. throw;
  2874. }
  2875. finally {
  2876. // Free up the state only for synchronous execution. For asynchronous execution, free only if there was an exception.
  2877. PrepareTransparentEncryptionFinallyBlock(closeDataReader: (processFinallyBlock && !async) || exceptionCaught,
  2878. decrementAsyncCount: decrementAsyncCountInFinallyBlock && exceptionCaught,
  2879. clearDataStructures: (processFinallyBlock && !async) || exceptionCaught,
  2880. wasDescribeParameterEncryptionNeeded: describeParameterEncryptionNeeded,
  2881. describeParameterEncryptionRpcOriginalRpcMap: describeParameterEncryptionRpcOriginalRpcMap,
  2882. describeParameterEncryptionDataReader: describeParameterEncryptionDataReader);
  2883. }
  2884. }
  2885. #if DEBUG
  2886. finally {
  2887. tdsReliabilitySection.Stop();
  2888. }
  2889. #endif //DEBUG
  2890. }
  2891. catch (System.OutOfMemoryException e) {
  2892. _activeConnection.Abort(e);
  2893. throw;
  2894. }
  2895. catch (System.StackOverflowException e) {
  2896. _activeConnection.Abort(e);
  2897. throw;
  2898. }
  2899. catch (System.Threading.ThreadAbortException e) {
  2900. _activeConnection.Abort(e);
  2901. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  2902. throw;
  2903. }
  2904. catch (Exception e) {
  2905. if (cachedAsyncState != null) {
  2906. cachedAsyncState.ResetAsyncState();
  2907. }
  2908. if (ADP.IsCatchableExceptionType(e)) {
  2909. ReliablePutStateObject();
  2910. }
  2911. throw;
  2912. }
  2913. }
  2914. /// <summary>
  2915. /// Executes an RPC to fetch param encryption info from SQL Engine. If this method is not done writing
  2916. /// the request to wire, it'll set the "task" parameter which can be used to create continuations.
  2917. /// </summary>
  2918. /// <param name="timeout"></param>
  2919. /// <param name="async"></param>
  2920. /// <param name="asyncWrite"></param>
  2921. /// <param name="inputParameterEncryptionNeeded"></param>
  2922. /// <param name="task"></param>
  2923. /// <param name="describeParameterEncryptionRpcOriginalRpcMap"></param>
  2924. /// <returns></returns>
  2925. private SqlDataReader TryFetchInputParameterEncryptionInfo(int timeout,
  2926. bool async,
  2927. bool asyncWrite,
  2928. out bool inputParameterEncryptionNeeded,
  2929. out Task task,
  2930. out ReadOnlyDictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcMap) {
  2931. inputParameterEncryptionNeeded = false;
  2932. task = null;
  2933. describeParameterEncryptionRpcOriginalRpcMap = null;
  2934. if (BatchRPCMode) {
  2935. // Count the rpc requests that need to be transparently encrypted
  2936. // We simply look for any parameters in a request and add the request to be queried for parameter encryption
  2937. Dictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcDictionary = new Dictionary<_SqlRPC, _SqlRPC>();
  2938. for (int i = 0; i < _SqlRPCBatchArray.Length; i++) {
  2939. // In BatchRPCMode, the actual T-SQL query is in the first parameter and not present as the rpcName, as is the case with non-BatchRPCMode.
  2940. // So input parameters start at parameters[1]. parameters[0] is the actual T-SQL Statement. rpcName is sp_executesql.
  2941. if (_SqlRPCBatchArray[i].parameters.Length > 1) {
  2942. _SqlRPCBatchArray[i].needsFetchParameterEncryptionMetadata = true;
  2943. // Since we are going to need multiple RPC objects, allocate a new one here for each command in the batch.
  2944. _SqlRPC rpcDescribeParameterEncryptionRequest = new _SqlRPC();
  2945. // Prepare the describe parameter encryption request.
  2946. PrepareDescribeParameterEncryptionRequest(_SqlRPCBatchArray[i], ref rpcDescribeParameterEncryptionRequest);
  2947. Debug.Assert(rpcDescribeParameterEncryptionRequest != null, "rpcDescribeParameterEncryptionRequest should not be null, after call to PrepareDescribeParameterEncryptionRequest.");
  2948. Debug.Assert(!describeParameterEncryptionRpcOriginalRpcDictionary.ContainsKey(rpcDescribeParameterEncryptionRequest),
  2949. "There should not already be a key referring to the current rpcDescribeParameterEncryptionRequest, in the dictionary describeParameterEncryptionRpcOriginalRpcDictionary.");
  2950. // Add the describe parameter encryption RPC request as the key and its corresponding original rpc request to the dictionary.
  2951. describeParameterEncryptionRpcOriginalRpcDictionary.Add(rpcDescribeParameterEncryptionRequest, _SqlRPCBatchArray[i]);
  2952. }
  2953. }
  2954. describeParameterEncryptionRpcOriginalRpcMap = new ReadOnlyDictionary<_SqlRPC, _SqlRPC>(describeParameterEncryptionRpcOriginalRpcDictionary);
  2955. if (describeParameterEncryptionRpcOriginalRpcMap.Count == 0) {
  2956. // If no parameters are present, nothing to do, simply return.
  2957. return null;
  2958. }
  2959. else {
  2960. inputParameterEncryptionNeeded = true;
  2961. }
  2962. _sqlRPCParameterEncryptionReqArray = describeParameterEncryptionRpcOriginalRpcMap.Keys.ToArray();
  2963. Debug.Assert(_sqlRPCParameterEncryptionReqArray.Length > 0, "There should be at-least 1 describe parameter encryption rpc request.");
  2964. Debug.Assert(_sqlRPCParameterEncryptionReqArray.Length <= _SqlRPCBatchArray.Length,
  2965. "The number of decribe parameter encryption RPC requests is more than the number of original RPC requests.");
  2966. }
  2967. else if (0 != GetParameterCount(_parameters)) {
  2968. // Fetch params for a single batch
  2969. inputParameterEncryptionNeeded = true;
  2970. _sqlRPCParameterEncryptionReqArray = new _SqlRPC[1];
  2971. _SqlRPC rpc = null;
  2972. GetRPCObject(_parameters.Count, ref rpc);
  2973. Debug.Assert(rpc != null, "GetRPCObject should not return rpc as null.");
  2974. rpc.rpcName = CommandText;
  2975. int i = 0;
  2976. foreach (SqlParameter sqlParam in _parameters) {
  2977. rpc.parameters[i++] = sqlParam;
  2978. }
  2979. // Prepare the RPC request for describe parameter encryption procedure.
  2980. PrepareDescribeParameterEncryptionRequest(rpc, ref _sqlRPCParameterEncryptionReqArray[0]);
  2981. Debug.Assert(_sqlRPCParameterEncryptionReqArray[0] != null, "_sqlRPCParameterEncryptionReqArray[0] should not be null, after call to PrepareDescribeParameterEncryptionRequest.");
  2982. }
  2983. if (inputParameterEncryptionNeeded) {
  2984. // Set the flag that indicates that parameter encryption requests are currently in-progress.
  2985. _isDescribeParameterEncryptionRPCCurrentlyInProgress = true;
  2986. #if DEBUG
  2987. // Failpoint to force the thread to halt to simulate cancellation of SqlCommand.
  2988. if (_sleepDuringTryFetchInputParameterEncryptionInfo) {
  2989. Thread.Sleep(10000);
  2990. }
  2991. #endif
  2992. // Execute the RPC.
  2993. return RunExecuteReaderTds( CommandBehavior.Default,
  2994. runBehavior: RunBehavior.ReturnImmediately, // Other RunBehavior modes will skip reading rows.
  2995. returnStream: true,
  2996. async: async,
  2997. timeout: timeout,
  2998. task: out task,
  2999. asyncWrite: asyncWrite,
  3000. ds: null,
  3001. describeParameterEncryptionRequest: true);
  3002. }
  3003. else {
  3004. return null;
  3005. }
  3006. }
  3007. /// <summary>
  3008. /// Constructs a SqlParameter with a given string value
  3009. /// </summary>
  3010. /// <param name="queryText"></param>
  3011. /// <returns></returns>
  3012. private SqlParameter GetSqlParameterWithQueryText(string queryText)
  3013. {
  3014. SqlParameter sqlParam = new SqlParameter(null, ((queryText.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText, queryText.Length);
  3015. sqlParam.Value = queryText;
  3016. return sqlParam;
  3017. }
  3018. /// <summary>
  3019. /// Constructs the sp_describe_parameter_encryption request with the values from the original RPC call.
  3020. /// Prototype for <sp_describe_parameter_encryption> is
  3021. /// exec sp_describe_parameter_encryption @tsql=N'[SQL Statement]', @params=N'@p1 varbinary(256)'
  3022. /// </summary>
  3023. /// <param name="originalRpcRequest">Original RPC request</param>
  3024. /// <param name="describeParameterEncryptionRequest">sp_describe_parameter_encryption request being built</param>
  3025. private void PrepareDescribeParameterEncryptionRequest(_SqlRPC originalRpcRequest, ref _SqlRPC describeParameterEncryptionRequest) {
  3026. Debug.Assert(originalRpcRequest != null);
  3027. // Construct the RPC request for sp_describe_parameter_encryption
  3028. // sp_describe_parameter_encryption always has 2 parameters (stmt, paramlist).
  3029. GetRPCObject(2, ref describeParameterEncryptionRequest, forSpDescribeParameterEncryption:true);
  3030. describeParameterEncryptionRequest.rpcName = "sp_describe_parameter_encryption";
  3031. // Prepare @tsql parameter
  3032. SqlParameter sqlParam;
  3033. string text;
  3034. // In BatchRPCMode, The actual T-SQL query is in the first parameter and not present as the rpcName, as is the case with non-BatchRPCMode.
  3035. if (BatchRPCMode) {
  3036. Debug.Assert(originalRpcRequest.parameters != null && originalRpcRequest.parameters.Length > 0,
  3037. "originalRpcRequest didn't have at-least 1 parameter in BatchRPCMode, in PrepareDescribeParameterEncryptionRequest.");
  3038. text = (string)originalRpcRequest.parameters[0].Value;
  3039. sqlParam = GetSqlParameterWithQueryText(text);
  3040. }
  3041. else {
  3042. text = originalRpcRequest.rpcName;
  3043. if (CommandType == Data.CommandType.StoredProcedure) {
  3044. // For stored procedures, we need to prepare @tsql in the following format
  3045. // N'EXEC sp_name @param1=@param1, @param1=@param2, ..., @paramN=@paramN'
  3046. sqlParam = BuildStoredProcedureStatementForColumnEncryption(text, originalRpcRequest.parameters);
  3047. }
  3048. else {
  3049. sqlParam = GetSqlParameterWithQueryText(text);
  3050. }
  3051. }
  3052. Debug.Assert(text != null, "@tsql parameter is null in PrepareDescribeParameterEncryptionRequest.");
  3053. describeParameterEncryptionRequest.parameters[0] = sqlParam;
  3054. string parameterList = null;
  3055. // In BatchRPCMode, the input parameters start at parameters[1]. parameters[0] is the T-SQL statement. rpcName is sp_executesql.
  3056. // And it is already in the format expected out of BuildParamList, which is not the case with Non-BatchRPCMode.
  3057. if (BatchRPCMode) {
  3058. if (originalRpcRequest.parameters.Length > 1) {
  3059. parameterList = (string)originalRpcRequest.parameters[1].Value;
  3060. }
  3061. }
  3062. else {
  3063. // Prepare @params parameter
  3064. // Need to create new parameters as we cannot have the same parameter being part of two SqlCommand objects
  3065. SqlParameter paramCopy;
  3066. SqlParameterCollection tempCollection = new SqlParameterCollection();
  3067. for (int i = 0; i < _parameters.Count; i++) {
  3068. SqlParameter param = originalRpcRequest.parameters[i];
  3069. paramCopy = new SqlParameter(param.ParameterName, param.SqlDbType, param.Size, param.Direction, param.Precision, param.Scale, param.SourceColumn, param.SourceVersion,
  3070. param.SourceColumnNullMapping, param.Value, param.XmlSchemaCollectionDatabase, param.XmlSchemaCollectionOwningSchema, param.XmlSchemaCollectionName);
  3071. tempCollection.Add(paramCopy);
  3072. }
  3073. Debug.Assert(_stateObj == null, "_stateObj should be null at this time, in PrepareDescribeParameterEncryptionRequest.");
  3074. Debug.Assert(_activeConnection != null, "_activeConnection should not be null at this time, in PrepareDescribeParameterEncryptionRequest.");
  3075. TdsParser tdsParser = null;
  3076. if (_activeConnection.Parser != null) {
  3077. tdsParser = _activeConnection.Parser;
  3078. if ((tdsParser == null) || (tdsParser.State == TdsParserState.Broken) || (tdsParser.State == TdsParserState.Closed)) {
  3079. // Connection's parser is null as well, therefore we must be closed
  3080. throw ADP.ClosedConnectionError();
  3081. }
  3082. }
  3083. parameterList = BuildParamList(tdsParser, tempCollection, includeReturnValue:true);
  3084. }
  3085. Debug.Assert(!string.IsNullOrWhiteSpace(parameterList), "parameterList should not be null or empty or whitespace.");
  3086. sqlParam = new SqlParameter(null, ((parameterList.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText, parameterList.Length);
  3087. sqlParam.Value = parameterList;
  3088. describeParameterEncryptionRequest.parameters[1] = sqlParam;
  3089. }
  3090. /// <summary>
  3091. /// Read the output of sp_describe_parameter_encryption
  3092. /// </summary>
  3093. /// <param name="ds">Resultset from calling to sp_describe_parameter_encryption</param>
  3094. /// <param name="describeParameterEncryptionRpcOriginalRpcMap"> Readonly dictionary with the map of parameter encryption rpc requests with the corresponding original rpc requests.</param>
  3095. private void ReadDescribeEncryptionParameterResults(SqlDataReader ds, ReadOnlyDictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcMap) {
  3096. _SqlRPC rpc = null;
  3097. int currentOrdinal = -1;
  3098. SqlTceCipherInfoEntry cipherInfoEntry;
  3099. Dictionary<int, SqlTceCipherInfoEntry> columnEncryptionKeyTable = new Dictionary<int, SqlTceCipherInfoEntry>();
  3100. Debug.Assert((describeParameterEncryptionRpcOriginalRpcMap != null) == BatchRPCMode,
  3101. "describeParameterEncryptionRpcOriginalRpcMap should be non-null if and only if it is BatchRPCMode.");
  3102. // Indicates the current result set we are reading, used in BatchRPCMode, where we can have more than 1 result set.
  3103. int resultSetSequenceNumber = 0;
  3104. #if DEBUG
  3105. // Keep track of the number of rows in the result sets.
  3106. int rowsAffected = 0;
  3107. #endif
  3108. // A flag that used in BatchRPCMode, to assert the result of lookup in to the dictionary maintaining the map of describe parameter encryption requests
  3109. // and the corresponding original rpc requests.
  3110. bool lookupDictionaryResult;
  3111. do {
  3112. if (BatchRPCMode) {
  3113. // If we got more RPC results from the server than what was requested.
  3114. if (resultSetSequenceNumber >= _sqlRPCParameterEncryptionReqArray.Length) {
  3115. Debug.Assert(false, "Server sent back more results than what was expected for describe parameter encryption requests in BatchRPCMode.");
  3116. // Ignore the rest of the results from the server, if for whatever reason it sends back more than what we expect.
  3117. break;
  3118. }
  3119. }
  3120. // First read the column encryption key list
  3121. while (ds.Read()) {
  3122. #if DEBUG
  3123. rowsAffected++;
  3124. #endif
  3125. // Column Encryption Key Ordinal.
  3126. currentOrdinal = ds.GetInt32((int)DescribeParameterEncryptionResultSet1.KeyOrdinal);
  3127. Debug.Assert(currentOrdinal >= 0, "currentOrdinal cannot be negative.");
  3128. // Try to see if there was already an entry for the current ordinal.
  3129. if (!columnEncryptionKeyTable.TryGetValue(currentOrdinal, out cipherInfoEntry)) {
  3130. // If an entry for this ordinal was not found, create an entry in the columnEncryptionKeyTable for this ordinal.
  3131. cipherInfoEntry = new SqlTceCipherInfoEntry(currentOrdinal);
  3132. columnEncryptionKeyTable.Add(currentOrdinal, cipherInfoEntry);
  3133. }
  3134. Debug.Assert(!cipherInfoEntry.Equals(default(SqlTceCipherInfoEntry)), "cipherInfoEntry should not be un-initialized.");
  3135. // Read the CEK.
  3136. byte[] encryptedKey = null;
  3137. int encryptedKeyLength = (int)ds.GetBytes((int)DescribeParameterEncryptionResultSet1.EncryptedKey, 0, encryptedKey, 0, 0);
  3138. encryptedKey = new byte[encryptedKeyLength];
  3139. ds.GetBytes((int)DescribeParameterEncryptionResultSet1.EncryptedKey, 0, encryptedKey, 0, encryptedKeyLength);
  3140. // Read the metadata version of the key.
  3141. // It should always be 8 bytes.
  3142. byte[] keyMdVersion = new byte[8];
  3143. ds.GetBytes((int)DescribeParameterEncryptionResultSet1.KeyMdVersion, 0, keyMdVersion, 0, keyMdVersion.Length);
  3144. // Validate the provider name
  3145. string providerName = ds.GetString((int)DescribeParameterEncryptionResultSet1.ProviderName);
  3146. //SqlColumnEncryptionKeyStoreProvider keyStoreProvider;
  3147. //if (!SqlConnection.TryGetColumnEncryptionKeyStoreProvider (providerName, out keyStoreProvider)) {
  3148. // // unknown provider, skip processing this cek.
  3149. // Bid.Trace("<sc.SqlCommand.ReadDescribeEncryptionParameterResults|INFO>Unknown provider name recevied %s, skipping\n", providerName);
  3150. // continue;
  3151. //}
  3152. cipherInfoEntry.Add(encryptedKey: encryptedKey,
  3153. databaseId: ds.GetInt32((int)DescribeParameterEncryptionResultSet1.DbId),
  3154. cekId: ds.GetInt32((int)DescribeParameterEncryptionResultSet1.KeyId),
  3155. cekVersion: ds.GetInt32((int)DescribeParameterEncryptionResultSet1.KeyVersion),
  3156. cekMdVersion: keyMdVersion,
  3157. keyPath: ds.GetString((int)DescribeParameterEncryptionResultSet1.KeyPath),
  3158. keyStoreName: providerName,
  3159. algorithmName: ds.GetString((int)DescribeParameterEncryptionResultSet1.KeyEncryptionAlgorithm));
  3160. }
  3161. if (!ds.NextResult()) {
  3162. throw SQL.UnexpectedDescribeParamFormat ();
  3163. }
  3164. // Find the RPC command that generated this tce request
  3165. if (BatchRPCMode) {
  3166. Debug.Assert(_sqlRPCParameterEncryptionReqArray[resultSetSequenceNumber] != null, "_sqlRPCParameterEncryptionReqArray[resultSetSequenceNumber] should not be null.");
  3167. // Lookup in the dictionary to get the original rpc request corresponding to the describe parameter encryption request
  3168. // pointed to by _sqlRPCParameterEncryptionReqArray[resultSetSequenceNumber]
  3169. rpc = null;
  3170. lookupDictionaryResult = describeParameterEncryptionRpcOriginalRpcMap.TryGetValue(_sqlRPCParameterEncryptionReqArray[resultSetSequenceNumber++], out rpc);
  3171. Debug.Assert(lookupDictionaryResult,
  3172. "Describe Parameter Encryption RPC request key must be present in the dictionary describeParameterEncryptionRpcOriginalRpcMap");
  3173. Debug.Assert(rpc != null,
  3174. "Describe Parameter Encryption RPC request's corresponding original rpc request must not be null in the dictionary describeParameterEncryptionRpcOriginalRpcMap");
  3175. }
  3176. else {
  3177. rpc = _rpcArrayOf1[0];
  3178. }
  3179. Debug.Assert(rpc != null, "rpc should not be null here.");
  3180. // This is the index in the parameters array where the actual parameters start.
  3181. // In BatchRPCMode, parameters[0] has the t-sql, parameters[1] has the param list
  3182. // and actual parameters of the query start at parameters[2].
  3183. int parameterStartIndex = (BatchRPCMode ? 2 : 0);
  3184. // Iterate over the parameter names to read the encryption type info
  3185. int paramIdx;
  3186. while (ds.Read()) {
  3187. #if DEBUG
  3188. rowsAffected++;
  3189. #endif
  3190. Debug.Assert(rpc != null, "Describe Parameter Encryption requested for non-tce spec proc");
  3191. string parameterName = ds.GetString((int)DescribeParameterEncryptionResultSet2.ParameterName);
  3192. // When the RPC object gets reused, the parameter array has more parameters that the valid params for the command.
  3193. // Null is used to indicate the end of the valid part of the array. Refer to GetRPCObject().
  3194. for (paramIdx = parameterStartIndex; paramIdx < rpc.parameters.Length && rpc.parameters[paramIdx] != null; paramIdx++) {
  3195. SqlParameter sqlParameter = rpc.parameters[paramIdx];
  3196. Debug.Assert(sqlParameter != null, "sqlParameter should not be null.");
  3197. if (sqlParameter.ParameterNameFixed.Equals(parameterName, StringComparison.Ordinal)) {
  3198. Debug.Assert(sqlParameter.CipherMetadata == null, "param.CipherMetadata should be null.");
  3199. sqlParameter.HasReceivedMetadata = true;
  3200. // Found the param, setup the encryption info.
  3201. byte columnEncryptionType = ds.GetByte((int)DescribeParameterEncryptionResultSet2.ColumnEncrytionType);
  3202. if ((byte)SqlClientEncryptionType.PlainText != columnEncryptionType) {
  3203. byte cipherAlgorithmId = ds.GetByte((int)DescribeParameterEncryptionResultSet2.ColumnEncryptionAlgorithm);
  3204. int columnEncryptionKeyOrdinal = ds.GetInt32((int)DescribeParameterEncryptionResultSet2.ColumnEncryptionKeyOrdinal);
  3205. byte columnNormalizationRuleVersion = ds.GetByte((int)DescribeParameterEncryptionResultSet2.NormalizationRuleVersion);
  3206. // Lookup the key, failing which throw an exception
  3207. if (!columnEncryptionKeyTable.TryGetValue(columnEncryptionKeyOrdinal, out cipherInfoEntry)) {
  3208. throw SQL.InvalidEncryptionKeyOrdinal(columnEncryptionKeyOrdinal, columnEncryptionKeyTable.Count);
  3209. }
  3210. sqlParameter.CipherMetadata = new SqlCipherMetadata(sqlTceCipherInfoEntry: cipherInfoEntry,
  3211. ordinal: unchecked((ushort)-1),
  3212. cipherAlgorithmId: cipherAlgorithmId,
  3213. cipherAlgorithmName: null,
  3214. encryptionType: columnEncryptionType,
  3215. normalizationRuleVersion: columnNormalizationRuleVersion);
  3216. // Decrypt the symmetric key.(This will also validate and throw if needed).
  3217. Debug.Assert(_activeConnection != null, @"_activeConnection should not be null");
  3218. SqlSecurityUtility.DecryptSymmetricKey(sqlParameter.CipherMetadata, this._activeConnection.DataSource);
  3219. // This is effective only for BatchRPCMode even though we set it for non-BatchRPCMode also,
  3220. // since for non-BatchRPCMode mode, paramoptions gets thrown away and reconstructed in BuildExecuteSql.
  3221. rpc.paramoptions[paramIdx] |= TdsEnums.RPC_PARAM_ENCRYPTED;
  3222. }
  3223. break;
  3224. }
  3225. }
  3226. }
  3227. // When the RPC object gets reused, the parameter array has more parameters that the valid params for the command.
  3228. // Null is used to indicate the end of the valid part of the array. Refer to GetRPCObject().
  3229. for (paramIdx = parameterStartIndex; paramIdx < rpc.parameters.Length && rpc.parameters[paramIdx] != null; paramIdx++) {
  3230. if (!rpc.parameters[paramIdx].HasReceivedMetadata && rpc.parameters[paramIdx].Direction != ParameterDirection.ReturnValue) {
  3231. // Encryption MD wasn't sent by the server - we expect the metadata to be sent for all the parameters
  3232. // that were sent in the original sp_describe_parameter_encryption but not necessarily for return values,
  3233. // since there might be multiple return values but server will only send for one of them.
  3234. // For parameters that don't need encryption, the encryption type is set to plaintext.
  3235. throw SQL.ParamEncryptionMetadataMissing(rpc.parameters[paramIdx].ParameterName, rpc.GetCommandTextOrRpcName());
  3236. }
  3237. }
  3238. #if DEBUG
  3239. Debug.Assert(rowsAffected == RowsAffectedByDescribeParameterEncryption,
  3240. "number of rows received for describe parameter encryption should be equal to rows affected by describe parameter encryption.");
  3241. #endif
  3242. // The server has responded with encryption related information for this rpc request. So clear the needsFetchParameterEncryptionMetadata flag.
  3243. rpc.needsFetchParameterEncryptionMetadata = false;
  3244. } while (ds.NextResult());
  3245. // Verify that we received response for each rpc call needs tce
  3246. if (BatchRPCMode) {
  3247. for (int i = 0; i < _SqlRPCBatchArray.Length; i++) {
  3248. if (_SqlRPCBatchArray[i].needsFetchParameterEncryptionMetadata) {
  3249. throw SQL.ProcEncryptionMetadataMissing(_SqlRPCBatchArray[i].rpcName);
  3250. }
  3251. }
  3252. }
  3253. }
  3254. internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method) {
  3255. Task unused; // sync execution
  3256. SqlDataReader reader = RunExecuteReader(cmdBehavior, runBehavior, returnStream, method, completion:null, timeout:CommandTimeout, task:out unused);
  3257. Debug.Assert(unused == null, "returned task during synchronous execution");
  3258. return reader;
  3259. }
  3260. // task is created in case of pending asynchronous write, returned SqlDataReader should not be utilized until that task is complete
  3261. internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method, TaskCompletionSource<object> completion, int timeout, out Task task, bool asyncWrite = false) {
  3262. bool async = (null != completion);
  3263. task = null;
  3264. _rowsAffected = -1;
  3265. _rowsAffectedBySpDescribeParameterEncryption = -1;
  3266. if (0 != (CommandBehavior.SingleRow & cmdBehavior)) {
  3267. // CommandBehavior.SingleRow implies CommandBehavior.SingleResult
  3268. cmdBehavior |= CommandBehavior.SingleResult;
  3269. }
  3270. // @devnote: this function may throw for an invalid connection
  3271. // @devnote: returns false for empty command text
  3272. ValidateCommand(method, async);
  3273. CheckNotificationStateAndAutoEnlist(); // Only call after validate - requires non null connection!
  3274. TdsParser bestEffortCleanupTarget = null;
  3275. // This section needs to occur AFTER ValidateCommand - otherwise it will AV without a connection.
  3276. RuntimeHelpers.PrepareConstrainedRegions();
  3277. try {
  3278. #if DEBUG
  3279. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  3280. RuntimeHelpers.PrepareConstrainedRegions();
  3281. try {
  3282. tdsReliabilitySection.Start();
  3283. #else
  3284. {
  3285. #endif //DEBUG
  3286. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  3287. SqlStatistics statistics = Statistics;
  3288. if (null != statistics) {
  3289. if ((!this.IsDirty && this.IsPrepared && !_hiddenPrepare)
  3290. || (this.IsPrepared && _execType == EXECTYPE.PREPAREPENDING))
  3291. {
  3292. statistics.SafeIncrement(ref statistics._preparedExecs);
  3293. }
  3294. else {
  3295. statistics.SafeIncrement(ref statistics._unpreparedExecs);
  3296. }
  3297. }
  3298. // Reset the encryption related state of the command and its parameters.
  3299. ResetEncryptionState();
  3300. if ( _activeConnection.IsContextConnection ) {
  3301. return RunExecuteReaderSmi( cmdBehavior, runBehavior, returnStream );
  3302. }
  3303. else if (IsColumnEncryptionEnabled) {
  3304. Task returnTask = null;
  3305. PrepareForTransparentEncryption(cmdBehavior, returnStream, async, timeout, completion, out returnTask, asyncWrite && async);
  3306. Debug.Assert(async == (returnTask != null), @"returnTask should be null if and only if async is false.");
  3307. return RunExecuteReaderTdsWithTransparentParameterEncryption( cmdBehavior, runBehavior, returnStream, async, timeout, out task, asyncWrite && async, ds: null,
  3308. describeParameterEncryptionRequest: false, describeParameterEncryptionTask: returnTask);
  3309. }
  3310. else {
  3311. return RunExecuteReaderTds( cmdBehavior, runBehavior, returnStream, async, timeout, out task, asyncWrite && async);
  3312. }
  3313. }
  3314. #if DEBUG
  3315. finally {
  3316. tdsReliabilitySection.Stop();
  3317. }
  3318. #endif //DEBUG
  3319. }
  3320. catch (System.OutOfMemoryException e) {
  3321. _activeConnection.Abort(e);
  3322. throw;
  3323. }
  3324. catch (System.StackOverflowException e) {
  3325. _activeConnection.Abort(e);
  3326. throw;
  3327. }
  3328. catch (System.Threading.ThreadAbortException e) {
  3329. _activeConnection.Abort(e);
  3330. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  3331. throw;
  3332. }
  3333. }
  3334. /// <summary>
  3335. /// RunExecuteReaderTds after Transparent Parameter Encryption is complete.
  3336. /// </summary>
  3337. /// <param name="cmdBehavior"></param>
  3338. /// <param name="runBehavior"></param>
  3339. /// <param name="returnStream"></param>
  3340. /// <param name="async"></param>
  3341. /// <param name="timeout"></param>
  3342. /// <param name="task"></param>
  3343. /// <param name="asyncWrite"></param>
  3344. /// <param name="ds"></param>
  3345. /// <param name="describeParameterEncryptionRequest"></param>
  3346. /// <param name="describeParameterEncryptionTask"></param>
  3347. /// <returns></returns>
  3348. private SqlDataReader RunExecuteReaderTdsWithTransparentParameterEncryption(CommandBehavior cmdBehavior,
  3349. RunBehavior runBehavior,
  3350. bool returnStream,
  3351. bool async,
  3352. int timeout,
  3353. out Task task,
  3354. bool asyncWrite,
  3355. SqlDataReader ds=null,
  3356. bool describeParameterEncryptionRequest = false,
  3357. Task describeParameterEncryptionTask = null) {
  3358. Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async");
  3359. Debug.Assert((describeParameterEncryptionTask != null) == async, @"async should be true if and only if describeParameterEncryptionTask is not null.");
  3360. if (ds == null && returnStream) {
  3361. ds = new SqlDataReader(this, cmdBehavior);
  3362. }
  3363. if (describeParameterEncryptionTask != null) {
  3364. long parameterEncryptionStart = ADP.TimerCurrent();
  3365. TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
  3366. AsyncHelper.ContinueTask(describeParameterEncryptionTask, completion,
  3367. () => {
  3368. Task subTask = null;
  3369. RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, parameterEncryptionStart), out subTask, asyncWrite, ds);
  3370. if (subTask == null) {
  3371. completion.SetResult(null);
  3372. }
  3373. else {
  3374. AsyncHelper.ContinueTask(subTask, completion, () => completion.SetResult(null));
  3375. }
  3376. }, connectionToDoom: null,
  3377. onFailure: ((exception) => {
  3378. if (_cachedAsyncState != null) {
  3379. _cachedAsyncState.ResetAsyncState();
  3380. }
  3381. if (exception != null) {
  3382. throw exception;
  3383. }}),
  3384. onCancellation: (() => {
  3385. if (_cachedAsyncState != null) {
  3386. _cachedAsyncState.ResetAsyncState();
  3387. }}),
  3388. connectionToAbort: _activeConnection);
  3389. task = completion.Task;
  3390. return ds;
  3391. }
  3392. else {
  3393. // Synchronous execution.
  3394. return RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, async, timeout, out task, asyncWrite, ds);
  3395. }
  3396. }
  3397. private SqlDataReader RunExecuteReaderTds( CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, bool async, int timeout, out Task task, bool asyncWrite, SqlDataReader ds=null, bool describeParameterEncryptionRequest = false) {
  3398. Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async");
  3399. if (ds == null && returnStream) {
  3400. ds = new SqlDataReader(this, cmdBehavior);
  3401. }
  3402. Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout);
  3403. if (reconnectTask != null) {
  3404. long reconnectionStart = ADP.TimerCurrent();
  3405. if (async) {
  3406. TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
  3407. _activeConnection.RegisterWaitingForReconnect(completion.Task);
  3408. _reconnectionCompletionSource = completion;
  3409. CancellationTokenSource timeoutCTS = new CancellationTokenSource();
  3410. AsyncHelper.SetTimeoutException(completion, timeout, SQL.CR_ReconnectTimeout, timeoutCTS.Token);
  3411. AsyncHelper.ContinueTask(reconnectTask, completion,
  3412. () => {
  3413. if (completion.Task.IsCompleted) {
  3414. return;
  3415. }
  3416. Interlocked.CompareExchange(ref _reconnectionCompletionSource, null, completion);
  3417. timeoutCTS.Cancel();
  3418. Task subTask;
  3419. RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart), out subTask, asyncWrite, ds);
  3420. if (subTask == null) {
  3421. completion.SetResult(null);
  3422. }
  3423. else {
  3424. AsyncHelper.ContinueTask(subTask, completion, () => completion.SetResult(null));
  3425. }
  3426. }, connectionToAbort: _activeConnection);
  3427. task = completion.Task;
  3428. return ds;
  3429. }
  3430. else {
  3431. AsyncHelper.WaitForCompletion(reconnectTask, timeout, () => { throw SQL.CR_ReconnectTimeout(); });
  3432. timeout = TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart);
  3433. }
  3434. }
  3435. // make sure we have good parameter information
  3436. // prepare the command
  3437. // execute
  3438. Debug.Assert(null != _activeConnection.Parser, "TdsParser class should not be null in Command.Execute!");
  3439. bool inSchema = (0 != (cmdBehavior & CommandBehavior.SchemaOnly));
  3440. // create a new RPC
  3441. _SqlRPC rpc=null;
  3442. task = null;
  3443. string optionSettings = null;
  3444. bool processFinallyBlock = true;
  3445. bool decrementAsyncCountOnFailure = false;
  3446. if (async) {
  3447. _activeConnection.GetOpenTdsConnection().IncrementAsyncCount();
  3448. decrementAsyncCountOnFailure = true;
  3449. }
  3450. try {
  3451. if (asyncWrite) {
  3452. _activeConnection.AddWeakReference(this, SqlReferenceCollection.CommandTag);
  3453. }
  3454. GetStateObject();
  3455. Task writeTask = null;
  3456. if (describeParameterEncryptionRequest) {
  3457. #if DEBUG
  3458. if (_sleepDuringRunExecuteReaderTdsForSpDescribeParameterEncryption) {
  3459. Thread.Sleep(10000);
  3460. }
  3461. #endif
  3462. Debug.Assert(_sqlRPCParameterEncryptionReqArray != null, "RunExecuteReader rpc array not provided for describe parameter encryption request.");
  3463. writeTask = _stateObj.Parser.TdsExecuteRPC(this, _sqlRPCParameterEncryptionReqArray, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite);
  3464. }
  3465. else if (BatchRPCMode) {
  3466. Debug.Assert(inSchema == false, "Batch RPC does not support schema only command beahvior");
  3467. Debug.Assert(!IsPrepared, "Batch RPC should not be prepared!");
  3468. Debug.Assert(!IsDirty, "Batch RPC should not be marked as dirty!");
  3469. //Currently returnStream is always false, but we may want to return a Reader later.
  3470. //if (returnStream) {
  3471. // Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as batch RPC.\n", ObjectID);
  3472. //}
  3473. Debug.Assert(_SqlRPCBatchArray != null, "RunExecuteReader rpc array not provided");
  3474. writeTask = _stateObj.Parser.TdsExecuteRPC(this, _SqlRPCBatchArray, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite );
  3475. }
  3476. else if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) {
  3477. // Send over SQL Batch command if we are not a stored proc and have no parameters
  3478. // MDAC
  3479. Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!");
  3480. if (returnStream) {
  3481. Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as SQLBATCH.\n", ObjectID);
  3482. }
  3483. string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior);
  3484. writeTask = _stateObj.Parser.TdsExecuteSQLBatch(text, timeout, this.Notification, _stateObj, sync: !asyncWrite);
  3485. }
  3486. else if (System.Data.CommandType.Text == this.CommandType) {
  3487. if (this.IsDirty) {
  3488. Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters
  3489. //
  3490. // someone changed the command text or the parameter schema so we must unprepare the command
  3491. //
  3492. // remeber that IsDirty includes test for IsPrepared!
  3493. if(_execType == EXECTYPE.PREPARED) {
  3494. _hiddenPrepare = true;
  3495. }
  3496. Unprepare();
  3497. IsDirty = false;
  3498. }
  3499. if (_execType == EXECTYPE.PREPARED) {
  3500. Debug.Assert(this.IsPrepared && (_prepareHandle != -1), "invalid attempt to call sp_execute without a handle!");
  3501. rpc = BuildExecute(inSchema);
  3502. }
  3503. else if (_execType == EXECTYPE.PREPAREPENDING) {
  3504. Debug.Assert(_activeConnection.IsShiloh, "Invalid attempt to call sp_prepexec on non 7.x server");
  3505. rpc = BuildPrepExec(cmdBehavior);
  3506. // next time through, only do an exec
  3507. _execType = EXECTYPE.PREPARED;
  3508. _preparedConnectionCloseCount = _activeConnection.CloseCount;
  3509. _preparedConnectionReconnectCount = _activeConnection.ReconnectCount;
  3510. // mark ourselves as preparing the command
  3511. _inPrepare = true;
  3512. }
  3513. else {
  3514. Debug.Assert(_execType == EXECTYPE.UNPREPARED, "Invalid execType!");
  3515. BuildExecuteSql(cmdBehavior, null, _parameters, ref rpc);
  3516. }
  3517. // if shiloh, then set NOMETADATA_UNLESSCHANGED flag
  3518. if (_activeConnection.IsShiloh)
  3519. rpc.options = TdsEnums.RPC_NOMETADATA;
  3520. if (returnStream) {
  3521. Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as RPC.\n", ObjectID);
  3522. }
  3523. //
  3524. Debug.Assert(_rpcArrayOf1[0] == rpc);
  3525. writeTask = _stateObj.Parser.TdsExecuteRPC(this, _rpcArrayOf1, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync:!asyncWrite);
  3526. }
  3527. else {
  3528. Debug.Assert(this.CommandType == System.Data.CommandType.StoredProcedure, "unknown command type!");
  3529. // note: invalid asserts on Shiloh. On 8.0 (Shiloh) and above a command is ALWAYS prepared
  3530. // and IsDirty is always set if there are changes and the command is marked Prepared!
  3531. Debug.Assert(IsShiloh || !IsPrepared, "RPC should not be prepared!");
  3532. Debug.Assert(IsShiloh || !IsDirty, "RPC should not be marked as dirty!");
  3533. BuildRPC(inSchema, _parameters, ref rpc);
  3534. // if we need to augment the command because a user has changed the command behavior (e.g. FillSchema)
  3535. // then batch sql them over. This is inefficient (3 round trips) but the only way we can get metadata only from
  3536. // a stored proc
  3537. optionSettings = GetSetOptionsString(cmdBehavior);
  3538. if (returnStream) {
  3539. Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as RPC.\n", ObjectID);
  3540. }
  3541. // turn set options ON
  3542. if (null != optionSettings) {
  3543. Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(optionSettings, timeout, this.Notification, _stateObj, sync: true);
  3544. Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
  3545. bool dataReady;
  3546. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  3547. bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady);
  3548. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  3549. // and turn OFF when the ds exhausts the stream on Close()
  3550. optionSettings = GetResetOptionsString(cmdBehavior);
  3551. }
  3552. // turn debugging on
  3553. _activeConnection.CheckSQLDebug();
  3554. // execute sp
  3555. Debug.Assert(_rpcArrayOf1[0] == rpc);
  3556. writeTask=_stateObj.Parser.TdsExecuteRPC(this, _rpcArrayOf1, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync:!asyncWrite);
  3557. }
  3558. Debug.Assert(writeTask == null || async, "Returned task in sync mode");
  3559. if (async) {
  3560. decrementAsyncCountOnFailure = false;
  3561. if (writeTask != null) {
  3562. task = AsyncHelper.CreateContinuationTask(writeTask, () => {
  3563. _activeConnection.GetOpenTdsConnection(); // it will throw if connection is closed
  3564. cachedAsyncState.SetAsyncReaderState(ds, runBehavior, optionSettings);
  3565. },
  3566. onFailure: (exc) => {
  3567. _activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
  3568. } );
  3569. }
  3570. else {
  3571. cachedAsyncState.SetAsyncReaderState(ds, runBehavior, optionSettings);
  3572. }
  3573. }
  3574. else {
  3575. // Always execute - even if no reader!
  3576. FinishExecuteReader(ds, runBehavior, optionSettings);
  3577. }
  3578. }
  3579. catch (Exception e) {
  3580. processFinallyBlock = ADP.IsCatchableExceptionType (e);
  3581. if (decrementAsyncCountOnFailure) {
  3582. SqlInternalConnectionTds innerConnectionTds = (_activeConnection.InnerConnection as SqlInternalConnectionTds);
  3583. if (null != innerConnectionTds) { // it may be closed
  3584. innerConnectionTds.DecrementAsyncCount();
  3585. }
  3586. }
  3587. throw;
  3588. }
  3589. finally {
  3590. TdsParser.ReliabilitySection.Assert("unreliable call to RunExecuteReaderTds"); // you need to setup for a thread abort somewhere before you call this method
  3591. if (processFinallyBlock && !async) {
  3592. // When executing async, we need to keep the _stateObj alive...
  3593. PutStateObject();
  3594. }
  3595. }
  3596. Debug.Assert(async || null == _stateObj, "non-null state object in RunExecuteReader");
  3597. return ds;
  3598. }
  3599. private SqlDataReader RunExecuteReaderSmi( CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream ) {
  3600. SqlInternalConnectionSmi innerConnection = InternalSmiConnection;
  3601. SmiEventStream eventStream = null;
  3602. SqlDataReader ds = null;
  3603. SmiRequestExecutor requestExecutor = null;
  3604. try {
  3605. // Set it up, process all of the events, and we're done!
  3606. requestExecutor = SetUpSmiRequest( innerConnection );
  3607. long transactionId;
  3608. SysTx.Transaction transaction;
  3609. innerConnection.GetCurrentTransactionPair(out transactionId, out transaction);
  3610. if (Bid.AdvancedOn) {
  3611. Bid.Trace("<sc.SqlCommand.RunExecuteReaderSmi|ADV> %d#, innerConnection=%d#, transactionId=0x%I64x, commandBehavior=%d.\n", ObjectID, innerConnection.ObjectID, transactionId, (int)cmdBehavior);
  3612. }
  3613. if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) {
  3614. eventStream = requestExecutor.Execute(
  3615. innerConnection.SmiConnection,
  3616. transactionId,
  3617. transaction,
  3618. cmdBehavior,
  3619. SmiExecuteType.Reader
  3620. );
  3621. }
  3622. else {
  3623. eventStream = requestExecutor.Execute(
  3624. innerConnection.SmiConnection,
  3625. transactionId,
  3626. cmdBehavior,
  3627. SmiExecuteType.Reader
  3628. );
  3629. }
  3630. if ( ( runBehavior & RunBehavior.UntilDone ) != 0 ) {
  3631. // Consume the results
  3632. while( eventStream.HasEvents ) {
  3633. eventStream.ProcessEvent( EventSink );
  3634. }
  3635. eventStream.Close( EventSink );
  3636. }
  3637. if ( returnStream ) {
  3638. ds = new SqlDataReaderSmi( eventStream, this, cmdBehavior, innerConnection, EventSink, requestExecutor );
  3639. ds.NextResult(); // Position on first set of results
  3640. _activeConnection.AddWeakReference(ds, SqlReferenceCollection.DataReaderTag);
  3641. }
  3642. EventSink.ProcessMessagesAndThrow();
  3643. }
  3644. catch (Exception e) {
  3645. // VSTS 159716 - we do not want to handle ThreadAbort, OutOfMemory or similar critical exceptions
  3646. // because the state of used objects might remain invalid in this case
  3647. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  3648. throw;
  3649. }
  3650. if (null != eventStream) {
  3651. eventStream.Close( EventSink ); // UNDONE: should cancel instead!
  3652. }
  3653. if (requestExecutor != null) {
  3654. requestExecutor.Close(EventSink);
  3655. EventSink.ProcessMessagesAndThrow(ignoreNonFatalMessages: true);
  3656. }
  3657. throw;
  3658. }
  3659. return ds;
  3660. }
  3661. private SqlDataReader CompleteAsyncExecuteReader() {
  3662. SqlDataReader ds = cachedAsyncState.CachedAsyncReader; // should not be null
  3663. bool processFinallyBlock = true;
  3664. try {
  3665. FinishExecuteReader(ds, cachedAsyncState.CachedRunBehavior, cachedAsyncState.CachedSetOptions);
  3666. }
  3667. catch (Exception e) {
  3668. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  3669. throw;
  3670. }
  3671. finally {
  3672. TdsParser.ReliabilitySection.Assert("unreliable call to CompleteAsyncExecuteReader"); // you need to setup for a thread abort somewhere before you call this method
  3673. if (processFinallyBlock) {
  3674. cachedAsyncState.ResetAsyncState();
  3675. PutStateObject();
  3676. }
  3677. }
  3678. return ds;
  3679. }
  3680. private void FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, string resetOptionsString) {
  3681. // always wrap with a try { FinishExecuteReader(...) } finally { PutStateObject(); }
  3682. NotifyDependency();
  3683. if (runBehavior == RunBehavior.UntilDone) {
  3684. try {
  3685. bool dataReady;
  3686. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  3687. bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, ds, null, _stateObj, out dataReady);
  3688. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  3689. }
  3690. catch (Exception e) {
  3691. //
  3692. if (ADP.IsCatchableExceptionType(e)) {
  3693. if (_inPrepare) {
  3694. // The flag is expected to be reset by OnReturnValue. We should receive
  3695. // the handle unless command execution failed. If fail, move back to pending
  3696. // state.
  3697. _inPrepare = false; // reset the flag
  3698. IsDirty = true; // mark command as dirty so it will be prepared next time we're comming through
  3699. _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending
  3700. }
  3701. if (null != ds) {
  3702. ds.Close();
  3703. }
  3704. }
  3705. throw;
  3706. }
  3707. }
  3708. // bind the parser to the reader if we get this far
  3709. if (ds != null) {
  3710. ds.Bind(_stateObj);
  3711. _stateObj = null; // the reader now owns this...
  3712. ds.ResetOptionsString = resetOptionsString;
  3713. //
  3714. // bind this reader to this connection now
  3715. _activeConnection.AddWeakReference(ds, SqlReferenceCollection.DataReaderTag);
  3716. // force this command to start reading data off the wire.
  3717. // this will cause an error to be reported at Execute() time instead of Read() time
  3718. // if the command is not set.
  3719. try {
  3720. _cachedMetaData = ds.MetaData;
  3721. ds.IsInitialized = true; // Webdata 104560
  3722. }
  3723. catch (Exception e) {
  3724. //
  3725. if (ADP.IsCatchableExceptionType(e)) {
  3726. if (_inPrepare) {
  3727. // The flag is expected to be reset by OnReturnValue. We should receive
  3728. // the handle unless command execution failed. If fail, move back to pending
  3729. // state.
  3730. _inPrepare = false; // reset the flag
  3731. IsDirty = true; // mark command as dirty so it will be prepared next time we're comming through
  3732. _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending
  3733. }
  3734. ds.Close();
  3735. }
  3736. throw;
  3737. }
  3738. }
  3739. }
  3740. private void NotifyDependency() {
  3741. if (_sqlDep != null) {
  3742. _sqlDep.StartTimer(Notification);
  3743. }
  3744. }
  3745. public SqlCommand Clone() {
  3746. SqlCommand clone = new SqlCommand(this);
  3747. Bid.Trace("<sc.SqlCommand.Clone|API> %d#, clone=%d#\n", ObjectID, clone.ObjectID);
  3748. return clone;
  3749. }
  3750. object ICloneable.Clone() {
  3751. return Clone();
  3752. }
  3753. private void RegisterForConnectionCloseNotification<T>(ref Task<T> outterTask) {
  3754. SqlConnection connection = _activeConnection;
  3755. if (connection == null) {
  3756. // No connection
  3757. throw ADP.ClosedConnectionError();
  3758. }
  3759. connection.RegisterForConnectionCloseNotification<T>(ref outterTask, this, SqlReferenceCollection.CommandTag);
  3760. }
  3761. // validates that a command has commandText and a non-busy open connection
  3762. // throws exception for error case, returns false if the commandText is empty
  3763. private void ValidateCommand(string method, bool async) {
  3764. if (null == _activeConnection) {
  3765. throw ADP.ConnectionRequired(method);
  3766. }
  3767. // Ensure that the connection is open and that the Parser is in the correct state
  3768. SqlInternalConnectionTds tdsConnection = _activeConnection.InnerConnection as SqlInternalConnectionTds;
  3769. // Ensure that if column encryption override was used then server supports its
  3770. if (((SqlCommandColumnEncryptionSetting.UseConnectionSetting == ColumnEncryptionSetting && _activeConnection.IsColumnEncryptionSettingEnabled)
  3771. || (ColumnEncryptionSetting == SqlCommandColumnEncryptionSetting.Enabled || ColumnEncryptionSetting == SqlCommandColumnEncryptionSetting.ResultSetOnly))
  3772. && null != tdsConnection
  3773. && null != tdsConnection.Parser
  3774. && !tdsConnection.Parser.IsColumnEncryptionSupported) {
  3775. throw SQL.TceNotSupported ();
  3776. }
  3777. if (tdsConnection != null) {
  3778. var parser = tdsConnection.Parser;
  3779. if ((parser == null) || (parser.State == TdsParserState.Closed)) {
  3780. throw ADP.OpenConnectionRequired(method, ConnectionState.Closed);
  3781. }
  3782. else if (parser.State != TdsParserState.OpenLoggedIn) {
  3783. throw ADP.OpenConnectionRequired(method, ConnectionState.Broken);
  3784. }
  3785. }
  3786. else if (_activeConnection.State == ConnectionState.Closed) {
  3787. throw ADP.OpenConnectionRequired(method, ConnectionState.Closed);
  3788. }
  3789. else if (_activeConnection.State == ConnectionState.Broken) {
  3790. throw ADP.OpenConnectionRequired(method, ConnectionState.Broken);
  3791. }
  3792. ValidateAsyncCommand();
  3793. TdsParser bestEffortCleanupTarget = null;
  3794. RuntimeHelpers.PrepareConstrainedRegions();
  3795. try {
  3796. #if DEBUG
  3797. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  3798. RuntimeHelpers.PrepareConstrainedRegions();
  3799. try {
  3800. tdsReliabilitySection.Start();
  3801. #else
  3802. {
  3803. #endif //DEBUG
  3804. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  3805. // close any non MARS dead readers, if applicable, and then throw if still busy.
  3806. // Throw if we have a live reader on this command
  3807. _activeConnection.ValidateConnectionForExecute(method, this);
  3808. }
  3809. #if DEBUG
  3810. finally {
  3811. tdsReliabilitySection.Stop();
  3812. }
  3813. #endif //DEBUG
  3814. }
  3815. catch (System.OutOfMemoryException e)
  3816. {
  3817. _activeConnection.Abort(e);
  3818. throw;
  3819. }
  3820. catch (System.StackOverflowException e)
  3821. {
  3822. _activeConnection.Abort(e);
  3823. throw;
  3824. }
  3825. catch (System.Threading.ThreadAbortException e)
  3826. {
  3827. _activeConnection.Abort(e);
  3828. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  3829. throw;
  3830. }
  3831. // Check to see if the currently set transaction has completed. If so,
  3832. // null out our local reference.
  3833. if (null != _transaction && _transaction.Connection == null)
  3834. _transaction = null;
  3835. // throw if the connection is in a transaction but there is no
  3836. // locally assigned transaction object
  3837. if (_activeConnection.HasLocalTransactionFromAPI && (null == _transaction))
  3838. throw ADP.TransactionRequired(method);
  3839. // if we have a transaction, check to ensure that the active
  3840. // connection property matches the connection associated with
  3841. // the transaction
  3842. if (null != _transaction && _activeConnection != _transaction.Connection)
  3843. throw ADP.TransactionConnectionMismatch();
  3844. if (ADP.IsEmpty(this.CommandText))
  3845. throw ADP.CommandTextRequired(method);
  3846. // Notification property must be null for pre-Yukon connections
  3847. if ((Notification != null) && !_activeConnection.IsYukonOrNewer) {
  3848. throw SQL.NotificationsRequireYukon();
  3849. }
  3850. if ((async) && (_activeConnection.IsContextConnection)) {
  3851. // Async not supported on Context Connections
  3852. throw SQL.NotAvailableOnContextConnection();
  3853. }
  3854. }
  3855. private void ValidateAsyncCommand() {
  3856. //
  3857. if (cachedAsyncState.PendingAsyncOperation) { // Enforce only one pending async execute at a time.
  3858. if (cachedAsyncState.IsActiveConnectionValid(_activeConnection)) {
  3859. throw SQL.PendingBeginXXXExists();
  3860. }
  3861. else {
  3862. _stateObj = null; // Session was re-claimed by session pool upon connection close.
  3863. cachedAsyncState.ResetAsyncState();
  3864. }
  3865. }
  3866. }
  3867. private void GetStateObject(TdsParser parser = null) {
  3868. Debug.Assert (null == _stateObj,"StateObject not null on GetStateObject");
  3869. Debug.Assert (null != _activeConnection, "no active connection?");
  3870. if (_pendingCancel) {
  3871. _pendingCancel = false; // Not really needed, but we'll reset anyways.
  3872. // If a pendingCancel exists on the object, we must have had a Cancel() call
  3873. // between the point that we entered an Execute* API and the point in Execute* that
  3874. // we proceeded to call this function and obtain a stateObject. In that case,
  3875. // we now throw a cancelled error.
  3876. throw SQL.OperationCancelled();
  3877. }
  3878. if (parser == null) {
  3879. parser = _activeConnection.Parser;
  3880. if ((parser == null) || (parser.State == TdsParserState.Broken) || (parser.State == TdsParserState.Closed)) {
  3881. // Connection's parser is null as well, therefore we must be closed
  3882. throw ADP.ClosedConnectionError();
  3883. }
  3884. }
  3885. TdsParserStateObject stateObj = parser.GetSession(this);
  3886. stateObj.StartSession(ObjectID);
  3887. _stateObj = stateObj;
  3888. if (_pendingCancel) {
  3889. _pendingCancel = false; // Not really needed, but we'll reset anyways.
  3890. // If a pendingCancel exists on the object, we must have had a Cancel() call
  3891. // between the point that we entered this function and the point where we obtained
  3892. // and actually assigned the stateObject to the local member. It is possible
  3893. // that the flag is set as well as a call to stateObj.Cancel - though that would
  3894. // be a no-op. So - throw.
  3895. throw SQL.OperationCancelled();
  3896. }
  3897. }
  3898. private void ReliablePutStateObject() {
  3899. TdsParser bestEffortCleanupTarget = null;
  3900. RuntimeHelpers.PrepareConstrainedRegions();
  3901. try {
  3902. #if DEBUG
  3903. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  3904. RuntimeHelpers.PrepareConstrainedRegions();
  3905. try {
  3906. tdsReliabilitySection.Start();
  3907. #else
  3908. {
  3909. #endif //DEBUG
  3910. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  3911. PutStateObject();
  3912. }
  3913. #if DEBUG
  3914. finally {
  3915. tdsReliabilitySection.Stop();
  3916. }
  3917. #endif //DEBUG
  3918. }
  3919. catch (System.OutOfMemoryException e)
  3920. {
  3921. _activeConnection.Abort(e);
  3922. throw;
  3923. }
  3924. catch (System.StackOverflowException e)
  3925. {
  3926. _activeConnection.Abort(e);
  3927. throw;
  3928. }
  3929. catch (System.Threading.ThreadAbortException e)
  3930. {
  3931. _activeConnection.Abort(e);
  3932. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  3933. throw;
  3934. }
  3935. }
  3936. private void PutStateObject() {
  3937. TdsParserStateObject stateObj = _stateObj;
  3938. _stateObj = null;
  3939. if (null != stateObj) {
  3940. stateObj.CloseSession();
  3941. }
  3942. }
  3943. /// <summary>
  3944. /// IMPORTANT NOTE: This is created as a copy of OnDoneProc below for Transparent Column Encryption improvement
  3945. /// as there is not much time, to address regressions. Will revisit removing the duplication, when we have time again.
  3946. /// </summary>
  3947. internal void OnDoneDescribeParameterEncryptionProc(TdsParserStateObject stateObj) {
  3948. // called per rpc batch complete
  3949. if (BatchRPCMode) {
  3950. // track the records affected for the just completed rpc batch
  3951. // _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches
  3952. _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC].cumulativeRecordsAffected = _rowsAffected;
  3953. _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC].recordsAffected =
  3954. (((0 < _currentlyExecutingDescribeParameterEncryptionRPC) && (0 <= _rowsAffected))
  3955. ? (_rowsAffected - Math.Max(_sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC - 1].cumulativeRecordsAffected, 0))
  3956. : _rowsAffected);
  3957. // track the error collection (not available from TdsParser after ExecuteNonQuery)
  3958. // and the which errors are associated with the just completed rpc batch
  3959. _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC].errorsIndexStart =
  3960. ((0 < _currentlyExecutingDescribeParameterEncryptionRPC)
  3961. ? _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC - 1].errorsIndexEnd
  3962. : 0);
  3963. _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC].errorsIndexEnd = stateObj.ErrorCount;
  3964. _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC].errors = stateObj._errors;
  3965. // track the warning collection (not available from TdsParser after ExecuteNonQuery)
  3966. // and the which warnings are associated with the just completed rpc batch
  3967. _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC].warningsIndexStart =
  3968. ((0 < _currentlyExecutingDescribeParameterEncryptionRPC)
  3969. ? _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC - 1].warningsIndexEnd
  3970. : 0);
  3971. _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC].warningsIndexEnd = stateObj.WarningCount;
  3972. _sqlRPCParameterEncryptionReqArray[_currentlyExecutingDescribeParameterEncryptionRPC].warnings = stateObj._warnings;
  3973. _currentlyExecutingDescribeParameterEncryptionRPC++;
  3974. }
  3975. }
  3976. /// <summary>
  3977. /// IMPORTANT NOTE: There is a copy of this function above in OnDoneDescribeParameterEncryptionProc.
  3978. /// Please consider the changes being done in this function for the above function as well.
  3979. /// </summary>
  3980. internal void OnDoneProc() { // called per rpc batch complete
  3981. if (BatchRPCMode) {
  3982. // track the records affected for the just completed rpc batch
  3983. // _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches
  3984. _SqlRPCBatchArray[_currentlyExecutingBatch].cumulativeRecordsAffected = _rowsAffected;
  3985. _SqlRPCBatchArray[_currentlyExecutingBatch].recordsAffected =
  3986. (((0 < _currentlyExecutingBatch) && (0 <= _rowsAffected))
  3987. ? (_rowsAffected - Math.Max(_SqlRPCBatchArray[_currentlyExecutingBatch-1].cumulativeRecordsAffected, 0))
  3988. : _rowsAffected);
  3989. // track the error collection (not available from TdsParser after ExecuteNonQuery)
  3990. // and the which errors are associated with the just completed rpc batch
  3991. _SqlRPCBatchArray[_currentlyExecutingBatch].errorsIndexStart =
  3992. ((0 < _currentlyExecutingBatch)
  3993. ? _SqlRPCBatchArray[_currentlyExecutingBatch-1].errorsIndexEnd
  3994. : 0);
  3995. _SqlRPCBatchArray[_currentlyExecutingBatch].errorsIndexEnd = _stateObj.ErrorCount;
  3996. _SqlRPCBatchArray[_currentlyExecutingBatch].errors = _stateObj._errors;
  3997. // track the warning collection (not available from TdsParser after ExecuteNonQuery)
  3998. // and the which warnings are associated with the just completed rpc batch
  3999. _SqlRPCBatchArray[_currentlyExecutingBatch].warningsIndexStart =
  4000. ((0 < _currentlyExecutingBatch)
  4001. ? _SqlRPCBatchArray[_currentlyExecutingBatch-1].warningsIndexEnd
  4002. : 0);
  4003. _SqlRPCBatchArray[_currentlyExecutingBatch].warningsIndexEnd = _stateObj.WarningCount;
  4004. _SqlRPCBatchArray[_currentlyExecutingBatch].warnings = _stateObj._warnings;
  4005. _currentlyExecutingBatch++;
  4006. Debug.Assert(_parameterCollectionList.Count >= _currentlyExecutingBatch, "OnDoneProc: Too many DONEPROC events");
  4007. }
  4008. }
  4009. //
  4010. //
  4011. internal void OnReturnStatus(int status) {
  4012. if (_inPrepare)
  4013. return;
  4014. // Don't set the return status if this is the status for sp_describe_parameter_encryption.
  4015. if (IsDescribeParameterEncryptionRPCCurrentlyInProgress)
  4016. return;
  4017. SqlParameterCollection parameters = _parameters;
  4018. if (BatchRPCMode) {
  4019. if (_parameterCollectionList.Count > _currentlyExecutingBatch) {
  4020. parameters = _parameterCollectionList[_currentlyExecutingBatch];
  4021. }
  4022. else {
  4023. Debug.Assert(false, "OnReturnStatus: SqlCommand got too many DONEPROC events");
  4024. parameters = null;
  4025. }
  4026. }
  4027. // see if a return value is bound
  4028. int count = GetParameterCount(parameters);
  4029. for (int i = 0; i < count; i++) {
  4030. SqlParameter parameter = parameters[i];
  4031. if (parameter.Direction == ParameterDirection.ReturnValue) {
  4032. object v = parameter.Value;
  4033. // if the user bound a sqlint32 (the only valid one for status, use it)
  4034. if ( (null != v) && (v.GetType() == typeof(SqlInt32)) ) {
  4035. parameter.Value = new SqlInt32(status); // value type
  4036. }
  4037. else {
  4038. parameter.Value = status;
  4039. }
  4040. break;
  4041. }
  4042. }
  4043. }
  4044. //
  4045. // Move the return value to the corresponding output parameter.
  4046. // Return parameters are sent in the order in which they were defined in the procedure.
  4047. // If named, match the parameter name, otherwise fill in based on ordinal position.
  4048. // If the parameter is not bound, then ignore the return value.
  4049. //
  4050. internal void OnReturnValue(SqlReturnValue rec, TdsParserStateObject stateObj) {
  4051. if (_inPrepare) {
  4052. if (!rec.value.IsNull) {
  4053. _prepareHandle = rec.value.Int32;
  4054. }
  4055. _inPrepare = false;
  4056. return;
  4057. }
  4058. SqlParameterCollection parameters = GetCurrentParameterCollection();
  4059. int count = GetParameterCount(parameters);
  4060. SqlParameter thisParam = GetParameterForOutputValueExtraction(parameters, rec.parameter, count);
  4061. if (null != thisParam) {
  4062. // If the parameter's direction is InputOutput, Output or ReturnValue and it needs to be transparently encrypted/decrypted
  4063. // then simply decrypt, deserialize and set the value.
  4064. if (rec.cipherMD != null &&
  4065. thisParam.CipherMetadata != null &&
  4066. (thisParam.Direction == ParameterDirection.Output ||
  4067. thisParam.Direction == ParameterDirection.InputOutput ||
  4068. thisParam.Direction == ParameterDirection.ReturnValue)) {
  4069. if(rec.tdsType != TdsEnums.SQLBIGVARBINARY) {
  4070. throw SQL.InvalidDataTypeForEncryptedParameter(thisParam.ParameterNameFixed, rec.tdsType, TdsEnums.SQLBIGVARBINARY);
  4071. }
  4072. // Decrypt the ciphertext
  4073. TdsParser parser = _activeConnection.Parser;
  4074. if ((parser == null) || (parser.State == TdsParserState.Closed) || (parser.State == TdsParserState.Broken)) {
  4075. throw ADP.ClosedConnectionError();
  4076. }
  4077. if (!rec.value.IsNull) {
  4078. try {
  4079. Debug.Assert(_activeConnection != null, @"_activeConnection should not be null");
  4080. // Get the key information from the parameter and decrypt the value.
  4081. rec.cipherMD.EncryptionInfo = thisParam.CipherMetadata.EncryptionInfo;
  4082. byte[] unencryptedBytes = SqlSecurityUtility.DecryptWithKey(rec.value.ByteArray, rec.cipherMD, _activeConnection.DataSource);
  4083. if (unencryptedBytes != null) {
  4084. // Denormalize the value and convert it to the parameter type.
  4085. SqlBuffer buffer = new SqlBuffer();
  4086. parser.DeserializeUnencryptedValue(buffer, unencryptedBytes, rec, stateObj, rec.NormalizationRuleVersion);
  4087. thisParam.SetSqlBuffer(buffer);
  4088. }
  4089. }
  4090. catch (Exception e) {
  4091. throw SQL.ParamDecryptionFailed(thisParam.ParameterNameFixed, null, e);
  4092. }
  4093. }
  4094. else {
  4095. // Create a new SqlBuffer and set it to null
  4096. // Note: We can't reuse the SqlBuffer in "rec" below since it's already been set (to varbinary)
  4097. // in previous call to TryProcessReturnValue().
  4098. // Note 2: We will be coming down this code path only if the Command Setting is set to use TCE.
  4099. // We pass the command setting as TCE enabled in the below call for this reason.
  4100. SqlBuffer buff = new SqlBuffer();
  4101. TdsParser.GetNullSqlValue(buff, rec, SqlCommandColumnEncryptionSetting.Enabled, parser.Connection);
  4102. thisParam.SetSqlBuffer(buff);
  4103. }
  4104. }
  4105. else {
  4106. // copy over data
  4107. // if the value user has supplied a SqlType class, then just copy over the SqlType, otherwise convert
  4108. // to the com type
  4109. object val = thisParam.Value;
  4110. //set the UDT value as typed object rather than bytes
  4111. if (SqlDbType.Udt == thisParam.SqlDbType) {
  4112. object data = null;
  4113. try {
  4114. Connection.CheckGetExtendedUDTInfo(rec, true);
  4115. //extract the byte array from the param value
  4116. if (rec.value.IsNull)
  4117. data = DBNull.Value;
  4118. else {
  4119. data = rec.value.ByteArray; //should work for both sql and non-sql values
  4120. }
  4121. //call the connection to instantiate the UDT object
  4122. thisParam.Value = Connection.GetUdtValue(data, rec, false);
  4123. }
  4124. catch (FileNotFoundException e) {
  4125. // SQL BU DT 329981
  4126. // Assign Assembly.Load failure in case where assembly not on client.
  4127. // This allows execution to complete and failure on SqlParameter.Value.
  4128. thisParam.SetUdtLoadError(e);
  4129. }
  4130. catch (FileLoadException e) {
  4131. // SQL BU DT 329981
  4132. // Assign Assembly.Load failure in case where assembly cannot be loaded on client.
  4133. // This allows execution to complete and failure on SqlParameter.Value.
  4134. thisParam.SetUdtLoadError(e);
  4135. }
  4136. return;
  4137. } else {
  4138. thisParam.SetSqlBuffer(rec.value);
  4139. }
  4140. MetaType mt = MetaType.GetMetaTypeFromSqlDbType(rec.type, rec.isMultiValued);
  4141. if (rec.type == SqlDbType.Decimal) {
  4142. thisParam.ScaleInternal = rec.scale;
  4143. thisParam.PrecisionInternal = rec.precision;
  4144. }
  4145. else if (mt.IsVarTime) {
  4146. thisParam.ScaleInternal = rec.scale;
  4147. }
  4148. else if (rec.type == SqlDbType.Xml) {
  4149. SqlCachedBuffer cachedBuffer = (thisParam.Value as SqlCachedBuffer);
  4150. if (null != cachedBuffer) {
  4151. thisParam.Value = cachedBuffer.ToString();
  4152. }
  4153. }
  4154. if (rec.collation != null) {
  4155. Debug.Assert(mt.IsCharType, "Invalid collation structure for non-char type");
  4156. thisParam.Collation = rec.collation;
  4157. }
  4158. }
  4159. }
  4160. return;
  4161. }
  4162. internal void OnParametersAvailableSmi( SmiParameterMetaData[] paramMetaData, ITypedGettersV3 parameterValues ) {
  4163. Debug.Assert(null != paramMetaData);
  4164. for(int index=0; index < paramMetaData.Length; index++) {
  4165. OnParameterAvailableSmi(paramMetaData[index], parameterValues, index);
  4166. }
  4167. }
  4168. internal void OnParameterAvailableSmi(SmiParameterMetaData metaData, ITypedGettersV3 parameterValues, int ordinal) {
  4169. if ( ParameterDirection.Input != metaData.Direction ) {
  4170. string name = null;
  4171. if (ParameterDirection.ReturnValue != metaData.Direction) {
  4172. name = metaData.Name;
  4173. }
  4174. SqlParameterCollection parameters = GetCurrentParameterCollection();
  4175. int count = GetParameterCount(parameters);
  4176. SqlParameter param = GetParameterForOutputValueExtraction(parameters, name, count);
  4177. if ( null != param ) {
  4178. param.LocaleId = (int)metaData.LocaleId;
  4179. param.CompareInfo = metaData.CompareOptions;
  4180. SqlBuffer buffer = new SqlBuffer();
  4181. object result;
  4182. if (_activeConnection.IsKatmaiOrNewer) {
  4183. result = ValueUtilsSmi.GetOutputParameterV200Smi(
  4184. OutParamEventSink, (SmiTypedGetterSetter)parameterValues, ordinal, metaData, _smiRequestContext, buffer );
  4185. }
  4186. else {
  4187. result = ValueUtilsSmi.GetOutputParameterV3Smi(
  4188. OutParamEventSink, parameterValues, ordinal, metaData, _smiRequestContext, buffer );
  4189. }
  4190. if ( null != result ) {
  4191. param.Value = result;
  4192. }
  4193. else {
  4194. param.SetSqlBuffer( buffer );
  4195. }
  4196. }
  4197. }
  4198. }
  4199. private SqlParameterCollection GetCurrentParameterCollection() {
  4200. if (BatchRPCMode) {
  4201. if (_parameterCollectionList.Count > _currentlyExecutingBatch) {
  4202. return _parameterCollectionList[_currentlyExecutingBatch];
  4203. }
  4204. else {
  4205. Debug.Assert(false, "OnReturnValue: SqlCommand got too many DONEPROC events");
  4206. return null;
  4207. }
  4208. }
  4209. else {
  4210. return _parameters;
  4211. }
  4212. }
  4213. private SqlParameter GetParameterForOutputValueExtraction( SqlParameterCollection parameters,
  4214. string paramName, int paramCount ) {
  4215. SqlParameter thisParam = null;
  4216. bool foundParam = false;
  4217. if (null == paramName) {
  4218. // rec.parameter should only be null for a return value from a function
  4219. for (int i = 0; i < paramCount; i++) {
  4220. thisParam = parameters[i];
  4221. // searching for ReturnValue
  4222. if (thisParam.Direction == ParameterDirection.ReturnValue) {
  4223. foundParam = true;
  4224. break; // found it
  4225. }
  4226. }
  4227. }
  4228. else {
  4229. for (int i = 0; i < paramCount; i++) {
  4230. thisParam = parameters[i];
  4231. // searching for Output or InputOutput or ReturnValue with matching name
  4232. if (thisParam.Direction != ParameterDirection.Input && thisParam.Direction != ParameterDirection.ReturnValue && paramName == thisParam.ParameterNameFixed) {
  4233. foundParam = true;
  4234. break; // found it
  4235. }
  4236. }
  4237. }
  4238. if (foundParam)
  4239. return thisParam;
  4240. else
  4241. return null;
  4242. }
  4243. private void GetRPCObject(int paramCount, ref _SqlRPC rpc, bool forSpDescribeParameterEncryption = false) {
  4244. // Designed to minimize necessary allocations
  4245. int ii;
  4246. if (rpc == null) {
  4247. if (!forSpDescribeParameterEncryption) {
  4248. if (_rpcArrayOf1 == null) {
  4249. _rpcArrayOf1 = new _SqlRPC[1];
  4250. _rpcArrayOf1[0] = new _SqlRPC();
  4251. }
  4252. rpc = _rpcArrayOf1[0];
  4253. }
  4254. else {
  4255. if (_rpcForEncryption == null) {
  4256. _rpcForEncryption = new _SqlRPC();
  4257. }
  4258. rpc = _rpcForEncryption;
  4259. }
  4260. }
  4261. rpc.ProcID = 0;
  4262. rpc.rpcName = null;
  4263. rpc.options = 0;
  4264. rpc.recordsAffected = default(int?);
  4265. rpc.cumulativeRecordsAffected = -1;
  4266. rpc.errorsIndexStart = 0;
  4267. rpc.errorsIndexEnd = 0;
  4268. rpc.errors = null;
  4269. rpc.warningsIndexStart = 0;
  4270. rpc.warningsIndexEnd = 0;
  4271. rpc.warnings = null;
  4272. rpc.needsFetchParameterEncryptionMetadata = false;
  4273. // Make sure there is enough space in the parameters and paramoptions arrays
  4274. if(rpc.parameters == null || rpc.parameters.Length < paramCount) {
  4275. rpc.parameters = new SqlParameter[paramCount];
  4276. }
  4277. else if (rpc.parameters.Length > paramCount) {
  4278. rpc.parameters[paramCount]=null; // Terminator
  4279. }
  4280. if(rpc.paramoptions == null || (rpc.paramoptions.Length < paramCount)) {
  4281. rpc.paramoptions = new byte[paramCount];
  4282. }
  4283. else {
  4284. for (ii = 0 ; ii < paramCount ; ii++)
  4285. rpc.paramoptions[ii] = 0;
  4286. }
  4287. }
  4288. private void SetUpRPCParameters (_SqlRPC rpc, int startCount, bool inSchema, SqlParameterCollection parameters) {
  4289. int ii;
  4290. int paramCount = GetParameterCount(parameters) ;
  4291. int j = startCount;
  4292. TdsParser parser = _activeConnection.Parser;
  4293. bool yukonOrNewer = parser.IsYukonOrNewer;
  4294. for (ii = 0; ii < paramCount; ii++) {
  4295. SqlParameter parameter = parameters[ii];
  4296. parameter.Validate(ii, CommandType.StoredProcedure == CommandType);
  4297. // func will change type to that with a 4 byte length if the type has a two
  4298. // byte length and a parameter length > than that expressable in 2 bytes
  4299. if ((!parameter.ValidateTypeLengths(yukonOrNewer).IsPlp) && (parameter.Direction != ParameterDirection.Output)) {
  4300. parameter.FixStreamDataForNonPLP();
  4301. }
  4302. if (ShouldSendParameter(parameter)) {
  4303. rpc.parameters[j] = parameter;
  4304. // set output bit
  4305. if (parameter.Direction == ParameterDirection.InputOutput ||
  4306. parameter.Direction == ParameterDirection.Output)
  4307. rpc.paramoptions[j] = TdsEnums.RPC_PARAM_BYREF;
  4308. // Set the encryped bit, if the parameter is to be encrypted.
  4309. if (parameter.CipherMetadata != null) {
  4310. rpc.paramoptions[j] |= TdsEnums.RPC_PARAM_ENCRYPTED;
  4311. }
  4312. // set default value bit
  4313. if (parameter.Direction != ParameterDirection.Output) {
  4314. // remember that null == Convert.IsEmpty, DBNull.Value is a database null!
  4315. // MDAC 62117, don't assume a default value exists for parameters in the case when
  4316. // the user is simply requesting schema
  4317. // SQLBUVSTS 179488 TVPs use DEFAULT and do not allow NULL, even for schema only.
  4318. if (null == parameter.Value && (!inSchema || SqlDbType.Structured == parameter.SqlDbType)) {
  4319. rpc.paramoptions[j] |= TdsEnums.RPC_PARAM_DEFAULT;
  4320. }
  4321. }
  4322. // Must set parameter option bit for LOB_COOKIE if unfilled LazyMat blob
  4323. j++;
  4324. }
  4325. }
  4326. }
  4327. //
  4328. // 7.5
  4329. // prototype for sp_prepexec is:
  4330. // sp_prepexec(@handle int IN/OUT, @batch_params ntext, @batch_text ntext, param1value,param2value...)
  4331. //
  4332. private _SqlRPC BuildPrepExec(CommandBehavior behavior) {
  4333. Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_prepexec for stored proc invocation!");
  4334. SqlParameter sqlParam;
  4335. int j = 3;
  4336. int count = CountSendableParameters(_parameters);
  4337. _SqlRPC rpc = null;
  4338. GetRPCObject(count + j, ref rpc);
  4339. rpc.ProcID = TdsEnums.RPC_PROCID_PREPEXEC;
  4340. rpc.rpcName = TdsEnums.SP_PREPEXEC;
  4341. //@handle
  4342. sqlParam = new SqlParameter(null, SqlDbType.Int);
  4343. sqlParam.Direction = ParameterDirection.InputOutput;
  4344. sqlParam.Value = _prepareHandle;
  4345. rpc.parameters[0] = sqlParam;
  4346. rpc.paramoptions[0] = TdsEnums.RPC_PARAM_BYREF;
  4347. //@batch_params
  4348. string paramList = BuildParamList(_stateObj.Parser, _parameters);
  4349. sqlParam = new SqlParameter(null, ((paramList.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, paramList.Length);
  4350. sqlParam.Value = paramList;
  4351. rpc.parameters[1] = sqlParam;
  4352. //@batch_text
  4353. string text = GetCommandText(behavior);
  4354. sqlParam = new SqlParameter(null, ((text.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, text.Length);
  4355. sqlParam.Value = text;
  4356. rpc.parameters[2] = sqlParam;
  4357. SetUpRPCParameters (rpc, j, false, _parameters);
  4358. return rpc;
  4359. }
  4360. //
  4361. // returns true if the parameter is not a return value
  4362. // and it's value is not DBNull (for a nullable parameter)
  4363. //
  4364. private static bool ShouldSendParameter(SqlParameter p, bool includeReturnValue = false) {
  4365. switch (p.Direction) {
  4366. case ParameterDirection.ReturnValue:
  4367. // return value parameters are not sent, except for the parameter list of sp_describe_parameter_encryption
  4368. return includeReturnValue;
  4369. case ParameterDirection.Output:
  4370. case ParameterDirection.InputOutput:
  4371. case ParameterDirection.Input:
  4372. // InputOutput/Output parameters are aways sent
  4373. return true;
  4374. default:
  4375. Debug.Assert(false, "Invalid ParameterDirection!");
  4376. return false;
  4377. }
  4378. }
  4379. private int CountSendableParameters(SqlParameterCollection parameters) {
  4380. int cParams = 0;
  4381. if (parameters != null) {
  4382. int count = parameters.Count;
  4383. for (int i = 0; i < count; i++) {
  4384. if (ShouldSendParameter(parameters[i]))
  4385. cParams++;
  4386. }
  4387. }
  4388. return cParams;
  4389. }
  4390. // Returns total number of parameters
  4391. private int GetParameterCount(SqlParameterCollection parameters) {
  4392. return ((null != parameters) ? parameters.Count : 0);
  4393. }
  4394. //
  4395. // build the RPC record header for this stored proc and add parameters
  4396. //
  4397. private void BuildRPC(bool inSchema, SqlParameterCollection parameters, ref _SqlRPC rpc) {
  4398. Debug.Assert(this.CommandType == System.Data.CommandType.StoredProcedure, "Command must be a stored proc to execute an RPC");
  4399. int count = CountSendableParameters(parameters);
  4400. GetRPCObject(count, ref rpc);
  4401. rpc.rpcName = this.CommandText; // just get the raw command text
  4402. SetUpRPCParameters ( rpc, 0, inSchema, parameters);
  4403. }
  4404. //
  4405. // build the RPC record header for sp_unprepare
  4406. //
  4407. // prototype for sp_unprepare is:
  4408. // sp_unprepare(@handle)
  4409. //
  4410. //
  4411. private _SqlRPC BuildUnprepare() {
  4412. Debug.Assert(_prepareHandle != 0, "Invalid call to sp_unprepare without a valid handle!");
  4413. _SqlRPC rpc = null;
  4414. GetRPCObject(1, ref rpc);
  4415. SqlParameter sqlParam;
  4416. rpc.ProcID = TdsEnums.RPC_PROCID_UNPREPARE;
  4417. rpc.rpcName = TdsEnums.SP_UNPREPARE;
  4418. //@handle
  4419. sqlParam = new SqlParameter(null, SqlDbType.Int);
  4420. sqlParam.Value = _prepareHandle;
  4421. rpc.parameters[0] = sqlParam;
  4422. return rpc;
  4423. }
  4424. //
  4425. // build the RPC record header for sp_execute
  4426. //
  4427. // prototype for sp_execute is:
  4428. // sp_execute(@handle int,param1value,param2value...)
  4429. //
  4430. private _SqlRPC BuildExecute(bool inSchema) {
  4431. Debug.Assert(_prepareHandle != -1, "Invalid call to sp_execute without a valid handle!");
  4432. int j = 1;
  4433. int count = CountSendableParameters(_parameters);
  4434. _SqlRPC rpc = null;
  4435. GetRPCObject(count + j, ref rpc);
  4436. SqlParameter sqlParam;
  4437. rpc.ProcID = TdsEnums.RPC_PROCID_EXECUTE;
  4438. rpc.rpcName = TdsEnums.SP_EXECUTE;
  4439. //@handle
  4440. sqlParam = new SqlParameter(null, SqlDbType.Int);
  4441. sqlParam.Value = _prepareHandle;
  4442. rpc.parameters[0] = sqlParam;
  4443. SetUpRPCParameters (rpc, j, inSchema, _parameters);
  4444. return rpc;
  4445. }
  4446. //
  4447. // build the RPC record header for sp_executesql and add the parameters
  4448. //
  4449. // prototype for sp_executesql is:
  4450. // sp_executesql(@batch_text nvarchar(4000),@batch_params nvarchar(4000), param1,.. paramN)
  4451. private void BuildExecuteSql(CommandBehavior behavior, string commandText, SqlParameterCollection parameters, ref _SqlRPC rpc) {
  4452. Debug.Assert(_prepareHandle == -1, "This command has an existing handle, use sp_execute!");
  4453. Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_executesql for stored proc invocation!");
  4454. int j;
  4455. SqlParameter sqlParam;
  4456. int cParams = CountSendableParameters(parameters);
  4457. if (cParams > 0) {
  4458. j = 2;
  4459. }
  4460. else {
  4461. j =1;
  4462. }
  4463. GetRPCObject(cParams + j, ref rpc);
  4464. rpc.ProcID = TdsEnums.RPC_PROCID_EXECUTESQL;
  4465. rpc.rpcName = TdsEnums.SP_EXECUTESQL;
  4466. // @sql
  4467. if (commandText == null) {
  4468. commandText = GetCommandText(behavior);
  4469. }
  4470. sqlParam = new SqlParameter(null, ((commandText.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, commandText.Length);
  4471. sqlParam.Value = commandText;
  4472. rpc.parameters[0] = sqlParam;
  4473. if (cParams > 0) {
  4474. string paramList = BuildParamList(_stateObj.Parser, BatchRPCMode ? parameters : _parameters);
  4475. sqlParam = new SqlParameter(null, ((paramList.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, paramList.Length);
  4476. sqlParam.Value = paramList;
  4477. rpc.parameters[1] = sqlParam;
  4478. bool inSchema = (0 != (behavior & CommandBehavior.SchemaOnly));
  4479. SetUpRPCParameters (rpc, j, inSchema, parameters);
  4480. }
  4481. }
  4482. /// <summary>
  4483. /// This function constructs a string parameter containing the exec statement in the following format
  4484. /// N'EXEC sp_name @param1=@param1, @param1=@param2, ..., @paramN=@paramN'
  4485. ///
  4486. private SqlParameter BuildStoredProcedureStatementForColumnEncryption(string storedProcedureName, SqlParameter[] parameters) {
  4487. Debug.Assert(CommandType == CommandType.StoredProcedure, "BuildStoredProcedureStatementForColumnEncryption() should only be called for stored procedures");
  4488. Debug.Assert(!string.IsNullOrWhiteSpace(storedProcedureName), "storedProcedureName cannot be null or empty in BuildStoredProcedureStatementForColumnEncryption");
  4489. Debug.Assert(parameters != null, "parameters cannot be null in BuildStoredProcedureStatementForColumnEncryption");
  4490. StringBuilder execStatement = new StringBuilder();
  4491. execStatement.Append(@"EXEC ");
  4492. // Find the return value parameter (if any).
  4493. SqlParameter returnValueParameter = null;
  4494. foreach (SqlParameter parameter in parameters) {
  4495. if (parameter.Direction == ParameterDirection.ReturnValue) {
  4496. returnValueParameter = parameter;
  4497. break;
  4498. }
  4499. }
  4500. // If there is a return value parameter we need to assign the result to it.
  4501. // EXEC @returnValue = moduleName [parameters]
  4502. if (returnValueParameter != null) {
  4503. execStatement.AppendFormat(@"{0}=", returnValueParameter.ParameterNameFixed);
  4504. }
  4505. execStatement.Append(ParseAndQuoteIdentifier(storedProcedureName, false));
  4506. // Build parameter list in the format
  4507. // @param1=@param1, @param1=@param2, ..., @paramn=@paramn
  4508. // Append the first parameter
  4509. int i = 0;
  4510. if(parameters.Count() > 0) {
  4511. // Skip the return value parameters.
  4512. while (i < parameters.Count() && parameters[i].Direction == ParameterDirection.ReturnValue) {
  4513. i++;
  4514. }
  4515. if (i < parameters.Count()) {
  4516. // Possibility of a SQL Injection issue through parameter names and how to construct valid identifier for parameters.
  4517. // Since the parameters comes from application itself, there should not be a security vulnerability.
  4518. // Also since the query is not executed, but only analyzed there is no possibility for elevation of priviledge, but only for
  4519. // incorrect results which would only affect the user that attempts the injection.
  4520. execStatement.AppendFormat(@" {0}={0}", parameters[i].ParameterNameFixed);
  4521. // InputOutput and Output parameters need to be marked as such.
  4522. if (parameters[i].Direction == ParameterDirection.Output ||
  4523. parameters[i].Direction == ParameterDirection.InputOutput) {
  4524. execStatement.AppendFormat(@" OUTPUT");
  4525. }
  4526. }
  4527. }
  4528. // Move to the next parameter.
  4529. i++;
  4530. // Append the rest of parameters
  4531. for (; i < parameters.Count(); i++) {
  4532. if (parameters[i].Direction != ParameterDirection.ReturnValue) {
  4533. execStatement.AppendFormat(@", {0}={0}", parameters[i].ParameterNameFixed);
  4534. // InputOutput and Output parameters need to be marked as such.
  4535. if (parameters[i].Direction == ParameterDirection.Output ||
  4536. parameters[i].Direction == ParameterDirection.InputOutput) {
  4537. execStatement.AppendFormat(@" OUTPUT");
  4538. }
  4539. }
  4540. }
  4541. // Construct @tsql SqlParameter to be returned
  4542. SqlParameter tsqlParameter = new SqlParameter(null, ((execStatement.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText, execStatement.Length);
  4543. tsqlParameter.Value = execStatement.ToString();
  4544. return tsqlParameter;
  4545. }
  4546. // paramList parameter for sp_executesql, sp_prepare, and sp_prepexec
  4547. internal string BuildParamList(TdsParser parser, SqlParameterCollection parameters, bool includeReturnValue = false) {
  4548. StringBuilder paramList = new StringBuilder();
  4549. bool fAddSeperator = false;
  4550. bool yukonOrNewer = parser.IsYukonOrNewer;
  4551. int count = 0;
  4552. count = parameters.Count;
  4553. for (int i = 0; i < count; i++) {
  4554. SqlParameter sqlParam = parameters[i];
  4555. sqlParam.Validate(i, CommandType.StoredProcedure == CommandType);
  4556. // skip ReturnValue parameters; we never send them to the server
  4557. if (!ShouldSendParameter(sqlParam, includeReturnValue))
  4558. continue;
  4559. // add our separator for the ith parmeter
  4560. if (fAddSeperator)
  4561. paramList.Append(',');
  4562. paramList.Append(sqlParam.ParameterNameFixed);
  4563. MetaType mt = sqlParam.InternalMetaType;
  4564. //for UDTs, get the actual type name. Get only the typename, omitt catalog and schema names.
  4565. //in TSQL you should only specify the unqualified type name
  4566. // paragraph above doesn't seem to be correct. Server won't find the type
  4567. // if we don't provide a fully qualified name
  4568. paramList.Append(" ");
  4569. if (mt.SqlDbType == SqlDbType.Udt) {
  4570. string fullTypeName = sqlParam.UdtTypeName;
  4571. if(ADP.IsEmpty(fullTypeName))
  4572. throw SQL.MustSetUdtTypeNameForUdtParams();
  4573. // DEVNOTE: do we need to escape the full type name?
  4574. paramList.Append(ParseAndQuoteIdentifier(fullTypeName, true /* is UdtTypeName */));
  4575. }
  4576. else if (mt.SqlDbType == SqlDbType.Structured) {
  4577. string typeName = sqlParam.TypeName;
  4578. if (ADP.IsEmpty(typeName)) {
  4579. throw SQL.MustSetTypeNameForParam(mt.TypeName, sqlParam.ParameterNameFixed);
  4580. }
  4581. paramList.Append(ParseAndQuoteIdentifier(typeName, false /* is not UdtTypeName*/));
  4582. // TVPs currently are the only Structured type and must be read only, so add that keyword
  4583. paramList.Append(" READONLY");
  4584. }
  4585. else {
  4586. // func will change type to that with a 4 byte length if the type has a two
  4587. // byte length and a parameter length > than that expressable in 2 bytes
  4588. mt = sqlParam.ValidateTypeLengths(yukonOrNewer);
  4589. if ((!mt.IsPlp) && (sqlParam.Direction != ParameterDirection.Output)) {
  4590. sqlParam.FixStreamDataForNonPLP();
  4591. }
  4592. paramList.Append(mt.TypeName);
  4593. }
  4594. fAddSeperator = true;
  4595. if (mt.SqlDbType == SqlDbType.Decimal) {
  4596. byte precision = sqlParam.GetActualPrecision();
  4597. byte scale = sqlParam.GetActualScale();
  4598. paramList.Append('(');
  4599. if (0 == precision) {
  4600. if (IsShiloh) {
  4601. precision = TdsEnums.DEFAULT_NUMERIC_PRECISION;
  4602. } else {
  4603. precision = TdsEnums.SPHINX_DEFAULT_NUMERIC_PRECISION;
  4604. }
  4605. }
  4606. paramList.Append(precision);
  4607. paramList.Append(',');
  4608. paramList.Append(scale);
  4609. paramList.Append(')');
  4610. }
  4611. else if (mt.IsVarTime) {
  4612. byte scale = sqlParam.GetActualScale();
  4613. paramList.Append('(');
  4614. paramList.Append(scale);
  4615. paramList.Append(')');
  4616. }
  4617. else if (false == mt.IsFixed && false == mt.IsLong && mt.SqlDbType != SqlDbType.Timestamp && mt.SqlDbType != SqlDbType.Udt && SqlDbType.Structured != mt.SqlDbType) {
  4618. int size = sqlParam.Size;
  4619. paramList.Append('(');
  4620. // if using non unicode types, obtain the actual byte length from the parser, with it's associated code page
  4621. if (mt.IsAnsiType) {
  4622. object val = sqlParam.GetCoercedValue();
  4623. string s = null;
  4624. // deal with the sql types
  4625. if ((null != val) && (DBNull.Value != val)) {
  4626. s = (val as string);
  4627. if (null == s) {
  4628. SqlString sval = val is SqlString ? (SqlString)val : SqlString.Null;
  4629. if (!sval.IsNull) {
  4630. s = sval.Value;
  4631. }
  4632. }
  4633. }
  4634. if (null != s) {
  4635. int actualBytes = parser.GetEncodingCharLength(s, sqlParam.GetActualSize(), sqlParam.Offset, null);
  4636. // if actual number of bytes is greater than the user given number of chars, use actual bytes
  4637. if (actualBytes > size)
  4638. size = actualBytes;
  4639. }
  4640. }
  4641. // bug 49497, if the user specifies a 0-sized parameter for a variable len field
  4642. // pass over max size (8000 bytes or 4000 characters for wide types)
  4643. if (0 == size)
  4644. size = mt.IsSizeInCharacters ? (TdsEnums.MAXSIZE >> 1) : TdsEnums.MAXSIZE;
  4645. paramList.Append(size);
  4646. paramList.Append(')');
  4647. }
  4648. else if (mt.IsPlp && (mt.SqlDbType != SqlDbType.Xml) && (mt.SqlDbType != SqlDbType.Udt)) {
  4649. paramList.Append("(max) ");
  4650. }
  4651. // set the output bit for Output or InputOutput parameters
  4652. if (sqlParam.Direction != ParameterDirection.Input)
  4653. paramList.Append(" " + TdsEnums.PARAM_OUTPUT);
  4654. }
  4655. return paramList.ToString();
  4656. }
  4657. // Adds quotes to each part of a SQL identifier that may be multi-part, while leaving
  4658. // the result as a single composite name.
  4659. private string ParseAndQuoteIdentifier(string identifier, bool isUdtTypeName) {
  4660. string[] strings = SqlParameter.ParseTypeName(identifier, isUdtTypeName);
  4661. StringBuilder bld = new StringBuilder();
  4662. // Stitching back together is a little tricky. Assume we want to build a full multi-part name
  4663. // with all parts except trimming separators for leading empty names (null or empty strings,
  4664. // but not whitespace). Separators in the middle should be added, even if the name part is
  4665. // null/empty, to maintain proper location of the parts.
  4666. for (int i = 0; i < strings.Length; i++ ) {
  4667. if (0 < bld.Length) {
  4668. bld.Append('.');
  4669. }
  4670. if (null != strings[i] && 0 != strings[i].Length) {
  4671. bld.Append(ADP.BuildQuotedString("[", "]", strings[i]));
  4672. }
  4673. }
  4674. return bld.ToString();
  4675. }
  4676. // returns set option text to turn on format only and key info on and off
  4677. // @devnote: When we are executing as a text command, then we never need
  4678. // to turn off the options since they command text is executed in the scope of sp_executesql.
  4679. // For a stored proc command, however, we must send over batch sql and then turn off
  4680. // the set options after we read the data. See the code in Command.Execute()
  4681. private string GetSetOptionsString(CommandBehavior behavior) {
  4682. string s = null;
  4683. if ((System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) ||
  4684. (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo))) {
  4685. // MDAC 56898 - SET FMTONLY ON will cause the server to ignore other SET OPTIONS, so turn
  4686. // it off before we ask for browse mode metadata
  4687. s = TdsEnums.FMTONLY_OFF;
  4688. if (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo)) {
  4689. s = s + TdsEnums.BROWSE_ON;
  4690. }
  4691. if (System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) {
  4692. s = s + TdsEnums.FMTONLY_ON;
  4693. }
  4694. }
  4695. return s;
  4696. }
  4697. private string GetResetOptionsString(CommandBehavior behavior) {
  4698. string s = null;
  4699. // SET FMTONLY ON OFF
  4700. if (System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) {
  4701. s = s + TdsEnums.FMTONLY_OFF;
  4702. }
  4703. // SET NO_BROWSETABLE OFF
  4704. if (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo)) {
  4705. s = s + TdsEnums.BROWSE_OFF;
  4706. }
  4707. return s;
  4708. }
  4709. private String GetCommandText(CommandBehavior behavior) {
  4710. // build the batch string we send over, since we execute within a stored proc (sp_executesql), the SET options never need to be
  4711. // turned off since they are scoped to the sproc
  4712. Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid call to GetCommandText for stored proc!");
  4713. return GetSetOptionsString(behavior) + this.CommandText;
  4714. }
  4715. //
  4716. // build the RPC record header for sp_executesql and add the parameters
  4717. //
  4718. // the prototype for sp_prepare is:
  4719. // sp_prepare(@handle int OUTPUT, @batch_params ntext, @batch_text ntext, @options int default 0x1)
  4720. private _SqlRPC BuildPrepare(CommandBehavior behavior) {
  4721. Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_prepare for stored proc invocation!");
  4722. _SqlRPC rpc = null;
  4723. GetRPCObject(3, ref rpc);
  4724. SqlParameter sqlParam;
  4725. rpc.ProcID = TdsEnums.RPC_PROCID_PREPARE;
  4726. rpc.rpcName = TdsEnums.SP_PREPARE;
  4727. //@handle
  4728. sqlParam = new SqlParameter(null, SqlDbType.Int);
  4729. sqlParam.Direction = ParameterDirection.Output;
  4730. rpc.parameters[0] = sqlParam;
  4731. rpc.paramoptions[0] = TdsEnums.RPC_PARAM_BYREF;
  4732. //@batch_params
  4733. string paramList = BuildParamList(_stateObj.Parser, _parameters);
  4734. sqlParam = new SqlParameter(null, ((paramList.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, paramList.Length);
  4735. sqlParam.Value = paramList;
  4736. rpc.parameters[1] = sqlParam;
  4737. //@batch_text
  4738. string text = GetCommandText(behavior);
  4739. sqlParam = new SqlParameter(null, ((text.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, text.Length);
  4740. sqlParam.Value = text;
  4741. rpc.parameters[2] = sqlParam;
  4742. /*
  4743. //@options
  4744. sqlParam = new SqlParameter(null, SqlDbType.Int);
  4745. rpc.Parameters[3] = sqlParam;
  4746. */
  4747. return rpc;
  4748. }
  4749. internal void CheckThrowSNIException() {
  4750. var stateObj = _stateObj;
  4751. if (stateObj != null) {
  4752. stateObj.CheckThrowSNIException();
  4753. }
  4754. }
  4755. // We're being notified that the underlying connection has closed
  4756. internal void OnConnectionClosed() {
  4757. var stateObj = _stateObj;
  4758. if (stateObj != null) {
  4759. stateObj.OnConnectionClosed();
  4760. }
  4761. }
  4762. internal TdsParserStateObject StateObject {
  4763. get {
  4764. return _stateObj;
  4765. }
  4766. }
  4767. private bool IsPrepared {
  4768. get { return(_execType != EXECTYPE.UNPREPARED);}
  4769. }
  4770. private bool IsUserPrepared {
  4771. get { return IsPrepared && !_hiddenPrepare && !IsDirty; }
  4772. }
  4773. internal bool IsDirty {
  4774. get {
  4775. // only dirty if prepared
  4776. var activeConnection = _activeConnection;
  4777. return (IsPrepared &&
  4778. (_dirty ||
  4779. ((_parameters != null) && (_parameters.IsDirty)) ||
  4780. ((activeConnection != null) && ((activeConnection.CloseCount != _preparedConnectionCloseCount) || (activeConnection.ReconnectCount != _preparedConnectionReconnectCount)))));
  4781. }
  4782. set {
  4783. // only mark the command as dirty if it is already prepared
  4784. // but always clear the value if it we are clearing the dirty flag
  4785. _dirty = value ? IsPrepared : false;
  4786. if (null != _parameters) {
  4787. _parameters.IsDirty = _dirty;
  4788. }
  4789. _cachedMetaData = null;
  4790. }
  4791. }
  4792. /// <summary>
  4793. /// Get or set the number of records affected by SpDescribeParameterEncryption.
  4794. /// The below line is used only for debug asserts and not exposed publicly or impacts functionality otherwise.
  4795. /// </summary>
  4796. internal int RowsAffectedByDescribeParameterEncryption
  4797. {
  4798. get {
  4799. return _rowsAffectedBySpDescribeParameterEncryption;
  4800. }
  4801. set {
  4802. if (-1 == _rowsAffectedBySpDescribeParameterEncryption) {
  4803. _rowsAffectedBySpDescribeParameterEncryption = value;
  4804. }
  4805. else if (0 < value) {
  4806. _rowsAffectedBySpDescribeParameterEncryption += value;
  4807. }
  4808. }
  4809. }
  4810. internal int InternalRecordsAffected {
  4811. get {
  4812. return _rowsAffected;
  4813. }
  4814. set {
  4815. if (-1 == _rowsAffected) {
  4816. _rowsAffected = value;
  4817. }
  4818. else if (0 < value) {
  4819. _rowsAffected += value;
  4820. }
  4821. }
  4822. }
  4823. internal bool BatchRPCMode {
  4824. get {
  4825. return _batchRPCMode;
  4826. }
  4827. set {
  4828. _batchRPCMode = value;
  4829. if (_batchRPCMode == false) {
  4830. ClearBatchCommand();
  4831. } else {
  4832. if (_RPCList == null) {
  4833. _RPCList = new List<_SqlRPC>();
  4834. }
  4835. if (_parameterCollectionList == null) {
  4836. _parameterCollectionList = new List<SqlParameterCollection>();
  4837. }
  4838. }
  4839. }
  4840. }
  4841. /// <summary>
  4842. /// Clear the state in sqlcommand related to describe parameter encryption RPC requests.
  4843. /// </summary>
  4844. private void ClearDescribeParameterEncryptionRequests() {
  4845. _sqlRPCParameterEncryptionReqArray = null;
  4846. _currentlyExecutingDescribeParameterEncryptionRPC = 0;
  4847. _isDescribeParameterEncryptionRPCCurrentlyInProgress = false;
  4848. _rowsAffectedBySpDescribeParameterEncryption = -1;
  4849. }
  4850. internal void ClearBatchCommand() {
  4851. List<_SqlRPC> rpcList = _RPCList;
  4852. if (null != rpcList) {
  4853. rpcList.Clear();
  4854. }
  4855. if (null != _parameterCollectionList) {
  4856. _parameterCollectionList.Clear();
  4857. }
  4858. _SqlRPCBatchArray = null;
  4859. _currentlyExecutingBatch = 0;
  4860. }
  4861. /// <summary>
  4862. /// Set the column encryption setting to the new one.
  4863. /// Do not allow conflicting column encryption settings.
  4864. /// </summary>
  4865. private void SetColumnEncryptionSetting(SqlCommandColumnEncryptionSetting newColumnEncryptionSetting) {
  4866. if (!this._wasBatchModeColumnEncryptionSettingSetOnce) {
  4867. this._columnEncryptionSetting = newColumnEncryptionSetting;
  4868. this._wasBatchModeColumnEncryptionSettingSetOnce = true;
  4869. }
  4870. else {
  4871. if (this._columnEncryptionSetting != newColumnEncryptionSetting) {
  4872. throw SQL.BatchedUpdateColumnEncryptionSettingMismatch();
  4873. }
  4874. }
  4875. }
  4876. internal void AddBatchCommand(string commandText, SqlParameterCollection parameters, CommandType cmdType, SqlCommandColumnEncryptionSetting columnEncryptionSetting) {
  4877. Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
  4878. Debug.Assert(_RPCList != null);
  4879. Debug.Assert(_parameterCollectionList != null);
  4880. _SqlRPC rpc = new _SqlRPC();
  4881. this.CommandText = commandText;
  4882. this.CommandType = cmdType;
  4883. // Set the column encryption setting.
  4884. SetColumnEncryptionSetting(columnEncryptionSetting);
  4885. GetStateObject();
  4886. if (cmdType == CommandType.StoredProcedure) {
  4887. BuildRPC(false, parameters, ref rpc);
  4888. }
  4889. else {
  4890. // All batch sql statements must be executed inside sp_executesql, including those without parameters
  4891. BuildExecuteSql(CommandBehavior.Default, commandText, parameters, ref rpc);
  4892. }
  4893. _RPCList.Add(rpc);
  4894. // Always add a parameters collection per RPC, even if there are no parameters.
  4895. _parameterCollectionList.Add(parameters);
  4896. ReliablePutStateObject();
  4897. }
  4898. internal int ExecuteBatchRPCCommand() {
  4899. Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
  4900. Debug.Assert(_RPCList != null, "No batch commands specified");
  4901. _SqlRPCBatchArray = _RPCList.ToArray();
  4902. _currentlyExecutingBatch = 0;
  4903. return ExecuteNonQuery(); // Check permissions, execute, return output params
  4904. }
  4905. internal int? GetRecordsAffected(int commandIndex) {
  4906. Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
  4907. Debug.Assert(_SqlRPCBatchArray != null, "batch command have been cleared");
  4908. return _SqlRPCBatchArray[commandIndex].recordsAffected;
  4909. }
  4910. internal SqlException GetErrors(int commandIndex) {
  4911. SqlException result = null;
  4912. int length = (_SqlRPCBatchArray[commandIndex].errorsIndexEnd - _SqlRPCBatchArray[commandIndex].errorsIndexStart);
  4913. if (0 < length) {
  4914. SqlErrorCollection errors = new SqlErrorCollection();
  4915. for(int i = _SqlRPCBatchArray[commandIndex].errorsIndexStart; i < _SqlRPCBatchArray[commandIndex].errorsIndexEnd; ++i) {
  4916. errors.Add(_SqlRPCBatchArray[commandIndex].errors[i]);
  4917. }
  4918. for(int i = _SqlRPCBatchArray[commandIndex].warningsIndexStart; i < _SqlRPCBatchArray[commandIndex].warningsIndexEnd; ++i) {
  4919. errors.Add(_SqlRPCBatchArray[commandIndex].warnings[i]);
  4920. }
  4921. result = SqlException.CreateException(errors, Connection.ServerVersion, Connection.ClientConnectionId);
  4922. }
  4923. return result;
  4924. }
  4925. // Allocates and initializes a new SmiRequestExecutor based on the current command state
  4926. private SmiRequestExecutor SetUpSmiRequest( SqlInternalConnectionSmi innerConnection ) {
  4927. // General Approach To Ensure Security of Marshalling:
  4928. // Only touch each item in the command once
  4929. // (i.e. only grab a reference to each param once, only
  4930. // read the type from that param once, etc.). The problem is
  4931. // that if the user changes something on the command in the
  4932. // middle of marshaling, it can overwrite the native buffers
  4933. // set up. For example, if max length is used to allocate
  4934. // buffers, but then re-read from the parameter to truncate
  4935. // strings, the user could extend the length and overwrite
  4936. // the buffer.
  4937. if (null != Notification){
  4938. throw SQL.NotificationsNotAvailableOnContextConnection();
  4939. }
  4940. SmiParameterMetaData[] requestMetaData = null;
  4941. ParameterPeekAheadValue[] peekAheadValues = null;
  4942. // Length of rgMetadata becomes *the* official count of parameters to use,
  4943. // don't rely on Parameters.Count after this point, as the user could change it.
  4944. int count = GetParameterCount( Parameters );
  4945. if ( 0 < count ) {
  4946. requestMetaData = new SmiParameterMetaData[count];
  4947. peekAheadValues = new ParameterPeekAheadValue[count];
  4948. // set up the metadata
  4949. for ( int index=0; index<count; index++ ) {
  4950. SqlParameter param = Parameters[index];
  4951. param.Validate(index, CommandType.StoredProcedure == CommandType);
  4952. requestMetaData[index] = param.MetaDataForSmi(out peekAheadValues[index]);
  4953. // Check for valid type for version negotiated
  4954. if (!innerConnection.IsKatmaiOrNewer) {
  4955. MetaType mt = MetaType.GetMetaTypeFromSqlDbType(requestMetaData[index].SqlDbType, requestMetaData[index].IsMultiValued);
  4956. if (!mt.Is90Supported) {
  4957. throw ADP.VersionDoesNotSupportDataType(mt.TypeName);
  4958. }
  4959. }
  4960. }
  4961. }
  4962. // Allocate the new request
  4963. CommandType cmdType = CommandType;
  4964. _smiRequestContext = innerConnection.InternalContext;
  4965. SmiRequestExecutor requestExecutor = _smiRequestContext.CreateRequestExecutor(
  4966. CommandText,
  4967. cmdType,
  4968. requestMetaData,
  4969. EventSink
  4970. );
  4971. // deal with errors
  4972. EventSink.ProcessMessagesAndThrow();
  4973. // Now assign param values
  4974. for ( int index=0; index<count; index++ ) {
  4975. if ( ParameterDirection.Output != requestMetaData[index].Direction &&
  4976. ParameterDirection.ReturnValue != requestMetaData[index].Direction ) {
  4977. SqlParameter param = Parameters[index];
  4978. // going back to command for parameter is ok, since we'll only pick up values now.
  4979. object value = param.GetCoercedValue();
  4980. if (value is XmlDataFeed && requestMetaData[index].SqlDbType != SqlDbType.Xml) {
  4981. value = MetaType.GetStringFromXml(((XmlDataFeed)value)._source);
  4982. }
  4983. ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(requestMetaData[index].SqlDbType, requestMetaData[index].IsMultiValued, value, null /* parameters don't use CLR Type for UDTs */, SmiContextFactory.Instance.NegotiatedSmiVersion);
  4984. // Handle null reference as special case for parameters
  4985. if ( CommandType.StoredProcedure == cmdType &&
  4986. ExtendedClrTypeCode.Empty == typeCode ) {
  4987. requestExecutor.SetDefault( index );
  4988. }
  4989. else {
  4990. // SQLBU 402391 & 403631: Exception to prevent Parameter.Size data corruption cases from working.
  4991. // This should be temporary until changing to correct behavior can be safely implemented.
  4992. // initial size criteria is the same for all affected types
  4993. // NOTE: assumes size < -1 is handled by SqlParameter.Size setter
  4994. int size = param.Size;
  4995. if (size != 0 && size != SmiMetaData.UnlimitedMaxLengthIndicator && !param.SizeInferred) {
  4996. switch(requestMetaData[index].SqlDbType) {
  4997. case SqlDbType.Image:
  4998. case SqlDbType.Text:
  4999. if (size != Int32.MaxValue) {
  5000. throw SQL.ParameterSizeRestrictionFailure(index);
  5001. }
  5002. break;
  5003. case SqlDbType.NText:
  5004. if (size != Int32.MaxValue/2) {
  5005. throw SQL.ParameterSizeRestrictionFailure(index);
  5006. }
  5007. break;
  5008. case SqlDbType.VarBinary:
  5009. case SqlDbType.VarChar:
  5010. // Allow size==Int32.MaxValue because of DeriveParameters
  5011. if (size > 0 && size != Int32.MaxValue && requestMetaData[index].MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator) {
  5012. throw SQL.ParameterSizeRestrictionFailure(index);
  5013. }
  5014. break;
  5015. case SqlDbType.NVarChar:
  5016. // Allow size==Int32.MaxValue/2 because of DeriveParameters
  5017. if (size > 0 && size != Int32.MaxValue/2 && requestMetaData[index].MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator) {
  5018. throw SQL.ParameterSizeRestrictionFailure(index);
  5019. }
  5020. break;
  5021. case SqlDbType.Timestamp:
  5022. // Size limiting for larger values will happen due to MaxLength
  5023. if (size < SmiMetaData.DefaultTimestamp.MaxLength) {
  5024. throw SQL.ParameterSizeRestrictionFailure(index);
  5025. }
  5026. break;
  5027. case SqlDbType.Variant:
  5028. // Variant problems happen when Size is less than maximums for character and binary values
  5029. // Size limiting for larger values will happen due to MaxLength
  5030. // NOTE: assumes xml and udt types are handled in parameter value coercion
  5031. // since server does not allow these types in a variant
  5032. if (null != value) {
  5033. MetaType mt = MetaType.GetMetaTypeFromValue(value);
  5034. if ((mt.IsNCharType && size < SmiMetaData.MaxUnicodeCharacters) ||
  5035. (mt.IsBinType && size < SmiMetaData.MaxBinaryLength) ||
  5036. (mt.IsAnsiType && size < SmiMetaData.MaxANSICharacters)) {
  5037. throw SQL.ParameterSizeRestrictionFailure(index);
  5038. }
  5039. }
  5040. break;
  5041. case SqlDbType.Xml:
  5042. // Xml is an issue for non-SqlXml types
  5043. if (null != value && ExtendedClrTypeCode.SqlXml != typeCode) {
  5044. throw SQL.ParameterSizeRestrictionFailure(index);
  5045. }
  5046. break;
  5047. // NOTE: Char, NChar, Binary and UDT do not need restricting because they are always 8k or less,
  5048. // so the metadata MaxLength will match the Size setting.
  5049. default:
  5050. break;
  5051. }
  5052. }
  5053. if (innerConnection.IsKatmaiOrNewer) {
  5054. ValueUtilsSmi.SetCompatibleValueV200(EventSink, requestExecutor, index, requestMetaData[index], value, typeCode, param.Offset, param.Size, peekAheadValues[index]);
  5055. }
  5056. else {
  5057. ValueUtilsSmi.SetCompatibleValue( EventSink, requestExecutor, index, requestMetaData[index], value, typeCode, param.Offset );
  5058. }
  5059. }
  5060. }
  5061. }
  5062. return requestExecutor;
  5063. }
  5064. private void WriteBeginExecuteEvent()
  5065. {
  5066. if (SqlEventSource.Log.IsEnabled() && Connection != null)
  5067. {
  5068. string commandText = CommandType == CommandType.StoredProcedure ? CommandText : string.Empty;
  5069. SqlEventSource.Log.BeginExecute(GetHashCode(), Connection.DataSource, Connection.Database, commandText);
  5070. }
  5071. }
  5072. /// <summary>
  5073. /// Writes and end execute event in Event Source.
  5074. /// </summary>
  5075. /// <param name="success">True if SQL command finished successfully, otherwise false.</param>
  5076. /// <param name="sqlExceptionNumber">Gets a number that identifies the type of error.</param>
  5077. /// <param name="synchronous">True if SQL command was executed synchronously, otherwise false.</param>
  5078. private void WriteEndExecuteEvent(bool success, int? sqlExceptionNumber, bool synchronous)
  5079. {
  5080. if (SqlEventSource.Log.IsEnabled())
  5081. {
  5082. // SqlEventSource.WriteEvent(int, int, int, int) is faster than provided overload SqlEventSource.WriteEvent(int, object[]).
  5083. // that's why trying to fit several booleans in one integer value
  5084. // success state is stored the first bit in compositeState 0x01
  5085. int successFlag = success ? 1 : 0;
  5086. // isSqlException is stored in the 2nd bit in compositeState 0x100
  5087. int isSqlExceptionFlag = sqlExceptionNumber.HasValue ? 2 : 0;
  5088. // synchronous state is stored in the second bit in compositeState 0x10
  5089. int synchronousFlag = synchronous ? 4 : 0;
  5090. int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag;
  5091. SqlEventSource.Log.EndExecute(GetHashCode(), compositeState, sqlExceptionNumber.GetValueOrDefault());
  5092. }
  5093. }
  5094. #if DEBUG
  5095. internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) {
  5096. var stateObj = _stateObj;
  5097. if (stateObj != null) {
  5098. stateObj.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
  5099. }
  5100. else {
  5101. var tempCachedAsyncState = cachedAsyncState;
  5102. if (tempCachedAsyncState != null) {
  5103. var reader = tempCachedAsyncState.CachedAsyncReader;
  5104. if (reader != null) {
  5105. reader.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
  5106. }
  5107. }
  5108. }
  5109. }
  5110. internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) {
  5111. var stateObj = _stateObj;
  5112. if (stateObj != null) {
  5113. stateObj.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
  5114. }
  5115. else {
  5116. var tempCachedAsyncState = _cachedAsyncState;
  5117. if (tempCachedAsyncState != null) {
  5118. var reader = tempCachedAsyncState.CachedAsyncReader;
  5119. if (reader != null) {
  5120. reader.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
  5121. }
  5122. }
  5123. }
  5124. }
  5125. #endif
  5126. }
  5127. }