SqlCommand.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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. commandText = commandText;
  81. }
  82. public SqlCommand (string commandText, SqlConnection connection)
  83. : this (commandText, connection, null)
  84. {
  85. Connection = connection;
  86. }
  87. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  88. {
  89. this.commandText = commandText;
  90. this.connection = connection;
  91. this.transaction = transaction;
  92. this.commandType = CommandType.Text;
  93. this.updatedRowSource = UpdateRowSource.Both;
  94. this.designTimeVisible = false;
  95. this.commandTimeout = 30;
  96. parameters = new SqlParameterCollection (this);
  97. }
  98. private SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction, CommandType commandType, UpdateRowSource updatedRowSource, bool designTimeVisible, int commandTimeout, SqlParameterCollection parameters)
  99. {
  100. this.commandText = commandText;
  101. this.connection = connection;
  102. this.transaction = transaction;
  103. this.commandType = commandType;
  104. this.updatedRowSource = updatedRowSource;
  105. this.designTimeVisible = designTimeVisible;
  106. this.commandTimeout = commandTimeout;
  107. this.parameters = new SqlParameterCollection(this);
  108. for (int i = 0;i < parameters.Count;i++)
  109. this.parameters.Add(((ICloneable)parameters[i]).Clone());
  110. }
  111. #endregion // Constructors
  112. #region Properties
  113. internal CommandBehavior CommandBehavior {
  114. get { return behavior; }
  115. }
  116. [DataCategory ("Data")]
  117. [DataSysDescription ("Command text to execute.")]
  118. [DefaultValue ("")]
  119. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  120. [RefreshProperties (RefreshProperties.All)]
  121. public
  122. #if NET_2_0
  123. override
  124. #endif //NET_2_0
  125. string CommandText {
  126. get { return commandText; }
  127. set {
  128. if (value != commandText && preparedStatement != null)
  129. Unprepare ();
  130. commandText = value;
  131. }
  132. }
  133. [DataSysDescription ("Time to wait for command to execute.")]
  134. [DefaultValue (30)]
  135. public
  136. #if NET_2_0
  137. override
  138. #endif //NET_2_0
  139. int CommandTimeout {
  140. get { return commandTimeout; }
  141. set {
  142. if (commandTimeout < 0)
  143. throw new ArgumentException ("The property value assigned is less than 0.");
  144. commandTimeout = value;
  145. }
  146. }
  147. [DataCategory ("Data")]
  148. [DataSysDescription ("How to interpret the CommandText.")]
  149. [DefaultValue (CommandType.Text)]
  150. [RefreshProperties (RefreshProperties.All)]
  151. public
  152. #if NET_2_0
  153. override
  154. #endif //NET_2_0
  155. CommandType CommandType {
  156. get { return commandType; }
  157. set {
  158. if (value == CommandType.TableDirect)
  159. throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
  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 { updatedRowSource = value; }
  240. }
  241. #endregion // Fields
  242. #region Methods
  243. public
  244. #if NET_2_0
  245. override
  246. #endif // NET_2_0
  247. void Cancel ()
  248. {
  249. if (Connection == null || Connection.Tds == null)
  250. return;
  251. Connection.Tds.Cancel ();
  252. }
  253. internal void CloseDataReader (bool moreResults)
  254. {
  255. Connection.DataReader = null;
  256. if ((behavior & CommandBehavior.CloseConnection) != 0)
  257. Connection.Close ();
  258. }
  259. public new SqlParameter CreateParameter ()
  260. {
  261. return new SqlParameter ();
  262. }
  263. internal void DeriveParameters ()
  264. {
  265. if (commandType != CommandType.StoredProcedure)
  266. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  267. ValidateCommand ("DeriveParameters");
  268. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  269. localParameters.Add ("@procedure_name", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  270. string sql = "sp_procedure_params_rowset";
  271. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  272. SqlDataReader reader = new SqlDataReader (this);
  273. parameters.Clear ();
  274. object[] dbValues = new object[reader.FieldCount];
  275. while (reader.Read ()) {
  276. reader.GetValues (dbValues);
  277. parameters.Add (new SqlParameter (dbValues));
  278. }
  279. reader.Close ();
  280. }
  281. private void Execute (CommandBehavior behavior, bool wantResults)
  282. {
  283. Connection.Tds.RecordsAffected = 0;
  284. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  285. if (preparedStatement == null) {
  286. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  287. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  288. StringBuilder sql1 = new StringBuilder ();
  289. StringBuilder sql2 = new StringBuilder ();
  290. if (schemaOnly || keyInfo)
  291. sql1.Append ("SET FMTONLY OFF;");
  292. if (keyInfo) {
  293. sql1.Append ("SET NO_BROWSETABLE ON;");
  294. sql2.Append ("SET NO_BROWSETABLE OFF;");
  295. }
  296. if (schemaOnly) {
  297. sql1.Append ("SET FMTONLY ON;");
  298. sql2.Append ("SET FMTONLY OFF;");
  299. }
  300. switch (CommandType) {
  301. case CommandType.StoredProcedure:
  302. if (keyInfo || schemaOnly)
  303. Connection.Tds.Execute (sql1.ToString ());
  304. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  305. if (keyInfo || schemaOnly)
  306. Connection.Tds.Execute (sql2.ToString ());
  307. break;
  308. case CommandType.Text:
  309. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  310. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  311. break;
  312. }
  313. }
  314. else
  315. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  316. }
  317. public
  318. #if NET_2_0
  319. override
  320. #endif // NET_2_0
  321. int ExecuteNonQuery ()
  322. {
  323. ValidateCommand ("ExecuteNonQuery");
  324. int result = 0;
  325. behavior = CommandBehavior.Default;
  326. try {
  327. Execute (CommandBehavior.Default, false);
  328. if (commandType == CommandType.StoredProcedure)
  329. result = -1;
  330. else {
  331. // .NET documentation says that except for INSERT, UPDATE and
  332. // DELETE where the return value is the number of rows affected
  333. // for the rest of the commands the return value is -1.
  334. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  335. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  336. (CommandText.ToUpper().IndexOf("DELETE")!=-1))
  337. result = Connection.Tds.RecordsAffected;
  338. else
  339. result = -1;
  340. }
  341. }
  342. catch (TdsTimeoutException e) {
  343. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  344. }
  345. GetOutputParameters ();
  346. return result;
  347. }
  348. public new SqlDataReader ExecuteReader ()
  349. {
  350. return ExecuteReader (CommandBehavior.Default);
  351. }
  352. public new SqlDataReader ExecuteReader (CommandBehavior behavior)
  353. {
  354. ValidateCommand ("ExecuteReader");
  355. try {
  356. this.behavior = behavior;
  357. Execute (behavior, true);
  358. Connection.DataReader = new SqlDataReader (this);
  359. }
  360. catch (TdsTimeoutException e) {
  361. // if behavior is closeconnection, even if it throws exception
  362. // the connection has to be closed.
  363. if ((behavior & CommandBehavior.CloseConnection) != 0)
  364. Connection.Close ();
  365. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  366. } catch (SqlException) {
  367. // if behavior is closeconnection, even if it throws exception
  368. // the connection has to be closed.
  369. if ((behavior & CommandBehavior.CloseConnection) != 0)
  370. Connection.Close ();
  371. throw;
  372. }
  373. return Connection.DataReader;
  374. }
  375. public
  376. #if NET_2_0
  377. override
  378. #endif // NET_2_0
  379. object ExecuteScalar ()
  380. {
  381. ValidateCommand ("ExecuteScalar");
  382. behavior = CommandBehavior.Default;
  383. try {
  384. Execute (CommandBehavior.Default, true);
  385. }
  386. catch (TdsTimeoutException e) {
  387. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  388. }
  389. if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
  390. return null;
  391. object result = Connection.Tds.ColumnValues [0];
  392. CloseDataReader (true);
  393. return result;
  394. }
  395. public XmlReader ExecuteXmlReader ()
  396. {
  397. ValidateCommand ("ExecuteXmlReader");
  398. behavior = CommandBehavior.Default;
  399. try {
  400. Execute (CommandBehavior.Default, true);
  401. }
  402. catch (TdsTimeoutException e) {
  403. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  404. }
  405. SqlDataReader dataReader = new SqlDataReader (this);
  406. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  407. XmlReader xmlReader = new XmlTextReader (textReader);
  408. return xmlReader;
  409. }
  410. internal void GetOutputParameters ()
  411. {
  412. IList list = Connection.Tds.OutputParameters;
  413. if (list != null && list.Count > 0) {
  414. int index = 0;
  415. foreach (SqlParameter parameter in parameters) {
  416. if (parameter.Direction != ParameterDirection.Input) {
  417. parameter.Value = list [index];
  418. index += 1;
  419. }
  420. if (index >= list.Count)
  421. break;
  422. }
  423. }
  424. }
  425. object ICloneable.Clone ()
  426. {
  427. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  428. }
  429. IDbDataParameter IDbCommand.CreateParameter ()
  430. {
  431. return CreateParameter ();
  432. }
  433. IDataReader IDbCommand.ExecuteReader ()
  434. {
  435. return ExecuteReader ();
  436. }
  437. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  438. {
  439. return ExecuteReader (behavior);
  440. }
  441. public
  442. #if NET_2_0
  443. override
  444. #endif // NET_2_0
  445. void Prepare ()
  446. {
  447. ValidateCommand ("Prepare");
  448. if (CommandType == CommandType.Text)
  449. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  450. }
  451. public
  452. #if NET_2_0
  453. override
  454. #endif // NET_2_0
  455. void ResetCommandTimeout ()
  456. {
  457. commandTimeout = 30;
  458. }
  459. private void Unprepare ()
  460. {
  461. Connection.Tds.Unprepare (preparedStatement);
  462. preparedStatement = null;
  463. }
  464. private void ValidateCommand (string method)
  465. {
  466. if (Connection == null)
  467. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  468. if (Connection.Transaction != null && transaction != Connection.Transaction)
  469. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  470. if (Connection.State != ConnectionState.Open)
  471. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  472. if (commandText == String.Empty || commandText == null)
  473. throw new InvalidOperationException ("The command text for this Command has not been set.");
  474. if (Connection.DataReader != null)
  475. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  476. if (Connection.XmlReader != null)
  477. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  478. #if NET_2_0
  479. if (method.StartsWith ("Begin") && !Connection.AsyncProcessing)
  480. throw new InvalidOperationException ("This Connection object is not " +
  481. "in Asynchronous mode. Use 'Asynchronous" +
  482. " Processing = true' to set it.");
  483. #endif // NET_2_0
  484. }
  485. #if NET_2_0
  486. [MonoTODO]
  487. protected override DbParameter CreateDbParameter ()
  488. {
  489. return (DbParameter) CreateParameter ();
  490. }
  491. [MonoTODO]
  492. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  493. {
  494. return (DbDataReader) ExecuteReader (behavior);
  495. }
  496. [MonoTODO]
  497. protected override DbConnection DbConnection
  498. {
  499. get { return (DbConnection) Connection; }
  500. set { Connection = (SqlConnection) value; }
  501. }
  502. [MonoTODO]
  503. protected override DbParameterCollection DbParameterCollection
  504. {
  505. get { return (DbParameterCollection) Parameters; }
  506. }
  507. [MonoTODO]
  508. protected override DbTransaction DbTransaction
  509. {
  510. get { return (DbTransaction) Transaction; }
  511. set { Transaction = (SqlTransaction) value; }
  512. }
  513. #endif // NET_2_0
  514. #endregion // Methods
  515. #if NET_2_0
  516. #region Asynchronous Methods
  517. internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior,
  518. bool wantResults,
  519. AsyncCallback callback,
  520. object state)
  521. {
  522. IAsyncResult ar = null;
  523. Connection.Tds.RecordsAffected = 0;
  524. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  525. if (preparedStatement == null) {
  526. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  527. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  528. StringBuilder sql1 = new StringBuilder ();
  529. StringBuilder sql2 = new StringBuilder ();
  530. if (schemaOnly || keyInfo)
  531. sql1.Append ("SET FMTONLY OFF;");
  532. if (keyInfo) {
  533. sql1.Append ("SET NO_BROWSETABLE ON;");
  534. sql2.Append ("SET NO_BROWSETABLE OFF;");
  535. }
  536. if (schemaOnly) {
  537. sql1.Append ("SET FMTONLY ON;");
  538. sql2.Append ("SET FMTONLY OFF;");
  539. }
  540. switch (CommandType) {
  541. case CommandType.StoredProcedure:
  542. string prolog = "";
  543. string epilog = "";
  544. if (keyInfo || schemaOnly)
  545. prolog = sql1.ToString ();
  546. if (keyInfo || schemaOnly)
  547. epilog = sql2.ToString ();
  548. Connection.Tds.BeginExecuteProcedure (prolog,
  549. epilog,
  550. CommandText,
  551. !wantResults,
  552. parms,
  553. callback,
  554. state);
  555. break;
  556. case CommandType.Text:
  557. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  558. if (wantResults)
  559. ar = Connection.Tds.BeginExecuteQuery (sql, parms,
  560. callback, state);
  561. else
  562. ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
  563. break;
  564. }
  565. }
  566. else
  567. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  568. return ar;
  569. }
  570. internal void EndExecuteInternal (IAsyncResult ar)
  571. {
  572. SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
  573. Connection.Tds.WaitFor (sqlResult.InternalResult);
  574. Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
  575. }
  576. public IAsyncResult BeginExecuteNonQuery ()
  577. {
  578. return BeginExecuteNonQuery (null, null);
  579. }
  580. public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object state)
  581. {
  582. ValidateCommand ("BeginExecuteNonQuery");
  583. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  584. ar.EndMethod = "EndExecuteNonQuery";
  585. ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
  586. return ar;
  587. }
  588. public int EndExecuteNonQuery (IAsyncResult ar)
  589. {
  590. ValidateAsyncResult (ar, "EndExecuteNonQuery");
  591. EndExecuteInternal (ar);
  592. int ret;
  593. if (commandType == CommandType.StoredProcedure)
  594. ret = -1;
  595. else {
  596. // .NET documentation says that except for INSERT, UPDATE and
  597. // DELETE where the return value is the number of rows affected
  598. // for the rest of the commands the return value is -1.
  599. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  600. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  601. (CommandText.ToUpper().IndexOf("DELETE")!=-1))
  602. ret = Connection.Tds.RecordsAffected;
  603. else
  604. ret = -1;
  605. }
  606. GetOutputParameters ();
  607. ( (SqlAsyncResult) ar).Ended = true;
  608. return ret;
  609. }
  610. public IAsyncResult BeginExecuteReader ()
  611. {
  612. return BeginExecuteReader (null, null, CommandBehavior.Default);
  613. }
  614. public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
  615. {
  616. return BeginExecuteReader (null, null, behavior);
  617. }
  618. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state)
  619. {
  620. return BeginExecuteReader (callback, state, CommandBehavior.Default);
  621. }
  622. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state, CommandBehavior behavior)
  623. {
  624. ValidateCommand ("BeginExecuteReader");
  625. this.behavior = behavior;
  626. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  627. ar.EndMethod = "EndExecuteReader";
  628. IAsyncResult tdsResult = BeginExecuteInternal (behavior, true,
  629. ar.BubbleCallback, state);
  630. ar.InternalResult = tdsResult;
  631. return ar;
  632. }
  633. public SqlDataReader EndExecuteReader (IAsyncResult ar)
  634. {
  635. ValidateAsyncResult (ar, "EndExecuteReader");
  636. EndExecuteInternal (ar);
  637. SqlDataReader reader = null;
  638. try {
  639. reader = new SqlDataReader (this);
  640. }
  641. catch (TdsTimeoutException e) {
  642. // if behavior is closeconnection, even if it throws exception
  643. // the connection has to be closed.
  644. if ((behavior & CommandBehavior.CloseConnection) != 0)
  645. Connection.Close ();
  646. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  647. } catch (SqlException) {
  648. // if behavior is closeconnection, even if it throws exception
  649. // the connection has to be closed.
  650. if ((behavior & CommandBehavior.CloseConnection) != 0)
  651. Connection.Close ();
  652. throw;
  653. }
  654. ( (SqlAsyncResult) ar).Ended = true;
  655. return reader;
  656. }
  657. public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object state)
  658. {
  659. ValidateCommand ("BeginExecuteXmlReader");
  660. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  661. ar.EndMethod = "EndExecuteXmlReader";
  662. ar.InternalResult = BeginExecuteInternal (behavior, true,
  663. ar.BubbleCallback, state);
  664. return ar;
  665. }
  666. public XmlReader EndExecuteXmlReader (IAsyncResult ar)
  667. {
  668. ValidateAsyncResult (ar, "EndExecuteXmlReader");
  669. EndExecuteInternal (ar);
  670. SqlDataReader reader = new SqlDataReader (this);
  671. SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
  672. XmlReader xmlReader = new XmlTextReader (textReader);
  673. ( (SqlAsyncResult) ar).Ended = true;
  674. return xmlReader;
  675. }
  676. internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
  677. {
  678. if (ar == null)
  679. throw new ArgumentException ("result passed is null!");
  680. if (! (ar is SqlAsyncResult))
  681. throw new ArgumentException (String.Format ("cannot test validity of types {0}",
  682. ar.GetType ()
  683. ));
  684. SqlAsyncResult result = (SqlAsyncResult) ar;
  685. if (result.EndMethod != endMethod)
  686. throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " +
  687. "Expected call to {1} but {0} is called instead.",
  688. endMethod,
  689. result.EndMethod
  690. ));
  691. if (result.Ended)
  692. throw new InvalidOperationException (String.Format ("The method {0} cannot be called " +
  693. "more than once for the same AsyncResult.",
  694. endMethod));
  695. }
  696. #endregion // Asynchronous Methods
  697. #endif // NET_2_0
  698. }
  699. }