SqlCommand.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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 Tds 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. if (parameters.Count == 0)
  355. throw new InvalidOperationException ("Stored procedure '" + procName + "' does not exist.");
  356. }
  357. private void Execute (CommandBehavior behavior, bool wantResults)
  358. {
  359. int index = 0;
  360. Connection.Tds.RecordsAffected = -1;
  361. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  362. foreach (TdsMetaParameter param in parms) {
  363. param.Validate (index++);
  364. }
  365. if (preparedStatement == null) {
  366. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  367. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  368. StringBuilder sql1 = new StringBuilder ();
  369. StringBuilder sql2 = new StringBuilder ();
  370. if (schemaOnly || keyInfo)
  371. sql1.Append ("SET FMTONLY OFF;");
  372. if (keyInfo) {
  373. sql1.Append ("SET NO_BROWSETABLE ON;");
  374. sql2.Append ("SET NO_BROWSETABLE OFF;");
  375. }
  376. if (schemaOnly) {
  377. sql1.Append ("SET FMTONLY ON;");
  378. sql2.Append ("SET FMTONLY OFF;");
  379. }
  380. switch (CommandType) {
  381. case CommandType.StoredProcedure:
  382. try {
  383. if (keyInfo || schemaOnly)
  384. Connection.Tds.Execute (sql1.ToString ());
  385. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  386. if (keyInfo || schemaOnly)
  387. Connection.Tds.Execute (sql2.ToString ());
  388. } catch (TdsTimeoutException ex) {
  389. // If it is a timeout exception there can be many reasons:
  390. // 1) Network is down/server is down/not reachable
  391. // 2) Somebody has an exclusive lock on Table/DB
  392. // In any of these cases, don't close the connection. Let the user do it
  393. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  394. } catch (TdsInternalException ex) {
  395. Connection.Close ();
  396. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  397. }
  398. break;
  399. case CommandType.Text:
  400. string sql;
  401. if (sql2.Length > 0) {
  402. sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  403. } else {
  404. sql = String.Format ("{0}{1}", sql1.ToString (), CommandText);
  405. }
  406. try {
  407. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  408. } catch (TdsTimeoutException ex) {
  409. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  410. } catch (TdsInternalException ex) {
  411. Connection.Close ();
  412. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  413. }
  414. break;
  415. }
  416. }
  417. else {
  418. try {
  419. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  420. } catch (TdsTimeoutException ex) {
  421. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  422. } catch (TdsInternalException ex) {
  423. Connection.Close ();
  424. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  425. }
  426. }
  427. }
  428. public
  429. #if NET_2_0
  430. override
  431. #endif // NET_2_0
  432. int ExecuteNonQuery ()
  433. {
  434. ValidateCommand ("ExecuteNonQuery");
  435. int result = 0;
  436. behavior = CommandBehavior.Default;
  437. try {
  438. Execute (CommandBehavior.Default, false);
  439. result = Connection.Tds.RecordsAffected;
  440. }
  441. catch (TdsTimeoutException e) {
  442. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  443. }
  444. GetOutputParameters ();
  445. return result;
  446. }
  447. public new SqlDataReader ExecuteReader ()
  448. {
  449. return ExecuteReader (CommandBehavior.Default);
  450. }
  451. public new SqlDataReader ExecuteReader (CommandBehavior behavior)
  452. {
  453. ValidateCommand ("ExecuteReader");
  454. this.behavior = behavior;
  455. if ((behavior & CommandBehavior.SequentialAccess) != 0)
  456. Tds.SequentialAccess = true;
  457. Execute (behavior, true);
  458. Connection.DataReader = new SqlDataReader (this);
  459. return Connection.DataReader;
  460. }
  461. public
  462. #if NET_2_0
  463. override
  464. #endif // NET_2_0
  465. object ExecuteScalar ()
  466. {
  467. try {
  468. object result = null;
  469. ValidateCommand ("ExecuteScalar");
  470. behavior = CommandBehavior.Default;
  471. Execute (CommandBehavior.Default, true);
  472. try {
  473. if (Connection.Tds.NextResult () && Connection.Tds.NextRow ())
  474. result = Connection.Tds.ColumnValues[0];
  475. if (commandType == CommandType.StoredProcedure) {
  476. Connection.Tds.SkipToEnd ();
  477. GetOutputParameters ();
  478. }
  479. } catch (TdsTimeoutException ex) {
  480. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  481. } catch (TdsInternalException ex) {
  482. Connection.Close ();
  483. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  484. }
  485. return result;
  486. }
  487. finally {
  488. CloseDataReader (true);
  489. }
  490. }
  491. public XmlReader ExecuteXmlReader ()
  492. {
  493. ValidateCommand ("ExecuteXmlReader");
  494. behavior = CommandBehavior.Default;
  495. try {
  496. Execute (CommandBehavior.Default, true);
  497. } catch (TdsTimeoutException e) {
  498. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  499. }
  500. SqlDataReader dataReader = new SqlDataReader (this);
  501. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  502. XmlReader xmlReader = new XmlTextReader (textReader);
  503. return xmlReader;
  504. }
  505. internal void GetOutputParameters ()
  506. {
  507. IList list = Connection.Tds.OutputParameters;
  508. if (list != null && list.Count > 0) {
  509. int index = 0;
  510. foreach (SqlParameter parameter in parameters) {
  511. if (parameter.Direction != ParameterDirection.Input) {
  512. parameter.Value = list [index];
  513. index += 1;
  514. }
  515. if (index >= list.Count)
  516. break;
  517. }
  518. }
  519. }
  520. object ICloneable.Clone ()
  521. {
  522. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  523. }
  524. #if !NET_2_0
  525. IDbDataParameter IDbCommand.CreateParameter ()
  526. {
  527. return CreateParameter ();
  528. }
  529. IDataReader IDbCommand.ExecuteReader ()
  530. {
  531. return ExecuteReader ();
  532. }
  533. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  534. {
  535. return ExecuteReader (behavior);
  536. }
  537. #endif
  538. #if NET_2_0
  539. protected override void Dispose (bool disposing)
  540. {
  541. if (disposed) return;
  542. if (disposing) {
  543. parameters.Clear();
  544. }
  545. base.Dispose (disposing);
  546. disposed = true;
  547. }
  548. #endif
  549. public
  550. #if NET_2_0
  551. override
  552. #endif // NET_2_0
  553. void Prepare ()
  554. {
  555. ValidateCommand ("Prepare");
  556. if (CommandType == CommandType.StoredProcedure)
  557. return;
  558. try {
  559. foreach (SqlParameter param in Parameters)
  560. param.CheckIfInitialized ();
  561. } catch (Exception e) {
  562. throw new InvalidOperationException ("SqlCommand.Prepare requires " + e.Message);
  563. }
  564. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  565. }
  566. public void ResetCommandTimeout ()
  567. {
  568. commandTimeout = DEFAULT_COMMAND_TIMEOUT;
  569. }
  570. private void Unprepare ()
  571. {
  572. Connection.Tds.Unprepare (preparedStatement);
  573. preparedStatement = null;
  574. }
  575. private void ValidateCommand (string method)
  576. {
  577. if (Connection == null)
  578. #if NET_2_0
  579. throw new NullReferenceException (String.Format ("{0} requires a Connection object to continue.", method));
  580. #else
  581. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  582. #endif
  583. if (Connection.Transaction != null && transaction != Connection.Transaction)
  584. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  585. if (Connection.State != ConnectionState.Open)
  586. #if NET_2_0
  587. throw new NullReferenceException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  588. #else
  589. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  590. #endif
  591. if (CommandText.Length == 0)
  592. throw new InvalidOperationException ("The command text for this Command has not been set.");
  593. if (Connection.DataReader != null)
  594. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  595. if (Connection.XmlReader != null)
  596. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  597. #if NET_2_0
  598. if (method.StartsWith ("Begin") && !Connection.AsyncProcessing)
  599. throw new InvalidOperationException ("This Connection object is not " +
  600. "in Asynchronous mode. Use 'Asynchronous" +
  601. " Processing = true' to set it.");
  602. #endif // NET_2_0
  603. }
  604. #if NET_2_0
  605. protected override DbParameter CreateDbParameter ()
  606. {
  607. return CreateParameter ();
  608. }
  609. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  610. {
  611. return ExecuteReader (behavior);
  612. }
  613. protected override DbConnection DbConnection {
  614. get { return Connection; }
  615. set { Connection = (SqlConnection) value; }
  616. }
  617. protected override DbParameterCollection DbParameterCollection {
  618. get { return Parameters; }
  619. }
  620. protected override DbTransaction DbTransaction {
  621. get { return Transaction; }
  622. set { Transaction = (SqlTransaction) value; }
  623. }
  624. #endif // NET_2_0
  625. #endregion // Methods
  626. #if NET_2_0
  627. #region Asynchronous Methods
  628. internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior,
  629. bool wantResults,
  630. AsyncCallback callback,
  631. object state)
  632. {
  633. IAsyncResult ar = null;
  634. Connection.Tds.RecordsAffected = -1;
  635. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  636. if (preparedStatement == null) {
  637. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  638. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  639. StringBuilder sql1 = new StringBuilder ();
  640. StringBuilder sql2 = new StringBuilder ();
  641. if (schemaOnly || keyInfo)
  642. sql1.Append ("SET FMTONLY OFF;");
  643. if (keyInfo) {
  644. sql1.Append ("SET NO_BROWSETABLE ON;");
  645. sql2.Append ("SET NO_BROWSETABLE OFF;");
  646. }
  647. if (schemaOnly) {
  648. sql1.Append ("SET FMTONLY ON;");
  649. sql2.Append ("SET FMTONLY OFF;");
  650. }
  651. switch (CommandType) {
  652. case CommandType.StoredProcedure:
  653. string prolog = "";
  654. string epilog = "";
  655. if (keyInfo || schemaOnly)
  656. prolog = sql1.ToString ();
  657. if (keyInfo || schemaOnly)
  658. epilog = sql2.ToString ();
  659. try {
  660. Connection.Tds.BeginExecuteProcedure (prolog,
  661. epilog,
  662. CommandText,
  663. !wantResults,
  664. parms,
  665. callback,
  666. state);
  667. } catch (TdsTimeoutException ex) {
  668. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  669. } catch (TdsInternalException ex) {
  670. Connection.Close ();
  671. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  672. }
  673. break;
  674. case CommandType.Text:
  675. string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
  676. try {
  677. if (wantResults)
  678. ar = Connection.Tds.BeginExecuteQuery (sql, parms, callback, state);
  679. else
  680. ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
  681. } catch (TdsTimeoutException ex) {
  682. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  683. } catch (TdsInternalException ex) {
  684. Connection.Close ();
  685. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  686. }
  687. break;
  688. }
  689. }
  690. else {
  691. try {
  692. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  693. } catch (TdsTimeoutException ex) {
  694. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  695. } catch (TdsInternalException ex) {
  696. Connection.Close ();
  697. throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
  698. }
  699. }
  700. return ar;
  701. }
  702. internal void EndExecuteInternal (IAsyncResult ar)
  703. {
  704. SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
  705. Connection.Tds.WaitFor (sqlResult.InternalResult);
  706. Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
  707. }
  708. public IAsyncResult BeginExecuteNonQuery ()
  709. {
  710. return BeginExecuteNonQuery (null, null);
  711. }
  712. public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object stateObject)
  713. {
  714. ValidateCommand ("BeginExecuteNonQuery");
  715. SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
  716. ar.EndMethod = "EndExecuteNonQuery";
  717. ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
  718. return ar;
  719. }
  720. public int EndExecuteNonQuery (IAsyncResult asyncResult)
  721. {
  722. ValidateAsyncResult (asyncResult, "EndExecuteNonQuery");
  723. EndExecuteInternal (asyncResult);
  724. int ret = Connection.Tds.RecordsAffected;
  725. GetOutputParameters ();
  726. ((SqlAsyncResult) asyncResult).Ended = true;
  727. return ret;
  728. }
  729. public IAsyncResult BeginExecuteReader ()
  730. {
  731. return BeginExecuteReader (null, null, CommandBehavior.Default);
  732. }
  733. public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
  734. {
  735. return BeginExecuteReader (null, null, behavior);
  736. }
  737. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject)
  738. {
  739. return BeginExecuteReader (callback, stateObject, CommandBehavior.Default);
  740. }
  741. public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject, CommandBehavior behavior)
  742. {
  743. ValidateCommand ("BeginExecuteReader");
  744. this.behavior = behavior;
  745. SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
  746. ar.EndMethod = "EndExecuteReader";
  747. IAsyncResult tdsResult = BeginExecuteInternal (behavior, true,
  748. ar.BubbleCallback, stateObject);
  749. ar.InternalResult = tdsResult;
  750. return ar;
  751. }
  752. public SqlDataReader EndExecuteReader (IAsyncResult asyncResult)
  753. {
  754. ValidateAsyncResult (asyncResult, "EndExecuteReader");
  755. EndExecuteInternal (asyncResult);
  756. SqlDataReader reader = null;
  757. try {
  758. reader = new SqlDataReader (this);
  759. } catch (TdsTimeoutException e) {
  760. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  761. } catch (TdsInternalException e) {
  762. // if behavior is closeconnection, even if it throws exception
  763. // the connection has to be closed.
  764. if ((behavior & CommandBehavior.CloseConnection) != 0)
  765. Connection.Close ();
  766. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  767. }
  768. ((SqlAsyncResult) asyncResult).Ended = true;
  769. return reader;
  770. }
  771. public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object stateObject)
  772. {
  773. ValidateCommand ("BeginExecuteXmlReader");
  774. SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
  775. ar.EndMethod = "EndExecuteXmlReader";
  776. ar.InternalResult = BeginExecuteInternal (behavior, true,
  777. ar.BubbleCallback, stateObject);
  778. return ar;
  779. }
  780. public IAsyncResult BeginExecuteXmlReader ()
  781. {
  782. return BeginExecuteXmlReader (null, null);
  783. }
  784. public XmlReader EndExecuteXmlReader (IAsyncResult asyncResult)
  785. {
  786. ValidateAsyncResult (asyncResult, "EndExecuteXmlReader");
  787. EndExecuteInternal (asyncResult);
  788. SqlDataReader reader = new SqlDataReader (this);
  789. SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
  790. XmlReader xmlReader = new XmlTextReader (textReader);
  791. ((SqlAsyncResult) asyncResult).Ended = true;
  792. return xmlReader;
  793. }
  794. internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
  795. {
  796. if (ar == null)
  797. throw new ArgumentException ("result passed is null!");
  798. if (! (ar is SqlAsyncResult))
  799. throw new ArgumentException (String.Format ("cannot test validity of types {0}",
  800. ar.GetType ()));
  801. SqlAsyncResult result = (SqlAsyncResult) ar;
  802. if (result.EndMethod != endMethod)
  803. throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " +
  804. "Expected call to {1} but {0} is called instead.",
  805. endMethod, result.EndMethod));
  806. if (result.Ended)
  807. throw new InvalidOperationException (String.Format ("The method {0} cannot be called " +
  808. "more than once for the same AsyncResult.", endMethod));
  809. }
  810. #endregion // Asynchronous Methods
  811. public event StatementCompletedEventHandler StatementCompleted;
  812. #endif // NET_2_0
  813. }
  814. }