SqlCommand.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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.IO;
  40. using System.Collections;
  41. using System.Collections.Specialized;
  42. using System.ComponentModel;
  43. using System.Data;
  44. using System.Data.Common;
  45. #if NET_2_0
  46. using System.Data.Sql;
  47. #endif
  48. using System.Runtime.InteropServices;
  49. using System.Text;
  50. using System.Xml;
  51. namespace System.Data.SqlClient {
  52. [DesignerAttribute ("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
  53. [ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
  54. #if NET_2_0
  55. [DefaultEventAttribute ("RecordsAffected")]
  56. public sealed class SqlCommand : DbCommand, IDbCommand, ICloneable
  57. #else
  58. public sealed class SqlCommand : Component, IDbCommand, ICloneable
  59. #endif // NET_2_0
  60. {
  61. #region Fields
  62. const int DEFAULT_COMMAND_TIMEOUT = 30;
  63. bool disposed;
  64. int commandTimeout;
  65. bool designTimeVisible;
  66. string commandText;
  67. CommandType commandType;
  68. SqlConnection connection;
  69. SqlTransaction transaction;
  70. UpdateRowSource updatedRowSource;
  71. CommandBehavior behavior = CommandBehavior.Default;
  72. SqlParameterCollection parameters;
  73. string preparedStatement;
  74. #if NET_2_0
  75. SqlNotificationRequest notification;
  76. bool notificationAutoEnlist;
  77. #endif
  78. #endregion // Fields
  79. #region Constructors
  80. public SqlCommand()
  81. : this (String.Empty, null, null)
  82. {
  83. }
  84. public SqlCommand (string commandText)
  85. : this (commandText, null, null)
  86. {
  87. }
  88. public SqlCommand (string commandText, SqlConnection connection)
  89. : this (commandText, connection, null)
  90. {
  91. }
  92. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  93. {
  94. this.commandText = commandText;
  95. this.connection = connection;
  96. this.transaction = transaction;
  97. this.commandType = CommandType.Text;
  98. this.updatedRowSource = UpdateRowSource.Both;
  99. this.commandTimeout = DEFAULT_COMMAND_TIMEOUT;
  100. #if NET_2_0
  101. notificationAutoEnlist = true;
  102. #endif
  103. designTimeVisible = true;
  104. parameters = new SqlParameterCollection (this);
  105. }
  106. private SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction, CommandType commandType, UpdateRowSource updatedRowSource, bool designTimeVisible, int commandTimeout, SqlParameterCollection parameters)
  107. {
  108. this.commandText = commandText;
  109. this.connection = connection;
  110. this.transaction = transaction;
  111. this.commandType = commandType;
  112. this.updatedRowSource = updatedRowSource;
  113. this.designTimeVisible = designTimeVisible;
  114. this.commandTimeout = commandTimeout;
  115. this.parameters = new SqlParameterCollection(this);
  116. for (int i = 0;i < parameters.Count;i++)
  117. this.parameters.Add(((ICloneable)parameters[i]).Clone());
  118. }
  119. #endregion // Constructors
  120. #region Properties
  121. internal CommandBehavior CommandBehavior {
  122. get { return behavior; }
  123. }
  124. #if !NET_2_0
  125. [DataSysDescription ("Command text to execute.")]
  126. #endif
  127. [DefaultValue ("")]
  128. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  129. [RefreshProperties (RefreshProperties.All)]
  130. public
  131. #if NET_2_0
  132. override
  133. #endif //NET_2_0
  134. string CommandText {
  135. get {
  136. if (commandText == null)
  137. return string.Empty;
  138. return commandText;
  139. }
  140. set {
  141. if (value != commandText && preparedStatement != null)
  142. Unprepare ();
  143. commandText = value;
  144. }
  145. }
  146. #if !NET_2_0
  147. [DataSysDescription ("Time to wait for command to execute.")]
  148. [DefaultValue (DEFAULT_COMMAND_TIMEOUT)]
  149. #endif
  150. public
  151. #if NET_2_0
  152. override
  153. #endif //NET_2_0
  154. int CommandTimeout {
  155. get { return commandTimeout; }
  156. set {
  157. if (value < 0)
  158. throw new ArgumentException ("The property value assigned is less than 0.");
  159. commandTimeout = value;
  160. }
  161. }
  162. #if !NET_2_0
  163. [DataSysDescription ("How to interpret the CommandText.")]
  164. #endif
  165. [DefaultValue (CommandType.Text)]
  166. [RefreshProperties (RefreshProperties.All)]
  167. public
  168. #if NET_2_0
  169. override
  170. #endif //NET_2_0
  171. CommandType CommandType {
  172. get { return commandType; }
  173. set {
  174. if (value == CommandType.TableDirect)
  175. #if NET_2_0
  176. throw new ArgumentOutOfRangeException ("CommandType.TableDirect is not supported " +
  177. "by the Mono SqlClient Data Provider.");
  178. #else
  179. throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
  180. #endif
  181. ExceptionHelper.CheckEnumValue (typeof (CommandType), value);
  182. commandType = value;
  183. }
  184. }
  185. [DefaultValue (null)]
  186. #if !NET_2_0
  187. [DataSysDescription ("Connection used by the command.")]
  188. #endif
  189. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  190. public
  191. #if NET_2_0
  192. new
  193. #endif //NET_2_0
  194. SqlConnection Connection {
  195. get { return connection; }
  196. set {
  197. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  198. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  199. transaction = null;
  200. connection = value;
  201. }
  202. }
  203. [Browsable (false)]
  204. [DefaultValue (true)]
  205. [DesignOnly (true)]
  206. #if NET_2_0
  207. [EditorBrowsable (EditorBrowsableState.Never)]
  208. #endif
  209. public
  210. #if NET_2_0
  211. override
  212. #endif //NET_2_0
  213. bool DesignTimeVisible {
  214. get { return designTimeVisible; }
  215. set { designTimeVisible = value; }
  216. }
  217. #if !NET_2_0
  218. [DataSysDescription ("The parameters collection.")]
  219. #endif
  220. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  221. public
  222. #if NET_2_0
  223. new
  224. #endif //NET_2_0
  225. SqlParameterCollection Parameters {
  226. get { return parameters; }
  227. }
  228. internal ITds Tds {
  229. get { return Connection.Tds; }
  230. }
  231. IDbConnection IDbCommand.Connection {
  232. get { return Connection; }
  233. set {
  234. if (!(value == null || value is SqlConnection))
  235. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  236. Connection = (SqlConnection) value;
  237. }
  238. }
  239. IDataParameterCollection IDbCommand.Parameters {
  240. get { return Parameters; }
  241. }
  242. IDbTransaction IDbCommand.Transaction {
  243. get { return Transaction; }
  244. set {
  245. if (!(value == null || value is SqlTransaction))
  246. throw new ArgumentException ();
  247. Transaction = (SqlTransaction) value;
  248. }
  249. }
  250. [Browsable (false)]
  251. #if !NET_2_0
  252. [DataSysDescription ("The transaction used by the command.")]
  253. #endif
  254. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  255. public new SqlTransaction Transaction {
  256. get { return transaction; }
  257. set { transaction = value; }
  258. }
  259. #if !NET_2_0
  260. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  261. #endif
  262. [DefaultValue (UpdateRowSource.Both)]
  263. public
  264. #if NET_2_0
  265. override
  266. #endif // NET_2_0
  267. UpdateRowSource UpdatedRowSource {
  268. get { return updatedRowSource; }
  269. set {
  270. ExceptionHelper.CheckEnumValue (typeof (UpdateRowSource), value);
  271. updatedRowSource = value;
  272. }
  273. }
  274. #if NET_2_0
  275. [Browsable (false)]
  276. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  277. public SqlNotificationRequest Notification {
  278. get { return notification; }
  279. set { notification = value; }
  280. }
  281. [DefaultValue (true)]
  282. public bool NotificationAutoEnlist {
  283. get { return notificationAutoEnlist; }
  284. set { notificationAutoEnlist = value; }
  285. }
  286. #endif
  287. #endregion // Fields
  288. #region Methods
  289. public
  290. #if NET_2_0
  291. override
  292. #endif // NET_2_0
  293. void Cancel ()
  294. {
  295. if (Connection == null || Connection.Tds == null)
  296. return;
  297. Connection.Tds.Cancel ();
  298. }
  299. #if NET_2_0
  300. public SqlCommand Clone ()
  301. {
  302. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  303. }
  304. #endif // NET_2_0
  305. internal void CloseDataReader (bool moreResults)
  306. {
  307. Connection.DataReader = null;
  308. if ((behavior & CommandBehavior.CloseConnection) != 0)
  309. Connection.Close ();
  310. // Reset the behavior
  311. behavior = CommandBehavior.Default;
  312. if (Tds != null)
  313. Tds.SequentialAccess = false;
  314. }
  315. public new SqlParameter CreateParameter ()
  316. {
  317. return new SqlParameter ();
  318. }
  319. internal void DeriveParameters ()
  320. {
  321. if (commandType != CommandType.StoredProcedure)
  322. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  323. ValidateCommand ("DeriveParameters");
  324. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  325. localParameters.Add ("@procedure_name", SqlDbType.NVarChar, CommandText.Length).Value = CommandText;
  326. string sql = "sp_procedure_params_rowset";
  327. try {
  328. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  329. } catch (TdsInternalException ex) {
  330. Connection.Close ();
  331. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  332. }
  333. SqlDataReader reader = new SqlDataReader (this);
  334. parameters.Clear ();
  335. object[] dbValues = new object[reader.FieldCount];
  336. while (reader.Read ()) {
  337. reader.GetValues (dbValues);
  338. parameters.Add (new SqlParameter (dbValues));
  339. }
  340. reader.Close ();
  341. }
  342. private void Execute (CommandBehavior behavior, bool wantResults)
  343. {
  344. int index = 0;
  345. Connection.Tds.RecordsAffected = -1;
  346. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  347. foreach (TdsMetaParameter param in parms) {
  348. param.Validate (index++);
  349. }
  350. if (preparedStatement == null) {
  351. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  352. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  353. StringBuilder sql1 = new StringBuilder ();
  354. StringBuilder sql2 = new StringBuilder ();
  355. if (schemaOnly || keyInfo)
  356. sql1.Append ("SET FMTONLY OFF;");
  357. if (keyInfo) {
  358. sql1.Append ("SET NO_BROWSETABLE ON;");
  359. sql2.Append ("SET NO_BROWSETABLE OFF;");
  360. }
  361. if (schemaOnly) {
  362. sql1.Append ("SET FMTONLY ON;");
  363. sql2.Append ("SET FMTONLY OFF;");
  364. }
  365. switch (CommandType) {
  366. case CommandType.StoredProcedure:
  367. try {
  368. if (keyInfo || schemaOnly)
  369. Connection.Tds.Execute (sql1.ToString ());
  370. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  371. if (keyInfo || schemaOnly)
  372. Connection.Tds.Execute (sql2.ToString ());
  373. } catch (TdsInternalException ex) {
  374. Connection.Close ();
  375. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  376. }
  377. break;
  378. case CommandType.Text:
  379. string sql;
  380. if (sql2.Length > 0) {
  381. sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  382. } else {
  383. sql = String.Format ("{0}{1}", sql1.ToString (), CommandText);
  384. }
  385. try {
  386. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  387. } catch (TdsInternalException ex) {
  388. Connection.Close ();
  389. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  390. }
  391. break;
  392. }
  393. }
  394. else {
  395. try {
  396. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  397. } catch (TdsInternalException ex) {
  398. Connection.Close ();
  399. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  400. }
  401. }
  402. }
  403. public
  404. #if NET_2_0
  405. override
  406. #endif // NET_2_0
  407. int ExecuteNonQuery ()
  408. {
  409. ValidateCommand ("ExecuteNonQuery");
  410. int result = 0;
  411. behavior = CommandBehavior.Default;
  412. try {
  413. Execute (CommandBehavior.Default, false);
  414. result = Connection.Tds.RecordsAffected;
  415. }
  416. catch (TdsTimeoutException e) {
  417. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  418. }
  419. GetOutputParameters ();
  420. return result;
  421. }
  422. public new SqlDataReader ExecuteReader ()
  423. {
  424. return ExecuteReader (CommandBehavior.Default);
  425. }
  426. public new SqlDataReader ExecuteReader (CommandBehavior behavior)
  427. {
  428. ValidateCommand ("ExecuteReader");
  429. try {
  430. this.behavior = behavior;
  431. if ((behavior & CommandBehavior.SequentialAccess) != 0)
  432. Tds.SequentialAccess = true;
  433. Execute (behavior, true);
  434. Connection.DataReader = new SqlDataReader (this);
  435. } catch (TdsTimeoutException e) {
  436. // if behavior is closeconnection, even if it throws exception
  437. // the connection has to be closed.
  438. if ((behavior & CommandBehavior.CloseConnection) != 0)
  439. Connection.Close ();
  440. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  441. } catch (SqlException) {
  442. // if behavior is closeconnection, even if it throws exception
  443. // the connection has to be closed.
  444. if ((behavior & CommandBehavior.CloseConnection) != 0)
  445. Connection.Close ();
  446. throw;
  447. }
  448. return Connection.DataReader;
  449. }
  450. public
  451. #if NET_2_0
  452. override
  453. #endif // NET_2_0
  454. object ExecuteScalar ()
  455. {
  456. try {
  457. object result = null;
  458. ValidateCommand ("ExecuteScalar");
  459. behavior = CommandBehavior.Default;
  460. try {
  461. Execute (CommandBehavior.Default, true);
  462. }
  463. catch (TdsTimeoutException e) {
  464. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  465. }
  466. try {
  467. if (Connection.Tds.NextResult () && Connection.Tds.NextRow ())
  468. result = Connection.Tds.ColumnValues[0];
  469. if (commandType == CommandType.StoredProcedure) {
  470. Connection.Tds.SkipToEnd ();
  471. GetOutputParameters ();
  472. }
  473. } catch (TdsInternalException ex) {
  474. Connection.Close ();
  475. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  476. }
  477. return result;
  478. }
  479. finally {
  480. CloseDataReader (true);
  481. }
  482. }
  483. public XmlReader ExecuteXmlReader ()
  484. {
  485. ValidateCommand ("ExecuteXmlReader");
  486. behavior = CommandBehavior.Default;
  487. try {
  488. Execute (CommandBehavior.Default, true);
  489. } catch (TdsTimeoutException e) {
  490. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  491. }
  492. SqlDataReader dataReader = new SqlDataReader (this);
  493. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  494. XmlReader xmlReader = new XmlTextReader (textReader);
  495. return xmlReader;
  496. }
  497. internal void GetOutputParameters ()
  498. {
  499. IList list = Connection.Tds.OutputParameters;
  500. if (list != null && list.Count > 0) {
  501. int index = 0;
  502. foreach (SqlParameter parameter in parameters) {
  503. if (parameter.Direction != ParameterDirection.Input) {
  504. parameter.Value = list [index];
  505. index += 1;
  506. }
  507. if (index >= list.Count)
  508. break;
  509. }
  510. }
  511. }
  512. object ICloneable.Clone ()
  513. {
  514. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  515. }
  516. #if !NET_2_0
  517. IDbDataParameter IDbCommand.CreateParameter ()
  518. {
  519. return CreateParameter ();
  520. }
  521. IDataReader IDbCommand.ExecuteReader ()
  522. {
  523. return ExecuteReader ();
  524. }
  525. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  526. {
  527. return ExecuteReader (behavior);
  528. }
  529. #endif
  530. #if NET_2_0
  531. protected override void Dispose (bool disposing)
  532. {
  533. if (disposed) return;
  534. if (disposing) {
  535. parameters.Clear();
  536. }
  537. base.Dispose (disposing);
  538. disposed = true;
  539. }
  540. #endif
  541. public
  542. #if NET_2_0
  543. override
  544. #endif // NET_2_0
  545. void Prepare ()
  546. {
  547. ValidateCommand ("Prepare");
  548. if (CommandType == CommandType.StoredProcedure)
  549. return;
  550. try {
  551. foreach (SqlParameter param in Parameters)
  552. param.CheckIfInitialized ();
  553. } catch (Exception e) {
  554. throw new InvalidOperationException ("SqlCommand.Prepare requires " + e.Message);
  555. }
  556. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  557. }
  558. public void ResetCommandTimeout ()
  559. {
  560. commandTimeout = DEFAULT_COMMAND_TIMEOUT;
  561. }
  562. private void Unprepare ()
  563. {
  564. Connection.Tds.Unprepare (preparedStatement);
  565. preparedStatement = null;
  566. }
  567. private void ValidateCommand (string method)
  568. {
  569. if (Connection == null)
  570. #if NET_2_0
  571. throw new NullReferenceException (String.Format ("{0} requires a Connection object to continue.", method));
  572. #else
  573. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  574. #endif
  575. if (Connection.Transaction != null && transaction != Connection.Transaction)
  576. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  577. if (Connection.State != ConnectionState.Open)
  578. #if NET_2_0
  579. throw new NullReferenceException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  580. #else
  581. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  582. #endif
  583. if (CommandText.Length == 0)
  584. throw new InvalidOperationException ("The command text for this Command has not been set.");
  585. if (Connection.DataReader != null)
  586. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  587. if (Connection.XmlReader != null)
  588. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  589. #if NET_2_0
  590. if (method.StartsWith ("Begin") && !Connection.AsyncProcessing)
  591. throw new InvalidOperationException ("This Connection object is not " +
  592. "in Asynchronous mode. Use 'Asynchronous" +
  593. " Processing = true' to set it.");
  594. #endif // NET_2_0
  595. }
  596. #if NET_2_0
  597. protected override DbParameter CreateDbParameter ()
  598. {
  599. return CreateParameter ();
  600. }
  601. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  602. {
  603. return ExecuteReader (behavior);
  604. }
  605. protected override DbConnection DbConnection {
  606. get { return Connection; }
  607. set { Connection = (SqlConnection) value; }
  608. }
  609. protected override DbParameterCollection DbParameterCollection {
  610. get { return Parameters; }
  611. }
  612. protected override DbTransaction DbTransaction {
  613. get { return Transaction; }
  614. set { Transaction = (SqlTransaction) value; }
  615. }
  616. #endif // NET_2_0
  617. #endregion // Methods
  618. #if NET_2_0
  619. #region Asynchronous Methods
  620. internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior,
  621. bool wantResults,
  622. AsyncCallback callback,
  623. object state)
  624. {
  625. IAsyncResult ar = null;
  626. Connection.Tds.RecordsAffected = -1;
  627. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  628. if (preparedStatement == null) {
  629. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  630. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  631. StringBuilder sql1 = new StringBuilder ();
  632. StringBuilder sql2 = new StringBuilder ();
  633. if (schemaOnly || keyInfo)
  634. sql1.Append ("SET FMTONLY OFF;");
  635. if (keyInfo) {
  636. sql1.Append ("SET NO_BROWSETABLE ON;");
  637. sql2.Append ("SET NO_BROWSETABLE OFF;");
  638. }
  639. if (schemaOnly) {
  640. sql1.Append ("SET FMTONLY ON;");
  641. sql2.Append ("SET FMTONLY OFF;");
  642. }
  643. switch (CommandType) {
  644. case CommandType.StoredProcedure:
  645. string prolog = "";
  646. string epilog = "";
  647. if (keyInfo || schemaOnly)
  648. prolog = sql1.ToString ();
  649. if (keyInfo || schemaOnly)
  650. epilog = sql2.ToString ();
  651. try {
  652. Connection.Tds.BeginExecuteProcedure (prolog,
  653. epilog,
  654. CommandText,
  655. !wantResults,
  656. parms,
  657. callback,
  658. state);
  659. } catch (TdsInternalException ex) {
  660. Connection.Close ();
  661. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  662. }
  663. break;
  664. case CommandType.Text:
  665. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  666. try {
  667. if (wantResults)
  668. ar = Connection.Tds.BeginExecuteQuery (sql, parms, callback, state);
  669. else
  670. ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
  671. } catch (TdsInternalException ex) {
  672. Connection.Close ();
  673. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  674. }
  675. break;
  676. }
  677. }
  678. else {
  679. try {
  680. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  681. } catch (TdsInternalException ex) {
  682. Connection.Close ();
  683. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  684. }
  685. }
  686. return ar;
  687. }
  688. internal void EndExecuteInternal (IAsyncResult ar)
  689. {
  690. SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
  691. Connection.Tds.WaitFor (sqlResult.InternalResult);
  692. Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
  693. }
  694. public IAsyncResult BeginExecuteNonQuery ()
  695. {
  696. return BeginExecuteNonQuery (null, null);
  697. }
  698. public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object state)
  699. {
  700. ValidateCommand ("BeginExecuteNonQuery");
  701. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  702. ar.EndMethod = "EndExecuteNonQuery";
  703. ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
  704. return ar;
  705. }
  706. public int EndExecuteNonQuery (IAsyncResult ar)
  707. {
  708. ValidateAsyncResult (ar, "EndExecuteNonQuery");
  709. EndExecuteInternal (ar);
  710. int ret = Connection.Tds.RecordsAffected;
  711. GetOutputParameters ();
  712. ((SqlAsyncResult) ar).Ended = true;
  713. return ret;
  714. }
  715. public IAsyncResult BeginExecuteReader ()
  716. {
  717. return BeginExecuteReader (null, null, CommandBehavior.Default);
  718. }
  719. public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
  720. {
  721. return BeginExecuteReader (null, null, behavior);
  722. }
  723. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state)
  724. {
  725. return BeginExecuteReader (callback, state, CommandBehavior.Default);
  726. }
  727. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state, CommandBehavior behavior)
  728. {
  729. ValidateCommand ("BeginExecuteReader");
  730. this.behavior = behavior;
  731. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  732. ar.EndMethod = "EndExecuteReader";
  733. IAsyncResult tdsResult = BeginExecuteInternal (behavior, true,
  734. ar.BubbleCallback, state);
  735. ar.InternalResult = tdsResult;
  736. return ar;
  737. }
  738. public SqlDataReader EndExecuteReader (IAsyncResult ar)
  739. {
  740. ValidateAsyncResult (ar, "EndExecuteReader");
  741. EndExecuteInternal (ar);
  742. SqlDataReader reader = null;
  743. try {
  744. reader = new SqlDataReader (this);
  745. } catch (TdsTimeoutException e) {
  746. // if behavior is closeconnection, even if it throws exception
  747. // the connection has to be closed.
  748. if ((behavior & CommandBehavior.CloseConnection) != 0)
  749. Connection.Close ();
  750. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  751. } catch (SqlException) {
  752. // if behavior is closeconnection, even if it throws exception
  753. // the connection has to be closed.
  754. if ((behavior & CommandBehavior.CloseConnection) != 0)
  755. Connection.Close ();
  756. throw;
  757. }
  758. ((SqlAsyncResult) ar).Ended = true;
  759. return reader;
  760. }
  761. public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object state)
  762. {
  763. ValidateCommand ("BeginExecuteXmlReader");
  764. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  765. ar.EndMethod = "EndExecuteXmlReader";
  766. ar.InternalResult = BeginExecuteInternal (behavior, true,
  767. ar.BubbleCallback, state);
  768. return ar;
  769. }
  770. public IAsyncResult BeginExecuteXmlReader ()
  771. {
  772. return BeginExecuteXmlReader (null, null);
  773. }
  774. public XmlReader EndExecuteXmlReader (IAsyncResult ar)
  775. {
  776. ValidateAsyncResult (ar, "EndExecuteXmlReader");
  777. EndExecuteInternal (ar);
  778. SqlDataReader reader = new SqlDataReader (this);
  779. SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
  780. XmlReader xmlReader = new XmlTextReader (textReader);
  781. ((SqlAsyncResult) ar).Ended = true;
  782. return xmlReader;
  783. }
  784. internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
  785. {
  786. if (ar == null)
  787. throw new ArgumentException ("result passed is null!");
  788. if (! (ar is SqlAsyncResult))
  789. throw new ArgumentException (String.Format ("cannot test validity of types {0}",
  790. ar.GetType ()));
  791. SqlAsyncResult result = (SqlAsyncResult) ar;
  792. if (result.EndMethod != endMethod)
  793. throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " +
  794. "Expected call to {1} but {0} is called instead.",
  795. endMethod, result.EndMethod));
  796. if (result.Ended)
  797. throw new InvalidOperationException (String.Format ("The method {0} cannot be called " +
  798. "more than once for the same AsyncResult.", endMethod));
  799. }
  800. #endregion // Asynchronous Methods
  801. public event StatementCompletedEventHandler StatementCompleted;
  802. #endif // NET_2_0
  803. }
  804. }