SqlCommand.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. //
  2. // System.Data.SqlClient.SqlCommand.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Daniel Morgan ([email protected])
  7. // Tim Coleman ([email protected])
  8. // Diego Caravana ([email protected])
  9. //
  10. // (C) Ximian, Inc 2002 http://www.ximian.com/
  11. // (C) Daniel Morgan, 2002
  12. // Copyright (C) Tim Coleman, 2002
  13. //
  14. //
  15. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  16. //
  17. // Permission is hereby granted, free of charge, to any person obtaining
  18. // a copy of this software and associated documentation files (the
  19. // "Software"), to deal in the Software without restriction, including
  20. // without limitation the rights to use, copy, modify, merge, publish,
  21. // distribute, sublicense, and/or sell copies of the Software, and to
  22. // permit persons to whom the Software is furnished to do so, subject to
  23. // the following conditions:
  24. //
  25. // The above copyright notice and this permission notice shall be
  26. // included in all copies or substantial portions of the Software.
  27. //
  28. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  29. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  31. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  32. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  33. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  34. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  35. //
  36. using Mono.Data.Tds;
  37. using Mono.Data.Tds.Protocol;
  38. using System;
  39. using System.Collections;
  40. using System.Collections.Specialized;
  41. using System.ComponentModel;
  42. using System.Data;
  43. using System.Data.Common;
  44. #if NET_2_0
  45. using System.Data.ProviderBase;
  46. #endif // NET_2_0
  47. using System.Runtime.InteropServices;
  48. using System.Text;
  49. using System.Xml;
  50. namespace System.Data.SqlClient {
  51. [DesignerAttribute ("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
  52. [ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
  53. #if NET_2_0
  54. public sealed class SqlCommand : DbCommandBase, IDbCommand, ICloneable
  55. #else
  56. public sealed class SqlCommand : Component, IDbCommand, ICloneable
  57. #endif // NET_2_0
  58. {
  59. #region Fields
  60. bool disposed = false;
  61. int commandTimeout;
  62. bool designTimeVisible;
  63. string commandText;
  64. CommandType commandType;
  65. SqlConnection connection;
  66. SqlTransaction transaction;
  67. UpdateRowSource updatedRowSource;
  68. CommandBehavior behavior = CommandBehavior.Default;
  69. SqlParameterCollection parameters;
  70. string preparedStatement = null;
  71. #endregion // Fields
  72. #region Constructors
  73. public SqlCommand()
  74. : this (String.Empty, null, null)
  75. {
  76. }
  77. public SqlCommand (string commandText)
  78. : this (commandText, null, null)
  79. {
  80. }
  81. public SqlCommand (string commandText, SqlConnection connection)
  82. : this (commandText, connection, null)
  83. {
  84. }
  85. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  86. {
  87. this.commandText = commandText;
  88. this.connection = connection;
  89. this.transaction = transaction;
  90. this.commandType = CommandType.Text;
  91. this.updatedRowSource = UpdateRowSource.Both;
  92. this.designTimeVisible = false;
  93. this.commandTimeout = 30;
  94. parameters = new SqlParameterCollection (this);
  95. }
  96. private SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction, CommandType commandType, UpdateRowSource updatedRowSource, bool designTimeVisible, int commandTimeout, SqlParameterCollection parameters)
  97. {
  98. this.commandText = commandText;
  99. this.connection = connection;
  100. this.transaction = transaction;
  101. this.commandType = commandType;
  102. this.updatedRowSource = updatedRowSource;
  103. this.designTimeVisible = designTimeVisible;
  104. this.commandTimeout = commandTimeout;
  105. this.parameters = new SqlParameterCollection(this);
  106. for (int i = 0;i < parameters.Count;i++)
  107. this.parameters.Add(((ICloneable)parameters[i]).Clone());
  108. }
  109. #endregion // Constructors
  110. #region Properties
  111. internal CommandBehavior CommandBehavior {
  112. get { return behavior; }
  113. }
  114. [DataCategory ("Data")]
  115. [DataSysDescription ("Command text to execute.")]
  116. [DefaultValue ("")]
  117. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  118. [RefreshProperties (RefreshProperties.All)]
  119. public
  120. #if NET_2_0
  121. override
  122. #endif //NET_2_0
  123. string CommandText {
  124. get { return commandText; }
  125. set {
  126. if (value != commandText && preparedStatement != null)
  127. Unprepare ();
  128. commandText = value;
  129. }
  130. }
  131. [DataSysDescription ("Time to wait for command to execute.")]
  132. [DefaultValue (30)]
  133. public
  134. #if NET_2_0
  135. override
  136. #endif //NET_2_0
  137. int CommandTimeout {
  138. get { return commandTimeout; }
  139. set {
  140. if (value < 0)
  141. throw new ArgumentException ("The property value assigned is less than 0.");
  142. commandTimeout = value;
  143. }
  144. }
  145. [DataCategory ("Data")]
  146. [DataSysDescription ("How to interpret the CommandText.")]
  147. [DefaultValue (CommandType.Text)]
  148. [RefreshProperties (RefreshProperties.All)]
  149. public
  150. #if NET_2_0
  151. override
  152. #endif //NET_2_0
  153. CommandType CommandType {
  154. get { return commandType; }
  155. set {
  156. if (value == CommandType.TableDirect)
  157. throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
  158. if (!Enum.IsDefined (typeof (CommandType), value))
  159. throw ExceptionHelper.InvalidEnumValueException ("CommandType", value);
  160. commandType = value;
  161. }
  162. }
  163. [DataCategory ("Behavior")]
  164. [DefaultValue (null)]
  165. [DataSysDescription ("Connection used by the command.")]
  166. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  167. public
  168. #if NET_2_0
  169. new
  170. #endif //NET_2_0
  171. SqlConnection Connection {
  172. get { return connection; }
  173. set {
  174. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  175. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  176. transaction = null;
  177. connection = value;
  178. }
  179. }
  180. [Browsable (false)]
  181. [DefaultValue (true)]
  182. [DesignOnly (true)]
  183. public
  184. #if NET_2_0
  185. override
  186. #endif //NET_2_0
  187. bool DesignTimeVisible {
  188. get { return designTimeVisible; }
  189. set { designTimeVisible = value; }
  190. }
  191. [DataCategory ("Data")]
  192. [DataSysDescription ("The parameters collection.")]
  193. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  194. public
  195. #if NET_2_0
  196. new
  197. #endif //NET_2_0
  198. SqlParameterCollection Parameters {
  199. get { return parameters; }
  200. }
  201. internal ITds Tds {
  202. get { return Connection.Tds; }
  203. }
  204. IDbConnection IDbCommand.Connection {
  205. get { return Connection; }
  206. set {
  207. if (!(value is SqlConnection))
  208. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  209. Connection = (SqlConnection) value;
  210. }
  211. }
  212. IDataParameterCollection IDbCommand.Parameters {
  213. get { return Parameters; }
  214. }
  215. IDbTransaction IDbCommand.Transaction {
  216. get { return Transaction; }
  217. set {
  218. if (!(value is SqlTransaction))
  219. throw new ArgumentException ();
  220. Transaction = (SqlTransaction) value;
  221. }
  222. }
  223. [Browsable (false)]
  224. [DataSysDescription ("The transaction used by the command.")]
  225. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  226. public new SqlTransaction Transaction {
  227. get { return transaction; }
  228. set { transaction = value; }
  229. }
  230. [DataCategory ("Behavior")]
  231. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  232. [DefaultValue (UpdateRowSource.Both)]
  233. public
  234. #if NET_2_0
  235. override
  236. #endif // NET_2_0
  237. UpdateRowSource UpdatedRowSource {
  238. get { return updatedRowSource; }
  239. set {
  240. if (!Enum.IsDefined (typeof (UpdateRowSource), value))
  241. throw ExceptionHelper.InvalidEnumValueException ("UpdateRowSource", value);
  242. updatedRowSource = value;
  243. }
  244. }
  245. #endregion // Fields
  246. #region Methods
  247. public
  248. #if NET_2_0
  249. override
  250. #endif // NET_2_0
  251. void Cancel ()
  252. {
  253. if (Connection == null || Connection.Tds == null)
  254. return;
  255. Connection.Tds.Cancel ();
  256. }
  257. internal void CloseDataReader (bool moreResults)
  258. {
  259. Connection.DataReader = null;
  260. if ((behavior & CommandBehavior.CloseConnection) != 0)
  261. Connection.Close ();
  262. // Reset the behavior
  263. behavior = CommandBehavior.Default;
  264. Tds.SequentialAccess = false;
  265. }
  266. public new SqlParameter CreateParameter ()
  267. {
  268. return new SqlParameter ();
  269. }
  270. internal void DeriveParameters ()
  271. {
  272. if (commandType != CommandType.StoredProcedure)
  273. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  274. ValidateCommand ("DeriveParameters");
  275. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  276. localParameters.Add ("@procedure_name", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  277. string sql = "sp_procedure_params_rowset";
  278. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  279. SqlDataReader reader = new SqlDataReader (this);
  280. parameters.Clear ();
  281. object[] dbValues = new object[reader.FieldCount];
  282. while (reader.Read ()) {
  283. reader.GetValues (dbValues);
  284. parameters.Add (new SqlParameter (dbValues));
  285. }
  286. reader.Close ();
  287. }
  288. private void Execute (CommandBehavior behavior, bool wantResults)
  289. {
  290. Connection.Tds.RecordsAffected = -1;
  291. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  292. if (preparedStatement == null) {
  293. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  294. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  295. StringBuilder sql1 = new StringBuilder ();
  296. StringBuilder sql2 = new StringBuilder ();
  297. if (schemaOnly || keyInfo)
  298. sql1.Append ("SET FMTONLY OFF;");
  299. if (keyInfo) {
  300. sql1.Append ("SET NO_BROWSETABLE ON;");
  301. sql2.Append ("SET NO_BROWSETABLE OFF;");
  302. }
  303. if (schemaOnly) {
  304. sql1.Append ("SET FMTONLY ON;");
  305. sql2.Append ("SET FMTONLY OFF;");
  306. }
  307. switch (CommandType) {
  308. case CommandType.StoredProcedure:
  309. if (keyInfo || schemaOnly)
  310. Connection.Tds.Execute (sql1.ToString ());
  311. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  312. if (keyInfo || schemaOnly)
  313. Connection.Tds.Execute (sql2.ToString ());
  314. break;
  315. case CommandType.Text:
  316. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  317. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  318. break;
  319. }
  320. }
  321. else
  322. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  323. }
  324. public
  325. #if NET_2_0
  326. override
  327. #endif // NET_2_0
  328. int ExecuteNonQuery ()
  329. {
  330. ValidateCommand ("ExecuteNonQuery");
  331. int result = 0;
  332. behavior = CommandBehavior.Default;
  333. try {
  334. Execute (CommandBehavior.Default, false);
  335. result = Connection.Tds.RecordsAffected;
  336. }
  337. catch (TdsTimeoutException e) {
  338. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  339. }
  340. GetOutputParameters ();
  341. return result;
  342. }
  343. public new SqlDataReader ExecuteReader ()
  344. {
  345. return ExecuteReader (CommandBehavior.Default);
  346. }
  347. public new SqlDataReader ExecuteReader (CommandBehavior behavior)
  348. {
  349. ValidateCommand ("ExecuteReader");
  350. try {
  351. this.behavior = behavior;
  352. if ((behavior & CommandBehavior.SequentialAccess) != 0)
  353. Tds.SequentialAccess = true;
  354. Execute (behavior, true);
  355. Connection.DataReader = new SqlDataReader (this);
  356. }
  357. catch (TdsTimeoutException e) {
  358. // if behavior is closeconnection, even if it throws exception
  359. // the connection has to be closed.
  360. if ((behavior & CommandBehavior.CloseConnection) != 0)
  361. Connection.Close ();
  362. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  363. } catch (SqlException) {
  364. // if behavior is closeconnection, even if it throws exception
  365. // the connection has to be closed.
  366. if ((behavior & CommandBehavior.CloseConnection) != 0)
  367. Connection.Close ();
  368. throw;
  369. }
  370. return Connection.DataReader;
  371. }
  372. public
  373. #if NET_2_0
  374. override
  375. #endif // NET_2_0
  376. object ExecuteScalar ()
  377. {
  378. ValidateCommand ("ExecuteScalar");
  379. behavior = CommandBehavior.Default;
  380. try {
  381. Execute (CommandBehavior.Default, true);
  382. }
  383. catch (TdsTimeoutException e) {
  384. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  385. }
  386. if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
  387. return null;
  388. object result = Connection.Tds.ColumnValues [0];
  389. CloseDataReader (true);
  390. return result;
  391. }
  392. public XmlReader ExecuteXmlReader ()
  393. {
  394. ValidateCommand ("ExecuteXmlReader");
  395. behavior = CommandBehavior.Default;
  396. try {
  397. Execute (CommandBehavior.Default, true);
  398. }
  399. catch (TdsTimeoutException e) {
  400. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  401. }
  402. SqlDataReader dataReader = new SqlDataReader (this);
  403. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  404. XmlReader xmlReader = new XmlTextReader (textReader);
  405. return xmlReader;
  406. }
  407. internal void GetOutputParameters ()
  408. {
  409. IList list = Connection.Tds.OutputParameters;
  410. if (list != null && list.Count > 0) {
  411. int index = 0;
  412. foreach (SqlParameter parameter in parameters) {
  413. if (parameter.Direction != ParameterDirection.Input) {
  414. parameter.Value = list [index];
  415. index += 1;
  416. }
  417. if (index >= list.Count)
  418. break;
  419. }
  420. }
  421. }
  422. object ICloneable.Clone ()
  423. {
  424. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  425. }
  426. IDbDataParameter IDbCommand.CreateParameter ()
  427. {
  428. return CreateParameter ();
  429. }
  430. IDataReader IDbCommand.ExecuteReader ()
  431. {
  432. return ExecuteReader ();
  433. }
  434. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  435. {
  436. return ExecuteReader (behavior);
  437. }
  438. public
  439. #if NET_2_0
  440. override
  441. #endif // NET_2_0
  442. void Prepare ()
  443. {
  444. ValidateCommand ("Prepare");
  445. if (CommandType == CommandType.StoredProcedure)
  446. return;
  447. try {
  448. foreach (SqlParameter param in Parameters)
  449. param.CheckIfInitialized ();
  450. }catch (Exception e) {
  451. throw new InvalidOperationException ("SqlCommand.Prepare requires " + e.Message);
  452. }
  453. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  454. }
  455. public
  456. #if NET_2_0
  457. override
  458. #endif // NET_2_0
  459. void ResetCommandTimeout ()
  460. {
  461. commandTimeout = 30;
  462. }
  463. private void Unprepare ()
  464. {
  465. Connection.Tds.Unprepare (preparedStatement);
  466. preparedStatement = null;
  467. }
  468. private void ValidateCommand (string method)
  469. {
  470. if (Connection == null)
  471. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  472. if (Connection.Transaction != null && transaction != Connection.Transaction)
  473. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  474. if (Connection.State != ConnectionState.Open)
  475. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  476. if (commandText == String.Empty || commandText == null)
  477. throw new InvalidOperationException ("The command text for this Command has not been set.");
  478. if (Connection.DataReader != null)
  479. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  480. if (Connection.XmlReader != null)
  481. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  482. #if NET_2_0
  483. if (method.StartsWith ("Begin") && !Connection.AsyncProcessing)
  484. throw new InvalidOperationException ("This Connection object is not " +
  485. "in Asynchronous mode. Use 'Asynchronous" +
  486. " Processing = true' to set it.");
  487. #endif // NET_2_0
  488. }
  489. #if NET_2_0
  490. [MonoTODO]
  491. protected override DbParameter CreateDbParameter ()
  492. {
  493. return (DbParameter) CreateParameter ();
  494. }
  495. [MonoTODO]
  496. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  497. {
  498. return (DbDataReader) ExecuteReader (behavior);
  499. }
  500. [MonoTODO]
  501. protected override DbConnection DbConnection
  502. {
  503. get { return (DbConnection) Connection; }
  504. set { Connection = (SqlConnection) value; }
  505. }
  506. [MonoTODO]
  507. protected override DbParameterCollection DbParameterCollection
  508. {
  509. get { return (DbParameterCollection) Parameters; }
  510. }
  511. [MonoTODO]
  512. protected override DbTransaction DbTransaction
  513. {
  514. get { return (DbTransaction) Transaction; }
  515. set { Transaction = (SqlTransaction) value; }
  516. }
  517. #endif // NET_2_0
  518. #endregion // Methods
  519. #if NET_2_0
  520. #region Asynchronous Methods
  521. internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior,
  522. bool wantResults,
  523. AsyncCallback callback,
  524. object state)
  525. {
  526. IAsyncResult ar = null;
  527. Connection.Tds.RecordsAffected = -1;
  528. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  529. if (preparedStatement == null) {
  530. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  531. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  532. StringBuilder sql1 = new StringBuilder ();
  533. StringBuilder sql2 = new StringBuilder ();
  534. if (schemaOnly || keyInfo)
  535. sql1.Append ("SET FMTONLY OFF;");
  536. if (keyInfo) {
  537. sql1.Append ("SET NO_BROWSETABLE ON;");
  538. sql2.Append ("SET NO_BROWSETABLE OFF;");
  539. }
  540. if (schemaOnly) {
  541. sql1.Append ("SET FMTONLY ON;");
  542. sql2.Append ("SET FMTONLY OFF;");
  543. }
  544. switch (CommandType) {
  545. case CommandType.StoredProcedure:
  546. string prolog = "";
  547. string epilog = "";
  548. if (keyInfo || schemaOnly)
  549. prolog = sql1.ToString ();
  550. if (keyInfo || schemaOnly)
  551. epilog = sql2.ToString ();
  552. Connection.Tds.BeginExecuteProcedure (prolog,
  553. epilog,
  554. CommandText,
  555. !wantResults,
  556. parms,
  557. callback,
  558. state);
  559. break;
  560. case CommandType.Text:
  561. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  562. if (wantResults)
  563. ar = Connection.Tds.BeginExecuteQuery (sql, parms,
  564. callback, state);
  565. else
  566. ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
  567. break;
  568. }
  569. }
  570. else
  571. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  572. return ar;
  573. }
  574. internal void EndExecuteInternal (IAsyncResult ar)
  575. {
  576. SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
  577. Connection.Tds.WaitFor (sqlResult.InternalResult);
  578. Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
  579. }
  580. public IAsyncResult BeginExecuteNonQuery ()
  581. {
  582. return BeginExecuteNonQuery (null, null);
  583. }
  584. public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object state)
  585. {
  586. ValidateCommand ("BeginExecuteNonQuery");
  587. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  588. ar.EndMethod = "EndExecuteNonQuery";
  589. ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
  590. return ar;
  591. }
  592. public int EndExecuteNonQuery (IAsyncResult ar)
  593. {
  594. ValidateAsyncResult (ar, "EndExecuteNonQuery");
  595. EndExecuteInternal (ar);
  596. int ret = Connection.Tds.RecordsAffected;
  597. GetOutputParameters ();
  598. ( (SqlAsyncResult) ar).Ended = true;
  599. return ret;
  600. }
  601. public IAsyncResult BeginExecuteReader ()
  602. {
  603. return BeginExecuteReader (null, null, CommandBehavior.Default);
  604. }
  605. public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
  606. {
  607. return BeginExecuteReader (null, null, behavior);
  608. }
  609. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state)
  610. {
  611. return BeginExecuteReader (callback, state, CommandBehavior.Default);
  612. }
  613. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state, CommandBehavior behavior)
  614. {
  615. ValidateCommand ("BeginExecuteReader");
  616. this.behavior = behavior;
  617. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  618. ar.EndMethod = "EndExecuteReader";
  619. IAsyncResult tdsResult = BeginExecuteInternal (behavior, true,
  620. ar.BubbleCallback, state);
  621. ar.InternalResult = tdsResult;
  622. return ar;
  623. }
  624. public SqlDataReader EndExecuteReader (IAsyncResult ar)
  625. {
  626. ValidateAsyncResult (ar, "EndExecuteReader");
  627. EndExecuteInternal (ar);
  628. SqlDataReader reader = null;
  629. try {
  630. reader = new SqlDataReader (this);
  631. }
  632. catch (TdsTimeoutException e) {
  633. // if behavior is closeconnection, even if it throws exception
  634. // the connection has to be closed.
  635. if ((behavior & CommandBehavior.CloseConnection) != 0)
  636. Connection.Close ();
  637. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  638. } catch (SqlException) {
  639. // if behavior is closeconnection, even if it throws exception
  640. // the connection has to be closed.
  641. if ((behavior & CommandBehavior.CloseConnection) != 0)
  642. Connection.Close ();
  643. throw;
  644. }
  645. ( (SqlAsyncResult) ar).Ended = true;
  646. return reader;
  647. }
  648. public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object state)
  649. {
  650. ValidateCommand ("BeginExecuteXmlReader");
  651. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  652. ar.EndMethod = "EndExecuteXmlReader";
  653. ar.InternalResult = BeginExecuteInternal (behavior, true,
  654. ar.BubbleCallback, state);
  655. return ar;
  656. }
  657. public XmlReader EndExecuteXmlReader (IAsyncResult ar)
  658. {
  659. ValidateAsyncResult (ar, "EndExecuteXmlReader");
  660. EndExecuteInternal (ar);
  661. SqlDataReader reader = new SqlDataReader (this);
  662. SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
  663. XmlReader xmlReader = new XmlTextReader (textReader);
  664. ( (SqlAsyncResult) ar).Ended = true;
  665. return xmlReader;
  666. }
  667. internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
  668. {
  669. if (ar == null)
  670. throw new ArgumentException ("result passed is null!");
  671. if (! (ar is SqlAsyncResult))
  672. throw new ArgumentException (String.Format ("cannot test validity of types {0}",
  673. ar.GetType ()
  674. ));
  675. SqlAsyncResult result = (SqlAsyncResult) ar;
  676. if (result.EndMethod != endMethod)
  677. throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " +
  678. "Expected call to {1} but {0} is called instead.",
  679. endMethod,
  680. result.EndMethod
  681. ));
  682. if (result.Ended)
  683. throw new InvalidOperationException (String.Format ("The method {0} cannot be called " +
  684. "more than once for the same AsyncResult.",
  685. endMethod));
  686. }
  687. #endregion // Asynchronous Methods
  688. #endif // NET_2_0
  689. }
  690. }