SqlCommand.cs 27 KB

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