SqlCommand.cs 27 KB

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