SqlCommand.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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. [DefaultEventAttribute ("RecordsAffected")]
  54. #if NET_2_0
  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. [EditorBrowsable (EditorBrowsableState.Never)]
  208. public
  209. #if NET_2_0
  210. override
  211. #endif //NET_2_0
  212. bool DesignTimeVisible {
  213. get { return designTimeVisible; }
  214. set { designTimeVisible = value; }
  215. }
  216. [DataCategory ("Data")]
  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 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 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. [DataCategory ("Behavior")]
  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. #if NET_2_0
  273. throw new ArgumentOutOfRangeException (String.Format ("The UpdateRowSource enumeration value, {0}, is invalid",
  274. value));
  275. #else
  276. throw ExceptionHelper.InvalidEnumValueException ("UpdateRowSource", value);
  277. #endif
  278. updatedRowSource = value;
  279. }
  280. }
  281. #if NET_2_0
  282. public SqlNotificationRequest Notification {
  283. get { return notification; }
  284. set { notification = value; }
  285. }
  286. [DefaultValue (true)]
  287. public bool NotificationAutoEnlist {
  288. get { return notificationAutoEnlist; }
  289. set { notificationAutoEnlist = value; }
  290. }
  291. #endif
  292. #endregion // Fields
  293. #region Methods
  294. public
  295. #if NET_2_0
  296. override
  297. #endif // NET_2_0
  298. void Cancel ()
  299. {
  300. if (Connection == null || Connection.Tds == null)
  301. return;
  302. Connection.Tds.Cancel ();
  303. }
  304. #if NET_2_0
  305. public SqlCommand Clone ()
  306. {
  307. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  308. }
  309. #endif // NET_2_0
  310. internal void CloseDataReader (bool moreResults)
  311. {
  312. Connection.DataReader = null;
  313. if ((behavior & CommandBehavior.CloseConnection) != 0)
  314. Connection.Close ();
  315. // Reset the behavior
  316. behavior = CommandBehavior.Default;
  317. if (Tds != null)
  318. Tds.SequentialAccess = false;
  319. }
  320. public new SqlParameter CreateParameter ()
  321. {
  322. return new SqlParameter ();
  323. }
  324. internal void DeriveParameters ()
  325. {
  326. if (commandType != CommandType.StoredProcedure)
  327. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  328. ValidateCommand ("DeriveParameters");
  329. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  330. localParameters.Add ("@procedure_name", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  331. string sql = "sp_procedure_params_rowset";
  332. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  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. if (keyInfo || schemaOnly)
  368. Connection.Tds.Execute (sql1.ToString ());
  369. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  370. if (keyInfo || schemaOnly)
  371. Connection.Tds.Execute (sql2.ToString ());
  372. break;
  373. case CommandType.Text:
  374. string sql;
  375. if (sql2.Length > 0) {
  376. sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  377. } else {
  378. sql = String.Format ("{0}{1}", sql1.ToString (), CommandText);
  379. }
  380. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  381. break;
  382. }
  383. }
  384. else
  385. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  386. }
  387. public
  388. #if NET_2_0
  389. override
  390. #endif // NET_2_0
  391. int ExecuteNonQuery ()
  392. {
  393. ValidateCommand ("ExecuteNonQuery");
  394. int result = 0;
  395. behavior = CommandBehavior.Default;
  396. try {
  397. Execute (CommandBehavior.Default, false);
  398. result = Connection.Tds.RecordsAffected;
  399. }
  400. catch (TdsTimeoutException e) {
  401. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  402. }
  403. GetOutputParameters ();
  404. return result;
  405. }
  406. public new SqlDataReader ExecuteReader ()
  407. {
  408. return ExecuteReader (CommandBehavior.Default);
  409. }
  410. public new SqlDataReader ExecuteReader (CommandBehavior behavior)
  411. {
  412. ValidateCommand ("ExecuteReader");
  413. try {
  414. this.behavior = behavior;
  415. if ((behavior & CommandBehavior.SequentialAccess) != 0)
  416. Tds.SequentialAccess = true;
  417. Execute (behavior, true);
  418. Connection.DataReader = new SqlDataReader (this);
  419. }
  420. catch (TdsTimeoutException e) {
  421. // if behavior is closeconnection, even if it throws exception
  422. // the connection has to be closed.
  423. if ((behavior & CommandBehavior.CloseConnection) != 0)
  424. Connection.Close ();
  425. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  426. } catch (SqlException) {
  427. // if behavior is closeconnection, even if it throws exception
  428. // the connection has to be closed.
  429. if ((behavior & CommandBehavior.CloseConnection) != 0)
  430. Connection.Close ();
  431. throw;
  432. }
  433. return Connection.DataReader;
  434. }
  435. public
  436. #if NET_2_0
  437. override
  438. #endif // NET_2_0
  439. object ExecuteScalar ()
  440. {
  441. try {
  442. object result = null;
  443. ValidateCommand ("ExecuteScalar");
  444. behavior = CommandBehavior.Default;
  445. try {
  446. Execute (CommandBehavior.Default, true);
  447. }
  448. catch (TdsTimeoutException e) {
  449. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  450. }
  451. if (Connection.Tds.NextResult () && Connection.Tds.NextRow ())
  452. result = Connection.Tds.ColumnValues[0];
  453. if (commandType == CommandType.StoredProcedure) {
  454. Connection.Tds.SkipToEnd ();
  455. GetOutputParameters ();
  456. }
  457. return result;
  458. }
  459. finally {
  460. CloseDataReader (true);
  461. }
  462. }
  463. public XmlReader ExecuteXmlReader ()
  464. {
  465. ValidateCommand ("ExecuteXmlReader");
  466. behavior = CommandBehavior.Default;
  467. try {
  468. Execute (CommandBehavior.Default, true);
  469. }
  470. catch (TdsTimeoutException e) {
  471. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  472. }
  473. SqlDataReader dataReader = new SqlDataReader (this);
  474. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  475. XmlReader xmlReader = new XmlTextReader (textReader);
  476. return xmlReader;
  477. }
  478. internal void GetOutputParameters ()
  479. {
  480. IList list = Connection.Tds.OutputParameters;
  481. if (list != null && list.Count > 0) {
  482. int index = 0;
  483. foreach (SqlParameter parameter in parameters) {
  484. if (parameter.Direction != ParameterDirection.Input) {
  485. parameter.Value = list [index];
  486. index += 1;
  487. }
  488. if (index >= list.Count)
  489. break;
  490. }
  491. }
  492. }
  493. object ICloneable.Clone ()
  494. {
  495. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  496. }
  497. IDbDataParameter IDbCommand.CreateParameter ()
  498. {
  499. return CreateParameter ();
  500. }
  501. IDataReader IDbCommand.ExecuteReader ()
  502. {
  503. return ExecuteReader ();
  504. }
  505. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  506. {
  507. return ExecuteReader (behavior);
  508. }
  509. protected override void Dispose (bool disposing)
  510. {
  511. if (disposed) return;
  512. if (disposing) {
  513. parameters.Clear();
  514. transaction = null;
  515. connection = null;
  516. }
  517. disposed = true;
  518. }
  519. public
  520. #if NET_2_0
  521. override
  522. #endif // NET_2_0
  523. void Prepare ()
  524. {
  525. ValidateCommand ("Prepare");
  526. if (CommandType == CommandType.StoredProcedure)
  527. return;
  528. try {
  529. foreach (SqlParameter param in Parameters)
  530. param.CheckIfInitialized ();
  531. }catch (Exception e) {
  532. throw new InvalidOperationException ("SqlCommand.Prepare requires " + e.Message);
  533. }
  534. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  535. }
  536. public void ResetCommandTimeout ()
  537. {
  538. commandTimeout = 30;
  539. }
  540. private void Unprepare ()
  541. {
  542. Connection.Tds.Unprepare (preparedStatement);
  543. preparedStatement = null;
  544. }
  545. private void ValidateCommand (string method)
  546. {
  547. if (Connection == null)
  548. #if NET_2_0
  549. throw new NullReferenceException (String.Format ("{0} requires a Connection object to continue.", method));
  550. #else
  551. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  552. #endif
  553. if (Connection.Transaction != null && transaction != Connection.Transaction)
  554. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  555. if (Connection.State != ConnectionState.Open)
  556. #if NET_2_0
  557. throw new NullReferenceException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  558. #else
  559. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  560. #endif
  561. if (commandText == String.Empty || commandText == null)
  562. throw new InvalidOperationException ("The command text for this Command has not been set.");
  563. if (Connection.DataReader != null)
  564. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  565. if (Connection.XmlReader != null)
  566. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  567. #if NET_2_0
  568. if (method.StartsWith ("Begin") && !Connection.AsyncProcessing)
  569. throw new InvalidOperationException ("This Connection object is not " +
  570. "in Asynchronous mode. Use 'Asynchronous" +
  571. " Processing = true' to set it.");
  572. #endif // NET_2_0
  573. }
  574. #if NET_2_0
  575. protected override DbParameter CreateDbParameter ()
  576. {
  577. return (DbParameter) CreateParameter ();
  578. }
  579. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  580. {
  581. return (DbDataReader) ExecuteReader (behavior);
  582. }
  583. protected override DbConnection DbConnection
  584. {
  585. get { return (DbConnection) Connection; }
  586. set { Connection = (SqlConnection) value; }
  587. }
  588. protected override DbParameterCollection DbParameterCollection
  589. {
  590. get { return (DbParameterCollection) Parameters; }
  591. }
  592. protected override DbTransaction DbTransaction
  593. {
  594. get { return (DbTransaction) Transaction; }
  595. set { Transaction = (SqlTransaction) value; }
  596. }
  597. #endif // NET_2_0
  598. #endregion // Methods
  599. #if NET_2_0
  600. #region Asynchronous Methods
  601. internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior,
  602. bool wantResults,
  603. AsyncCallback callback,
  604. object state)
  605. {
  606. IAsyncResult ar = null;
  607. Connection.Tds.RecordsAffected = -1;
  608. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  609. if (preparedStatement == null) {
  610. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  611. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  612. StringBuilder sql1 = new StringBuilder ();
  613. StringBuilder sql2 = new StringBuilder ();
  614. if (schemaOnly || keyInfo)
  615. sql1.Append ("SET FMTONLY OFF;");
  616. if (keyInfo) {
  617. sql1.Append ("SET NO_BROWSETABLE ON;");
  618. sql2.Append ("SET NO_BROWSETABLE OFF;");
  619. }
  620. if (schemaOnly) {
  621. sql1.Append ("SET FMTONLY ON;");
  622. sql2.Append ("SET FMTONLY OFF;");
  623. }
  624. switch (CommandType) {
  625. case CommandType.StoredProcedure:
  626. string prolog = "";
  627. string epilog = "";
  628. if (keyInfo || schemaOnly)
  629. prolog = sql1.ToString ();
  630. if (keyInfo || schemaOnly)
  631. epilog = sql2.ToString ();
  632. Connection.Tds.BeginExecuteProcedure (prolog,
  633. epilog,
  634. CommandText,
  635. !wantResults,
  636. parms,
  637. callback,
  638. state);
  639. break;
  640. case CommandType.Text:
  641. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  642. if (wantResults)
  643. ar = Connection.Tds.BeginExecuteQuery (sql, parms,
  644. callback, state);
  645. else
  646. ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
  647. break;
  648. }
  649. }
  650. else
  651. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  652. return ar;
  653. }
  654. internal void EndExecuteInternal (IAsyncResult ar)
  655. {
  656. SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
  657. Connection.Tds.WaitFor (sqlResult.InternalResult);
  658. Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
  659. }
  660. public IAsyncResult BeginExecuteNonQuery ()
  661. {
  662. return BeginExecuteNonQuery (null, null);
  663. }
  664. public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object state)
  665. {
  666. ValidateCommand ("BeginExecuteNonQuery");
  667. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  668. ar.EndMethod = "EndExecuteNonQuery";
  669. ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
  670. return ar;
  671. }
  672. public int EndExecuteNonQuery (IAsyncResult ar)
  673. {
  674. ValidateAsyncResult (ar, "EndExecuteNonQuery");
  675. EndExecuteInternal (ar);
  676. int ret = Connection.Tds.RecordsAffected;
  677. GetOutputParameters ();
  678. ( (SqlAsyncResult) ar).Ended = true;
  679. return ret;
  680. }
  681. public IAsyncResult BeginExecuteReader ()
  682. {
  683. return BeginExecuteReader (null, null, CommandBehavior.Default);
  684. }
  685. public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
  686. {
  687. return BeginExecuteReader (null, null, behavior);
  688. }
  689. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state)
  690. {
  691. return BeginExecuteReader (callback, state, CommandBehavior.Default);
  692. }
  693. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state, CommandBehavior behavior)
  694. {
  695. ValidateCommand ("BeginExecuteReader");
  696. this.behavior = behavior;
  697. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  698. ar.EndMethod = "EndExecuteReader";
  699. IAsyncResult tdsResult = BeginExecuteInternal (behavior, true,
  700. ar.BubbleCallback, state);
  701. ar.InternalResult = tdsResult;
  702. return ar;
  703. }
  704. public SqlDataReader EndExecuteReader (IAsyncResult ar)
  705. {
  706. ValidateAsyncResult (ar, "EndExecuteReader");
  707. EndExecuteInternal (ar);
  708. SqlDataReader reader = null;
  709. try {
  710. reader = new SqlDataReader (this);
  711. }
  712. catch (TdsTimeoutException e) {
  713. // if behavior is closeconnection, even if it throws exception
  714. // the connection has to be closed.
  715. if ((behavior & CommandBehavior.CloseConnection) != 0)
  716. Connection.Close ();
  717. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  718. } catch (SqlException) {
  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;
  724. }
  725. ( (SqlAsyncResult) ar).Ended = true;
  726. return reader;
  727. }
  728. public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object state)
  729. {
  730. ValidateCommand ("BeginExecuteXmlReader");
  731. SqlAsyncResult ar = new SqlAsyncResult (callback, state);
  732. ar.EndMethod = "EndExecuteXmlReader";
  733. ar.InternalResult = BeginExecuteInternal (behavior, true,
  734. ar.BubbleCallback, state);
  735. return ar;
  736. }
  737. public IAsyncResult BeginExecuteXmlReader ()
  738. {
  739. return BeginExecuteXmlReader (null, null);
  740. }
  741. public XmlReader EndExecuteXmlReader (IAsyncResult ar)
  742. {
  743. ValidateAsyncResult (ar, "EndExecuteXmlReader");
  744. EndExecuteInternal (ar);
  745. SqlDataReader reader = new SqlDataReader (this);
  746. SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
  747. XmlReader xmlReader = new XmlTextReader (textReader);
  748. ( (SqlAsyncResult) ar).Ended = true;
  749. return xmlReader;
  750. }
  751. internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
  752. {
  753. if (ar == null)
  754. throw new ArgumentException ("result passed is null!");
  755. if (! (ar is SqlAsyncResult))
  756. throw new ArgumentException (String.Format ("cannot test validity of types {0}",
  757. ar.GetType ()
  758. ));
  759. SqlAsyncResult result = (SqlAsyncResult) ar;
  760. if (result.EndMethod != endMethod)
  761. throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " +
  762. "Expected call to {1} but {0} is called instead.",
  763. endMethod,
  764. result.EndMethod
  765. ));
  766. if (result.Ended)
  767. throw new InvalidOperationException (String.Format ("The method {0} cannot be called " +
  768. "more than once for the same AsyncResult.",
  769. endMethod));
  770. }
  771. #endregion // Asynchronous Methods
  772. public event StatementCompletedEventHandler StatementCompleted;
  773. #endif // NET_2_0
  774. }
  775. }