SqlCommand.cs 26 KB

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