2
0

SqlCommand.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. }
  263. public new SqlParameter CreateParameter ()
  264. {
  265. return new SqlParameter ();
  266. }
  267. internal void DeriveParameters ()
  268. {
  269. if (commandType != CommandType.StoredProcedure)
  270. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  271. ValidateCommand ("DeriveParameters");
  272. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  273. localParameters.Add ("@procedure_name", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  274. string sql = "sp_procedure_params_rowset";
  275. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  276. SqlDataReader reader = new SqlDataReader (this);
  277. parameters.Clear ();
  278. object[] dbValues = new object[reader.FieldCount];
  279. while (reader.Read ()) {
  280. reader.GetValues (dbValues);
  281. parameters.Add (new SqlParameter (dbValues));
  282. }
  283. reader.Close ();
  284. }
  285. private void Execute (CommandBehavior behavior, bool wantResults)
  286. {
  287. Connection.Tds.RecordsAffected = -1;
  288. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  289. if (preparedStatement == null) {
  290. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  291. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  292. StringBuilder sql1 = new StringBuilder ();
  293. StringBuilder sql2 = new StringBuilder ();
  294. if (schemaOnly || keyInfo)
  295. sql1.Append ("SET FMTONLY OFF;");
  296. if (keyInfo) {
  297. sql1.Append ("SET NO_BROWSETABLE ON;");
  298. sql2.Append ("SET NO_BROWSETABLE OFF;");
  299. }
  300. if (schemaOnly) {
  301. sql1.Append ("SET FMTONLY ON;");
  302. sql2.Append ("SET FMTONLY OFF;");
  303. }
  304. switch (CommandType) {
  305. case CommandType.StoredProcedure:
  306. if (keyInfo || schemaOnly)
  307. Connection.Tds.Execute (sql1.ToString ());
  308. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  309. if (keyInfo || schemaOnly)
  310. Connection.Tds.Execute (sql2.ToString ());
  311. break;
  312. case CommandType.Text:
  313. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  314. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  315. break;
  316. }
  317. }
  318. else
  319. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  320. }
  321. public
  322. #if NET_2_0
  323. override
  324. #endif // NET_2_0
  325. int ExecuteNonQuery ()
  326. {
  327. ValidateCommand ("ExecuteNonQuery");
  328. int result = 0;
  329. behavior = CommandBehavior.Default;
  330. try {
  331. Execute (CommandBehavior.Default, false);
  332. result = Connection.Tds.RecordsAffected;
  333. }
  334. catch (TdsTimeoutException e) {
  335. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  336. }
  337. GetOutputParameters ();
  338. return result;
  339. }
  340. public new SqlDataReader ExecuteReader ()
  341. {
  342. return ExecuteReader (CommandBehavior.Default);
  343. }
  344. public new SqlDataReader ExecuteReader (CommandBehavior behavior)
  345. {
  346. ValidateCommand ("ExecuteReader");
  347. try {
  348. this.behavior = behavior;
  349. Execute (behavior, true);
  350. Connection.DataReader = new SqlDataReader (this);
  351. }
  352. catch (TdsTimeoutException e) {
  353. // if behavior is closeconnection, even if it throws exception
  354. // the connection has to be closed.
  355. if ((behavior & CommandBehavior.CloseConnection) != 0)
  356. Connection.Close ();
  357. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  358. } catch (SqlException) {
  359. // if behavior is closeconnection, even if it throws exception
  360. // the connection has to be closed.
  361. if ((behavior & CommandBehavior.CloseConnection) != 0)
  362. Connection.Close ();
  363. throw;
  364. }
  365. return Connection.DataReader;
  366. }
  367. public
  368. #if NET_2_0
  369. override
  370. #endif // NET_2_0
  371. object ExecuteScalar ()
  372. {
  373. ValidateCommand ("ExecuteScalar");
  374. behavior = CommandBehavior.Default;
  375. try {
  376. Execute (CommandBehavior.Default, true);
  377. }
  378. catch (TdsTimeoutException e) {
  379. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  380. }
  381. if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
  382. return null;
  383. object result = Connection.Tds.ColumnValues [0];
  384. CloseDataReader (true);
  385. return result;
  386. }
  387. public XmlReader ExecuteXmlReader ()
  388. {
  389. ValidateCommand ("ExecuteXmlReader");
  390. behavior = CommandBehavior.Default;
  391. try {
  392. Execute (CommandBehavior.Default, true);
  393. }
  394. catch (TdsTimeoutException e) {
  395. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  396. }
  397. SqlDataReader dataReader = new SqlDataReader (this);
  398. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  399. XmlReader xmlReader = new XmlTextReader (textReader);
  400. return xmlReader;
  401. }
  402. internal void GetOutputParameters ()
  403. {
  404. IList list = Connection.Tds.OutputParameters;
  405. if (list != null && list.Count > 0) {
  406. int index = 0;
  407. foreach (SqlParameter parameter in parameters) {
  408. if (parameter.Direction != ParameterDirection.Input) {
  409. parameter.Value = list [index];
  410. index += 1;
  411. }
  412. if (index >= list.Count)
  413. break;
  414. }
  415. }
  416. }
  417. object ICloneable.Clone ()
  418. {
  419. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  420. }
  421. IDbDataParameter IDbCommand.CreateParameter ()
  422. {
  423. return CreateParameter ();
  424. }
  425. IDataReader IDbCommand.ExecuteReader ()
  426. {
  427. return ExecuteReader ();
  428. }
  429. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  430. {
  431. return ExecuteReader (behavior);
  432. }
  433. public
  434. #if NET_2_0
  435. override
  436. #endif // NET_2_0
  437. void Prepare ()
  438. {
  439. ValidateCommand ("Prepare");
  440. if (CommandType == CommandType.StoredProcedure)
  441. return;
  442. try {
  443. foreach (SqlParameter param in Parameters)
  444. param.CheckIfInitialized ();
  445. }catch (Exception e) {
  446. throw new InvalidOperationException ("SqlCommand.Prepare requires " + e.Message);
  447. }
  448. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  449. }
  450. public
  451. #if NET_2_0
  452. override
  453. #endif // NET_2_0
  454. void ResetCommandTimeout ()
  455. {
  456. commandTimeout = 30;
  457. }
  458. private void Unprepare ()
  459. {
  460. Connection.Tds.Unprepare (preparedStatement);
  461. preparedStatement = null;
  462. }
  463. private void ValidateCommand (string method)
  464. {
  465. if (Connection == null)
  466. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  467. if (Connection.Transaction != null && transaction != Connection.Transaction)
  468. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  469. if (Connection.State != ConnectionState.Open)
  470. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  471. if (commandText == String.Empty || commandText == null)
  472. throw new InvalidOperationException ("The command text for this Command has not been set.");
  473. if (Connection.DataReader != null)
  474. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  475. if (Connection.XmlReader != null)
  476. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  477. #if NET_2_0
  478. if (method.StartsWith ("Begin") && !Connection.AsyncProcessing)
  479. throw new InvalidOperationException ("This Connection object is not " +
  480. "in Asynchronous mode. Use 'Asynchronous" +
  481. " Processing = true' to set it.");
  482. #endif // NET_2_0
  483. }
  484. #if NET_2_0
  485. [MonoTODO]
  486. protected override DbParameter CreateDbParameter ()
  487. {
  488. return (DbParameter) CreateParameter ();
  489. }
  490. [MonoTODO]
  491. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  492. {
  493. return (DbDataReader) ExecuteReader (behavior);
  494. }
  495. [MonoTODO]
  496. protected override DbConnection DbConnection
  497. {
  498. get { return (DbConnection) Connection; }
  499. set { Connection = (SqlConnection) value; }
  500. }
  501. [MonoTODO]
  502. protected override DbParameterCollection DbParameterCollection
  503. {
  504. get { return (DbParameterCollection) Parameters; }
  505. }
  506. [MonoTODO]
  507. protected override DbTransaction DbTransaction
  508. {
  509. get { return (DbTransaction) Transaction; }
  510. set { Transaction = (SqlTransaction) value; }
  511. }
  512. #endif // NET_2_0
  513. #endregion // Methods
  514. #if NET_2_0
  515. #region Asynchronous Methods
  516. internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior,
  517. bool wantResults,
  518. AsyncCallback callback,
  519. object state)
  520. {
  521. IAsyncResult ar = null;
  522. Connection.Tds.RecordsAffected = -1;
  523. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  524. if (preparedStatement == null) {
  525. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  526. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  527. StringBuilder sql1 = new StringBuilder ();
  528. StringBuilder sql2 = new StringBuilder ();
  529. if (schemaOnly || keyInfo)
  530. sql1.Append ("SET FMTONLY OFF;");
  531. if (keyInfo) {
  532. sql1.Append ("SET NO_BROWSETABLE ON;");
  533. sql2.Append ("SET NO_BROWSETABLE OFF;");
  534. }
  535. if (schemaOnly) {
  536. sql1.Append ("SET FMTONLY ON;");
  537. sql2.Append ("SET FMTONLY OFF;");
  538. }
  539. switch (CommandType) {
  540. case CommandType.StoredProcedure:
  541. string prolog = "";
  542. string epilog = "";
  543. if (keyInfo || schemaOnly)
  544. prolog = sql1.ToString ();
  545. if (keyInfo || schemaOnly)
  546. epilog = sql2.ToString ();
  547. Connection.Tds.BeginExecuteProcedure (prolog,
  548. epilog,
  549. CommandText,
  550. !wantResults,
  551. parms,
  552. callback,
  553. state);
  554. break;
  555. case CommandType.Text:
  556. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  557. if (wantResults)
  558. ar = Connection.Tds.BeginExecuteQuery (sql, parms,
  559. callback, state);
  560. else
  561. ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
  562. break;
  563. }
  564. }
  565. else
  566. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  567. return ar;
  568. }
  569. internal void EndExecuteInternal (IAsyncResult ar)
  570. {
  571. SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
  572. Connection.Tds.WaitFor (sqlResult.InternalResult);
  573. Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
  574. }
  575. public IAsyncResult BeginExecuteNonQuery ()
  576. {
  577. return BeginExecuteNonQuery (null, null);
  578. }
  579. public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object state)
  580. {
  581. ValidateCommand ("BeginExecuteNonQuery");
  582. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  583. ar.EndMethod = "EndExecuteNonQuery";
  584. ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
  585. return ar;
  586. }
  587. public int EndExecuteNonQuery (IAsyncResult ar)
  588. {
  589. ValidateAsyncResult (ar, "EndExecuteNonQuery");
  590. EndExecuteInternal (ar);
  591. int ret = Connection.Tds.RecordsAffected;
  592. GetOutputParameters ();
  593. ( (SqlAsyncResult) ar).Ended = true;
  594. return ret;
  595. }
  596. public IAsyncResult BeginExecuteReader ()
  597. {
  598. return BeginExecuteReader (null, null, CommandBehavior.Default);
  599. }
  600. public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
  601. {
  602. return BeginExecuteReader (null, null, behavior);
  603. }
  604. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state)
  605. {
  606. return BeginExecuteReader (callback, state, CommandBehavior.Default);
  607. }
  608. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state, CommandBehavior behavior)
  609. {
  610. ValidateCommand ("BeginExecuteReader");
  611. this.behavior = behavior;
  612. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  613. ar.EndMethod = "EndExecuteReader";
  614. IAsyncResult tdsResult = BeginExecuteInternal (behavior, true,
  615. ar.BubbleCallback, state);
  616. ar.InternalResult = tdsResult;
  617. return ar;
  618. }
  619. public SqlDataReader EndExecuteReader (IAsyncResult ar)
  620. {
  621. ValidateAsyncResult (ar, "EndExecuteReader");
  622. EndExecuteInternal (ar);
  623. SqlDataReader reader = null;
  624. try {
  625. reader = new SqlDataReader (this);
  626. }
  627. catch (TdsTimeoutException e) {
  628. // if behavior is closeconnection, even if it throws exception
  629. // the connection has to be closed.
  630. if ((behavior & CommandBehavior.CloseConnection) != 0)
  631. Connection.Close ();
  632. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  633. } catch (SqlException) {
  634. // if behavior is closeconnection, even if it throws exception
  635. // the connection has to be closed.
  636. if ((behavior & CommandBehavior.CloseConnection) != 0)
  637. Connection.Close ();
  638. throw;
  639. }
  640. ( (SqlAsyncResult) ar).Ended = true;
  641. return reader;
  642. }
  643. public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object state)
  644. {
  645. ValidateCommand ("BeginExecuteXmlReader");
  646. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  647. ar.EndMethod = "EndExecuteXmlReader";
  648. ar.InternalResult = BeginExecuteInternal (behavior, true,
  649. ar.BubbleCallback, state);
  650. return ar;
  651. }
  652. public XmlReader EndExecuteXmlReader (IAsyncResult ar)
  653. {
  654. ValidateAsyncResult (ar, "EndExecuteXmlReader");
  655. EndExecuteInternal (ar);
  656. SqlDataReader reader = new SqlDataReader (this);
  657. SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
  658. XmlReader xmlReader = new XmlTextReader (textReader);
  659. ( (SqlAsyncResult) ar).Ended = true;
  660. return xmlReader;
  661. }
  662. internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
  663. {
  664. if (ar == null)
  665. throw new ArgumentException ("result passed is null!");
  666. if (! (ar is SqlAsyncResult))
  667. throw new ArgumentException (String.Format ("cannot test validity of types {0}",
  668. ar.GetType ()
  669. ));
  670. SqlAsyncResult result = (SqlAsyncResult) ar;
  671. if (result.EndMethod != endMethod)
  672. throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " +
  673. "Expected call to {1} but {0} is called instead.",
  674. endMethod,
  675. result.EndMethod
  676. ));
  677. if (result.Ended)
  678. throw new InvalidOperationException (String.Format ("The method {0} cannot be called " +
  679. "more than once for the same AsyncResult.",
  680. endMethod));
  681. }
  682. #endregion // Asynchronous Methods
  683. #endif // NET_2_0
  684. }
  685. }