SqlCommand.cs 204 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576
  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.ComponentModel;
  13. using System.Configuration.Assemblies;
  14. using System.Data;
  15. using System.Data.Common;
  16. using System.Data.ProviderBase;
  17. using System.Data.Sql;
  18. using System.Data.SqlTypes;
  19. using System.Diagnostics;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Reflection;
  23. using System.Runtime.CompilerServices;
  24. using System.Runtime.ConstrainedExecution;
  25. using System.Runtime.Serialization.Formatters;
  26. using System.Security.Permissions;
  27. using System.Text;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. using SysTx = System.Transactions;
  31. using System.Xml;
  32. using Microsoft.SqlServer.Server;
  33. [
  34. DefaultEvent("RecordsAffected"),
  35. ToolboxItem(true),
  36. Designer("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, " + AssemblyRef.MicrosoftVSDesigner)
  37. ]
  38. public sealed class SqlCommand : DbCommand, ICloneable {
  39. private static int _objectTypeCount; // Bid counter
  40. internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
  41. private string _commandText;
  42. private CommandType _commandType;
  43. private int _commandTimeout = ADP.DefaultCommandTimeout;
  44. private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
  45. private bool _designTimeInvisible;
  46. internal SqlDependency _sqlDep;
  47. // devnote: Prepare
  48. // Against 7.0 Server (Sphinx) a prepare/unprepare requires an extra roundtrip to the server.
  49. //
  50. // From 8.0 (Shiloh) and above (Yukon) the preparation can be done as part of the command execution.
  51. //
  52. private enum EXECTYPE {
  53. UNPREPARED, // execute unprepared commands, all server versions (results in sp_execsql call)
  54. PREPAREPENDING, // prepare and execute command, 8.0 and above only (results in sp_prepexec call)
  55. PREPARED, // execute prepared commands, all server versions (results in sp_exec call)
  56. }
  57. // devnotes
  58. //
  59. // _hiddenPrepare
  60. // On 8.0 and above the Prepared state cannot be left. Once a command is prepared it will always be prepared.
  61. // A change in parameters, commandtext etc (IsDirty) automatically causes a hidden prepare
  62. //
  63. // _inPrepare will be set immediately before the actual prepare is done.
  64. // The OnReturnValue function will test this flag to determine whether the returned value is a _prepareHandle or something else.
  65. //
  66. // _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.
  67. private bool _inPrepare = false;
  68. private int _prepareHandle = -1;
  69. private bool _hiddenPrepare = false;
  70. private int _preparedConnectionCloseCount = -1;
  71. private int _preparedConnectionReconnectCount = -1;
  72. private SqlParameterCollection _parameters;
  73. private SqlConnection _activeConnection;
  74. private bool _dirty = false; // true if the user changes the commandtext or number of parameters after the command is already prepared
  75. private EXECTYPE _execType = EXECTYPE.UNPREPARED; // by default, assume the user is not sharing a connection so the command has not been prepared
  76. private _SqlRPC[] _rpcArrayOf1 = null; // Used for RPC executes
  77. // cut down on object creation and cache all these
  78. // cached metadata
  79. private _SqlMetaDataSet _cachedMetaData;
  80. // Last TaskCompletionSource for reconnect task - use for cancellation only
  81. TaskCompletionSource<object> _reconnectionCompletionSource = null;
  82. #if DEBUG
  83. static internal int DebugForceAsyncWriteDelay { get; set; }
  84. #endif
  85. internal bool InPrepare {
  86. get {
  87. return _inPrepare;
  88. }
  89. }
  90. // Cached info for async executions
  91. private class CachedAsyncState {
  92. 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
  93. private TaskCompletionSource<object> _cachedAsyncResult = null;
  94. private SqlConnection _cachedAsyncConnection = null; // Used to validate that the connection hasn't changed when end the connection;
  95. private SqlDataReader _cachedAsyncReader = null;
  96. private RunBehavior _cachedRunBehavior = RunBehavior.ReturnImmediately;
  97. private string _cachedSetOptions = null;
  98. private string _cachedEndMethod = null;
  99. internal CachedAsyncState () {
  100. }
  101. internal SqlDataReader CachedAsyncReader {
  102. get {return _cachedAsyncReader;}
  103. }
  104. internal RunBehavior CachedRunBehavior {
  105. get {return _cachedRunBehavior;}
  106. }
  107. internal string CachedSetOptions {
  108. get {return _cachedSetOptions;}
  109. }
  110. internal bool PendingAsyncOperation {
  111. get {return (null != _cachedAsyncResult);}
  112. }
  113. internal string EndMethodName {
  114. get { return _cachedEndMethod; }
  115. }
  116. internal bool IsActiveConnectionValid(SqlConnection activeConnection) {
  117. return (_cachedAsyncConnection == activeConnection && _cachedAsyncCloseCount == activeConnection.CloseCount);
  118. }
  119. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  120. internal void ResetAsyncState() {
  121. _cachedAsyncCloseCount = -1;
  122. _cachedAsyncResult = null;
  123. if (_cachedAsyncConnection != null) {
  124. _cachedAsyncConnection.AsyncCommandInProgress = false;
  125. _cachedAsyncConnection = null;
  126. }
  127. _cachedAsyncReader = null;
  128. _cachedRunBehavior = RunBehavior.ReturnImmediately;
  129. _cachedSetOptions = null;
  130. _cachedEndMethod = null;
  131. }
  132. internal void SetActiveConnectionAndResult(TaskCompletionSource<object> completion, string endMethod, SqlConnection activeConnection) {
  133. Debug.Assert(activeConnection != null, "Unexpected null connection argument on SetActiveConnectionAndResult!");
  134. TdsParser parser = activeConnection.Parser;
  135. if ((parser == null) || (parser.State == TdsParserState.Closed) || (parser.State == TdsParserState.Broken)) {
  136. throw ADP.ClosedConnectionError();
  137. }
  138. _cachedAsyncCloseCount = activeConnection.CloseCount;
  139. _cachedAsyncResult = completion;
  140. if (null != activeConnection && !parser.MARSOn) {
  141. if (activeConnection.AsyncCommandInProgress)
  142. throw SQL.MARSUnspportedOnConnection();
  143. }
  144. _cachedAsyncConnection = activeConnection;
  145. // Should only be needed for non-MARS, but set anyways.
  146. _cachedAsyncConnection.AsyncCommandInProgress = true;
  147. _cachedEndMethod = endMethod;
  148. }
  149. internal void SetAsyncReaderState (SqlDataReader ds, RunBehavior runBehavior, string optionSettings) {
  150. _cachedAsyncReader = ds;
  151. _cachedRunBehavior = runBehavior;
  152. _cachedSetOptions = optionSettings;
  153. }
  154. }
  155. CachedAsyncState _cachedAsyncState = null;
  156. private CachedAsyncState cachedAsyncState {
  157. get {
  158. if (_cachedAsyncState == null) {
  159. _cachedAsyncState = new CachedAsyncState ();
  160. }
  161. return _cachedAsyncState;
  162. }
  163. }
  164. // sql reader will pull this value out for each NextResult call. It is not cumulative
  165. // _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches
  166. internal int _rowsAffected = -1; // rows affected by the command
  167. private SqlNotificationRequest _notification;
  168. private bool _notificationAutoEnlist = true; // Notifications auto enlistment is turned on by default
  169. // transaction support
  170. private SqlTransaction _transaction;
  171. private StatementCompletedEventHandler _statementCompletedEventHandler;
  172. private TdsParserStateObject _stateObj; // this is the TDS session we're using.
  173. // Volatile bool used to synchronize with cancel thread the state change of an executing
  174. // command going from pre-processing to obtaining a stateObject. The cancel synchronization
  175. // we require in the command is only from entering an Execute* API to obtaining a
  176. // stateObj. Once a stateObj is successfully obtained, cancel synchronization is handled
  177. // by the stateObject.
  178. private volatile bool _pendingCancel;
  179. private bool _batchRPCMode;
  180. private List<_SqlRPC> _RPCList;
  181. private _SqlRPC[] _SqlRPCBatchArray;
  182. private List<SqlParameterCollection> _parameterCollectionList;
  183. private int _currentlyExecutingBatch;
  184. //
  185. // Smi execution-specific stuff
  186. //
  187. sealed private class CommandEventSink : SmiEventSink_Default {
  188. private SqlCommand _command;
  189. internal CommandEventSink( SqlCommand command ) : base( ) {
  190. _command = command;
  191. }
  192. internal override void StatementCompleted( int rowsAffected ) {
  193. if (Bid.AdvancedOn) {
  194. Bid.Trace("<sc.SqlCommand.CommandEventSink.StatementCompleted|ADV> %d#, rowsAffected=%d.\n", _command.ObjectID, rowsAffected);
  195. }
  196. _command.InternalRecordsAffected = rowsAffected;
  197. //
  198. }
  199. internal override void BatchCompleted() {
  200. if (Bid.AdvancedOn) {
  201. Bid.Trace("<sc.SqlCommand.CommandEventSink.BatchCompleted|ADV> %d#.\n", _command.ObjectID);
  202. }
  203. }
  204. internal override void ParametersAvailable( SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues ) {
  205. if (Bid.AdvancedOn) {
  206. Bid.Trace("<sc.SqlCommand.CommandEventSink.ParametersAvailable|ADV> %d# metaData.Length=%d.\n", _command.ObjectID, (null!=metaData)?metaData.Length:-1);
  207. if (null != metaData) {
  208. for (int i=0; i < metaData.Length; i++) {
  209. Bid.Trace("<sc.SqlCommand.CommandEventSink.ParametersAvailable|ADV> %d#, metaData[%d] is %ls%ls\n",
  210. _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString());
  211. }
  212. }
  213. }
  214. Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.YukonVersion);
  215. _command.OnParametersAvailableSmi( metaData, parameterValues );
  216. }
  217. internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal)
  218. {
  219. if (Bid.AdvancedOn) {
  220. if (null != metaData) {
  221. Bid.Trace("<sc.SqlCommand.CommandEventSink.ParameterAvailable|ADV> %d#, metaData[%d] is %ls%ls\n",
  222. _command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString());
  223. }
  224. }
  225. Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion);
  226. _command.OnParameterAvailableSmi(metaData, parameterValues, ordinal);
  227. }
  228. }
  229. private SmiContext _smiRequestContext; // context that _smiRequest came from
  230. private CommandEventSink _smiEventSink;
  231. private SmiEventSink_DeferedProcessing _outParamEventSink;
  232. private CommandEventSink EventSink {
  233. get {
  234. if ( null == _smiEventSink ) {
  235. _smiEventSink = new CommandEventSink( this );
  236. }
  237. _smiEventSink.Parent = InternalSmiConnection.CurrentEventSink;
  238. return _smiEventSink;
  239. }
  240. }
  241. private SmiEventSink_DeferedProcessing OutParamEventSink {
  242. get {
  243. if (null == _outParamEventSink) {
  244. _outParamEventSink = new SmiEventSink_DeferedProcessing(EventSink);
  245. }
  246. else {
  247. _outParamEventSink.Parent = EventSink;
  248. }
  249. return _outParamEventSink;
  250. }
  251. }
  252. public SqlCommand() : base() {
  253. GC.SuppressFinalize(this);
  254. }
  255. public SqlCommand(string cmdText) : this() {
  256. CommandText = cmdText;
  257. }
  258. public SqlCommand(string cmdText, SqlConnection connection) : this() {
  259. CommandText = cmdText;
  260. Connection = connection;
  261. }
  262. public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction) : this() {
  263. CommandText = cmdText;
  264. Connection = connection;
  265. Transaction = transaction;
  266. }
  267. private SqlCommand(SqlCommand from) : this() { // Clone
  268. CommandText = from.CommandText;
  269. CommandTimeout = from.CommandTimeout;
  270. CommandType = from.CommandType;
  271. Connection = from.Connection;
  272. DesignTimeVisible = from.DesignTimeVisible;
  273. Transaction = from.Transaction;
  274. UpdatedRowSource = from.UpdatedRowSource;
  275. SqlParameterCollection parameters = Parameters;
  276. foreach(object parameter in from.Parameters) {
  277. parameters.Add((parameter is ICloneable) ? (parameter as ICloneable).Clone() : parameter);
  278. }
  279. }
  280. [
  281. DefaultValue(null),
  282. Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
  283. ResCategoryAttribute(Res.DataCategory_Data),
  284. ResDescriptionAttribute(Res.DbCommand_Connection),
  285. ]
  286. new public SqlConnection Connection {
  287. get {
  288. return _activeConnection;
  289. }
  290. set {
  291. // Don't allow the connection to be changed while in a async opperation.
  292. if (_activeConnection != value && _activeConnection != null) { // If new value...
  293. if (cachedAsyncState.PendingAsyncOperation) { // If in pending async state, throw.
  294. throw SQL.CannotModifyPropertyAsyncOperationInProgress(SQL.Connection);
  295. }
  296. }
  297. // Check to see if the currently set transaction has completed. If so,
  298. // null out our local reference.
  299. if (null != _transaction && _transaction.Connection == null) {
  300. _transaction = null;
  301. }
  302. // If the connection has changes, then the request context may have changed as well
  303. _smiRequestContext = null;
  304. // Command is no longer prepared on new connection, cleanup prepare status
  305. if (IsPrepared) {
  306. if (_activeConnection != value && _activeConnection != null) {
  307. RuntimeHelpers.PrepareConstrainedRegions();
  308. try {
  309. #if DEBUG
  310. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  311. RuntimeHelpers.PrepareConstrainedRegions();
  312. try {
  313. tdsReliabilitySection.Start();
  314. #endif //DEBUG
  315. // cleanup
  316. Unprepare();
  317. #if DEBUG
  318. }
  319. finally {
  320. tdsReliabilitySection.Stop();
  321. }
  322. #endif //DEBUG
  323. }
  324. catch (System.OutOfMemoryException) {
  325. _activeConnection.InnerConnection.DoomThisConnection();
  326. throw;
  327. }
  328. catch (System.StackOverflowException) {
  329. _activeConnection.InnerConnection.DoomThisConnection();
  330. throw;
  331. }
  332. catch (System.Threading.ThreadAbortException) {
  333. _activeConnection.InnerConnection.DoomThisConnection();
  334. throw;
  335. }
  336. catch (Exception) {
  337. // we do not really care about errors in unprepare (may be the old connection went bad)
  338. }
  339. finally {
  340. // clean prepare status (even successfull Unprepare does not do that)
  341. _prepareHandle = -1;
  342. _execType = EXECTYPE.UNPREPARED;
  343. }
  344. }
  345. }
  346. _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios?
  347. Bid.Trace("<sc.SqlCommand.set_Connection|API> %d#, %d#\n", ObjectID, ((null != value) ? value.ObjectID : -1));
  348. }
  349. }
  350. override protected DbConnection DbConnection { // V1.2.3300
  351. get {
  352. return Connection;
  353. }
  354. set {
  355. Connection = (SqlConnection)value;
  356. }
  357. }
  358. private SqlInternalConnectionSmi InternalSmiConnection {
  359. get {
  360. return (SqlInternalConnectionSmi)_activeConnection.InnerConnection;
  361. }
  362. }
  363. private SqlInternalConnectionTds InternalTdsConnection {
  364. get {
  365. return (SqlInternalConnectionTds)_activeConnection.InnerConnection;
  366. }
  367. }
  368. private bool IsShiloh {
  369. get {
  370. Debug.Assert(_activeConnection != null, "The active connection is null!");
  371. if (_activeConnection == null)
  372. return false;
  373. return _activeConnection.IsShiloh;
  374. }
  375. }
  376. [
  377. DefaultValue(true),
  378. ResCategoryAttribute(Res.DataCategory_Notification),
  379. ResDescriptionAttribute(Res.SqlCommand_NotificationAutoEnlist),
  380. ]
  381. public bool NotificationAutoEnlist {
  382. get {
  383. return _notificationAutoEnlist;
  384. }
  385. set {
  386. _notificationAutoEnlist = value;
  387. }
  388. }
  389. [
  390. Browsable(false),
  391. DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), // MDAC 90471
  392. ResCategoryAttribute(Res.DataCategory_Notification),
  393. ResDescriptionAttribute(Res.SqlCommand_Notification),
  394. ]
  395. public SqlNotificationRequest Notification {
  396. get {
  397. return _notification;
  398. }
  399. set {
  400. Bid.Trace("<sc.SqlCommand.set_Notification|API> %d#\n", ObjectID);
  401. _sqlDep = null;
  402. _notification = value;
  403. }
  404. }
  405. internal SqlStatistics Statistics {
  406. get {
  407. if (null != _activeConnection) {
  408. if (_activeConnection.StatisticsEnabled) {
  409. return _activeConnection.Statistics;
  410. }
  411. }
  412. return null;
  413. }
  414. }
  415. [
  416. Browsable(false),
  417. DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
  418. ResDescriptionAttribute(Res.DbCommand_Transaction),
  419. ]
  420. new public SqlTransaction Transaction {
  421. get {
  422. // if the transaction object has been zombied, just return null
  423. if ((null != _transaction) && (null == _transaction.Connection)) { // MDAC 72720
  424. _transaction = null;
  425. }
  426. return _transaction;
  427. }
  428. set {
  429. // Don't allow the transaction to be changed while in a async opperation.
  430. if (_transaction != value && _activeConnection != null) { // If new value...
  431. if (cachedAsyncState.PendingAsyncOperation) { // If in pending async state, throw
  432. throw SQL.CannotModifyPropertyAsyncOperationInProgress(SQL.Transaction);
  433. }
  434. }
  435. //
  436. Bid.Trace("<sc.SqlCommand.set_Transaction|API> %d#\n", ObjectID);
  437. _transaction = value;
  438. }
  439. }
  440. override protected DbTransaction DbTransaction { // V1.2.3300
  441. get {
  442. return Transaction;
  443. }
  444. set {
  445. Transaction = (SqlTransaction)value;
  446. }
  447. }
  448. [
  449. DefaultValue(""),
  450. Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
  451. RefreshProperties(RefreshProperties.All), // MDAC 67707
  452. ResCategoryAttribute(Res.DataCategory_Data),
  453. ResDescriptionAttribute(Res.DbCommand_CommandText),
  454. ]
  455. override public string CommandText { // V1.2.3300, XXXCommand V1.0.5000
  456. get {
  457. string value = _commandText;
  458. return ((null != value) ? value : ADP.StrEmpty);
  459. }
  460. set {
  461. if (Bid.TraceOn) {
  462. Bid.Trace("<sc.SqlCommand.set_CommandText|API> %d#, '", ObjectID);
  463. Bid.PutStr(value); // Use PutStr to write out entire string
  464. Bid.Trace("'\n");
  465. }
  466. if (0 != ADP.SrcCompare(_commandText, value)) {
  467. PropertyChanging();
  468. _commandText = value;
  469. }
  470. }
  471. }
  472. [
  473. ResCategoryAttribute(Res.DataCategory_Data),
  474. ResDescriptionAttribute(Res.DbCommand_CommandTimeout),
  475. ]
  476. override public int CommandTimeout { // V1.2.3300, XXXCommand V1.0.5000
  477. get {
  478. return _commandTimeout;
  479. }
  480. set {
  481. Bid.Trace("<sc.SqlCommand.set_CommandTimeout|API> %d#, %d\n", ObjectID, value);
  482. if (value < 0) {
  483. throw ADP.InvalidCommandTimeout(value);
  484. }
  485. if (value != _commandTimeout) {
  486. PropertyChanging();
  487. _commandTimeout = value;
  488. }
  489. }
  490. }
  491. public void ResetCommandTimeout() { // V1.2.3300
  492. if (ADP.DefaultCommandTimeout != _commandTimeout) {
  493. PropertyChanging();
  494. _commandTimeout = ADP.DefaultCommandTimeout;
  495. }
  496. }
  497. private bool ShouldSerializeCommandTimeout() { // V1.2.3300
  498. return (ADP.DefaultCommandTimeout != _commandTimeout);
  499. }
  500. [
  501. DefaultValue(System.Data.CommandType.Text),
  502. RefreshProperties(RefreshProperties.All),
  503. ResCategoryAttribute(Res.DataCategory_Data),
  504. ResDescriptionAttribute(Res.DbCommand_CommandType),
  505. ]
  506. override public CommandType CommandType { // V1.2.3300, XXXCommand V1.0.5000
  507. get {
  508. CommandType cmdType = _commandType;
  509. return ((0 != cmdType) ? cmdType : CommandType.Text);
  510. }
  511. set {
  512. Bid.Trace("<sc.SqlCommand.set_CommandType|API> %d#, %d{ds.CommandType}\n", ObjectID, (int)value);
  513. if (_commandType != value) {
  514. switch(value) { // @perfnote: Enum.IsDefined
  515. case CommandType.Text:
  516. case CommandType.StoredProcedure:
  517. PropertyChanging();
  518. _commandType = value;
  519. break;
  520. case System.Data.CommandType.TableDirect:
  521. throw SQL.NotSupportedCommandType(value);
  522. default:
  523. throw ADP.InvalidCommandType(value);
  524. }
  525. }
  526. }
  527. }
  528. // @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
  529. // to limit the number of components that clutter the design surface,
  530. // when the DataAdapter design wizard generates the insert/update/delete commands it will
  531. // set the DesignTimeVisible property to false so that cmds won't appear as individual objects
  532. [
  533. DefaultValue(true),
  534. DesignOnly(true),
  535. Browsable(false),
  536. EditorBrowsableAttribute(EditorBrowsableState.Never),
  537. ]
  538. public override bool DesignTimeVisible { // V1.2.3300, XXXCommand V1.0.5000
  539. get {
  540. return !_designTimeInvisible;
  541. }
  542. set {
  543. _designTimeInvisible = !value;
  544. TypeDescriptor.Refresh(this); // VS7 208845
  545. }
  546. }
  547. [
  548. DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
  549. ResCategoryAttribute(Res.DataCategory_Data),
  550. ResDescriptionAttribute(Res.DbCommand_Parameters),
  551. ]
  552. new public SqlParameterCollection Parameters {
  553. get {
  554. if (null == this._parameters) {
  555. // delay the creation of the SqlParameterCollection
  556. // until user actually uses the Parameters property
  557. this._parameters = new SqlParameterCollection();
  558. }
  559. return this._parameters;
  560. }
  561. }
  562. override protected DbParameterCollection DbParameterCollection { // V1.2.3300
  563. get {
  564. return Parameters;
  565. }
  566. }
  567. [
  568. DefaultValue(System.Data.UpdateRowSource.Both),
  569. ResCategoryAttribute(Res.DataCategory_Update),
  570. ResDescriptionAttribute(Res.DbCommand_UpdatedRowSource),
  571. ]
  572. override public UpdateRowSource UpdatedRowSource { // V1.2.3300, XXXCommand V1.0.5000
  573. get {
  574. return _updatedRowSource;
  575. }
  576. set {
  577. switch(value) { // @perfnote: Enum.IsDefined
  578. case UpdateRowSource.None:
  579. case UpdateRowSource.OutputParameters:
  580. case UpdateRowSource.FirstReturnedRecord:
  581. case UpdateRowSource.Both:
  582. _updatedRowSource = value;
  583. break;
  584. default:
  585. throw ADP.InvalidUpdateRowSource(value);
  586. }
  587. }
  588. }
  589. [
  590. ResCategoryAttribute(Res.DataCategory_StatementCompleted),
  591. ResDescriptionAttribute(Res.DbCommand_StatementCompleted),
  592. ]
  593. public event StatementCompletedEventHandler StatementCompleted {
  594. add {
  595. _statementCompletedEventHandler += value;
  596. }
  597. remove {
  598. _statementCompletedEventHandler -= value;
  599. }
  600. }
  601. internal void OnStatementCompleted(int recordCount) { // V1.2.3300
  602. if (0 <= recordCount) {
  603. StatementCompletedEventHandler handler = _statementCompletedEventHandler;
  604. if (null != handler) {
  605. try {
  606. Bid.Trace("<sc.SqlCommand.OnStatementCompleted|INFO> %d#, recordCount=%d\n", ObjectID, recordCount);
  607. handler(this, new StatementCompletedEventArgs(recordCount));
  608. }
  609. catch(Exception e) {
  610. //
  611. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  612. throw;
  613. }
  614. ADP.TraceExceptionWithoutRethrow(e);
  615. }
  616. }
  617. }
  618. }
  619. private void PropertyChanging() { // also called from SqlParameterCollection
  620. this.IsDirty = true;
  621. }
  622. override public void Prepare() {
  623. SqlConnection.ExecutePermission.Demand();
  624. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  625. // between entry into Execute* API and the thread obtaining the stateObject.
  626. _pendingCancel = false;
  627. // Context connection's prepare is a no-op
  628. if (null != _activeConnection && _activeConnection.IsContextConnection) {
  629. return;
  630. }
  631. SqlStatistics statistics = null;
  632. IntPtr hscp;
  633. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.Prepare|API> %d#", ObjectID);
  634. Bid.CorrelationTrace("<sc.SqlCommand.Prepare|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  635. statistics = SqlStatistics.StartTimer(Statistics);
  636. // only prepare if batch with parameters
  637. // MDAC
  638. if (
  639. this.IsPrepared && !this.IsDirty
  640. || (this.CommandType == CommandType.StoredProcedure)
  641. || (
  642. (System.Data.CommandType.Text == this.CommandType)
  643. && (0 == GetParameterCount (_parameters))
  644. )
  645. ) {
  646. if (null != Statistics) {
  647. Statistics.SafeIncrement (ref Statistics._prepares);
  648. }
  649. _hiddenPrepare = false;
  650. }
  651. else {
  652. // Validate the command outside of the try\catch to avoid putting the _stateObj on error
  653. ValidateCommand(ADP.Prepare, false /*not async*/);
  654. bool processFinallyBlock = true;
  655. TdsParser bestEffortCleanupTarget = null;
  656. RuntimeHelpers.PrepareConstrainedRegions();
  657. try {
  658. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  659. // 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)
  660. GetStateObject();
  661. // Loop through parameters ensuring that we do not have unspecified types, sizes, scales, or precisions
  662. if (null != _parameters) {
  663. int count = _parameters.Count;
  664. for (int i = 0; i < count; ++i) {
  665. _parameters[i].Prepare(this); // MDAC 67063
  666. }
  667. }
  668. #if DEBUG
  669. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  670. RuntimeHelpers.PrepareConstrainedRegions();
  671. try {
  672. tdsReliabilitySection.Start();
  673. #else
  674. {
  675. #endif //DEBUG
  676. InternalPrepare();
  677. }
  678. #if DEBUG
  679. finally {
  680. tdsReliabilitySection.Stop();
  681. }
  682. #endif //DEBUG
  683. }
  684. catch (System.OutOfMemoryException e) {
  685. processFinallyBlock = false;
  686. _activeConnection.Abort(e);
  687. throw;
  688. }
  689. catch (System.StackOverflowException e) {
  690. processFinallyBlock = false;
  691. _activeConnection.Abort(e);
  692. throw;
  693. }
  694. catch (System.Threading.ThreadAbortException e) {
  695. processFinallyBlock = false;
  696. _activeConnection.Abort(e);
  697. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  698. throw;
  699. }
  700. catch (Exception e) {
  701. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  702. throw;
  703. }
  704. finally {
  705. if (processFinallyBlock) {
  706. _hiddenPrepare = false; // The command is now officially prepared
  707. ReliablePutStateObject();
  708. }
  709. }
  710. }
  711. SqlStatistics.StopTimer(statistics);
  712. Bid.ScopeLeave(ref hscp);
  713. }
  714. private void InternalPrepare() {
  715. if (this.IsDirty) {
  716. Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters
  717. //
  718. // someone changed the command text or the parameter schema so we must unprepare the command
  719. //
  720. this.Unprepare();
  721. this.IsDirty = false;
  722. }
  723. Debug.Assert(_execType != EXECTYPE.PREPARED, "Invalid attempt to Prepare already Prepared command!");
  724. Debug.Assert(_activeConnection != null, "must have an open connection to Prepare");
  725. Debug.Assert(null != _stateObj, "TdsParserStateObject should not be null");
  726. Debug.Assert(null != _stateObj.Parser, "TdsParser class should not be null in Command.Execute!");
  727. Debug.Assert(_stateObj.Parser == _activeConnection.Parser, "stateobject parser not same as connection parser");
  728. Debug.Assert(false == _inPrepare, "Already in Prepare cycle, this.inPrepare should be false!");
  729. // remember that the user wants to do a prepare but don't actually do an rpc
  730. _execType = EXECTYPE.PREPAREPENDING;
  731. // Note the current close count of the connection - this will tell us if the connection has been closed between calls to Prepare() and Execute
  732. _preparedConnectionCloseCount = _activeConnection.CloseCount;
  733. _preparedConnectionReconnectCount = _activeConnection.ReconnectCount;
  734. if (null != Statistics) {
  735. Statistics.SafeIncrement(ref Statistics._prepares);
  736. }
  737. }
  738. // SqlInternalConnectionTds needs to be able to unprepare a statement
  739. internal void Unprepare() {
  740. // Context connection's prepare is a no-op
  741. if (_activeConnection.IsContextConnection) {
  742. return;
  743. }
  744. Debug.Assert(true == IsPrepared, "Invalid attempt to Unprepare a non-prepared command!");
  745. Debug.Assert(_activeConnection != null, "must have an open connection to UnPrepare");
  746. Debug.Assert(false == _inPrepare, "_inPrepare should be false!");
  747. // @devnote: we're always falling back to Prepare pending
  748. // @devnote: This seems broken because once the command is prepared it will - always - be a
  749. // @devnote: prepared execution.
  750. // @devnote: Even replacing the parameterlist with something completely different or
  751. // @devnote: changing the commandtext to a non-parameterized query will result in prepared execution
  752. // @devnote:
  753. // @devnote: We need to keep the behavior for backward compatibility though (non-breaking change)
  754. //
  755. _execType = EXECTYPE.PREPAREPENDING;
  756. // Don't zero out the handle because we'll pass it in to sp_prepexec on the next prepare
  757. // Unless the close count isn't the same as when we last prepared
  758. if ((_activeConnection.CloseCount != _preparedConnectionCloseCount) || (_activeConnection.ReconnectCount != _preparedConnectionReconnectCount)) {
  759. // reset our handle
  760. _prepareHandle = -1;
  761. }
  762. _cachedMetaData = null;
  763. Bid.Trace("<sc.SqlCommand.Prepare|INFO> %d#, Command unprepared.\n", ObjectID);
  764. }
  765. // Cancel is supposed to be multi-thread safe.
  766. // It doesn't make sense to verify the connection exists or that it is open during cancel
  767. // because immediately after checkin the connection can be closed or removed via another thread.
  768. //
  769. override public void Cancel() {
  770. IntPtr hscp;
  771. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.Cancel|API> %d#", ObjectID);
  772. Bid.CorrelationTrace("<sc.SqlCommand.Cancel|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  773. SqlStatistics statistics = null;
  774. try {
  775. statistics = SqlStatistics.StartTimer(Statistics);
  776. // If we are in reconnect phase simply cancel the waiting task
  777. var reconnectCompletionSource = _reconnectionCompletionSource;
  778. if (reconnectCompletionSource != null) {
  779. if (reconnectCompletionSource.TrySetCanceled()) {
  780. return;
  781. }
  782. }
  783. // the pending data flag means that we are awaiting a response or are in the middle of proccessing a response
  784. // if we have no pending data, then there is nothing to cancel
  785. // if we have pending data, but it is not a result of this command, then we don't cancel either. Note that
  786. // this model is implementable because we only allow one active command at any one time. This code
  787. // will have to change we allow multiple outstanding batches
  788. //
  789. if (null == _activeConnection) {
  790. return;
  791. }
  792. SqlInternalConnectionTds connection = (_activeConnection.InnerConnection as SqlInternalConnectionTds);
  793. if (null == connection) { // Fail with out locking
  794. return;
  795. }
  796. // The lock here is to protect against the command.cancel / connection.close race condition
  797. // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
  798. // the command will no longer be cancelable. It might be desirable to be able to cancel the close opperation, but this is
  799. // outside of the scope of Whidbey RTM. See (SqlConnection::Close) for other lock.
  800. lock (connection) {
  801. 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
  802. return;
  803. }
  804. TdsParser parser = connection.Parser;
  805. if (null == parser) {
  806. return;
  807. }
  808. TdsParser bestEffortCleanupTarget = null;
  809. RuntimeHelpers.PrepareConstrainedRegions();
  810. try {
  811. #if DEBUG
  812. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  813. RuntimeHelpers.PrepareConstrainedRegions();
  814. try {
  815. tdsReliabilitySection.Start();
  816. #else
  817. {
  818. #endif //DEBUG
  819. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  820. if (!_pendingCancel) { // Do nothing if aleady pending.
  821. // Before attempting actual cancel, set the _pendingCancel flag to false.
  822. // This denotes to other thread before obtaining stateObject from the
  823. // session pool that there is another thread wishing to cancel.
  824. // The period in question is between entering the ExecuteAPI and obtaining
  825. // a stateObject.
  826. _pendingCancel = true;
  827. TdsParserStateObject stateObj = _stateObj;
  828. if (null != stateObj) {
  829. stateObj.Cancel(ObjectID);
  830. }
  831. else {
  832. SqlDataReader reader = connection.FindLiveReader(this);
  833. if (reader != null) {
  834. reader.Cancel(ObjectID);
  835. }
  836. }
  837. }
  838. }
  839. #if DEBUG
  840. finally {
  841. tdsReliabilitySection.Stop();
  842. }
  843. #endif //DEBUG
  844. }
  845. catch (System.OutOfMemoryException e) {
  846. _activeConnection.Abort(e);
  847. throw;
  848. }
  849. catch (System.StackOverflowException e) {
  850. _activeConnection.Abort(e);
  851. throw;
  852. }
  853. catch (System.Threading.ThreadAbortException e) {
  854. _activeConnection.Abort(e);
  855. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  856. throw;
  857. }
  858. }
  859. }
  860. finally {
  861. SqlStatistics.StopTimer(statistics);
  862. Bid.ScopeLeave(ref hscp);
  863. }
  864. }
  865. new public SqlParameter CreateParameter() {
  866. return new SqlParameter();
  867. }
  868. override protected DbParameter CreateDbParameter() {
  869. return CreateParameter();
  870. }
  871. override protected void Dispose(bool disposing) {
  872. if (disposing) { // release mananged objects
  873. // V1.0, V1.1 did not reset the Connection, Parameters, CommandText, WebData 100524
  874. //_parameters = null;
  875. //_activeConnection = null;
  876. //_statistics = null;
  877. //CommandText = null;
  878. _cachedMetaData = null;
  879. }
  880. // release unmanaged objects
  881. base.Dispose(disposing);
  882. }
  883. override public object ExecuteScalar() {
  884. SqlConnection.ExecutePermission.Demand();
  885. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  886. // between entry into Execute* API and the thread obtaining the stateObject.
  887. _pendingCancel = false;
  888. SqlStatistics statistics = null;
  889. IntPtr hscp;
  890. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteScalar|API> %d#", ObjectID);
  891. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteScalar|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  892. try {
  893. statistics = SqlStatistics.StartTimer(Statistics);
  894. SqlDataReader ds;
  895. ds = RunExecuteReader(0, RunBehavior.ReturnImmediately, true, ADP.ExecuteScalar);
  896. return CompleteExecuteScalar(ds, false);
  897. }
  898. finally {
  899. SqlStatistics.StopTimer(statistics);
  900. Bid.ScopeLeave(ref hscp);
  901. }
  902. }
  903. private object CompleteExecuteScalar(SqlDataReader ds, bool returnSqlValue) {
  904. object retResult = null;
  905. try {
  906. if (ds.Read()) {
  907. if (ds.FieldCount > 0) {
  908. if (returnSqlValue) {
  909. retResult = ds.GetSqlValue(0);
  910. }
  911. else {
  912. retResult = ds.GetValue(0);
  913. }
  914. }
  915. }
  916. }
  917. finally {
  918. // clean off the wire
  919. ds.Close();
  920. }
  921. return retResult;
  922. }
  923. override public int ExecuteNonQuery() {
  924. SqlConnection.ExecutePermission.Demand();
  925. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  926. // between entry into Execute* API and the thread obtaining the stateObject.
  927. _pendingCancel = false;
  928. SqlStatistics statistics = null;
  929. IntPtr hscp;
  930. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteNonQuery|API> %d#", ObjectID);
  931. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  932. try {
  933. statistics = SqlStatistics.StartTimer(Statistics);
  934. InternalExecuteNonQuery(null, ADP.ExecuteNonQuery, false, CommandTimeout);
  935. return _rowsAffected;
  936. }
  937. finally {
  938. SqlStatistics.StopTimer(statistics);
  939. Bid.ScopeLeave(ref hscp);
  940. }
  941. }
  942. // Handles in-proc execute-to-pipe functionality
  943. // Identical to ExecuteNonQuery
  944. internal void ExecuteToPipe( SmiContext pipeContext ) {
  945. SqlConnection.ExecutePermission.Demand();
  946. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  947. // between entry into Execute* API and the thread obtaining the stateObject.
  948. _pendingCancel = false;
  949. SqlStatistics statistics = null;
  950. IntPtr hscp;
  951. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteToPipe|INFO> %d#", ObjectID);
  952. try {
  953. statistics = SqlStatistics.StartTimer(Statistics);
  954. InternalExecuteNonQuery(null, ADP.ExecuteNonQuery, true, CommandTimeout);
  955. }
  956. finally {
  957. SqlStatistics.StopTimer(statistics);
  958. Bid.ScopeLeave(ref hscp);
  959. }
  960. }
  961. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  962. public IAsyncResult BeginExecuteNonQuery() {
  963. // BeginExecuteNonQuery will track ExecutionTime for us
  964. return BeginExecuteNonQuery(null, null);
  965. }
  966. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  967. public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) {
  968. Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  969. SqlConnection.ExecutePermission.Demand();
  970. return BeginExecuteNonQueryInternal(callback, stateObject, 0);
  971. }
  972. private IAsyncResult BeginExecuteNonQueryAsync(AsyncCallback callback, object stateObject) {
  973. return BeginExecuteNonQueryInternal(callback, stateObject, CommandTimeout, asyncWrite:true);
  974. }
  975. private IAsyncResult BeginExecuteNonQueryInternal(AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false) {
  976. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  977. // between entry into Execute* API and the thread obtaining the stateObject.
  978. _pendingCancel = false;
  979. ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
  980. // back into pool when we should not.
  981. SqlStatistics statistics = null;
  982. try {
  983. statistics = SqlStatistics.StartTimer(Statistics);
  984. TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
  985. try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
  986. Task execNQ = InternalExecuteNonQuery(completion, ADP.BeginExecuteNonQuery, false, timeout, asyncWrite);
  987. if (execNQ != null) {
  988. AsyncHelper.ContinueTask(execNQ, completion, () => BeginExecuteNonQueryInternalReadStage(completion));
  989. }
  990. else {
  991. BeginExecuteNonQueryInternalReadStage(completion);
  992. }
  993. }
  994. catch (Exception e) {
  995. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  996. // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
  997. throw;
  998. }
  999. // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
  1000. ReliablePutStateObject();
  1001. throw;
  1002. }
  1003. // Add callback after work is done to avoid overlapping Begin\End methods
  1004. if (callback != null) {
  1005. completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default);
  1006. }
  1007. return completion.Task;
  1008. }
  1009. finally {
  1010. SqlStatistics.StopTimer(statistics);
  1011. }
  1012. }
  1013. private void BeginExecuteNonQueryInternalReadStage(TaskCompletionSource<object> completion) {
  1014. // Read SNI does not have catches for async exceptions, handle here.
  1015. TdsParser bestEffortCleanupTarget = null;
  1016. RuntimeHelpers.PrepareConstrainedRegions();
  1017. try {
  1018. #if DEBUG
  1019. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1020. RuntimeHelpers.PrepareConstrainedRegions();
  1021. try {
  1022. tdsReliabilitySection.Start();
  1023. #else
  1024. {
  1025. #endif //DEBUG
  1026. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1027. // must finish caching information before ReadSni which can activate the callback before returning
  1028. cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteNonQuery, _activeConnection);
  1029. _stateObj.ReadSni(completion);
  1030. }
  1031. #if DEBUG
  1032. finally {
  1033. tdsReliabilitySection.Stop();
  1034. }
  1035. #endif //DEBUG
  1036. }
  1037. catch (System.OutOfMemoryException e) {
  1038. _activeConnection.Abort(e);
  1039. throw;
  1040. }
  1041. catch (System.StackOverflowException e) {
  1042. _activeConnection.Abort(e);
  1043. throw;
  1044. }
  1045. catch (System.Threading.ThreadAbortException e) {
  1046. _activeConnection.Abort(e);
  1047. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1048. throw;
  1049. }
  1050. catch (Exception) {
  1051. // Similarly, if an exception occurs put the stateObj back into the pool.
  1052. // and reset async cache information to allow a second async execute
  1053. if (null != _cachedAsyncState) {
  1054. _cachedAsyncState.ResetAsyncState();
  1055. }
  1056. ReliablePutStateObject();
  1057. throw;
  1058. }
  1059. }
  1060. private void VerifyEndExecuteState(Task completionTask, String endMethod) {
  1061. if (null == completionTask) {
  1062. throw ADP.ArgumentNull("asyncResult");
  1063. }
  1064. if (completionTask.IsCanceled) {
  1065. if (_stateObj != null) {
  1066. _stateObj.Parser.State = TdsParserState.Broken; // We failed to respond to attention, we have to quit!
  1067. _stateObj.Parser.Connection.BreakConnection();
  1068. _stateObj.Parser.ThrowExceptionAndWarning(_stateObj);
  1069. }
  1070. else {
  1071. Debug.Assert(_reconnectionCompletionSource == null || _reconnectionCompletionSource.Task.IsCanceled, "ReconnectCompletionSource should be null or cancelled");
  1072. throw SQL.CR_ReconnectionCancelled();
  1073. }
  1074. }
  1075. else if (completionTask.IsFaulted) {
  1076. throw completionTask.Exception.InnerException;
  1077. }
  1078. if (cachedAsyncState.EndMethodName == null) {
  1079. throw ADP.MethodCalledTwice(endMethod);
  1080. }
  1081. if (endMethod != cachedAsyncState.EndMethodName) {
  1082. throw ADP.MismatchedAsyncResult(cachedAsyncState.EndMethodName, endMethod);
  1083. }
  1084. if ((_activeConnection.State != ConnectionState.Open) || (!cachedAsyncState.IsActiveConnectionValid(_activeConnection))) {
  1085. // If the connection is not 'valid' then it was closed while we were executing
  1086. throw ADP.ClosedConnectionError();
  1087. }
  1088. }
  1089. private void WaitForAsyncResults(IAsyncResult asyncResult) {
  1090. Task completionTask = (Task) asyncResult;
  1091. if (!asyncResult.IsCompleted) {
  1092. asyncResult.AsyncWaitHandle.WaitOne();
  1093. }
  1094. _stateObj._networkPacketTaskSource = null;
  1095. _activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
  1096. }
  1097. public int EndExecuteNonQuery(IAsyncResult asyncResult) {
  1098. try {
  1099. return EndExecuteNonQueryInternal(asyncResult);
  1100. }
  1101. finally {
  1102. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1103. }
  1104. }
  1105. private void ThrowIfReconnectionHasBeenCanceled() {
  1106. if (_stateObj == null) {
  1107. var reconnectionCompletionSource = _reconnectionCompletionSource;
  1108. if (reconnectionCompletionSource != null && reconnectionCompletionSource.Task.IsCanceled) {
  1109. throw SQL.CR_ReconnectionCancelled();
  1110. }
  1111. }
  1112. }
  1113. private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) {
  1114. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteNonQueryAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1115. Exception asyncException = ((Task)asyncResult).Exception;
  1116. if (asyncException != null) {
  1117. // Leftover exception from the Begin...InternalReadStage
  1118. ReliablePutStateObject();
  1119. throw asyncException.InnerException;
  1120. }
  1121. else {
  1122. ThrowIfReconnectionHasBeenCanceled();
  1123. // lock on _stateObj prevents ----s with close/cancel.
  1124. lock (_stateObj) {
  1125. return EndExecuteNonQueryInternal(asyncResult);
  1126. }
  1127. }
  1128. }
  1129. private int EndExecuteNonQueryInternal(IAsyncResult asyncResult) {
  1130. SqlStatistics statistics = null;
  1131. TdsParser bestEffortCleanupTarget = null;
  1132. RuntimeHelpers.PrepareConstrainedRegions();
  1133. try {
  1134. #if DEBUG
  1135. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1136. RuntimeHelpers.PrepareConstrainedRegions();
  1137. try {
  1138. tdsReliabilitySection.Start();
  1139. #else
  1140. {
  1141. #endif //DEBUG
  1142. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1143. statistics = SqlStatistics.StartTimer(Statistics);
  1144. VerifyEndExecuteState((Task)asyncResult, ADP.EndExecuteNonQuery);
  1145. WaitForAsyncResults(asyncResult);
  1146. bool processFinallyBlock = true;
  1147. try {
  1148. NotifyDependency();
  1149. CheckThrowSNIException();
  1150. // only send over SQL Batch command if we are not a stored proc and have no parameters
  1151. if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) {
  1152. try {
  1153. bool dataReady;
  1154. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  1155. bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady);
  1156. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  1157. }
  1158. finally {
  1159. cachedAsyncState.ResetAsyncState();
  1160. }
  1161. }
  1162. else { // otherwise, use a full-fledged execute that can handle params and stored procs
  1163. SqlDataReader reader = CompleteAsyncExecuteReader();
  1164. if (null != reader) {
  1165. reader.Close();
  1166. }
  1167. }
  1168. }
  1169. catch (Exception e) {
  1170. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  1171. throw;
  1172. }
  1173. finally {
  1174. if (processFinallyBlock) {
  1175. PutStateObject();
  1176. }
  1177. }
  1178. Debug.Assert(null == _stateObj, "non-null state object in EndExecuteNonQuery");
  1179. return _rowsAffected;
  1180. }
  1181. #if DEBUG
  1182. finally {
  1183. tdsReliabilitySection.Stop();
  1184. }
  1185. #endif //DEBUG
  1186. }
  1187. catch (System.OutOfMemoryException e) {
  1188. _activeConnection.Abort(e);
  1189. throw;
  1190. }
  1191. catch (System.StackOverflowException e) {
  1192. _activeConnection.Abort(e);
  1193. throw;
  1194. }
  1195. catch (System.Threading.ThreadAbortException e) {
  1196. _activeConnection.Abort(e);
  1197. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1198. throw;
  1199. }
  1200. catch (Exception e) {
  1201. if (cachedAsyncState != null) {
  1202. cachedAsyncState.ResetAsyncState();
  1203. };
  1204. if (ADP.IsCatchableExceptionType(e)) {
  1205. ReliablePutStateObject();
  1206. };
  1207. throw;
  1208. }
  1209. finally {
  1210. SqlStatistics.StopTimer(statistics);
  1211. }
  1212. }
  1213. private Task InternalExecuteNonQuery(TaskCompletionSource<object> completion, string methodName, bool sendToPipe, int timeout, bool asyncWrite = false) {
  1214. bool async = (null != completion);
  1215. SqlStatistics statistics = Statistics;
  1216. _rowsAffected = -1;
  1217. TdsParser bestEffortCleanupTarget = null;
  1218. RuntimeHelpers.PrepareConstrainedRegions();
  1219. try {
  1220. #if DEBUG
  1221. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1222. RuntimeHelpers.PrepareConstrainedRegions();
  1223. try {
  1224. tdsReliabilitySection.Start();
  1225. #else
  1226. {
  1227. #endif //DEBUG
  1228. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1229. // @devnote: this function may throw for an invalid connection
  1230. // @devnote: returns false for empty command text
  1231. ValidateCommand(methodName, async);
  1232. CheckNotificationStateAndAutoEnlist(); // Only call after validate - requires non null connection!
  1233. Task task = null;
  1234. // only send over SQL Batch command if we are not a stored proc and have no parameters and not in batch RPC mode
  1235. if ( _activeConnection.IsContextConnection ) {
  1236. if (null != statistics) {
  1237. statistics.SafeIncrement(ref statistics._unpreparedExecs);
  1238. }
  1239. RunExecuteNonQuerySmi( sendToPipe );
  1240. }
  1241. else if (!BatchRPCMode && (System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) {
  1242. Debug.Assert( !sendToPipe, "trying to send non-context command to pipe" );
  1243. if (null != statistics) {
  1244. if (!this.IsDirty && this.IsPrepared) {
  1245. statistics.SafeIncrement(ref statistics._preparedExecs);
  1246. }
  1247. else {
  1248. statistics.SafeIncrement(ref statistics._unpreparedExecs);
  1249. }
  1250. }
  1251. task = RunExecuteNonQueryTds(methodName, async, timeout, asyncWrite);
  1252. }
  1253. else { // otherwise, use a full-fledged execute that can handle params and stored procs
  1254. Debug.Assert( !sendToPipe, "trying to send non-context command to pipe" );
  1255. Bid.Trace("<sc.SqlCommand.ExecuteNonQuery|INFO> %d#, Command executed as RPC.\n", ObjectID);
  1256. SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, asyncWrite);
  1257. if (null!=reader) {
  1258. if (task != null) {
  1259. task = AsyncHelper.CreateContinuationTask(task, () => reader.Close());
  1260. }
  1261. else {
  1262. reader.Close();
  1263. }
  1264. }
  1265. }
  1266. Debug.Assert(async || null == _stateObj, "non-null state object in InternalExecuteNonQuery");
  1267. return task;
  1268. }
  1269. #if DEBUG
  1270. finally {
  1271. tdsReliabilitySection.Stop();
  1272. }
  1273. #endif //DEBUG
  1274. }
  1275. catch (System.OutOfMemoryException e) {
  1276. _activeConnection.Abort(e);
  1277. throw;
  1278. }
  1279. catch (System.StackOverflowException e) {
  1280. _activeConnection.Abort(e);
  1281. throw;
  1282. }
  1283. catch (System.Threading.ThreadAbortException e) {
  1284. _activeConnection.Abort(e);
  1285. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1286. throw;
  1287. }
  1288. }
  1289. public XmlReader ExecuteXmlReader() {
  1290. SqlConnection.ExecutePermission.Demand();
  1291. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1292. // between entry into Execute* API and the thread obtaining the stateObject.
  1293. _pendingCancel = false;
  1294. SqlStatistics statistics = null;
  1295. IntPtr hscp;
  1296. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteXmlReader|API> %d#", ObjectID);
  1297. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1298. try {
  1299. statistics = SqlStatistics.StartTimer(Statistics);
  1300. // use the reader to consume metadata
  1301. SqlDataReader ds;
  1302. ds = RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, ADP.ExecuteXmlReader);
  1303. return CompleteXmlReader(ds);
  1304. }
  1305. finally {
  1306. SqlStatistics.StopTimer(statistics);
  1307. Bid.ScopeLeave(ref hscp);
  1308. }
  1309. }
  1310. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1311. public IAsyncResult BeginExecuteXmlReader() {
  1312. // BeginExecuteXmlReader will track executiontime
  1313. return BeginExecuteXmlReader(null, null);
  1314. }
  1315. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1316. public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) {
  1317. Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1318. SqlConnection.ExecutePermission.Demand();
  1319. return BeginExecuteXmlReaderInternal(callback, stateObject, 0);
  1320. }
  1321. private IAsyncResult BeginExecuteXmlReaderAsync(AsyncCallback callback, object stateObject) {
  1322. return BeginExecuteXmlReaderInternal(callback, stateObject, CommandTimeout, asyncWrite:true);
  1323. }
  1324. private IAsyncResult BeginExecuteXmlReaderInternal(AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false) {
  1325. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1326. // between entry into Execute* API and the thread obtaining the stateObject.
  1327. _pendingCancel = false;
  1328. ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
  1329. // back into pool when we should not.
  1330. SqlStatistics statistics = null;
  1331. try {
  1332. statistics = SqlStatistics.StartTimer(Statistics);
  1333. TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
  1334. Task writeTask;
  1335. try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
  1336. RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, ADP.BeginExecuteXmlReader, completion, timeout, out writeTask, asyncWrite);
  1337. }
  1338. catch (Exception e) {
  1339. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  1340. // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
  1341. throw;
  1342. }
  1343. // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
  1344. ReliablePutStateObject();
  1345. throw;
  1346. }
  1347. if (writeTask != null) {
  1348. AsyncHelper.ContinueTask(writeTask, completion, () => BeginExecuteXmlReaderInternalReadStage(completion));
  1349. }
  1350. else {
  1351. BeginExecuteXmlReaderInternalReadStage(completion);
  1352. }
  1353. // Add callback after work is done to avoid overlapping Begin\End methods
  1354. if (callback != null) {
  1355. completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default);
  1356. }
  1357. return completion.Task;
  1358. }
  1359. finally {
  1360. SqlStatistics.StopTimer(statistics);
  1361. }
  1362. }
  1363. private void BeginExecuteXmlReaderInternalReadStage(TaskCompletionSource<object> completion) {
  1364. Debug.Assert(completion != null,"Completion source should not be null");
  1365. // Read SNI does not have catches for async exceptions, handle here.
  1366. TdsParser bestEffortCleanupTarget = null;
  1367. RuntimeHelpers.PrepareConstrainedRegions();
  1368. try {
  1369. #if DEBUG
  1370. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1371. RuntimeHelpers.PrepareConstrainedRegions();
  1372. try {
  1373. tdsReliabilitySection.Start();
  1374. #else
  1375. {
  1376. #endif //DEBUG
  1377. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1378. // must finish caching information before ReadSni which can activate the callback before returning
  1379. cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteXmlReader, _activeConnection);
  1380. _stateObj.ReadSni(completion);
  1381. }
  1382. #if DEBUG
  1383. finally {
  1384. tdsReliabilitySection.Stop();
  1385. }
  1386. #endif //DEBUG
  1387. }
  1388. catch (System.OutOfMemoryException e) {
  1389. _activeConnection.Abort(e);
  1390. completion.TrySetException(e);
  1391. throw;
  1392. }
  1393. catch (System.StackOverflowException e) {
  1394. _activeConnection.Abort(e);
  1395. completion.TrySetException(e);
  1396. throw;
  1397. }
  1398. catch (System.Threading.ThreadAbortException e) {
  1399. _activeConnection.Abort(e);
  1400. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1401. completion.TrySetException(e);
  1402. throw;
  1403. }
  1404. catch (Exception e) {
  1405. // Similarly, if an exception occurs put the stateObj back into the pool.
  1406. // and reset async cache information to allow a second async execute
  1407. if (null != _cachedAsyncState) {
  1408. _cachedAsyncState.ResetAsyncState();
  1409. }
  1410. ReliablePutStateObject();
  1411. completion.TrySetException(e);
  1412. }
  1413. }
  1414. public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) {
  1415. try {
  1416. return EndExecuteXmlReaderInternal(asyncResult);
  1417. }
  1418. finally {
  1419. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1420. }
  1421. }
  1422. private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) {
  1423. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteXmlReaderAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1424. Exception asyncException = ((Task)asyncResult).Exception;
  1425. if (asyncException != null) {
  1426. // Leftover exception from the Begin...InternalReadStage
  1427. ReliablePutStateObject();
  1428. throw asyncException.InnerException;
  1429. }
  1430. else {
  1431. ThrowIfReconnectionHasBeenCanceled();
  1432. // lock on _stateObj prevents ----s with close/cancel.
  1433. lock (_stateObj) {
  1434. return EndExecuteXmlReaderInternal(asyncResult);
  1435. }
  1436. }
  1437. }
  1438. private XmlReader EndExecuteXmlReaderInternal(IAsyncResult asyncResult) {
  1439. try {
  1440. return CompleteXmlReader(InternalEndExecuteReader(asyncResult, ADP.EndExecuteXmlReader));
  1441. }
  1442. catch (Exception e) {
  1443. if (cachedAsyncState != null) {
  1444. cachedAsyncState.ResetAsyncState();
  1445. };
  1446. if (ADP.IsCatchableExceptionType(e)) {
  1447. ReliablePutStateObject();
  1448. };
  1449. throw;
  1450. }
  1451. }
  1452. private XmlReader CompleteXmlReader(SqlDataReader ds) {
  1453. XmlReader xr = null;
  1454. SmiExtendedMetaData[] md = ds.GetInternalSmiMetaData();
  1455. bool isXmlCapable = (null != md && md.Length == 1 && (md[0].SqlDbType == SqlDbType.NText
  1456. || md[0].SqlDbType == SqlDbType.NVarChar
  1457. || md[0].SqlDbType == SqlDbType.Xml));
  1458. if (isXmlCapable) {
  1459. try {
  1460. SqlStream sqlBuf = new SqlStream(ds, true /*addByteOrderMark*/, (md[0].SqlDbType == SqlDbType.Xml) ? false : true /*process all rows*/);
  1461. xr = sqlBuf.ToXmlReader();
  1462. }
  1463. catch (Exception e) {
  1464. if (ADP.IsCatchableExceptionType(e)) {
  1465. ds.Close();
  1466. }
  1467. throw;
  1468. }
  1469. }
  1470. if (xr == null) {
  1471. ds.Close();
  1472. throw SQL.NonXmlResult();
  1473. }
  1474. return xr;
  1475. }
  1476. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1477. public IAsyncResult BeginExecuteReader() {
  1478. return BeginExecuteReader(null, null, CommandBehavior.Default);
  1479. }
  1480. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1481. public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject) {
  1482. return BeginExecuteReader(callback, stateObject, CommandBehavior.Default);
  1483. }
  1484. override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) {
  1485. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteDbDataReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1486. return ExecuteReader(behavior, ADP.ExecuteReader);
  1487. }
  1488. new public SqlDataReader ExecuteReader() {
  1489. SqlStatistics statistics = null;
  1490. IntPtr hscp;
  1491. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteReader|API> %d#", ObjectID);
  1492. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1493. try {
  1494. statistics = SqlStatistics.StartTimer(Statistics);
  1495. return ExecuteReader(CommandBehavior.Default, ADP.ExecuteReader);
  1496. }
  1497. finally {
  1498. SqlStatistics.StopTimer(statistics);
  1499. Bid.ScopeLeave(ref hscp);
  1500. }
  1501. }
  1502. new public SqlDataReader ExecuteReader(CommandBehavior behavior) {
  1503. IntPtr hscp;
  1504. Bid.ScopeEnter(out hscp, "<sc.SqlCommand.ExecuteReader|API> %d#, behavior=%d{ds.CommandBehavior}", ObjectID, (int)behavior);
  1505. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReader|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior);
  1506. try {
  1507. return ExecuteReader(behavior, ADP.ExecuteReader);
  1508. }
  1509. finally {
  1510. Bid.ScopeLeave(ref hscp);
  1511. }
  1512. }
  1513. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1514. public IAsyncResult BeginExecuteReader(CommandBehavior behavior) {
  1515. return BeginExecuteReader(null, null, behavior);
  1516. }
  1517. [System.Security.Permissions.HostProtectionAttribute(ExternalThreading=true)]
  1518. public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) {
  1519. Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteReader|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior);
  1520. SqlConnection.ExecutePermission.Demand();
  1521. return BeginExecuteReaderInternal(behavior, callback, stateObject, 0);
  1522. }
  1523. internal SqlDataReader ExecuteReader(CommandBehavior behavior, string method) {
  1524. SqlConnection.ExecutePermission.Demand(); // TODO: Need to move this to public methods...
  1525. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1526. // between entry into Execute* API and the thread obtaining the stateObject.
  1527. _pendingCancel = false;
  1528. SqlStatistics statistics = null;
  1529. TdsParser bestEffortCleanupTarget = null;
  1530. RuntimeHelpers.PrepareConstrainedRegions();
  1531. try {
  1532. #if DEBUG
  1533. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1534. RuntimeHelpers.PrepareConstrainedRegions();
  1535. try {
  1536. tdsReliabilitySection.Start();
  1537. #else
  1538. {
  1539. #endif //DEBUG
  1540. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1541. statistics = SqlStatistics.StartTimer(Statistics);
  1542. return RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, method);
  1543. }
  1544. #if DEBUG
  1545. finally {
  1546. tdsReliabilitySection.Stop();
  1547. }
  1548. #endif //DEBUG
  1549. }
  1550. catch (System.OutOfMemoryException e) {
  1551. _activeConnection.Abort(e);
  1552. throw;
  1553. }
  1554. catch (System.StackOverflowException e) {
  1555. _activeConnection.Abort(e);
  1556. throw;
  1557. }
  1558. catch (System.Threading.ThreadAbortException e) {
  1559. _activeConnection.Abort(e);
  1560. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1561. throw;
  1562. }
  1563. finally {
  1564. SqlStatistics.StopTimer(statistics);
  1565. }
  1566. }
  1567. public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) {
  1568. try {
  1569. return EndExecuteReaderInternal(asyncResult);
  1570. }
  1571. finally {
  1572. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1573. }
  1574. }
  1575. private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) {
  1576. Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteReaderAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1577. Exception asyncException = ((Task)asyncResult).Exception;
  1578. if (asyncException != null) {
  1579. // Leftover exception from the Begin...InternalReadStage
  1580. ReliablePutStateObject();
  1581. throw asyncException.InnerException;
  1582. }
  1583. else {
  1584. ThrowIfReconnectionHasBeenCanceled();
  1585. // lock on _stateObj prevents ----s with close/cancel.
  1586. lock (_stateObj) {
  1587. return EndExecuteReaderInternal(asyncResult);
  1588. }
  1589. }
  1590. }
  1591. private SqlDataReader EndExecuteReaderInternal(IAsyncResult asyncResult) {
  1592. SqlStatistics statistics = null;
  1593. try {
  1594. statistics = SqlStatistics.StartTimer(Statistics);
  1595. return InternalEndExecuteReader(asyncResult, ADP.EndExecuteReader);
  1596. }
  1597. catch (Exception e) {
  1598. if (cachedAsyncState != null) {
  1599. cachedAsyncState.ResetAsyncState();
  1600. };
  1601. if (ADP.IsCatchableExceptionType(e)) {
  1602. ReliablePutStateObject();
  1603. };
  1604. throw;
  1605. }
  1606. finally {
  1607. SqlStatistics.StopTimer(statistics);
  1608. }
  1609. }
  1610. private IAsyncResult BeginExecuteReaderAsync(CommandBehavior behavior, AsyncCallback callback, object stateObject) {
  1611. return BeginExecuteReaderInternal(behavior, callback, stateObject, CommandTimeout, asyncWrite:true);
  1612. }
  1613. private IAsyncResult BeginExecuteReaderInternal(CommandBehavior behavior, AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false) {
  1614. // Reset _pendingCancel upon entry into any Execute - used to synchronize state
  1615. // between entry into Execute* API and the thread obtaining the stateObject.
  1616. _pendingCancel = false;
  1617. SqlStatistics statistics = null;
  1618. try {
  1619. statistics = SqlStatistics.StartTimer(Statistics);
  1620. TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
  1621. ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
  1622. // back into pool when we should not.
  1623. Task writeTask = null;
  1624. try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
  1625. RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, ADP.BeginExecuteReader, completion, timeout, out writeTask, asyncWrite);
  1626. }
  1627. catch (Exception e) {
  1628. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  1629. // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
  1630. throw;
  1631. }
  1632. // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
  1633. ReliablePutStateObject();
  1634. throw;
  1635. }
  1636. if (writeTask != null ) {
  1637. AsyncHelper.ContinueTask(writeTask,completion,()=> BeginExecuteReaderInternalReadStage(completion));
  1638. }
  1639. else {
  1640. BeginExecuteReaderInternalReadStage(completion);
  1641. }
  1642. // Add callback after work is done to avoid overlapping Begin\End methods
  1643. if (callback != null) {
  1644. completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default);
  1645. }
  1646. return completion.Task;
  1647. }
  1648. finally {
  1649. SqlStatistics.StopTimer(statistics);
  1650. }
  1651. }
  1652. private void BeginExecuteReaderInternalReadStage(TaskCompletionSource<object> completion) {
  1653. Debug.Assert(completion != null,"CompletionSource should not be null");
  1654. // Read SNI does not have catches for async exceptions, handle here.
  1655. TdsParser bestEffortCleanupTarget = null;
  1656. RuntimeHelpers.PrepareConstrainedRegions();
  1657. try {
  1658. #if DEBUG
  1659. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1660. RuntimeHelpers.PrepareConstrainedRegions();
  1661. try {
  1662. tdsReliabilitySection.Start();
  1663. #else
  1664. {
  1665. #endif //DEBUG
  1666. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1667. // must finish caching information before ReadSni which can activate the callback before returning
  1668. cachedAsyncState.SetActiveConnectionAndResult(completion, ADP.EndExecuteReader, _activeConnection);
  1669. _stateObj.ReadSni(completion);
  1670. }
  1671. #if DEBUG
  1672. finally {
  1673. tdsReliabilitySection.Stop();
  1674. }
  1675. #endif //DEBUG
  1676. }
  1677. catch (System.OutOfMemoryException e) {
  1678. _activeConnection.Abort(e);
  1679. completion.TrySetException(e);
  1680. throw;
  1681. }
  1682. catch (System.StackOverflowException e) {
  1683. _activeConnection.Abort(e);
  1684. completion.TrySetException(e);
  1685. throw;
  1686. }
  1687. catch (System.Threading.ThreadAbortException e) {
  1688. _activeConnection.Abort(e);
  1689. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1690. completion.TrySetException(e);
  1691. throw;
  1692. }
  1693. catch (Exception e) {
  1694. // Similarly, if an exception occurs put the stateObj back into the pool.
  1695. // and reset async cache information to allow a second async execute
  1696. if (null != _cachedAsyncState) {
  1697. _cachedAsyncState.ResetAsyncState();
  1698. }
  1699. ReliablePutStateObject();
  1700. completion.TrySetException(e);
  1701. }
  1702. }
  1703. private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string endMethod) {
  1704. VerifyEndExecuteState((Task) asyncResult, endMethod);
  1705. WaitForAsyncResults(asyncResult);
  1706. CheckThrowSNIException();
  1707. TdsParser bestEffortCleanupTarget = null;
  1708. RuntimeHelpers.PrepareConstrainedRegions();
  1709. try {
  1710. #if DEBUG
  1711. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1712. RuntimeHelpers.PrepareConstrainedRegions();
  1713. try {
  1714. tdsReliabilitySection.Start();
  1715. #else
  1716. {
  1717. #endif //DEBUG
  1718. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  1719. SqlDataReader reader = CompleteAsyncExecuteReader();
  1720. Debug.Assert(null == _stateObj, "non-null state object in InternalEndExecuteReader");
  1721. return reader;
  1722. }
  1723. #if DEBUG
  1724. finally {
  1725. tdsReliabilitySection.Stop();
  1726. }
  1727. #endif //DEBUG
  1728. }
  1729. catch (System.OutOfMemoryException e) {
  1730. _activeConnection.Abort(e);
  1731. throw;
  1732. }
  1733. catch (System.StackOverflowException e) {
  1734. _activeConnection.Abort(e);
  1735. throw;
  1736. }
  1737. catch (System.Threading.ThreadAbortException e) {
  1738. _activeConnection.Abort(e);
  1739. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  1740. throw;
  1741. }
  1742. }
  1743. public override Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) {
  1744. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteNonQueryAsync|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1745. SqlConnection.ExecutePermission.Demand();
  1746. TaskCompletionSource<int> source = new TaskCompletionSource<int>();
  1747. CancellationTokenRegistration registration = new CancellationTokenRegistration();
  1748. if (cancellationToken.CanBeCanceled) {
  1749. if (cancellationToken.IsCancellationRequested) {
  1750. source.SetCanceled();
  1751. return source.Task;
  1752. }
  1753. registration = cancellationToken.Register(CancelIgnoreFailure);
  1754. }
  1755. Task<int> returnedTask = source.Task;
  1756. try {
  1757. RegisterForConnectionCloseNotification(ref returnedTask);
  1758. Task<int>.Factory.FromAsync(BeginExecuteNonQueryAsync, EndExecuteNonQueryAsync, null).ContinueWith((t) => {
  1759. registration.Dispose();
  1760. if (t.IsFaulted) {
  1761. Exception e = t.Exception.InnerException;
  1762. source.SetException(e);
  1763. }
  1764. else {
  1765. if (t.IsCanceled) {
  1766. source.SetCanceled();
  1767. }
  1768. else {
  1769. source.SetResult(t.Result);
  1770. }
  1771. }
  1772. }, TaskScheduler.Default);
  1773. }
  1774. catch (Exception e) {
  1775. source.SetException(e);
  1776. }
  1777. return returnedTask;
  1778. }
  1779. protected override Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) {
  1780. return ExecuteReaderAsync(behavior, cancellationToken).ContinueWith<DbDataReader>((result) => {
  1781. if (result.IsFaulted) {
  1782. throw result.Exception.InnerException;
  1783. }
  1784. return result.Result;
  1785. }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default);
  1786. }
  1787. new public Task<SqlDataReader> ExecuteReaderAsync() {
  1788. return ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None);
  1789. }
  1790. new public Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior) {
  1791. return ExecuteReaderAsync(behavior, CancellationToken.None);
  1792. }
  1793. new public Task<SqlDataReader> ExecuteReaderAsync(CancellationToken cancellationToken) {
  1794. return ExecuteReaderAsync(CommandBehavior.Default, cancellationToken);
  1795. }
  1796. new public Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) {
  1797. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReaderAsync|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior);
  1798. SqlConnection.ExecutePermission.Demand();
  1799. TaskCompletionSource<SqlDataReader> source = new TaskCompletionSource<SqlDataReader>();
  1800. CancellationTokenRegistration registration = new CancellationTokenRegistration();
  1801. if (cancellationToken.CanBeCanceled) {
  1802. if (cancellationToken.IsCancellationRequested) {
  1803. source.SetCanceled();
  1804. return source.Task;
  1805. }
  1806. registration = cancellationToken.Register(CancelIgnoreFailure);
  1807. }
  1808. Task<SqlDataReader> returnedTask = source.Task;
  1809. try {
  1810. RegisterForConnectionCloseNotification(ref returnedTask);
  1811. Task<SqlDataReader>.Factory.FromAsync(BeginExecuteReaderAsync, EndExecuteReaderAsync, behavior, null).ContinueWith((t) => {
  1812. registration.Dispose();
  1813. if (t.IsFaulted) {
  1814. Exception e = t.Exception.InnerException;
  1815. source.SetException(e);
  1816. }
  1817. else {
  1818. if (t.IsCanceled) {
  1819. source.SetCanceled();
  1820. }
  1821. else {
  1822. source.SetResult(t.Result);
  1823. }
  1824. }
  1825. }, TaskScheduler.Default);
  1826. }
  1827. catch (Exception e) {
  1828. source.SetException(e);
  1829. }
  1830. return returnedTask;
  1831. }
  1832. public override Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
  1833. {
  1834. return ExecuteReaderAsync(cancellationToken).ContinueWith((executeTask) => {
  1835. TaskCompletionSource<object> source = new TaskCompletionSource<object>();
  1836. if (executeTask.IsCanceled) {
  1837. source.SetCanceled();
  1838. }
  1839. else if (executeTask.IsFaulted) {
  1840. source.SetException(executeTask.Exception.InnerException);
  1841. }
  1842. else {
  1843. SqlDataReader reader = executeTask.Result;
  1844. reader.ReadAsync(cancellationToken).ContinueWith((readTask) => {
  1845. try {
  1846. if (readTask.IsCanceled) {
  1847. reader.Dispose();
  1848. source.SetCanceled();
  1849. }
  1850. else if (readTask.IsFaulted) {
  1851. reader.Dispose();
  1852. source.SetException(readTask.Exception.InnerException);
  1853. }
  1854. else {
  1855. Exception exception = null;
  1856. object result = null;
  1857. try {
  1858. bool more = readTask.Result;
  1859. if (more && reader.FieldCount > 0) {
  1860. try {
  1861. result = reader.GetValue(0);
  1862. }
  1863. catch (Exception e) {
  1864. exception = e;
  1865. }
  1866. }
  1867. }
  1868. finally {
  1869. reader.Dispose();
  1870. }
  1871. if (exception != null) {
  1872. source.SetException(exception);
  1873. }
  1874. else {
  1875. source.SetResult(result);
  1876. }
  1877. }
  1878. }
  1879. catch (Exception e) {
  1880. // exception thrown by Dispose...
  1881. source.SetException(e);
  1882. }
  1883. }, TaskScheduler.Default);
  1884. }
  1885. return source.Task;
  1886. }, TaskScheduler.Default).Unwrap();
  1887. }
  1888. public Task<XmlReader> ExecuteXmlReaderAsync() {
  1889. return ExecuteXmlReaderAsync(CancellationToken.None);
  1890. }
  1891. public Task<XmlReader> ExecuteXmlReaderAsync(CancellationToken cancellationToken) {
  1892. Bid.CorrelationTrace("<sc.SqlCommand.ExecuteXmlReaderAsync|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  1893. SqlConnection.ExecutePermission.Demand();
  1894. TaskCompletionSource<XmlReader> source = new TaskCompletionSource<XmlReader>();
  1895. CancellationTokenRegistration registration = new CancellationTokenRegistration();
  1896. if (cancellationToken.CanBeCanceled) {
  1897. if (cancellationToken.IsCancellationRequested) {
  1898. source.SetCanceled();
  1899. return source.Task;
  1900. }
  1901. registration = cancellationToken.Register(CancelIgnoreFailure);
  1902. }
  1903. Task<XmlReader> returnedTask = source.Task;
  1904. try {
  1905. RegisterForConnectionCloseNotification(ref returnedTask);
  1906. Task<XmlReader>.Factory.FromAsync(BeginExecuteXmlReaderAsync, EndExecuteXmlReaderAsync, null).ContinueWith((t) => {
  1907. registration.Dispose();
  1908. if (t.IsFaulted) {
  1909. Exception e = t.Exception.InnerException;
  1910. source.SetException(e);
  1911. }
  1912. else {
  1913. if (t.IsCanceled) {
  1914. source.SetCanceled();
  1915. }
  1916. else {
  1917. source.SetResult(t.Result);
  1918. }
  1919. }
  1920. }, TaskScheduler.Default);
  1921. }
  1922. catch (Exception e) {
  1923. source.SetException(e);
  1924. }
  1925. return returnedTask;
  1926. }
  1927. // If the user part is quoted, remove first and last brackets and then unquote any right square
  1928. // brackets in the procedure. This is a very simple parser that performs no validation. As
  1929. // with the function below, ideally we should have support from the server for this.
  1930. private static string UnquoteProcedurePart(string part) {
  1931. if ((null != part) && (2 <= part.Length)) {
  1932. if ('[' == part[0] && ']' == part[part.Length-1]) {
  1933. part = part.Substring(1, part.Length-2); // strip outer '[' & ']'
  1934. part = part.Replace("]]", "]"); // undo quoted "]" from "]]" to "]"
  1935. }
  1936. }
  1937. return part;
  1938. }
  1939. // User value in this format: [server].[database].[schema].[sp_foo];1
  1940. // This function should only be passed "[sp_foo];1".
  1941. // This function uses a pretty simple parser that doesn't do any validation.
  1942. // Ideally, we would have support from the server rather than us having to do this.
  1943. private static string UnquoteProcedureName(string name, out object groupNumber) {
  1944. groupNumber = null; // Out param - initialize value to no value.
  1945. string sproc = name;
  1946. if (null != sproc) {
  1947. if (Char.IsDigit(sproc[sproc.Length-1])) { // If last char is a digit, parse.
  1948. int semicolon = sproc.LastIndexOf(';');
  1949. if (semicolon != -1) { // If we found a semicolon, obtain the integer.
  1950. string part = sproc.Substring(semicolon+1);
  1951. int number = 0;
  1952. if (Int32.TryParse(part, out number)) { // No checking, just fail if this doesn't work.
  1953. groupNumber = number;
  1954. sproc = sproc.Substring(0, semicolon);
  1955. }
  1956. }
  1957. }
  1958. sproc = UnquoteProcedurePart(sproc);
  1959. }
  1960. return sproc;
  1961. }
  1962. //index into indirection arrays for columns of interest to DeriveParameters
  1963. private enum ProcParamsColIndex {
  1964. ParameterName = 0,
  1965. ParameterType,
  1966. DataType, // obsolete in katmai, use ManagedDataType instead
  1967. ManagedDataType, // new in katmai
  1968. CharacterMaximumLength,
  1969. NumericPrecision,
  1970. NumericScale,
  1971. TypeCatalogName,
  1972. TypeSchemaName,
  1973. TypeName,
  1974. XmlSchemaCollectionCatalogName,
  1975. XmlSchemaCollectionSchemaName,
  1976. XmlSchemaCollectionName,
  1977. UdtTypeName, // obsolete in Katmai. Holds the actual typename if UDT, since TypeName didn't back then.
  1978. DateTimeScale // new in Katmai
  1979. };
  1980. // Yukon- column ordinals (this array indexed by ProcParamsColIndex
  1981. static readonly internal string[] PreKatmaiProcParamsNames = new string[] {
  1982. "PARAMETER_NAME", // ParameterName,
  1983. "PARAMETER_TYPE", // ParameterType,
  1984. "DATA_TYPE", // DataType
  1985. null, // ManagedDataType, introduced in Katmai
  1986. "CHARACTER_MAXIMUM_LENGTH", // CharacterMaximumLength,
  1987. "NUMERIC_PRECISION", // NumericPrecision,
  1988. "NUMERIC_SCALE", // NumericScale,
  1989. "UDT_CATALOG", // TypeCatalogName,
  1990. "UDT_SCHEMA", // TypeSchemaName,
  1991. "TYPE_NAME", // TypeName,
  1992. "XML_CATALOGNAME", // XmlSchemaCollectionCatalogName,
  1993. "XML_SCHEMANAME", // XmlSchemaCollectionSchemaName,
  1994. "XML_SCHEMACOLLECTIONNAME", // XmlSchemaCollectionName
  1995. "UDT_NAME", // UdtTypeName
  1996. null, // Scale for datetime types with scale, introduced in Katmai
  1997. };
  1998. // Katmai+ column ordinals (this array indexed by ProcParamsColIndex
  1999. static readonly internal string[] KatmaiProcParamsNames = new string[] {
  2000. "PARAMETER_NAME", // ParameterName,
  2001. "PARAMETER_TYPE", // ParameterType,
  2002. null, // DataType, removed from Katmai+
  2003. "MANAGED_DATA_TYPE", // ManagedDataType,
  2004. "CHARACTER_MAXIMUM_LENGTH", // CharacterMaximumLength,
  2005. "NUMERIC_PRECISION", // NumericPrecision,
  2006. "NUMERIC_SCALE", // NumericScale,
  2007. "TYPE_CATALOG_NAME", // TypeCatalogName,
  2008. "TYPE_SCHEMA_NAME", // TypeSchemaName,
  2009. "TYPE_NAME", // TypeName,
  2010. "XML_CATALOGNAME", // XmlSchemaCollectionCatalogName,
  2011. "XML_SCHEMANAME", // XmlSchemaCollectionSchemaName,
  2012. "XML_SCHEMACOLLECTIONNAME", // XmlSchemaCollectionName
  2013. null, // UdtTypeName, removed from Katmai+
  2014. "SS_DATETIME_PRECISION", // Scale for datetime types with scale
  2015. };
  2016. internal void DeriveParameters() {
  2017. switch (this.CommandType) {
  2018. case System.Data.CommandType.Text:
  2019. throw ADP.DeriveParametersNotSupported(this);
  2020. case System.Data.CommandType.StoredProcedure:
  2021. break;
  2022. case System.Data.CommandType.TableDirect:
  2023. // CommandType.TableDirect - do nothing, parameters are not supported
  2024. throw ADP.DeriveParametersNotSupported(this);
  2025. default:
  2026. throw ADP.InvalidCommandType(this.CommandType);
  2027. }
  2028. // validate that we have a valid connection
  2029. ValidateCommand(ADP.DeriveParameters, false /*not async*/);
  2030. // Use common parser for SqlClient and OleDb - parse into 4 parts - Server, Catalog, Schema, ProcedureName
  2031. string[] parsedSProc = MultipartIdentifier.ParseMultipartIdentifier(this.CommandText, "[\"", "]\"", Res.SQL_SqlCommandCommandText, false);
  2032. if (null == parsedSProc[3] || ADP.IsEmpty(parsedSProc[3]))
  2033. {
  2034. throw ADP.NoStoredProcedureExists(this.CommandText);
  2035. }
  2036. Debug.Assert(parsedSProc.Length == 4, "Invalid array length result from SqlCommandBuilder.ParseProcedureName");
  2037. SqlCommand paramsCmd = null;
  2038. StringBuilder cmdText = new StringBuilder();
  2039. // Build call for sp_procedure_params_rowset built of unquoted values from user:
  2040. // [user server, if provided].[user catalog, else current database].[sys if Yukon, else blank].[sp_procedure_params_rowset]
  2041. // Server - pass only if user provided.
  2042. if (!ADP.IsEmpty(parsedSProc[0])) {
  2043. SqlCommandSet.BuildStoredProcedureName(cmdText, parsedSProc[0]);
  2044. cmdText.Append(".");
  2045. }
  2046. // Catalog - pass user provided, otherwise use current database.
  2047. if (ADP.IsEmpty(parsedSProc[1])) {
  2048. parsedSProc[1] = this.Connection.Database;
  2049. }
  2050. SqlCommandSet.BuildStoredProcedureName(cmdText, parsedSProc[1]);
  2051. cmdText.Append(".");
  2052. // Schema - only if Yukon, and then only pass sys. Also - pass managed version of sproc
  2053. // for Yukon, else older sproc.
  2054. string[] colNames;
  2055. bool useManagedDataType;
  2056. if (this.Connection.IsKatmaiOrNewer) {
  2057. // Procedure - [sp_procedure_params_managed]
  2058. cmdText.Append("[sys].[").Append(TdsEnums.SP_PARAMS_MGD10).Append("]");
  2059. colNames = KatmaiProcParamsNames;
  2060. useManagedDataType = true;
  2061. }
  2062. else {
  2063. if (this.Connection.IsYukonOrNewer) {
  2064. // Procedure - [sp_procedure_params_managed]
  2065. cmdText.Append("[sys].[").Append(TdsEnums.SP_PARAMS_MANAGED).Append("]");
  2066. }
  2067. else {
  2068. // Procedure - [sp_procedure_params_rowset]
  2069. cmdText.Append(".[").Append(TdsEnums.SP_PARAMS).Append("]");
  2070. }
  2071. colNames = PreKatmaiProcParamsNames;
  2072. useManagedDataType = false;
  2073. }
  2074. paramsCmd = new SqlCommand(cmdText.ToString(), this.Connection, this.Transaction);
  2075. paramsCmd.CommandType = CommandType.StoredProcedure;
  2076. object groupNumber;
  2077. // Prepare parameters for sp_procedure_params_rowset:
  2078. // 1) procedure name - unquote user value
  2079. // 2) group number - parsed at the time we unquoted procedure name
  2080. // 3) procedure schema - unquote user value
  2081. //
  2082. paramsCmd.Parameters.Add(new SqlParameter("@procedure_name", SqlDbType.NVarChar, 255));
  2083. paramsCmd.Parameters[0].Value = UnquoteProcedureName(parsedSProc[3], out groupNumber); // ProcedureName is 4rd element in parsed array
  2084. if (null != groupNumber) {
  2085. SqlParameter param = paramsCmd.Parameters.Add(new SqlParameter("@group_number", SqlDbType.Int));
  2086. param.Value = groupNumber;
  2087. }
  2088. if (!ADP.IsEmpty(parsedSProc[2])) { // SchemaName is 3rd element in parsed array
  2089. SqlParameter param = paramsCmd.Parameters.Add(new SqlParameter("@procedure_schema", SqlDbType.NVarChar, 255));
  2090. param.Value = UnquoteProcedurePart(parsedSProc[2]);
  2091. }
  2092. SqlDataReader r = null;
  2093. List<SqlParameter> parameters = new List<SqlParameter>();
  2094. bool processFinallyBlock = true;
  2095. try {
  2096. r = paramsCmd.ExecuteReader();
  2097. SqlParameter p = null;
  2098. while (r.Read()) {
  2099. // each row corresponds to a parameter of the stored proc. Fill in all the info
  2100. p = new SqlParameter();
  2101. // name
  2102. p.ParameterName = (string) r[colNames[(int)ProcParamsColIndex.ParameterName]];
  2103. // type
  2104. if (useManagedDataType) {
  2105. p.SqlDbType = (SqlDbType)(short)r[colNames[(int)ProcParamsColIndex.ManagedDataType]];
  2106. // Yukon didn't have as accurate of information as we're getting for Katmai, so re-map a couple of
  2107. // types for backward compatability.
  2108. switch (p.SqlDbType) {
  2109. case SqlDbType.Image:
  2110. case SqlDbType.Timestamp:
  2111. p.SqlDbType = SqlDbType.VarBinary;
  2112. break;
  2113. case SqlDbType.NText:
  2114. p.SqlDbType = SqlDbType.NVarChar;
  2115. break;
  2116. case SqlDbType.Text:
  2117. p.SqlDbType = SqlDbType.VarChar;
  2118. break;
  2119. default:
  2120. break;
  2121. }
  2122. }
  2123. else {
  2124. p.SqlDbType = MetaType.GetSqlDbTypeFromOleDbType((short)r[colNames[(int)ProcParamsColIndex.DataType]],
  2125. ADP.IsNull(r[colNames[(int)ProcParamsColIndex.TypeName]]) ?
  2126. ADP.StrEmpty :
  2127. (string)r[colNames[(int)ProcParamsColIndex.TypeName]]);
  2128. }
  2129. // size
  2130. object a = r[colNames[(int)ProcParamsColIndex.CharacterMaximumLength]];
  2131. if (a is int) {
  2132. int size = (int)a;
  2133. // Map MAX sizes correctly. The Katmai server-side proc sends 0 for these instead of -1.
  2134. // Should be fixed on the Katmai side, but would likely hold up the RI, and is safer to fix here.
  2135. // If we can get the server-side fixed before shipping Katmai, we can remove this mapping.
  2136. if (0 == size &&
  2137. (p.SqlDbType == SqlDbType.NVarChar ||
  2138. p.SqlDbType == SqlDbType.VarBinary ||
  2139. p.SqlDbType == SqlDbType.VarChar)) {
  2140. size = -1;
  2141. }
  2142. p.Size = size;
  2143. }
  2144. // direction
  2145. p.Direction = ParameterDirectionFromOleDbDirection((short)r[colNames[(int)ProcParamsColIndex.ParameterType]]);
  2146. if (p.SqlDbType == SqlDbType.Decimal) {
  2147. p.ScaleInternal = (byte) ((short)r[colNames[(int)ProcParamsColIndex.NumericScale]] & 0xff);
  2148. p.PrecisionInternal = (byte)((short)r[colNames[(int)ProcParamsColIndex.NumericPrecision]] & 0xff);
  2149. }
  2150. // type name for Udt
  2151. if (SqlDbType.Udt == p.SqlDbType) {
  2152. Debug.Assert(this._activeConnection.IsYukonOrNewer,"Invalid datatype token received from pre-yukon server");
  2153. string udtTypeName;
  2154. if (useManagedDataType) {
  2155. udtTypeName = (string)r[colNames[(int)ProcParamsColIndex.TypeName]];
  2156. }
  2157. else {
  2158. udtTypeName = (string)r[colNames[(int)ProcParamsColIndex.UdtTypeName]];
  2159. }
  2160. //read the type name
  2161. p.UdtTypeName = r[colNames[(int)ProcParamsColIndex.TypeCatalogName]]+"."+
  2162. r[colNames[(int)ProcParamsColIndex.TypeSchemaName]]+"."+
  2163. udtTypeName;
  2164. }
  2165. // type name for Structured types (same as for Udt's except assign p.TypeName instead of p.UdtTypeName
  2166. if (SqlDbType.Structured == p.SqlDbType) {
  2167. Debug.Assert(this._activeConnection.IsKatmaiOrNewer,"Invalid datatype token received from pre-katmai server");
  2168. //read the type name
  2169. p.TypeName = r[colNames[(int)ProcParamsColIndex.TypeCatalogName]]+"."+
  2170. r[colNames[(int)ProcParamsColIndex.TypeSchemaName]]+"."+
  2171. r[colNames[(int)ProcParamsColIndex.TypeName]];
  2172. }
  2173. // XmlSchema name for Xml types
  2174. if (SqlDbType.Xml == p.SqlDbType) {
  2175. object value;
  2176. value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionCatalogName]];
  2177. p.XmlSchemaCollectionDatabase = ADP.IsNull(value) ? String.Empty : (string) value;
  2178. value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionSchemaName]];
  2179. p.XmlSchemaCollectionOwningSchema = ADP.IsNull(value) ? String.Empty : (string) value;
  2180. value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionName]];
  2181. p.XmlSchemaCollectionName = ADP.IsNull(value) ? String.Empty : (string) value;
  2182. }
  2183. if (MetaType._IsVarTime(p.SqlDbType)) {
  2184. object value = r[colNames[(int)ProcParamsColIndex.DateTimeScale]];
  2185. if (value is int) {
  2186. p.ScaleInternal = (byte)(((int)value) & 0xff);
  2187. }
  2188. }
  2189. parameters.Add(p);
  2190. }
  2191. }
  2192. catch (Exception e) {
  2193. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  2194. throw;
  2195. }
  2196. finally {
  2197. TdsParser.ReliabilitySection.Assert("unreliable call to DeriveParameters"); // you need to setup for a thread abort somewhere before you call this method
  2198. if (processFinallyBlock) {
  2199. if (null != r)
  2200. r.Close();
  2201. // always unhook the user's connection
  2202. paramsCmd.Connection = null;
  2203. }
  2204. }
  2205. if (parameters.Count == 0) {
  2206. throw ADP.NoStoredProcedureExists(this.CommandText);
  2207. }
  2208. this.Parameters.Clear();
  2209. foreach (SqlParameter temp in parameters) {
  2210. this._parameters.Add(temp);
  2211. }
  2212. }
  2213. private ParameterDirection ParameterDirectionFromOleDbDirection(short oledbDirection) {
  2214. Debug.Assert(oledbDirection >= 1 && oledbDirection <= 4, "invalid parameter direction from params_rowset!");
  2215. switch (oledbDirection) {
  2216. case 2:
  2217. return ParameterDirection.InputOutput;
  2218. case 3:
  2219. return ParameterDirection.Output;
  2220. case 4:
  2221. return ParameterDirection.ReturnValue;
  2222. default:
  2223. return ParameterDirection.Input;
  2224. }
  2225. }
  2226. // get cached metadata
  2227. internal _SqlMetaDataSet MetaData {
  2228. get {
  2229. return _cachedMetaData;
  2230. }
  2231. }
  2232. // Check to see if notificactions auto enlistment is turned on. Enlist if so.
  2233. private void CheckNotificationStateAndAutoEnlist() {
  2234. // First, if auto-enlist is on, check server version and then obtain context if
  2235. // present. If so, auto enlist to the dependency ID given in the context data.
  2236. if (NotificationAutoEnlist) {
  2237. if (_activeConnection.IsYukonOrNewer) { // Only supported for Yukon...
  2238. string notifyContext = SqlNotificationContext();
  2239. if (!ADP.IsEmpty(notifyContext)) {
  2240. // Map to dependency by ID set in context data.
  2241. SqlDependency dependency = SqlDependencyPerAppDomainDispatcher.SingletonInstance.LookupDependencyEntry(notifyContext);
  2242. if (null != dependency) {
  2243. // Add this command to the dependency.
  2244. dependency.AddCommandDependency(this);
  2245. }
  2246. }
  2247. }
  2248. }
  2249. // If we have a notification with a dependency, setup the notification options at this time.
  2250. // If user passes options, then we will always have option data at the time the SqlDependency
  2251. // ctor is called. But, if we are using default queue, then we do not have this data until
  2252. // Start(). Due to this, we always delay setting options until execute.
  2253. // There is a variance in order between Start(), SqlDependency(), and Execute. This is the
  2254. // best way to solve that problem.
  2255. if (null != Notification) {
  2256. if (_sqlDep != null) {
  2257. if (null == _sqlDep.Options) {
  2258. // If null, SqlDependency was not created with options, so we need to obtain default options now.
  2259. // GetDefaultOptions can and will throw under certain conditions.
  2260. // In order to match to the appropriate start - we need 3 pieces of info:
  2261. // 1) server 2) user identity (SQL Auth or Int Sec) 3) database
  2262. SqlDependency.IdentityUserNamePair identityUserName = null;
  2263. // Obtain identity from connection.
  2264. SqlInternalConnectionTds internalConnection = _activeConnection.InnerConnection as SqlInternalConnectionTds;
  2265. if (internalConnection.Identity != null) {
  2266. identityUserName = new SqlDependency.IdentityUserNamePair(internalConnection.Identity, null);
  2267. }
  2268. else {
  2269. identityUserName = new SqlDependency.IdentityUserNamePair(null, internalConnection.ConnectionOptions.UserID);
  2270. }
  2271. Notification.Options = SqlDependency.GetDefaultComposedOptions(_activeConnection.DataSource,
  2272. InternalTdsConnection.ServerProvidedFailOverPartner,
  2273. identityUserName, _activeConnection.Database);
  2274. }
  2275. // Set UserData on notifications, as well as adding to the appdomain dispatcher. The value is
  2276. // computed by an algorithm on the dependency - fixed and will always produce the same value
  2277. // given identical commandtext + parameter values.
  2278. Notification.UserData = _sqlDep.ComputeHashAndAddToDispatcher(this);
  2279. // Maintain server list for SqlDependency.
  2280. _sqlDep.AddToServerList(_activeConnection.DataSource);
  2281. }
  2282. }
  2283. }
  2284. [System.Security.Permissions.SecurityPermission(SecurityAction.Assert, Infrastructure=true)]
  2285. static internal string SqlNotificationContext() {
  2286. SqlConnection.VerifyExecutePermission();
  2287. // since this information is protected, follow it so that it is not exposed to the user.
  2288. // SQLBU 329633, SQLBU 329637
  2289. return (System.Runtime.Remoting.Messaging.CallContext.GetData("MS.SqlDependencyCookie") as string);
  2290. }
  2291. // Tds-specific logic for ExecuteNonQuery run handling
  2292. private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, bool asyncWrite ) {
  2293. Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async");
  2294. bool processFinallyBlock = true;
  2295. try {
  2296. Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout);
  2297. if (reconnectTask != null) {
  2298. long reconnectionStart = ADP.TimerCurrent();
  2299. if (async) {
  2300. TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
  2301. _activeConnection.RegisterWaitingForReconnect(completion.Task);
  2302. _reconnectionCompletionSource = completion;
  2303. CancellationTokenSource timeoutCTS = new CancellationTokenSource();
  2304. AsyncHelper.SetTimeoutException(completion, timeout, SQL.CR_ReconnectTimeout, timeoutCTS.Token);
  2305. AsyncHelper.ContinueTask(reconnectTask, completion,
  2306. () => {
  2307. if (completion.Task.IsCompleted) {
  2308. return;
  2309. }
  2310. Interlocked.CompareExchange(ref _reconnectionCompletionSource, null, completion);
  2311. timeoutCTS.Cancel();
  2312. Task subTask = RunExecuteNonQueryTds(methodName, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart), asyncWrite);
  2313. if (subTask == null) {
  2314. completion.SetResult(null);
  2315. }
  2316. else {
  2317. AsyncHelper.ContinueTask(subTask, completion, () => completion.SetResult(null));
  2318. }
  2319. }, connectionToAbort: _activeConnection);
  2320. return completion.Task;
  2321. }
  2322. else {
  2323. AsyncHelper.WaitForCompletion(reconnectTask, timeout, () => { throw SQL.CR_ReconnectTimeout(); });
  2324. timeout = TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart);
  2325. }
  2326. }
  2327. if (asyncWrite) {
  2328. _activeConnection.AddWeakReference(this, SqlReferenceCollection.CommandTag);
  2329. }
  2330. GetStateObject();
  2331. // we just send over the raw text with no annotation
  2332. // no parameters are sent over
  2333. // no data reader is returned
  2334. // use this overload for "batch SQL" tds token type
  2335. Bid.Trace("<sc.SqlCommand.ExecuteNonQuery|INFO> %d#, Command executed as SQLBATCH.\n", ObjectID);
  2336. Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true);
  2337. Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
  2338. NotifyDependency();
  2339. if (async) {
  2340. _activeConnection.GetOpenTdsConnection(methodName).IncrementAsyncCount();
  2341. }
  2342. else {
  2343. bool dataReady;
  2344. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2345. bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady);
  2346. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2347. }
  2348. }
  2349. catch (Exception e) {
  2350. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  2351. throw;
  2352. }
  2353. finally {
  2354. TdsParser.ReliabilitySection.Assert("unreliable call to RunExecuteNonQueryTds"); // you need to setup for a thread abort somewhere before you call this method
  2355. if (processFinallyBlock && !async) {
  2356. // When executing Async, we need to keep the _stateObj alive...
  2357. PutStateObject();
  2358. }
  2359. }
  2360. return null;
  2361. }
  2362. // Smi-specific logic for ExecuteNonQuery
  2363. private void RunExecuteNonQuerySmi( bool sendToPipe ) {
  2364. SqlInternalConnectionSmi innerConnection = InternalSmiConnection;
  2365. // Set it up, process all of the events, and we're done!
  2366. SmiRequestExecutor requestExecutor = null;
  2367. try {
  2368. requestExecutor = SetUpSmiRequest(innerConnection);
  2369. SmiExecuteType execType;
  2370. if ( sendToPipe )
  2371. execType = SmiExecuteType.ToPipe;
  2372. else
  2373. execType = SmiExecuteType.NonQuery;
  2374. SmiEventStream eventStream = null;
  2375. // Don't need a CER here because caller already has one that will doom the
  2376. // connection if it's a finally-skipping type of problem.
  2377. bool processFinallyBlock = true;
  2378. try {
  2379. long transactionId;
  2380. SysTx.Transaction transaction;
  2381. innerConnection.GetCurrentTransactionPair(out transactionId, out transaction);
  2382. if (Bid.AdvancedOn) {
  2383. Bid.Trace("<sc.SqlCommand.RunExecuteNonQuerySmi|ADV> %d#, innerConnection=%d#, transactionId=0x%I64x, cmdBehavior=%d.\n", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default);
  2384. }
  2385. if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) {
  2386. eventStream = requestExecutor.Execute(
  2387. innerConnection.SmiConnection,
  2388. transactionId,
  2389. transaction,
  2390. CommandBehavior.Default,
  2391. execType);
  2392. }
  2393. else {
  2394. eventStream = requestExecutor.Execute(
  2395. innerConnection.SmiConnection,
  2396. transactionId,
  2397. CommandBehavior.Default,
  2398. execType);
  2399. }
  2400. while ( eventStream.HasEvents ) {
  2401. eventStream.ProcessEvent( EventSink );
  2402. }
  2403. }
  2404. catch (Exception e) {
  2405. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  2406. throw;
  2407. }
  2408. finally {
  2409. TdsParser.ReliabilitySection.Assert("unreliable call to RunExecuteNonQuerySmi"); // you need to setup for a thread abort somewhere before you call this method
  2410. if (null != eventStream && processFinallyBlock) {
  2411. eventStream.Close( EventSink );
  2412. }
  2413. }
  2414. EventSink.ProcessMessagesAndThrow();
  2415. }
  2416. finally {
  2417. if (requestExecutor != null) {
  2418. requestExecutor.Close(EventSink);
  2419. EventSink.ProcessMessagesAndThrow(ignoreNonFatalMessages: true);
  2420. }
  2421. }
  2422. }
  2423. internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method) {
  2424. Task unused; // sync execution
  2425. SqlDataReader reader = RunExecuteReader(cmdBehavior, runBehavior, returnStream, method, completion:null, timeout:CommandTimeout, task:out unused);
  2426. Debug.Assert(unused == null, "returned task during synchronous execution");
  2427. return reader;
  2428. }
  2429. // task is created in case of pending asynchronous write, returned SqlDataReader should not be utilized until that task is complete
  2430. internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method, TaskCompletionSource<object> completion, int timeout, out Task task, bool asyncWrite = false) {
  2431. bool async = (null != completion);
  2432. task = null;
  2433. _rowsAffected = -1;
  2434. if (0 != (CommandBehavior.SingleRow & cmdBehavior)) {
  2435. // CommandBehavior.SingleRow implies CommandBehavior.SingleResult
  2436. cmdBehavior |= CommandBehavior.SingleResult;
  2437. }
  2438. // @devnote: this function may throw for an invalid connection
  2439. // @devnote: returns false for empty command text
  2440. ValidateCommand(method, async);
  2441. CheckNotificationStateAndAutoEnlist(); // Only call after validate - requires non null connection!
  2442. TdsParser bestEffortCleanupTarget = null;
  2443. // This section needs to occur AFTER ValidateCommand - otherwise it will AV without a connection.
  2444. RuntimeHelpers.PrepareConstrainedRegions();
  2445. try {
  2446. #if DEBUG
  2447. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  2448. RuntimeHelpers.PrepareConstrainedRegions();
  2449. try {
  2450. tdsReliabilitySection.Start();
  2451. #else
  2452. {
  2453. #endif //DEBUG
  2454. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  2455. SqlStatistics statistics = Statistics;
  2456. if (null != statistics) {
  2457. if ((!this.IsDirty && this.IsPrepared && !_hiddenPrepare)
  2458. || (this.IsPrepared && _execType == EXECTYPE.PREPAREPENDING))
  2459. {
  2460. statistics.SafeIncrement(ref statistics._preparedExecs);
  2461. }
  2462. else {
  2463. statistics.SafeIncrement(ref statistics._unpreparedExecs);
  2464. }
  2465. }
  2466. if ( _activeConnection.IsContextConnection ) {
  2467. return RunExecuteReaderSmi( cmdBehavior, runBehavior, returnStream );
  2468. }
  2469. else {
  2470. return RunExecuteReaderTds( cmdBehavior, runBehavior, returnStream, async, timeout, out task, asyncWrite && async);
  2471. }
  2472. }
  2473. #if DEBUG
  2474. finally {
  2475. tdsReliabilitySection.Stop();
  2476. }
  2477. #endif //DEBUG
  2478. }
  2479. catch (System.OutOfMemoryException e) {
  2480. _activeConnection.Abort(e);
  2481. throw;
  2482. }
  2483. catch (System.StackOverflowException e) {
  2484. _activeConnection.Abort(e);
  2485. throw;
  2486. }
  2487. catch (System.Threading.ThreadAbortException e) {
  2488. _activeConnection.Abort(e);
  2489. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  2490. throw;
  2491. }
  2492. }
  2493. private SqlDataReader RunExecuteReaderTds( CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, bool async, int timeout, out Task task, bool asyncWrite, SqlDataReader ds=null) {
  2494. Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async");
  2495. if (ds == null && returnStream) {
  2496. ds = new SqlDataReader(this, cmdBehavior);
  2497. }
  2498. Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout);
  2499. if (reconnectTask != null) {
  2500. long reconnectionStart = ADP.TimerCurrent();
  2501. if (async) {
  2502. TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
  2503. _activeConnection.RegisterWaitingForReconnect(completion.Task);
  2504. _reconnectionCompletionSource = completion;
  2505. CancellationTokenSource timeoutCTS = new CancellationTokenSource();
  2506. AsyncHelper.SetTimeoutException(completion, timeout, SQL.CR_ReconnectTimeout, timeoutCTS.Token);
  2507. AsyncHelper.ContinueTask(reconnectTask, completion,
  2508. () => {
  2509. if (completion.Task.IsCompleted) {
  2510. return;
  2511. }
  2512. Interlocked.CompareExchange(ref _reconnectionCompletionSource, null, completion);
  2513. timeoutCTS.Cancel();
  2514. Task subTask;
  2515. RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart), out subTask, asyncWrite, ds);
  2516. if (subTask == null) {
  2517. completion.SetResult(null);
  2518. }
  2519. else {
  2520. AsyncHelper.ContinueTask(subTask, completion, () => completion.SetResult(null));
  2521. }
  2522. }, connectionToAbort: _activeConnection);
  2523. task = completion.Task;
  2524. return ds;
  2525. }
  2526. else {
  2527. AsyncHelper.WaitForCompletion(reconnectTask, timeout, () => { throw SQL.CR_ReconnectTimeout(); });
  2528. timeout = TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart);
  2529. }
  2530. }
  2531. // make sure we have good parameter information
  2532. // prepare the command
  2533. // execute
  2534. Debug.Assert(null != _activeConnection.Parser, "TdsParser class should not be null in Command.Execute!");
  2535. bool inSchema = (0 != (cmdBehavior & CommandBehavior.SchemaOnly));
  2536. // create a new RPC
  2537. _SqlRPC rpc=null;
  2538. task = null;
  2539. string optionSettings = null;
  2540. bool processFinallyBlock = true;
  2541. bool decrementAsyncCountOnFailure = false;
  2542. if (async) {
  2543. _activeConnection.GetOpenTdsConnection().IncrementAsyncCount();
  2544. decrementAsyncCountOnFailure = true;
  2545. }
  2546. try {
  2547. if (asyncWrite) {
  2548. _activeConnection.AddWeakReference(this, SqlReferenceCollection.CommandTag);
  2549. }
  2550. GetStateObject();
  2551. Task writeTask = null;
  2552. if (BatchRPCMode) {
  2553. Debug.Assert(inSchema == false, "Batch RPC does not support schema only command beahvior");
  2554. Debug.Assert(!IsPrepared, "Batch RPC should not be prepared!");
  2555. Debug.Assert(!IsDirty, "Batch RPC should not be marked as dirty!");
  2556. //Currently returnStream is always false, but we may want to return a Reader later.
  2557. //if (returnStream) {
  2558. // Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as batch RPC.\n", ObjectID);
  2559. //}
  2560. Debug.Assert(_SqlRPCBatchArray != null, "RunExecuteReader rpc array not provided");
  2561. writeTask = _stateObj.Parser.TdsExecuteRPC(_SqlRPCBatchArray, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite );
  2562. }
  2563. else if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) {
  2564. // Send over SQL Batch command if we are not a stored proc and have no parameters
  2565. // MDAC
  2566. Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!");
  2567. if (returnStream) {
  2568. Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as SQLBATCH.\n", ObjectID);
  2569. }
  2570. string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior);
  2571. writeTask = _stateObj.Parser.TdsExecuteSQLBatch(text, timeout, this.Notification, _stateObj, sync: !asyncWrite);
  2572. }
  2573. else if (System.Data.CommandType.Text == this.CommandType) {
  2574. if (this.IsDirty) {
  2575. Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters
  2576. //
  2577. // someone changed the command text or the parameter schema so we must unprepare the command
  2578. //
  2579. // remeber that IsDirty includes test for IsPrepared!
  2580. if(_execType == EXECTYPE.PREPARED) {
  2581. _hiddenPrepare = true;
  2582. }
  2583. Unprepare();
  2584. IsDirty = false;
  2585. }
  2586. if (_execType == EXECTYPE.PREPARED) {
  2587. Debug.Assert(this.IsPrepared && (_prepareHandle != -1), "invalid attempt to call sp_execute without a handle!");
  2588. rpc = BuildExecute(inSchema);
  2589. }
  2590. else if (_execType == EXECTYPE.PREPAREPENDING) {
  2591. Debug.Assert(_activeConnection.IsShiloh, "Invalid attempt to call sp_prepexec on non 7.x server");
  2592. rpc = BuildPrepExec(cmdBehavior);
  2593. // next time through, only do an exec
  2594. _execType = EXECTYPE.PREPARED;
  2595. _preparedConnectionCloseCount = _activeConnection.CloseCount;
  2596. _preparedConnectionReconnectCount = _activeConnection.ReconnectCount;
  2597. // mark ourselves as preparing the command
  2598. _inPrepare = true;
  2599. }
  2600. else {
  2601. Debug.Assert(_execType == EXECTYPE.UNPREPARED, "Invalid execType!");
  2602. BuildExecuteSql(cmdBehavior, null, _parameters, ref rpc);
  2603. }
  2604. // if shiloh, then set NOMETADATA_UNLESSCHANGED flag
  2605. if (_activeConnection.IsShiloh)
  2606. rpc.options = TdsEnums.RPC_NOMETADATA;
  2607. if (returnStream) {
  2608. Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as RPC.\n", ObjectID);
  2609. }
  2610. //
  2611. Debug.Assert(_rpcArrayOf1[0] == rpc);
  2612. writeTask = _stateObj.Parser.TdsExecuteRPC(_rpcArrayOf1, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync:!asyncWrite);
  2613. }
  2614. else {
  2615. Debug.Assert(this.CommandType == System.Data.CommandType.StoredProcedure, "unknown command type!");
  2616. // note: invalid asserts on Shiloh. On 8.0 (Shiloh) and above a command is ALWAYS prepared
  2617. // and IsDirty is always set if there are changes and the command is marked Prepared!
  2618. Debug.Assert(IsShiloh || !IsPrepared, "RPC should not be prepared!");
  2619. Debug.Assert(IsShiloh || !IsDirty, "RPC should not be marked as dirty!");
  2620. BuildRPC(inSchema, _parameters, ref rpc);
  2621. // if we need to augment the command because a user has changed the command behavior (e.g. FillSchema)
  2622. // then batch sql them over. This is inefficient (3 round trips) but the only way we can get metadata only from
  2623. // a stored proc
  2624. optionSettings = GetSetOptionsString(cmdBehavior);
  2625. if (returnStream) {
  2626. Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as RPC.\n", ObjectID);
  2627. }
  2628. // turn set options ON
  2629. if (null != optionSettings) {
  2630. Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(optionSettings, timeout, this.Notification, _stateObj, sync: true);
  2631. Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
  2632. bool dataReady;
  2633. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2634. bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady);
  2635. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2636. // and turn OFF when the ds exhausts the stream on Close()
  2637. optionSettings = GetResetOptionsString(cmdBehavior);
  2638. }
  2639. // turn debugging on
  2640. _activeConnection.CheckSQLDebug();
  2641. // execute sp
  2642. Debug.Assert(_rpcArrayOf1[0] == rpc);
  2643. writeTask=_stateObj.Parser.TdsExecuteRPC(_rpcArrayOf1, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync:!asyncWrite);
  2644. }
  2645. Debug.Assert(writeTask == null || async, "Returned task in sync mode");
  2646. if (async) {
  2647. decrementAsyncCountOnFailure = false;
  2648. if (writeTask != null) {
  2649. task = AsyncHelper.CreateContinuationTask(writeTask, () => {
  2650. _activeConnection.GetOpenTdsConnection(); // it will throw if connection is closed
  2651. cachedAsyncState.SetAsyncReaderState(ds, runBehavior, optionSettings);
  2652. },
  2653. onFailure: (exc) => {
  2654. _activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
  2655. } );
  2656. }
  2657. else {
  2658. cachedAsyncState.SetAsyncReaderState(ds, runBehavior, optionSettings);
  2659. }
  2660. }
  2661. else {
  2662. // Always execute - even if no reader!
  2663. FinishExecuteReader(ds, runBehavior, optionSettings);
  2664. }
  2665. }
  2666. catch (Exception e) {
  2667. processFinallyBlock = ADP.IsCatchableExceptionType (e);
  2668. if (decrementAsyncCountOnFailure) {
  2669. SqlInternalConnectionTds innerConnectionTds = (_activeConnection.InnerConnection as SqlInternalConnectionTds);
  2670. if (null != innerConnectionTds) { // it may be closed
  2671. innerConnectionTds.DecrementAsyncCount();
  2672. }
  2673. }
  2674. throw;
  2675. }
  2676. finally {
  2677. TdsParser.ReliabilitySection.Assert("unreliable call to RunExecuteReaderTds"); // you need to setup for a thread abort somewhere before you call this method
  2678. if (processFinallyBlock && !async) {
  2679. // When executing async, we need to keep the _stateObj alive...
  2680. PutStateObject();
  2681. }
  2682. }
  2683. Debug.Assert(async || null == _stateObj, "non-null state object in RunExecuteReader");
  2684. return ds;
  2685. }
  2686. private SqlDataReader RunExecuteReaderSmi( CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream ) {
  2687. SqlInternalConnectionSmi innerConnection = InternalSmiConnection;
  2688. SmiEventStream eventStream = null;
  2689. SqlDataReader ds = null;
  2690. SmiRequestExecutor requestExecutor = null;
  2691. try {
  2692. // Set it up, process all of the events, and we're done!
  2693. requestExecutor = SetUpSmiRequest( innerConnection );
  2694. long transactionId;
  2695. SysTx.Transaction transaction;
  2696. innerConnection.GetCurrentTransactionPair(out transactionId, out transaction);
  2697. if (Bid.AdvancedOn) {
  2698. Bid.Trace("<sc.SqlCommand.RunExecuteReaderSmi|ADV> %d#, innerConnection=%d#, transactionId=0x%I64x, commandBehavior=%d.\n", ObjectID, innerConnection.ObjectID, transactionId, (int)cmdBehavior);
  2699. }
  2700. if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) {
  2701. eventStream = requestExecutor.Execute(
  2702. innerConnection.SmiConnection,
  2703. transactionId,
  2704. transaction,
  2705. cmdBehavior,
  2706. SmiExecuteType.Reader
  2707. );
  2708. }
  2709. else {
  2710. eventStream = requestExecutor.Execute(
  2711. innerConnection.SmiConnection,
  2712. transactionId,
  2713. cmdBehavior,
  2714. SmiExecuteType.Reader
  2715. );
  2716. }
  2717. if ( ( runBehavior & RunBehavior.UntilDone ) != 0 ) {
  2718. // Consume the results
  2719. while( eventStream.HasEvents ) {
  2720. eventStream.ProcessEvent( EventSink );
  2721. }
  2722. eventStream.Close( EventSink );
  2723. }
  2724. if ( returnStream ) {
  2725. ds = new SqlDataReaderSmi( eventStream, this, cmdBehavior, innerConnection, EventSink, requestExecutor );
  2726. ds.NextResult(); // Position on first set of results
  2727. _activeConnection.AddWeakReference(ds, SqlReferenceCollection.DataReaderTag);
  2728. }
  2729. EventSink.ProcessMessagesAndThrow();
  2730. }
  2731. catch (Exception e) {
  2732. // VSTS 159716 - we do not want to handle ThreadAbort, OutOfMemory or similar critical exceptions
  2733. // because the state of used objects might remain invalid in this case
  2734. if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
  2735. throw;
  2736. }
  2737. if (null != eventStream) {
  2738. eventStream.Close( EventSink ); // UNDONE: should cancel instead!
  2739. }
  2740. if (requestExecutor != null) {
  2741. requestExecutor.Close(EventSink);
  2742. EventSink.ProcessMessagesAndThrow(ignoreNonFatalMessages: true);
  2743. }
  2744. throw;
  2745. }
  2746. return ds;
  2747. }
  2748. private SqlDataReader CompleteAsyncExecuteReader() {
  2749. SqlDataReader ds = cachedAsyncState.CachedAsyncReader; // should not be null
  2750. bool processFinallyBlock = true;
  2751. try {
  2752. FinishExecuteReader(ds, cachedAsyncState.CachedRunBehavior, cachedAsyncState.CachedSetOptions);
  2753. }
  2754. catch (Exception e) {
  2755. processFinallyBlock = ADP.IsCatchableExceptionType(e);
  2756. throw;
  2757. }
  2758. finally {
  2759. TdsParser.ReliabilitySection.Assert("unreliable call to CompleteAsyncExecuteReader"); // you need to setup for a thread abort somewhere before you call this method
  2760. if (processFinallyBlock) {
  2761. cachedAsyncState.ResetAsyncState();
  2762. PutStateObject();
  2763. }
  2764. }
  2765. return ds;
  2766. }
  2767. private void FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, string resetOptionsString) {
  2768. // always wrap with a try { FinishExecuteReader(...) } finally { PutStateObject(); }
  2769. NotifyDependency();
  2770. if (runBehavior == RunBehavior.UntilDone) {
  2771. try {
  2772. bool dataReady;
  2773. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2774. bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, ds, null, _stateObj, out dataReady);
  2775. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2776. }
  2777. catch (Exception e) {
  2778. //
  2779. if (ADP.IsCatchableExceptionType(e)) {
  2780. if (_inPrepare) {
  2781. // The flag is expected to be reset by OnReturnValue. We should receive
  2782. // the handle unless command execution failed. If fail, move back to pending
  2783. // state.
  2784. _inPrepare = false; // reset the flag
  2785. IsDirty = true; // mark command as dirty so it will be prepared next time we're comming through
  2786. _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending
  2787. }
  2788. if (null != ds) {
  2789. ds.Close();
  2790. }
  2791. }
  2792. throw;
  2793. }
  2794. }
  2795. // bind the parser to the reader if we get this far
  2796. if (ds != null) {
  2797. ds.Bind(_stateObj);
  2798. _stateObj = null; // the reader now owns this...
  2799. ds.ResetOptionsString = resetOptionsString;
  2800. //
  2801. // bind this reader to this connection now
  2802. _activeConnection.AddWeakReference(ds, SqlReferenceCollection.DataReaderTag);
  2803. // force this command to start reading data off the wire.
  2804. // this will cause an error to be reported at Execute() time instead of Read() time
  2805. // if the command is not set.
  2806. try {
  2807. _cachedMetaData = ds.MetaData;
  2808. ds.IsInitialized = true; // Webdata 104560
  2809. }
  2810. catch (Exception e) {
  2811. //
  2812. if (ADP.IsCatchableExceptionType(e)) {
  2813. if (_inPrepare) {
  2814. // The flag is expected to be reset by OnReturnValue. We should receive
  2815. // the handle unless command execution failed. If fail, move back to pending
  2816. // state.
  2817. _inPrepare = false; // reset the flag
  2818. IsDirty = true; // mark command as dirty so it will be prepared next time we're comming through
  2819. _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending
  2820. }
  2821. ds.Close();
  2822. }
  2823. throw;
  2824. }
  2825. }
  2826. }
  2827. private void NotifyDependency() {
  2828. if (_sqlDep != null) {
  2829. _sqlDep.StartTimer(Notification);
  2830. }
  2831. }
  2832. public SqlCommand Clone() {
  2833. SqlCommand clone = new SqlCommand(this);
  2834. Bid.Trace("<sc.SqlCommand.Clone|API> %d#, clone=%d#\n", ObjectID, clone.ObjectID);
  2835. return clone;
  2836. }
  2837. object ICloneable.Clone() {
  2838. return Clone();
  2839. }
  2840. private void RegisterForConnectionCloseNotification<T>(ref Task<T> outterTask) {
  2841. SqlConnection connection = _activeConnection;
  2842. if (connection == null) {
  2843. // No connection
  2844. throw ADP.ClosedConnectionError();
  2845. }
  2846. connection.RegisterForConnectionCloseNotification<T>(ref outterTask, this, SqlReferenceCollection.CommandTag);
  2847. }
  2848. // validates that a command has commandText and a non-busy open connection
  2849. // throws exception for error case, returns false if the commandText is empty
  2850. private void ValidateCommand(string method, bool async) {
  2851. if (null == _activeConnection) {
  2852. throw ADP.ConnectionRequired(method);
  2853. }
  2854. // Ensure that the connection is open and that the Parser is in the correct state
  2855. SqlInternalConnectionTds tdsConnection = _activeConnection.InnerConnection as SqlInternalConnectionTds;
  2856. if (tdsConnection != null) {
  2857. var parser = tdsConnection.Parser;
  2858. if ((parser == null) || (parser.State == TdsParserState.Closed)) {
  2859. throw ADP.OpenConnectionRequired(method, ConnectionState.Closed);
  2860. }
  2861. else if (parser.State != TdsParserState.OpenLoggedIn) {
  2862. throw ADP.OpenConnectionRequired(method, ConnectionState.Broken);
  2863. }
  2864. }
  2865. else if (_activeConnection.State == ConnectionState.Closed) {
  2866. throw ADP.OpenConnectionRequired(method, ConnectionState.Closed);
  2867. }
  2868. else if (_activeConnection.State == ConnectionState.Broken) {
  2869. throw ADP.OpenConnectionRequired(method, ConnectionState.Broken);
  2870. }
  2871. ValidateAsyncCommand();
  2872. TdsParser bestEffortCleanupTarget = null;
  2873. RuntimeHelpers.PrepareConstrainedRegions();
  2874. try {
  2875. #if DEBUG
  2876. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  2877. RuntimeHelpers.PrepareConstrainedRegions();
  2878. try {
  2879. tdsReliabilitySection.Start();
  2880. #else
  2881. {
  2882. #endif //DEBUG
  2883. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  2884. // close any non MARS dead readers, if applicable, and then throw if still busy.
  2885. // Throw if we have a live reader on this command
  2886. _activeConnection.ValidateConnectionForExecute(method, this);
  2887. }
  2888. #if DEBUG
  2889. finally {
  2890. tdsReliabilitySection.Stop();
  2891. }
  2892. #endif //DEBUG
  2893. }
  2894. catch (System.OutOfMemoryException e)
  2895. {
  2896. _activeConnection.Abort(e);
  2897. throw;
  2898. }
  2899. catch (System.StackOverflowException e)
  2900. {
  2901. _activeConnection.Abort(e);
  2902. throw;
  2903. }
  2904. catch (System.Threading.ThreadAbortException e)
  2905. {
  2906. _activeConnection.Abort(e);
  2907. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  2908. throw;
  2909. }
  2910. // Check to see if the currently set transaction has completed. If so,
  2911. // null out our local reference.
  2912. if (null != _transaction && _transaction.Connection == null)
  2913. _transaction = null;
  2914. // throw if the connection is in a transaction but there is no
  2915. // locally assigned transaction object
  2916. if (_activeConnection.HasLocalTransactionFromAPI && (null == _transaction))
  2917. throw ADP.TransactionRequired(method);
  2918. // if we have a transaction, check to ensure that the active
  2919. // connection property matches the connection associated with
  2920. // the transaction
  2921. if (null != _transaction && _activeConnection != _transaction.Connection)
  2922. throw ADP.TransactionConnectionMismatch();
  2923. if (ADP.IsEmpty(this.CommandText))
  2924. throw ADP.CommandTextRequired(method);
  2925. // Notification property must be null for pre-Yukon connections
  2926. if ((Notification != null) && !_activeConnection.IsYukonOrNewer) {
  2927. throw SQL.NotificationsRequireYukon();
  2928. }
  2929. if ((async) && (_activeConnection.IsContextConnection)) {
  2930. // Async not supported on Context Connections
  2931. throw SQL.NotAvailableOnContextConnection();
  2932. }
  2933. }
  2934. private void ValidateAsyncCommand() {
  2935. //
  2936. if (cachedAsyncState.PendingAsyncOperation) { // Enforce only one pending async execute at a time.
  2937. if (cachedAsyncState.IsActiveConnectionValid(_activeConnection)) {
  2938. throw SQL.PendingBeginXXXExists();
  2939. }
  2940. else {
  2941. _stateObj = null; // Session was re-claimed by session pool upon connection close.
  2942. cachedAsyncState.ResetAsyncState();
  2943. }
  2944. }
  2945. }
  2946. private void GetStateObject(TdsParser parser = null) {
  2947. Debug.Assert (null == _stateObj,"StateObject not null on GetStateObject");
  2948. Debug.Assert (null != _activeConnection, "no active connection?");
  2949. if (_pendingCancel) {
  2950. _pendingCancel = false; // Not really needed, but we'll reset anyways.
  2951. // If a pendingCancel exists on the object, we must have had a Cancel() call
  2952. // between the point that we entered an Execute* API and the point in Execute* that
  2953. // we proceeded to call this function and obtain a stateObject. In that case,
  2954. // we now throw a cancelled error.
  2955. throw SQL.OperationCancelled();
  2956. }
  2957. if (parser == null) {
  2958. parser = _activeConnection.Parser;
  2959. if ((parser == null) || (parser.State == TdsParserState.Broken) || (parser.State == TdsParserState.Closed)) {
  2960. // Connection's parser is null as well, therefore we must be closed
  2961. throw ADP.ClosedConnectionError();
  2962. }
  2963. }
  2964. TdsParserStateObject stateObj = parser.GetSession(this);
  2965. stateObj.StartSession(ObjectID);
  2966. _stateObj = stateObj;
  2967. if (_pendingCancel) {
  2968. _pendingCancel = false; // Not really needed, but we'll reset anyways.
  2969. // If a pendingCancel exists on the object, we must have had a Cancel() call
  2970. // between the point that we entered this function and the point where we obtained
  2971. // and actually assigned the stateObject to the local member. It is possible
  2972. // that the flag is set as well as a call to stateObj.Cancel - though that would
  2973. // be a no-op. So - throw.
  2974. throw SQL.OperationCancelled();
  2975. }
  2976. }
  2977. private void ReliablePutStateObject() {
  2978. TdsParser bestEffortCleanupTarget = null;
  2979. RuntimeHelpers.PrepareConstrainedRegions();
  2980. try {
  2981. #if DEBUG
  2982. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  2983. RuntimeHelpers.PrepareConstrainedRegions();
  2984. try {
  2985. tdsReliabilitySection.Start();
  2986. #else
  2987. {
  2988. #endif //DEBUG
  2989. bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection);
  2990. PutStateObject();
  2991. }
  2992. #if DEBUG
  2993. finally {
  2994. tdsReliabilitySection.Stop();
  2995. }
  2996. #endif //DEBUG
  2997. }
  2998. catch (System.OutOfMemoryException e)
  2999. {
  3000. _activeConnection.Abort(e);
  3001. throw;
  3002. }
  3003. catch (System.StackOverflowException e)
  3004. {
  3005. _activeConnection.Abort(e);
  3006. throw;
  3007. }
  3008. catch (System.Threading.ThreadAbortException e)
  3009. {
  3010. _activeConnection.Abort(e);
  3011. SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
  3012. throw;
  3013. }
  3014. }
  3015. private void PutStateObject() {
  3016. TdsParserStateObject stateObj = _stateObj;
  3017. _stateObj = null;
  3018. if (null != stateObj) {
  3019. stateObj.CloseSession();
  3020. }
  3021. }
  3022. internal void OnDoneProc() { // called per rpc batch complete
  3023. if (BatchRPCMode) {
  3024. // track the records affected for the just completed rpc batch
  3025. // _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches
  3026. _SqlRPCBatchArray[_currentlyExecutingBatch].cumulativeRecordsAffected = _rowsAffected;
  3027. _SqlRPCBatchArray[_currentlyExecutingBatch].recordsAffected =
  3028. (((0 < _currentlyExecutingBatch) && (0 <= _rowsAffected))
  3029. ? (_rowsAffected - Math.Max(_SqlRPCBatchArray[_currentlyExecutingBatch-1].cumulativeRecordsAffected, 0))
  3030. : _rowsAffected);
  3031. // track the error collection (not available from TdsParser after ExecuteNonQuery)
  3032. // and the which errors are associated with the just completed rpc batch
  3033. _SqlRPCBatchArray[_currentlyExecutingBatch].errorsIndexStart =
  3034. ((0 < _currentlyExecutingBatch)
  3035. ? _SqlRPCBatchArray[_currentlyExecutingBatch-1].errorsIndexEnd
  3036. : 0);
  3037. _SqlRPCBatchArray[_currentlyExecutingBatch].errorsIndexEnd = _stateObj.ErrorCount;
  3038. _SqlRPCBatchArray[_currentlyExecutingBatch].errors = _stateObj._errors;
  3039. // track the warning collection (not available from TdsParser after ExecuteNonQuery)
  3040. // and the which warnings are associated with the just completed rpc batch
  3041. _SqlRPCBatchArray[_currentlyExecutingBatch].warningsIndexStart =
  3042. ((0 < _currentlyExecutingBatch)
  3043. ? _SqlRPCBatchArray[_currentlyExecutingBatch-1].warningsIndexEnd
  3044. : 0);
  3045. _SqlRPCBatchArray[_currentlyExecutingBatch].warningsIndexEnd = _stateObj.WarningCount;
  3046. _SqlRPCBatchArray[_currentlyExecutingBatch].warnings = _stateObj._warnings;
  3047. _currentlyExecutingBatch++;
  3048. Debug.Assert(_parameterCollectionList.Count >= _currentlyExecutingBatch, "OnDoneProc: Too many DONEPROC events");
  3049. }
  3050. }
  3051. //
  3052. //
  3053. internal void OnReturnStatus(int status) {
  3054. if (_inPrepare)
  3055. return;
  3056. SqlParameterCollection parameters = _parameters;
  3057. if (BatchRPCMode) {
  3058. if (_parameterCollectionList.Count > _currentlyExecutingBatch) {
  3059. parameters = _parameterCollectionList[_currentlyExecutingBatch];
  3060. }
  3061. else {
  3062. Debug.Assert(false, "OnReturnStatus: SqlCommand got too many DONEPROC events");
  3063. parameters = null;
  3064. }
  3065. }
  3066. // see if a return value is bound
  3067. int count = GetParameterCount(parameters);
  3068. for (int i = 0; i < count; i++) {
  3069. SqlParameter parameter = parameters[i];
  3070. if (parameter.Direction == ParameterDirection.ReturnValue) {
  3071. object v = parameter.Value;
  3072. // if the user bound a sqlint32 (the only valid one for status, use it)
  3073. if ( (null != v) && (v.GetType() == typeof(SqlInt32)) ) {
  3074. parameter.Value = new SqlInt32(status); // value type
  3075. }
  3076. else {
  3077. parameter.Value = status;
  3078. }
  3079. break;
  3080. }
  3081. }
  3082. }
  3083. //
  3084. // Move the return value to the corresponding output parameter.
  3085. // Return parameters are sent in the order in which they were defined in the procedure.
  3086. // If named, match the parameter name, otherwise fill in based on ordinal position.
  3087. // If the parameter is not bound, then ignore the return value.
  3088. //
  3089. internal void OnReturnValue(SqlReturnValue rec) {
  3090. if (_inPrepare) {
  3091. if (!rec.value.IsNull) {
  3092. _prepareHandle = rec.value.Int32;
  3093. }
  3094. _inPrepare = false;
  3095. return;
  3096. }
  3097. SqlParameterCollection parameters = GetCurrentParameterCollection();
  3098. int count = GetParameterCount(parameters);
  3099. SqlParameter thisParam = GetParameterForOutputValueExtraction(parameters, rec.parameter, count);
  3100. if (null != thisParam) {
  3101. // copy over data
  3102. // if the value user has supplied a SqlType class, then just copy over the SqlType, otherwise convert
  3103. // to the com type
  3104. object val = thisParam.Value;
  3105. //set the UDT value as typed object rather than bytes
  3106. if (SqlDbType.Udt == thisParam.SqlDbType) {
  3107. object data = null;
  3108. try {
  3109. Connection.CheckGetExtendedUDTInfo(rec, true);
  3110. //extract the byte array from the param value
  3111. if (rec.value.IsNull)
  3112. data = DBNull.Value;
  3113. else {
  3114. data = rec.value.ByteArray; //should work for both sql and non-sql values
  3115. }
  3116. //call the connection to instantiate the UDT object
  3117. thisParam.Value = Connection.GetUdtValue(data, rec, false);
  3118. }
  3119. catch (FileNotFoundException e) {
  3120. // SQL BU DT 329981
  3121. // Assign Assembly.Load failure in case where assembly not on client.
  3122. // This allows execution to complete and failure on SqlParameter.Value.
  3123. thisParam.SetUdtLoadError(e);
  3124. }
  3125. catch (FileLoadException e) {
  3126. // SQL BU DT 329981
  3127. // Assign Assembly.Load failure in case where assembly cannot be loaded on client.
  3128. // This allows execution to complete and failure on SqlParameter.Value.
  3129. thisParam.SetUdtLoadError(e);
  3130. }
  3131. return;
  3132. } else {
  3133. thisParam.SetSqlBuffer(rec.value);
  3134. }
  3135. MetaType mt = MetaType.GetMetaTypeFromSqlDbType(rec.type, rec.isMultiValued);
  3136. if (rec.type == SqlDbType.Decimal) {
  3137. thisParam.ScaleInternal = rec.scale;
  3138. thisParam.PrecisionInternal = rec.precision;
  3139. }
  3140. else if (mt.IsVarTime) {
  3141. thisParam.ScaleInternal = rec.scale;
  3142. }
  3143. else if (rec.type == SqlDbType.Xml) {
  3144. SqlCachedBuffer cachedBuffer = (thisParam.Value as SqlCachedBuffer);
  3145. if (null != cachedBuffer) {
  3146. thisParam.Value = cachedBuffer.ToString();
  3147. }
  3148. }
  3149. if (rec.collation != null) {
  3150. Debug.Assert(mt.IsCharType, "Invalid collation structure for non-char type");
  3151. thisParam.Collation = rec.collation;
  3152. }
  3153. }
  3154. return;
  3155. }
  3156. internal void OnParametersAvailableSmi( SmiParameterMetaData[] paramMetaData, ITypedGettersV3 parameterValues ) {
  3157. Debug.Assert(null != paramMetaData);
  3158. for(int index=0; index < paramMetaData.Length; index++) {
  3159. OnParameterAvailableSmi(paramMetaData[index], parameterValues, index);
  3160. }
  3161. }
  3162. internal void OnParameterAvailableSmi(SmiParameterMetaData metaData, ITypedGettersV3 parameterValues, int ordinal) {
  3163. if ( ParameterDirection.Input != metaData.Direction ) {
  3164. string name = null;
  3165. if (ParameterDirection.ReturnValue != metaData.Direction) {
  3166. name = metaData.Name;
  3167. }
  3168. SqlParameterCollection parameters = GetCurrentParameterCollection();
  3169. int count = GetParameterCount(parameters);
  3170. SqlParameter param = GetParameterForOutputValueExtraction(parameters, name, count);
  3171. if ( null != param ) {
  3172. param.LocaleId = (int)metaData.LocaleId;
  3173. param.CompareInfo = metaData.CompareOptions;
  3174. SqlBuffer buffer = new SqlBuffer();
  3175. object result;
  3176. if (_activeConnection.IsKatmaiOrNewer) {
  3177. result = ValueUtilsSmi.GetOutputParameterV200Smi(
  3178. OutParamEventSink, (SmiTypedGetterSetter)parameterValues, ordinal, metaData, _smiRequestContext, buffer );
  3179. }
  3180. else {
  3181. result = ValueUtilsSmi.GetOutputParameterV3Smi(
  3182. OutParamEventSink, parameterValues, ordinal, metaData, _smiRequestContext, buffer );
  3183. }
  3184. if ( null != result ) {
  3185. param.Value = result;
  3186. }
  3187. else {
  3188. param.SetSqlBuffer( buffer );
  3189. }
  3190. }
  3191. }
  3192. }
  3193. private SqlParameterCollection GetCurrentParameterCollection() {
  3194. if (BatchRPCMode) {
  3195. if (_parameterCollectionList.Count > _currentlyExecutingBatch) {
  3196. return _parameterCollectionList[_currentlyExecutingBatch];
  3197. }
  3198. else {
  3199. Debug.Assert(false, "OnReturnValue: SqlCommand got too many DONEPROC events");
  3200. return null;
  3201. }
  3202. }
  3203. else {
  3204. return _parameters;
  3205. }
  3206. }
  3207. private SqlParameter GetParameterForOutputValueExtraction( SqlParameterCollection parameters,
  3208. string paramName, int paramCount ) {
  3209. SqlParameter thisParam = null;
  3210. bool foundParam = false;
  3211. if (null == paramName) {
  3212. // rec.parameter should only be null for a return value from a function
  3213. for (int i = 0; i < paramCount; i++) {
  3214. thisParam = parameters[i];
  3215. // searching for ReturnValue
  3216. if (thisParam.Direction == ParameterDirection.ReturnValue) {
  3217. foundParam = true;
  3218. break; // found it
  3219. }
  3220. }
  3221. }
  3222. else {
  3223. for (int i = 0; i < paramCount; i++) {
  3224. thisParam = parameters[i];
  3225. // searching for Output or InputOutput or ReturnValue with matching name
  3226. if (thisParam.Direction != ParameterDirection.Input && thisParam.Direction != ParameterDirection.ReturnValue && paramName == thisParam.ParameterNameFixed) {
  3227. foundParam = true;
  3228. break; // found it
  3229. }
  3230. }
  3231. }
  3232. if (foundParam)
  3233. return thisParam;
  3234. else
  3235. return null;
  3236. }
  3237. private void GetRPCObject(int paramCount, ref _SqlRPC rpc) {
  3238. // Designed to minimize necessary allocations
  3239. int ii;
  3240. if (rpc == null) {
  3241. if (_rpcArrayOf1 == null) {
  3242. _rpcArrayOf1 = new _SqlRPC[1];
  3243. _rpcArrayOf1[0] = new _SqlRPC();
  3244. }
  3245. rpc = _rpcArrayOf1[0] ;
  3246. }
  3247. rpc.ProcID = 0;
  3248. rpc.rpcName = null;
  3249. rpc.options = 0;
  3250. rpc.recordsAffected = default(int?);
  3251. rpc.cumulativeRecordsAffected = -1;
  3252. rpc.errorsIndexStart = 0;
  3253. rpc.errorsIndexEnd = 0;
  3254. rpc.errors = null;
  3255. rpc.warningsIndexStart = 0;
  3256. rpc.warningsIndexEnd = 0;
  3257. rpc.warnings = null;
  3258. // Make sure there is enough space in the parameters and paramoptions arrays
  3259. if(rpc.parameters == null || rpc.parameters.Length < paramCount) {
  3260. rpc.parameters = new SqlParameter[paramCount];
  3261. }
  3262. else if (rpc.parameters.Length > paramCount) {
  3263. rpc.parameters[paramCount]=null; // Terminator
  3264. }
  3265. if(rpc.paramoptions == null || (rpc.paramoptions.Length < paramCount)) {
  3266. rpc.paramoptions = new byte[paramCount];
  3267. }
  3268. else {
  3269. for (ii = 0 ; ii < paramCount ; ii++)
  3270. rpc.paramoptions[ii] = 0;
  3271. }
  3272. }
  3273. private void SetUpRPCParameters (_SqlRPC rpc, int startCount, bool inSchema, SqlParameterCollection parameters) {
  3274. int ii;
  3275. int paramCount = GetParameterCount(parameters) ;
  3276. int j = startCount;
  3277. TdsParser parser = _activeConnection.Parser;
  3278. bool yukonOrNewer = parser.IsYukonOrNewer;
  3279. for (ii = 0; ii < paramCount; ii++) {
  3280. SqlParameter parameter = parameters[ii];
  3281. parameter.Validate(ii, CommandType.StoredProcedure == CommandType);
  3282. // func will change type to that with a 4 byte length if the type has a two
  3283. // byte length and a parameter length > than that expressable in 2 bytes
  3284. if ((!parameter.ValidateTypeLengths(yukonOrNewer).IsPlp) && (parameter.Direction != ParameterDirection.Output)) {
  3285. parameter.FixStreamDataForNonPLP();
  3286. }
  3287. if (ShouldSendParameter(parameter)) {
  3288. rpc.parameters[j] = parameter;
  3289. // set output bit
  3290. if (parameter.Direction == ParameterDirection.InputOutput ||
  3291. parameter.Direction == ParameterDirection.Output)
  3292. rpc.paramoptions[j] = TdsEnums.RPC_PARAM_BYREF;
  3293. // set default value bit
  3294. if (parameter.Direction != ParameterDirection.Output) {
  3295. // remember that null == Convert.IsEmpty, DBNull.Value is a database null!
  3296. // MDAC 62117, don't assume a default value exists for parameters in the case when
  3297. // the user is simply requesting schema
  3298. // SQLBUVSTS 179488 TVPs use DEFAULT and do not allow NULL, even for schema only.
  3299. if (null == parameter.Value && (!inSchema || SqlDbType.Structured == parameter.SqlDbType)) {
  3300. rpc.paramoptions[j] |= TdsEnums.RPC_PARAM_DEFAULT;
  3301. }
  3302. }
  3303. // Must set parameter option bit for LOB_COOKIE if unfilled LazyMat blob
  3304. j++;
  3305. }
  3306. }
  3307. }
  3308. //
  3309. // 7.5
  3310. // prototype for sp_prepexec is:
  3311. // sp_prepexec(@handle int IN/OUT, @batch_params ntext, @batch_text ntext, param1value,param2value...)
  3312. //
  3313. private _SqlRPC BuildPrepExec(CommandBehavior behavior) {
  3314. Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_prepexec for stored proc invocation!");
  3315. SqlParameter sqlParam;
  3316. int j = 3;
  3317. int count = CountSendableParameters(_parameters);
  3318. _SqlRPC rpc = null;
  3319. GetRPCObject(count + j, ref rpc);
  3320. rpc.ProcID = TdsEnums.RPC_PROCID_PREPEXEC;
  3321. rpc.rpcName = TdsEnums.SP_PREPEXEC;
  3322. //@handle
  3323. sqlParam = new SqlParameter(null, SqlDbType.Int);
  3324. sqlParam.Direction = ParameterDirection.InputOutput;
  3325. sqlParam.Value = _prepareHandle;
  3326. rpc.parameters[0] = sqlParam;
  3327. rpc.paramoptions[0] = TdsEnums.RPC_PARAM_BYREF;
  3328. //@batch_params
  3329. string paramList = BuildParamList(_stateObj.Parser, _parameters);
  3330. sqlParam = new SqlParameter(null, ((paramList.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, paramList.Length);
  3331. sqlParam.Value = paramList;
  3332. rpc.parameters[1] = sqlParam;
  3333. //@batch_text
  3334. string text = GetCommandText(behavior);
  3335. sqlParam = new SqlParameter(null, ((text.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, text.Length);
  3336. sqlParam.Value = text;
  3337. rpc.parameters[2] = sqlParam;
  3338. SetUpRPCParameters (rpc, j, false, _parameters);
  3339. return rpc;
  3340. }
  3341. //
  3342. // returns true if the parameter is not a return value
  3343. // and it's value is not DBNull (for a nullable parameter)
  3344. //
  3345. private static bool ShouldSendParameter(SqlParameter p) {
  3346. switch (p.Direction) {
  3347. case ParameterDirection.ReturnValue:
  3348. // return value parameters are never sent
  3349. return false;
  3350. case ParameterDirection.Output:
  3351. case ParameterDirection.InputOutput:
  3352. case ParameterDirection.Input:
  3353. // InputOutput/Output parameters are aways sent
  3354. return true;
  3355. default:
  3356. Debug.Assert(false, "Invalid ParameterDirection!");
  3357. return false;
  3358. }
  3359. }
  3360. private int CountSendableParameters(SqlParameterCollection parameters) {
  3361. int cParams = 0;
  3362. if (parameters != null) {
  3363. int count = parameters.Count;
  3364. for (int i = 0; i < count; i++) {
  3365. if (ShouldSendParameter(parameters[i]))
  3366. cParams++;
  3367. }
  3368. }
  3369. return cParams;
  3370. }
  3371. // Returns total number of parameters
  3372. private int GetParameterCount(SqlParameterCollection parameters) {
  3373. return ((null != parameters) ? parameters.Count : 0);
  3374. }
  3375. //
  3376. // build the RPC record header for this stored proc and add parameters
  3377. //
  3378. private void BuildRPC(bool inSchema, SqlParameterCollection parameters, ref _SqlRPC rpc) {
  3379. Debug.Assert(this.CommandType == System.Data.CommandType.StoredProcedure, "Command must be a stored proc to execute an RPC");
  3380. int count = CountSendableParameters(parameters);
  3381. GetRPCObject(count, ref rpc);
  3382. rpc.rpcName = this.CommandText; // just get the raw command text
  3383. SetUpRPCParameters ( rpc, 0, inSchema, parameters);
  3384. }
  3385. //
  3386. // build the RPC record header for sp_unprepare
  3387. //
  3388. // prototype for sp_unprepare is:
  3389. // sp_unprepare(@handle)
  3390. //
  3391. //
  3392. private _SqlRPC BuildUnprepare() {
  3393. Debug.Assert(_prepareHandle != 0, "Invalid call to sp_unprepare without a valid handle!");
  3394. _SqlRPC rpc = null;
  3395. GetRPCObject(1, ref rpc);
  3396. SqlParameter sqlParam;
  3397. rpc.ProcID = TdsEnums.RPC_PROCID_UNPREPARE;
  3398. rpc.rpcName = TdsEnums.SP_UNPREPARE;
  3399. //@handle
  3400. sqlParam = new SqlParameter(null, SqlDbType.Int);
  3401. sqlParam.Value = _prepareHandle;
  3402. rpc.parameters[0] = sqlParam;
  3403. return rpc;
  3404. }
  3405. //
  3406. // build the RPC record header for sp_execute
  3407. //
  3408. // prototype for sp_execute is:
  3409. // sp_execute(@handle int,param1value,param2value...)
  3410. //
  3411. private _SqlRPC BuildExecute(bool inSchema) {
  3412. Debug.Assert(_prepareHandle != -1, "Invalid call to sp_execute without a valid handle!");
  3413. int j = 1;
  3414. int count = CountSendableParameters(_parameters);
  3415. _SqlRPC rpc = null;
  3416. GetRPCObject(count + j, ref rpc);
  3417. SqlParameter sqlParam;
  3418. rpc.ProcID = TdsEnums.RPC_PROCID_EXECUTE;
  3419. rpc.rpcName = TdsEnums.SP_EXECUTE;
  3420. //@handle
  3421. sqlParam = new SqlParameter(null, SqlDbType.Int);
  3422. sqlParam.Value = _prepareHandle;
  3423. rpc.parameters[0] = sqlParam;
  3424. SetUpRPCParameters (rpc, j, inSchema, _parameters);
  3425. return rpc;
  3426. }
  3427. //
  3428. // build the RPC record header for sp_executesql and add the parameters
  3429. //
  3430. // prototype for sp_executesql is:
  3431. // sp_executesql(@batch_text nvarchar(4000),@batch_params nvarchar(4000), param1,.. paramN)
  3432. private void BuildExecuteSql(CommandBehavior behavior, string commandText, SqlParameterCollection parameters, ref _SqlRPC rpc) {
  3433. Debug.Assert(_prepareHandle == -1, "This command has an existing handle, use sp_execute!");
  3434. Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_executesql for stored proc invocation!");
  3435. int j;
  3436. SqlParameter sqlParam;
  3437. int cParams = CountSendableParameters(parameters);
  3438. if (cParams > 0) {
  3439. j = 2;
  3440. }
  3441. else {
  3442. j =1;
  3443. }
  3444. GetRPCObject(cParams + j, ref rpc);
  3445. rpc.ProcID = TdsEnums.RPC_PROCID_EXECUTESQL;
  3446. rpc.rpcName = TdsEnums.SP_EXECUTESQL;
  3447. // @sql
  3448. if (commandText == null) {
  3449. commandText = GetCommandText(behavior);
  3450. }
  3451. sqlParam = new SqlParameter(null, ((commandText.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, commandText.Length);
  3452. sqlParam.Value = commandText;
  3453. rpc.parameters[0] = sqlParam;
  3454. if (cParams > 0) {
  3455. string paramList = BuildParamList(_stateObj.Parser, BatchRPCMode ? parameters : _parameters);
  3456. sqlParam = new SqlParameter(null, ((paramList.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, paramList.Length);
  3457. sqlParam.Value = paramList;
  3458. rpc.parameters[1] = sqlParam;
  3459. bool inSchema = (0 != (behavior & CommandBehavior.SchemaOnly));
  3460. SetUpRPCParameters (rpc, j, inSchema, parameters);
  3461. }
  3462. }
  3463. // paramList parameter for sp_executesql, sp_prepare, and sp_prepexec
  3464. internal string BuildParamList(TdsParser parser, SqlParameterCollection parameters) {
  3465. StringBuilder paramList = new StringBuilder();
  3466. bool fAddSeperator = false;
  3467. bool yukonOrNewer = parser.IsYukonOrNewer;
  3468. int count = 0;
  3469. count = parameters.Count;
  3470. for (int i = 0; i < count; i++) {
  3471. SqlParameter sqlParam = parameters[i];
  3472. sqlParam.Validate(i, CommandType.StoredProcedure == CommandType);
  3473. // skip ReturnValue parameters; we never send them to the server
  3474. if (!ShouldSendParameter(sqlParam))
  3475. continue;
  3476. // add our separator for the ith parmeter
  3477. if (fAddSeperator)
  3478. paramList.Append(',');
  3479. paramList.Append(sqlParam.ParameterNameFixed);
  3480. MetaType mt = sqlParam.InternalMetaType;
  3481. //for UDTs, get the actual type name. Get only the typename, omitt catalog and schema names.
  3482. //in TSQL you should only specify the unqualified type name
  3483. // paragraph above doesn't seem to be correct. Server won't find the type
  3484. // if we don't provide a fully qualified name
  3485. paramList.Append(" ");
  3486. if (mt.SqlDbType == SqlDbType.Udt) {
  3487. string fullTypeName = sqlParam.UdtTypeName;
  3488. if(ADP.IsEmpty(fullTypeName))
  3489. throw SQL.MustSetUdtTypeNameForUdtParams();
  3490. // DEVNOTE: do we need to escape the full type name?
  3491. paramList.Append(ParseAndQuoteIdentifier(fullTypeName, true /* is UdtTypeName */));
  3492. }
  3493. else if (mt.SqlDbType == SqlDbType.Structured) {
  3494. string typeName = sqlParam.TypeName;
  3495. if (ADP.IsEmpty(typeName)) {
  3496. throw SQL.MustSetTypeNameForParam(mt.TypeName, sqlParam.ParameterNameFixed);
  3497. }
  3498. paramList.Append(ParseAndQuoteIdentifier(typeName, false /* is not UdtTypeName*/));
  3499. // TVPs currently are the only Structured type and must be read only, so add that keyword
  3500. paramList.Append(" READONLY");
  3501. }
  3502. else {
  3503. // func will change type to that with a 4 byte length if the type has a two
  3504. // byte length and a parameter length > than that expressable in 2 bytes
  3505. mt = sqlParam.ValidateTypeLengths(yukonOrNewer);
  3506. if ((!mt.IsPlp) && (sqlParam.Direction != ParameterDirection.Output)) {
  3507. sqlParam.FixStreamDataForNonPLP();
  3508. }
  3509. paramList.Append(mt.TypeName);
  3510. }
  3511. fAddSeperator = true;
  3512. if (mt.SqlDbType == SqlDbType.Decimal) {
  3513. byte precision = sqlParam.GetActualPrecision();
  3514. byte scale = sqlParam.GetActualScale();
  3515. paramList.Append('(');
  3516. if (0 == precision) {
  3517. if (IsShiloh) {
  3518. precision = TdsEnums.DEFAULT_NUMERIC_PRECISION;
  3519. } else {
  3520. precision = TdsEnums.SPHINX_DEFAULT_NUMERIC_PRECISION;
  3521. }
  3522. }
  3523. paramList.Append(precision);
  3524. paramList.Append(',');
  3525. paramList.Append(scale);
  3526. paramList.Append(')');
  3527. }
  3528. else if (mt.IsVarTime) {
  3529. byte scale = sqlParam.GetActualScale();
  3530. paramList.Append('(');
  3531. paramList.Append(scale);
  3532. paramList.Append(')');
  3533. }
  3534. else if (false == mt.IsFixed && false == mt.IsLong && mt.SqlDbType != SqlDbType.Timestamp && mt.SqlDbType != SqlDbType.Udt && SqlDbType.Structured != mt.SqlDbType) {
  3535. int size = sqlParam.Size;
  3536. paramList.Append('(');
  3537. // if using non unicode types, obtain the actual byte length from the parser, with it's associated code page
  3538. if (mt.IsAnsiType) {
  3539. object val = sqlParam.GetCoercedValue();
  3540. string s = null;
  3541. // deal with the sql types
  3542. if ((null != val) && (DBNull.Value != val)) {
  3543. s = (val as string);
  3544. if (null == s) {
  3545. SqlString sval = val is SqlString ? (SqlString)val : SqlString.Null;
  3546. if (!sval.IsNull) {
  3547. s = sval.Value;
  3548. }
  3549. }
  3550. }
  3551. if (null != s) {
  3552. int actualBytes = parser.GetEncodingCharLength(s, sqlParam.GetActualSize(), sqlParam.Offset, null);
  3553. // if actual number of bytes is greater than the user given number of chars, use actual bytes
  3554. if (actualBytes > size)
  3555. size = actualBytes;
  3556. }
  3557. }
  3558. // bug 49497, if the user specifies a 0-sized parameter for a variable len field
  3559. // pass over max size (8000 bytes or 4000 characters for wide types)
  3560. if (0 == size)
  3561. size = mt.IsSizeInCharacters ? (TdsEnums.MAXSIZE >> 1) : TdsEnums.MAXSIZE;
  3562. paramList.Append(size);
  3563. paramList.Append(')');
  3564. }
  3565. else if (mt.IsPlp && (mt.SqlDbType != SqlDbType.Xml) && (mt.SqlDbType != SqlDbType.Udt)) {
  3566. paramList.Append("(max) ");
  3567. }
  3568. // set the output bit for Output or InputOutput parameters
  3569. if (sqlParam.Direction != ParameterDirection.Input)
  3570. paramList.Append(" " + TdsEnums.PARAM_OUTPUT);
  3571. }
  3572. return paramList.ToString();
  3573. }
  3574. // Adds quotes to each part of a SQL identifier that may be multi-part, while leaving
  3575. // the result as a single composite name.
  3576. private string ParseAndQuoteIdentifier(string identifier, bool isUdtTypeName) {
  3577. string[] strings = SqlParameter.ParseTypeName(identifier, isUdtTypeName);
  3578. StringBuilder bld = new StringBuilder();
  3579. // Stitching back together is a little tricky. Assume we want to build a full multi-part name
  3580. // with all parts except trimming separators for leading empty names (null or empty strings,
  3581. // but not whitespace). Separators in the middle should be added, even if the name part is
  3582. // null/empty, to maintain proper location of the parts.
  3583. for (int i = 0; i < strings.Length; i++ ) {
  3584. if (0 < bld.Length) {
  3585. bld.Append('.');
  3586. }
  3587. if (null != strings[i] && 0 != strings[i].Length) {
  3588. bld.Append(ADP.BuildQuotedString("[", "]", strings[i]));
  3589. }
  3590. }
  3591. return bld.ToString();
  3592. }
  3593. // returns set option text to turn on format only and key info on and off
  3594. // @devnote: When we are executing as a text command, then we never need
  3595. // to turn off the options since they command text is executed in the scope of sp_executesql.
  3596. // For a stored proc command, however, we must send over batch sql and then turn off
  3597. // the set options after we read the data. See the code in Command.Execute()
  3598. private string GetSetOptionsString(CommandBehavior behavior) {
  3599. string s = null;
  3600. if ((System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) ||
  3601. (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo))) {
  3602. // MDAC 56898 - SET FMTONLY ON will cause the server to ignore other SET OPTIONS, so turn
  3603. // it off before we ask for browse mode metadata
  3604. s = TdsEnums.FMTONLY_OFF;
  3605. if (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo)) {
  3606. s = s + TdsEnums.BROWSE_ON;
  3607. }
  3608. if (System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) {
  3609. s = s + TdsEnums.FMTONLY_ON;
  3610. }
  3611. }
  3612. return s;
  3613. }
  3614. private string GetResetOptionsString(CommandBehavior behavior) {
  3615. string s = null;
  3616. // SET FMTONLY ON OFF
  3617. if (System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) {
  3618. s = s + TdsEnums.FMTONLY_OFF;
  3619. }
  3620. // SET NO_BROWSETABLE OFF
  3621. if (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo)) {
  3622. s = s + TdsEnums.BROWSE_OFF;
  3623. }
  3624. return s;
  3625. }
  3626. private String GetCommandText(CommandBehavior behavior) {
  3627. // build the batch string we send over, since we execute within a stored proc (sp_executesql), the SET options never need to be
  3628. // turned off since they are scoped to the sproc
  3629. Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid call to GetCommandText for stored proc!");
  3630. return GetSetOptionsString(behavior) + this.CommandText;
  3631. }
  3632. //
  3633. // build the RPC record header for sp_executesql and add the parameters
  3634. //
  3635. // the prototype for sp_prepare is:
  3636. // sp_prepare(@handle int OUTPUT, @batch_params ntext, @batch_text ntext, @options int default 0x1)
  3637. private _SqlRPC BuildPrepare(CommandBehavior behavior) {
  3638. Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_prepare for stored proc invocation!");
  3639. _SqlRPC rpc = null;
  3640. GetRPCObject(3, ref rpc);
  3641. SqlParameter sqlParam;
  3642. rpc.ProcID = TdsEnums.RPC_PROCID_PREPARE;
  3643. rpc.rpcName = TdsEnums.SP_PREPARE;
  3644. //@handle
  3645. sqlParam = new SqlParameter(null, SqlDbType.Int);
  3646. sqlParam.Direction = ParameterDirection.Output;
  3647. rpc.parameters[0] = sqlParam;
  3648. rpc.paramoptions[0] = TdsEnums.RPC_PARAM_BYREF;
  3649. //@batch_params
  3650. string paramList = BuildParamList(_stateObj.Parser, _parameters);
  3651. sqlParam = new SqlParameter(null, ((paramList.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, paramList.Length);
  3652. sqlParam.Value = paramList;
  3653. rpc.parameters[1] = sqlParam;
  3654. //@batch_text
  3655. string text = GetCommandText(behavior);
  3656. sqlParam = new SqlParameter(null, ((text.Length<<1)<=TdsEnums.TYPE_SIZE_LIMIT)?SqlDbType.NVarChar:SqlDbType.NText, text.Length);
  3657. sqlParam.Value = text;
  3658. rpc.parameters[2] = sqlParam;
  3659. /*
  3660. //@options
  3661. sqlParam = new SqlParameter(null, SqlDbType.Int);
  3662. rpc.Parameters[3] = sqlParam;
  3663. */
  3664. return rpc;
  3665. }
  3666. internal void CheckThrowSNIException() {
  3667. var stateObj = _stateObj;
  3668. if (stateObj != null) {
  3669. stateObj.CheckThrowSNIException();
  3670. }
  3671. }
  3672. // We're being notified that the underlying connection has closed
  3673. internal void OnConnectionClosed() {
  3674. var stateObj = _stateObj;
  3675. if (stateObj != null) {
  3676. stateObj.OnConnectionClosed();
  3677. }
  3678. }
  3679. internal TdsParserStateObject StateObject {
  3680. get {
  3681. return _stateObj;
  3682. }
  3683. }
  3684. private bool IsPrepared {
  3685. get { return(_execType != EXECTYPE.UNPREPARED);}
  3686. }
  3687. private bool IsUserPrepared {
  3688. get { return IsPrepared && !_hiddenPrepare && !IsDirty; }
  3689. }
  3690. internal bool IsDirty {
  3691. get {
  3692. // only dirty if prepared
  3693. var activeConnection = _activeConnection;
  3694. return (IsPrepared &&
  3695. (_dirty ||
  3696. ((_parameters != null) && (_parameters.IsDirty)) ||
  3697. ((activeConnection != null) && ((activeConnection.CloseCount != _preparedConnectionCloseCount) || (activeConnection.ReconnectCount != _preparedConnectionReconnectCount)))));
  3698. }
  3699. set {
  3700. // only mark the command as dirty if it is already prepared
  3701. // but always clear the value if it we are clearing the dirty flag
  3702. _dirty = value ? IsPrepared : false;
  3703. if (null != _parameters) {
  3704. _parameters.IsDirty = _dirty;
  3705. }
  3706. _cachedMetaData = null;
  3707. }
  3708. }
  3709. internal int InternalRecordsAffected {
  3710. get {
  3711. return _rowsAffected;
  3712. }
  3713. set {
  3714. if (-1 == _rowsAffected) {
  3715. _rowsAffected = value;
  3716. }
  3717. else if (0 < value) {
  3718. _rowsAffected += value;
  3719. }
  3720. }
  3721. }
  3722. internal bool BatchRPCMode {
  3723. get {
  3724. return _batchRPCMode;
  3725. }
  3726. set {
  3727. _batchRPCMode = value;
  3728. if (_batchRPCMode == false) {
  3729. ClearBatchCommand();
  3730. } else {
  3731. if (_RPCList == null) {
  3732. _RPCList = new List<_SqlRPC>();
  3733. }
  3734. if (_parameterCollectionList == null) {
  3735. _parameterCollectionList = new List<SqlParameterCollection>();
  3736. }
  3737. }
  3738. }
  3739. }
  3740. internal void ClearBatchCommand() {
  3741. List<_SqlRPC> rpcList = _RPCList;
  3742. if (null != rpcList) {
  3743. rpcList.Clear();
  3744. }
  3745. if (null != _parameterCollectionList) {
  3746. _parameterCollectionList.Clear();
  3747. }
  3748. _SqlRPCBatchArray = null;
  3749. _currentlyExecutingBatch = 0;
  3750. }
  3751. internal void AddBatchCommand(string commandText, SqlParameterCollection parameters, CommandType cmdType) {
  3752. Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
  3753. Debug.Assert(_RPCList != null);
  3754. Debug.Assert(_parameterCollectionList != null);
  3755. _SqlRPC rpc = new _SqlRPC();
  3756. this.CommandText = commandText;
  3757. this.CommandType = cmdType;
  3758. GetStateObject();
  3759. if (cmdType == CommandType.StoredProcedure) {
  3760. BuildRPC(false, parameters, ref rpc);
  3761. }
  3762. else {
  3763. // All batch sql statements must be executed inside sp_executesql, including those without parameters
  3764. BuildExecuteSql(CommandBehavior.Default, commandText, parameters, ref rpc);
  3765. }
  3766. _RPCList.Add(rpc);
  3767. // Always add a parameters collection per RPC, even if there are no parameters.
  3768. _parameterCollectionList.Add(parameters);
  3769. ReliablePutStateObject();
  3770. }
  3771. internal int ExecuteBatchRPCCommand() {
  3772. Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
  3773. Debug.Assert(_RPCList != null, "No batch commands specified");
  3774. _SqlRPCBatchArray = _RPCList.ToArray();
  3775. _currentlyExecutingBatch = 0;
  3776. return ExecuteNonQuery(); // Check permissions, execute, return output params
  3777. }
  3778. internal int? GetRecordsAffected(int commandIndex) {
  3779. Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
  3780. Debug.Assert(_SqlRPCBatchArray != null, "batch command have been cleared");
  3781. return _SqlRPCBatchArray[commandIndex].recordsAffected;
  3782. }
  3783. internal SqlException GetErrors(int commandIndex) {
  3784. SqlException result = null;
  3785. int length = (_SqlRPCBatchArray[commandIndex].errorsIndexEnd - _SqlRPCBatchArray[commandIndex].errorsIndexStart);
  3786. if (0 < length) {
  3787. SqlErrorCollection errors = new SqlErrorCollection();
  3788. for(int i = _SqlRPCBatchArray[commandIndex].errorsIndexStart; i < _SqlRPCBatchArray[commandIndex].errorsIndexEnd; ++i) {
  3789. errors.Add(_SqlRPCBatchArray[commandIndex].errors[i]);
  3790. }
  3791. for(int i = _SqlRPCBatchArray[commandIndex].warningsIndexStart; i < _SqlRPCBatchArray[commandIndex].warningsIndexEnd; ++i) {
  3792. errors.Add(_SqlRPCBatchArray[commandIndex].warnings[i]);
  3793. }
  3794. result = SqlException.CreateException(errors, Connection.ServerVersion, Connection.ClientConnectionId);
  3795. }
  3796. return result;
  3797. }
  3798. // Allocates and initializes a new SmiRequestExecutor based on the current command state
  3799. private SmiRequestExecutor SetUpSmiRequest( SqlInternalConnectionSmi innerConnection ) {
  3800. // General Approach To Ensure Security of Marshalling:
  3801. // Only touch each item in the command once
  3802. // (i.e. only grab a reference to each param once, only
  3803. // read the type from that param once, etc.). The problem is
  3804. // that if the user changes something on the command in the
  3805. // middle of marshaling, it can overwrite the native buffers
  3806. // set up. For example, if max length is used to allocate
  3807. // buffers, but then re-read from the parameter to truncate
  3808. // strings, the user could extend the length and overwrite
  3809. // the buffer.
  3810. if (null != Notification){
  3811. throw SQL.NotificationsNotAvailableOnContextConnection();
  3812. }
  3813. SmiParameterMetaData[] requestMetaData = null;
  3814. ParameterPeekAheadValue[] peekAheadValues = null;
  3815. // Length of rgMetadata becomes *the* official count of parameters to use,
  3816. // don't rely on Parameters.Count after this point, as the user could change it.
  3817. int count = GetParameterCount( Parameters );
  3818. if ( 0 < count ) {
  3819. requestMetaData = new SmiParameterMetaData[count];
  3820. peekAheadValues = new ParameterPeekAheadValue[count];
  3821. // set up the metadata
  3822. for ( int index=0; index<count; index++ ) {
  3823. SqlParameter param = Parameters[index];
  3824. param.Validate(index, CommandType.StoredProcedure == CommandType);
  3825. requestMetaData[index] = param.MetaDataForSmi(out peekAheadValues[index]);
  3826. // Check for valid type for version negotiated
  3827. if (!innerConnection.IsKatmaiOrNewer) {
  3828. MetaType mt = MetaType.GetMetaTypeFromSqlDbType(requestMetaData[index].SqlDbType, requestMetaData[index].IsMultiValued);
  3829. if (!mt.Is90Supported) {
  3830. throw ADP.VersionDoesNotSupportDataType(mt.TypeName);
  3831. }
  3832. }
  3833. }
  3834. }
  3835. // Allocate the new request
  3836. CommandType cmdType = CommandType;
  3837. _smiRequestContext = innerConnection.InternalContext;
  3838. SmiRequestExecutor requestExecutor = _smiRequestContext.CreateRequestExecutor(
  3839. CommandText,
  3840. cmdType,
  3841. requestMetaData,
  3842. EventSink
  3843. );
  3844. // deal with errors
  3845. EventSink.ProcessMessagesAndThrow();
  3846. // Now assign param values
  3847. for ( int index=0; index<count; index++ ) {
  3848. if ( ParameterDirection.Output != requestMetaData[index].Direction &&
  3849. ParameterDirection.ReturnValue != requestMetaData[index].Direction ) {
  3850. SqlParameter param = Parameters[index];
  3851. // going back to command for parameter is ok, since we'll only pick up values now.
  3852. object value = param.GetCoercedValue();
  3853. if (value is XmlDataFeed && requestMetaData[index].SqlDbType != SqlDbType.Xml) {
  3854. value = MetaType.GetStringFromXml(((XmlDataFeed)value)._source);
  3855. }
  3856. ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(requestMetaData[index].SqlDbType, requestMetaData[index].IsMultiValued, value, null /* parameters don't use CLR Type for UDTs */, SmiContextFactory.Instance.NegotiatedSmiVersion);
  3857. // Handle null reference as special case for parameters
  3858. if ( CommandType.StoredProcedure == cmdType &&
  3859. ExtendedClrTypeCode.Empty == typeCode ) {
  3860. requestExecutor.SetDefault( index );
  3861. }
  3862. else {
  3863. // SQLBU 402391 & 403631: Exception to prevent Parameter.Size data corruption cases from working.
  3864. // This should be temporary until changing to correct behavior can be safely implemented.
  3865. // initial size criteria is the same for all affected types
  3866. // NOTE: assumes size < -1 is handled by SqlParameter.Size setter
  3867. int size = param.Size;
  3868. if (size != 0 && size != SmiMetaData.UnlimitedMaxLengthIndicator && !param.SizeInferred) {
  3869. switch(requestMetaData[index].SqlDbType) {
  3870. case SqlDbType.Image:
  3871. case SqlDbType.Text:
  3872. if (size != Int32.MaxValue) {
  3873. throw SQL.ParameterSizeRestrictionFailure(index);
  3874. }
  3875. break;
  3876. case SqlDbType.NText:
  3877. if (size != Int32.MaxValue/2) {
  3878. throw SQL.ParameterSizeRestrictionFailure(index);
  3879. }
  3880. break;
  3881. case SqlDbType.VarBinary:
  3882. case SqlDbType.VarChar:
  3883. // Allow size==Int32.MaxValue because of DeriveParameters
  3884. if (size > 0 && size != Int32.MaxValue && requestMetaData[index].MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator) {
  3885. throw SQL.ParameterSizeRestrictionFailure(index);
  3886. }
  3887. break;
  3888. case SqlDbType.NVarChar:
  3889. // Allow size==Int32.MaxValue/2 because of DeriveParameters
  3890. if (size > 0 && size != Int32.MaxValue/2 && requestMetaData[index].MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator) {
  3891. throw SQL.ParameterSizeRestrictionFailure(index);
  3892. }
  3893. break;
  3894. case SqlDbType.Timestamp:
  3895. // Size limiting for larger values will happen due to MaxLength
  3896. if (size < SmiMetaData.DefaultTimestamp.MaxLength) {
  3897. throw SQL.ParameterSizeRestrictionFailure(index);
  3898. }
  3899. break;
  3900. case SqlDbType.Variant:
  3901. // Variant problems happen when Size is less than maximums for character and binary values
  3902. // Size limiting for larger values will happen due to MaxLength
  3903. // NOTE: assumes xml and udt types are handled in parameter value coercion
  3904. // since server does not allow these types in a variant
  3905. if (null != value) {
  3906. MetaType mt = MetaType.GetMetaTypeFromValue(value);
  3907. if ((mt.IsNCharType && size < SmiMetaData.MaxUnicodeCharacters) ||
  3908. (mt.IsBinType && size < SmiMetaData.MaxBinaryLength) ||
  3909. (mt.IsAnsiType && size < SmiMetaData.MaxANSICharacters)) {
  3910. throw SQL.ParameterSizeRestrictionFailure(index);
  3911. }
  3912. }
  3913. break;
  3914. case SqlDbType.Xml:
  3915. // Xml is an issue for non-SqlXml types
  3916. if (null != value && ExtendedClrTypeCode.SqlXml != typeCode) {
  3917. throw SQL.ParameterSizeRestrictionFailure(index);
  3918. }
  3919. break;
  3920. // NOTE: Char, NChar, Binary and UDT do not need restricting because they are always 8k or less,
  3921. // so the metadata MaxLength will match the Size setting.
  3922. default:
  3923. break;
  3924. }
  3925. }
  3926. if (innerConnection.IsKatmaiOrNewer) {
  3927. ValueUtilsSmi.SetCompatibleValueV200(EventSink, requestExecutor, index, requestMetaData[index], value, typeCode, param.Offset, param.Size, peekAheadValues[index]);
  3928. }
  3929. else {
  3930. ValueUtilsSmi.SetCompatibleValue( EventSink, requestExecutor, index, requestMetaData[index], value, typeCode, param.Offset );
  3931. }
  3932. }
  3933. }
  3934. }
  3935. return requestExecutor;
  3936. }
  3937. #if DEBUG
  3938. internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) {
  3939. var stateObj = _stateObj;
  3940. if (stateObj != null) {
  3941. stateObj.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
  3942. }
  3943. else {
  3944. var tempCachedAsyncState = cachedAsyncState;
  3945. if (tempCachedAsyncState != null) {
  3946. var reader = tempCachedAsyncState.CachedAsyncReader;
  3947. if (reader != null) {
  3948. reader.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
  3949. }
  3950. }
  3951. }
  3952. }
  3953. internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) {
  3954. var stateObj = _stateObj;
  3955. if (stateObj != null) {
  3956. stateObj.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
  3957. }
  3958. else {
  3959. var tempCachedAsyncState = _cachedAsyncState;
  3960. if (tempCachedAsyncState != null) {
  3961. var reader = tempCachedAsyncState.CachedAsyncReader;
  3962. if (reader != null) {
  3963. reader.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
  3964. }
  3965. }
  3966. }
  3967. }
  3968. #endif
  3969. }
  3970. }