2 // System.Data.SqlClient.SqlCommand.cs
5 // Rodrigo Moya (rodrigo@ximian.com)
6 // Daniel Morgan (danmorg@sc.rr.com)
7 // Tim Coleman (tim@timcoleman.com)
8 // Diego Caravana (diego@toth.it)
10 // (C) Ximian, Inc 2002 http://www.ximian.com/
11 // (C) Daniel Morgan, 2002
12 // Copyright (C) Tim Coleman, 2002
16 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
18 // Permission is hereby granted, free of charge, to any person obtaining
19 // a copy of this software and associated documentation files (the
20 // "Software"), to deal in the Software without restriction, including
21 // without limitation the rights to use, copy, modify, merge, publish,
22 // distribute, sublicense, and/or sell copies of the Software, and to
23 // permit persons to whom the Software is furnished to do so, subject to
24 // the following conditions:
26 // The above copyright notice and this permission notice shall be
27 // included in all copies or substantial portions of the Software.
29 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
32 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
33 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
34 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
39 using Mono.Data.Tds.Protocol;
42 using System.Collections;
43 using System.Collections.Specialized;
44 using System.ComponentModel;
46 using System.Data.Common;
47 using System.Data.Sql;
48 using System.Runtime.InteropServices;
50 using System.Threading;
51 using System.Threading.Tasks;
54 namespace System.Data.SqlClient {
55 [DesignerAttribute ("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
56 [ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
57 [DefaultEventAttribute ("RecordsAffected")]
58 public sealed class SqlCommand : DbCommand, IDbCommand, ICloneable
62 const int DEFAULT_COMMAND_TIMEOUT = 30;
65 bool designTimeVisible;
67 CommandType commandType;
68 SqlConnection connection;
69 SqlTransaction transaction;
70 UpdateRowSource updatedRowSource;
71 CommandBehavior behavior = CommandBehavior.Default;
72 SqlParameterCollection parameters;
73 string preparedStatement;
75 SqlNotificationRequest notification;
76 bool notificationAutoEnlist;
83 : this (String.Empty, null, null)
87 public SqlCommand (string cmdText)
88 : this (cmdText, null, null)
92 public SqlCommand (string cmdText, SqlConnection connection)
93 : this (cmdText, connection, null)
97 public SqlCommand (string cmdText, SqlConnection connection, SqlTransaction transaction)
99 this.commandText = cmdText;
100 this.connection = connection;
101 this.transaction = transaction;
102 this.commandType = CommandType.Text;
103 this.updatedRowSource = UpdateRowSource.Both;
105 this.commandTimeout = DEFAULT_COMMAND_TIMEOUT;
106 notificationAutoEnlist = true;
107 designTimeVisible = true;
108 parameters = new SqlParameterCollection (this);
111 private SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction, CommandType commandType, UpdateRowSource updatedRowSource, bool designTimeVisible, int commandTimeout, SqlParameterCollection parameters)
113 this.commandText = commandText;
114 this.connection = connection;
115 this.transaction = transaction;
116 this.commandType = commandType;
117 this.updatedRowSource = updatedRowSource;
118 this.designTimeVisible = designTimeVisible;
119 this.commandTimeout = commandTimeout;
120 this.parameters = new SqlParameterCollection(this);
121 for (int i = 0;i < parameters.Count;i++)
122 this.parameters.Add(((ICloneable)parameters[i]).Clone());
125 #endregion // Constructors
129 internal CommandBehavior CommandBehavior {
130 get { return behavior; }
134 [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
135 [RefreshProperties (RefreshProperties.All)]
140 if (commandText == null)
145 if (value != commandText && preparedStatement != null)
154 get { return commandTimeout; }
157 throw new ArgumentException ("The property value assigned is less than 0.",
159 commandTimeout = value;
163 [DefaultValue (CommandType.Text)]
164 [RefreshProperties (RefreshProperties.All)]
167 CommandType CommandType {
168 get { return commandType; }
170 if (value == CommandType.TableDirect)
171 throw new ArgumentOutOfRangeException ("CommandType.TableDirect is not supported " +
172 "by the Mono SqlClient Data Provider.");
174 ExceptionHelper.CheckEnumValue (typeof (CommandType), value);
179 [DefaultValue (null)]
180 [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
183 SqlConnection Connection {
184 get { return connection; }
192 [DefaultValue (true)]
194 [EditorBrowsable (EditorBrowsableState.Never)]
197 bool DesignTimeVisible {
198 get { return designTimeVisible; }
199 set { designTimeVisible = value; }
202 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
205 SqlParameterCollection Parameters {
206 get { return parameters; }
210 get { return Connection.Tds; }
215 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
216 public new SqlTransaction Transaction {
218 if (transaction != null && !transaction.IsOpen)
228 [DefaultValue (UpdateRowSource.Both)]
231 UpdateRowSource UpdatedRowSource {
232 get { return updatedRowSource; }
234 ExceptionHelper.CheckEnumValue (typeof (UpdateRowSource), value);
235 updatedRowSource = value;
240 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
241 public SqlNotificationRequest Notification {
242 get { return notification; }
243 set { notification = value; }
246 [DefaultValue (true)]
247 public bool NotificationAutoEnlist {
248 get { return notificationAutoEnlist; }
249 set { notificationAutoEnlist = value; }
259 if (Connection == null || Connection.Tds == null)
261 Connection.Tds.Cancel ();
264 public SqlCommand Clone ()
266 return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
269 internal void CloseDataReader ()
271 if (Connection != null) {
272 Connection.DataReader = null;
274 if ((behavior & CommandBehavior.CloseConnection) != 0)
278 Tds.SequentialAccess = false;
281 // Reset the behavior
282 behavior = CommandBehavior.Default;
285 public new SqlParameter CreateParameter ()
287 return new SqlParameter ();
290 private string EscapeProcName (string name, bool schema)
293 string tmpProcName = name.Trim ();
294 int procNameLen = tmpProcName.Length;
295 char[] brkts = new char [] {'[', ']'};
296 bool foundMatching = false;
297 int start = 0, count = procNameLen;
298 int sindex = -1, eindex = -1;
300 // We try to match most of the "brackets" combination here, however
301 // there could be other combinations that may generate a different type
302 // of exception in MS.NET
304 if (procNameLen > 1) {
305 if ((sindex = tmpProcName.IndexOf ('[')) <= 0)
306 foundMatching = true;
308 foundMatching = false;
310 if (foundMatching == true && sindex > -1) {
311 eindex = tmpProcName.IndexOf (']');
312 if (sindex > eindex && eindex != -1) {
313 foundMatching = false;
314 } else if (eindex == procNameLen-1) {
315 if (tmpProcName.IndexOfAny (brkts, 1, procNameLen-2) != -1) {
316 foundMatching = false;
319 count = procNameLen - 2;
321 } else if (eindex == -1 && schema) {
322 foundMatching = true;
324 foundMatching = false;
329 procName = tmpProcName.Substring (start, count);
331 throw new ArgumentException (String.Format ("SqlCommand.CommandText property value is an invalid multipart name {0}, incorrect usage of quotes", CommandText));
333 procName = tmpProcName;
338 internal void DeriveParameters ()
340 if (commandType != CommandType.StoredProcedure)
341 throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
342 ValidateCommand ("DeriveParameters", false);
344 string procName = CommandText;
345 string schemaName = String.Empty;
346 int dotPosition = procName.LastIndexOf ('.');
348 // Procedure name can be: [database].[user].[procname]
349 if (dotPosition >= 0) {
350 schemaName = procName.Substring (0, dotPosition);
351 procName = procName.Substring (dotPosition + 1);
352 if ((dotPosition = schemaName.LastIndexOf ('.')) >= 0)
353 schemaName = schemaName.Substring (dotPosition + 1);
356 procName = EscapeProcName (procName, false);
357 schemaName = EscapeProcName (schemaName, true);
359 SqlParameterCollection localParameters = new SqlParameterCollection (this);
360 localParameters.Add ("@procedure_name", SqlDbType.NVarChar, procName.Length).Value = procName;
361 if (schemaName.Length > 0)
362 localParameters.Add ("@procedure_schema", SqlDbType.NVarChar, schemaName.Length).Value = schemaName;
364 string sql = "sp_procedure_params_rowset";
367 Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
368 } catch (TdsTimeoutException ex) {
369 Connection.Tds.Reset ();
370 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
371 } catch (TdsInternalException ex) {
373 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
376 SqlDataReader reader = new SqlDataReader (this);
378 object[] dbValues = new object[reader.FieldCount];
380 while (reader.Read ()) {
381 reader.GetValues (dbValues);
382 parameters.Add (new SqlParameter (dbValues));
386 if (parameters.Count == 0)
387 throw new InvalidOperationException ("Stored procedure '" + procName + "' does not exist.");
390 private void Execute (bool wantResults)
393 Connection.Tds.RecordsAffected = -1;
394 TdsMetaParameterCollection parms = Parameters.MetaParameters;
395 foreach (TdsMetaParameter param in parms) {
396 param.Validate (index++);
399 if (preparedStatement == null) {
400 bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
401 bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
403 StringBuilder sql1 = new StringBuilder ();
404 StringBuilder sql2 = new StringBuilder ();
406 if (schemaOnly || keyInfo)
407 sql1.Append ("SET FMTONLY OFF;");
409 sql1.Append ("SET NO_BROWSETABLE ON;");
410 sql2.Append ("SET NO_BROWSETABLE OFF;");
413 sql1.Append ("SET FMTONLY ON;");
414 sql2.Append ("SET FMTONLY OFF;");
417 switch (CommandType) {
418 case CommandType.StoredProcedure:
420 if (keyInfo || schemaOnly)
421 Connection.Tds.Execute (sql1.ToString ());
422 Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
423 if (keyInfo || schemaOnly)
424 Connection.Tds.Execute (sql2.ToString ());
425 } catch (TdsTimeoutException ex) {
426 // If it is a timeout exception there can be many reasons:
427 // 1) Network is down/server is down/not reachable
428 // 2) Somebody has an exclusive lock on Table/DB
429 // In any of these cases, don't close the connection. Let the user do it
430 Connection.Tds.Reset ();
431 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
432 } catch (TdsInternalException ex) {
434 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
437 case CommandType.Text:
439 if (sql2.Length > 0) {
440 sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
442 sql = String.Format ("{0}{1}", sql1.ToString (), CommandText);
445 Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
446 } catch (TdsTimeoutException ex) {
447 Connection.Tds.Reset ();
448 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
449 } catch (TdsInternalException ex) {
451 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
458 Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
459 } catch (TdsTimeoutException ex) {
460 Connection.Tds.Reset ();
461 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
462 } catch (TdsInternalException ex) {
464 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
471 int ExecuteNonQuery ()
473 ValidateCommand ("ExecuteNonQuery", false);
475 behavior = CommandBehavior.Default;
479 result = Connection.Tds.RecordsAffected;
480 } catch (TdsTimeoutException e) {
481 Connection.Tds.Reset ();
482 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
485 GetOutputParameters ();
489 public new SqlDataReader ExecuteReader ()
491 return ExecuteReader (CommandBehavior.Default);
494 public new SqlDataReader ExecuteReader (CommandBehavior behavior)
496 ValidateCommand ("ExecuteReader", false);
497 if ((behavior & CommandBehavior.SingleRow) != 0)
498 behavior |= CommandBehavior.SingleResult;
499 this.behavior = behavior;
500 if ((behavior & CommandBehavior.SequentialAccess) != 0)
501 Tds.SequentialAccess = true;
504 Connection.DataReader = new SqlDataReader (this);
505 return Connection.DataReader;
507 if ((behavior & CommandBehavior.CloseConnection) != 0)
514 public new Task<SqlDataReader> ExecuteReaderAsync ()
516 throw new NotImplementedException ();
520 public new Task<SqlDataReader> ExecuteReaderAsync (CancellationToken cancellationToken)
522 throw new NotImplementedException ();
526 public new Task<SqlDataReader> ExecuteReaderAsync (CommandBehavior behavior)
528 throw new NotImplementedException ();
532 public new Task<SqlDataReader> ExecuteReaderAsync (CommandBehavior behavior, CancellationToken cancellationToken)
534 throw new NotImplementedException ();
538 public Task<XmlReader> ExecuteXmlReaderAsync ()
540 throw new NotImplementedException ();
544 public Task<XmlReader> ExecuteXmlReaderAsync (CancellationToken cancellationToken)
546 throw new NotImplementedException ();
551 object ExecuteScalar ()
554 object result = null;
555 ValidateCommand ("ExecuteScalar", false);
556 behavior = CommandBehavior.Default;
560 if (Connection.Tds.NextResult () && Connection.Tds.NextRow ())
561 result = Connection.Tds.ColumnValues[0];
563 if (commandType == CommandType.StoredProcedure) {
564 Connection.Tds.SkipToEnd ();
565 GetOutputParameters ();
567 } catch (TdsTimeoutException ex) {
568 Connection.Tds.Reset ();
569 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
570 } catch (TdsInternalException ex) {
572 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
581 public XmlReader ExecuteXmlReader ()
583 ValidateCommand ("ExecuteXmlReader", false);
584 behavior = CommandBehavior.Default;
587 } catch (TdsTimeoutException e) {
588 Connection.Tds.Reset ();
589 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
592 SqlDataReader dataReader = new SqlDataReader (this);
593 SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
594 XmlReader xmlReader = new XmlTextReader (textReader);
598 internal void GetOutputParameters ()
600 IList list = Connection.Tds.OutputParameters;
602 if (list != null && list.Count > 0) {
605 foreach (SqlParameter parameter in parameters) {
606 if (parameter.Direction != ParameterDirection.Input &&
607 parameter.Direction != ParameterDirection.ReturnValue) {
608 parameter.Value = list [index];
611 if (index >= list.Count)
617 object ICloneable.Clone ()
619 return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
624 protected override void Dispose (bool disposing)
626 if (disposed) return;
629 if (Connection != null)
630 Connection.DataReader = null;
632 base.Dispose (disposing);
640 if (Connection == null)
641 throw new NullReferenceException ();
643 if (CommandType == CommandType.StoredProcedure || CommandType == CommandType.Text && Parameters.Count == 0)
646 ValidateCommand ("Prepare", false);
649 foreach (SqlParameter param in Parameters)
650 param.CheckIfInitialized ();
651 } catch (Exception e) {
652 throw new InvalidOperationException ("SqlCommand.Prepare requires " + e.Message);
655 preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
658 public void ResetCommandTimeout ()
660 commandTimeout = DEFAULT_COMMAND_TIMEOUT;
663 private void Unprepare ()
665 Connection.Tds.Unprepare (preparedStatement);
666 preparedStatement = null;
669 private void ValidateCommand (string method, bool async)
671 if (Connection == null)
672 throw new InvalidOperationException (String.Format ("{0}: A Connection object is required to continue.", method));
673 if (Transaction == null && Connection.Transaction != null)
674 throw new InvalidOperationException (String.Format (
675 "{0} requires a transaction if the command's connection is in a pending transaction.",
677 if (Transaction != null && Transaction.Connection != Connection)
678 throw new InvalidOperationException ("The connection does not have the same transaction as the command.");
679 if (Connection.State != ConnectionState.Open)
680 throw new InvalidOperationException (String.Format ("{0} requires an open connection to continue. This connection is closed.", method));
681 if (CommandText.Length == 0)
682 throw new InvalidOperationException (String.Format ("{0}: CommandText has not been set for this Command.", method));
683 if (Connection.DataReader != null)
684 throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
685 if (Connection.XmlReader != null)
686 throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
687 if (async && !Connection.AsyncProcessing)
688 throw new InvalidOperationException ("This Connection object is not " +
689 "in Asynchronous mode. Use 'Asynchronous" +
690 " Processing = true' to set it.");
693 protected override DbParameter CreateDbParameter ()
695 return CreateParameter ();
698 protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
700 return ExecuteReader (behavior);
703 protected override DbConnection DbConnection {
704 get { return Connection; }
705 set { Connection = (SqlConnection) value; }
708 protected override DbParameterCollection DbParameterCollection {
709 get { return Parameters; }
712 protected override DbTransaction DbTransaction {
713 get { return Transaction; }
714 set { Transaction = (SqlTransaction) value; }
717 #endregion // Methods
719 #region Asynchronous Methods
721 internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior,
723 AsyncCallback callback,
726 IAsyncResult ar = null;
727 Connection.Tds.RecordsAffected = -1;
728 TdsMetaParameterCollection parms = Parameters.MetaParameters;
729 if (preparedStatement == null) {
730 bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
731 bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
733 StringBuilder sql1 = new StringBuilder ();
734 StringBuilder sql2 = new StringBuilder ();
736 if (schemaOnly || keyInfo)
737 sql1.Append ("SET FMTONLY OFF;");
739 sql1.Append ("SET NO_BROWSETABLE ON;");
740 sql2.Append ("SET NO_BROWSETABLE OFF;");
743 sql1.Append ("SET FMTONLY ON;");
744 sql2.Append ("SET FMTONLY OFF;");
746 switch (CommandType) {
747 case CommandType.StoredProcedure:
750 if (keyInfo || schemaOnly)
751 prolog = sql1.ToString ();
752 if (keyInfo || schemaOnly)
753 epilog = sql2.ToString ();
755 ar = Connection.Tds.BeginExecuteProcedure (prolog,
762 } catch (TdsTimeoutException ex) {
763 Connection.Tds.Reset ();
764 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
765 } catch (TdsInternalException ex) {
767 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
770 case CommandType.Text:
771 string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
774 ar = Connection.Tds.BeginExecuteQuery (sql, parms, callback, state);
776 ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
777 } catch (TdsTimeoutException ex) {
778 Connection.Tds.Reset ();
779 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
780 } catch (TdsInternalException ex) {
782 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
789 Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
790 } catch (TdsTimeoutException ex) {
791 Connection.Tds.Reset ();
792 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
793 } catch (TdsInternalException ex) {
795 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
801 internal void EndExecuteInternal (IAsyncResult ar)
803 SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
804 Connection.Tds.WaitFor (sqlResult.InternalResult);
805 Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
808 public IAsyncResult BeginExecuteNonQuery ()
810 return BeginExecuteNonQuery (null, null);
813 public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object stateObject)
815 ValidateCommand ("BeginExecuteNonQuery", true);
816 SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
817 ar.EndMethod = "EndExecuteNonQuery";
818 ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
822 public int EndExecuteNonQuery (IAsyncResult asyncResult)
824 ValidateAsyncResult (asyncResult, "EndExecuteNonQuery");
825 EndExecuteInternal (asyncResult);
827 int ret = Connection.Tds.RecordsAffected;
829 GetOutputParameters ();
830 ((SqlAsyncResult) asyncResult).Ended = true;
834 public IAsyncResult BeginExecuteReader ()
836 return BeginExecuteReader (null, null, CommandBehavior.Default);
839 public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
841 return BeginExecuteReader (null, null, behavior);
844 public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject)
846 return BeginExecuteReader (callback, stateObject, CommandBehavior.Default);
849 public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject, CommandBehavior behavior)
851 ValidateCommand ("BeginExecuteReader", true);
852 this.behavior = behavior;
853 SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
854 ar.EndMethod = "EndExecuteReader";
855 IAsyncResult tdsResult = BeginExecuteInternal (behavior, true,
856 ar.BubbleCallback, stateObject);
857 ar.InternalResult = tdsResult;
861 public SqlDataReader EndExecuteReader (IAsyncResult asyncResult)
863 ValidateAsyncResult (asyncResult, "EndExecuteReader");
864 EndExecuteInternal (asyncResult);
865 SqlDataReader reader = null;
867 reader = new SqlDataReader (this);
868 } catch (TdsTimeoutException e) {
869 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
870 } catch (TdsInternalException e) {
871 // if behavior is closeconnection, even if it throws exception
872 // the connection has to be closed.
873 if ((behavior & CommandBehavior.CloseConnection) != 0)
875 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
878 ((SqlAsyncResult) asyncResult).Ended = true;
882 public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object stateObject)
884 ValidateCommand ("BeginExecuteXmlReader", true);
885 SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
886 ar.EndMethod = "EndExecuteXmlReader";
887 ar.InternalResult = BeginExecuteInternal (behavior, true,
888 ar.BubbleCallback, stateObject);
892 public IAsyncResult BeginExecuteXmlReader ()
894 return BeginExecuteXmlReader (null, null);
898 public XmlReader EndExecuteXmlReader (IAsyncResult asyncResult)
900 ValidateAsyncResult (asyncResult, "EndExecuteXmlReader");
901 EndExecuteInternal (asyncResult);
902 SqlDataReader reader = new SqlDataReader (this);
903 SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
904 XmlReader xmlReader = new XmlTextReader (textReader);
905 ((SqlAsyncResult) asyncResult).Ended = true;
909 internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
912 throw new ArgumentException ("result passed is null!");
913 if (! (ar is SqlAsyncResult))
914 throw new ArgumentException (String.Format ("cannot test validity of types {0}",
916 SqlAsyncResult result = (SqlAsyncResult) ar;
917 if (result.EndMethod != endMethod)
918 throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " +
919 "Expected call to {1} but {0} is called instead.",
920 endMethod, result.EndMethod));
922 throw new InvalidOperationException (String.Format ("The method {0} cannot be called " +
923 "more than once for the same AsyncResult.", endMethod));
926 #endregion // Asynchronous Methods
928 public event StatementCompletedEventHandler StatementCompleted;