SqlCommand.cs 30 KB

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