Warnings cleanup
[mono.git] / mcs / class / System.Data / System.Data.SqlClient / SqlCommand.cs
1 //
2 // System.Data.SqlClient.SqlCommand.cs
3 //
4 // Author:
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)
9 //
10 // (C) Ximian, Inc 2002 http://www.ximian.com/
11 // (C) Daniel Morgan, 2002
12 // Copyright (C) Tim Coleman, 2002
13 //
14
15 //
16 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
17 //
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:
25 // 
26 // The above copyright notice and this permission notice shall be
27 // included in all copies or substantial portions of the Software.
28 // 
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.
36 //
37
38 using Mono.Data.Tds;
39 using Mono.Data.Tds.Protocol;
40 using System;
41 using System.IO;
42 using System.Collections;
43 using System.Collections.Specialized;
44 using System.ComponentModel;
45 using System.Data;
46 using System.Data.Common;
47 #if NET_2_0
48 using System.Data.Sql;
49 #endif
50 using System.Runtime.InteropServices;
51 using System.Text;
52 using System.Xml;
53
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 #if NET_2_0
58         [DefaultEventAttribute ("RecordsAffected")]
59         public sealed class SqlCommand : DbCommand, IDbCommand, ICloneable
60 #else
61         public sealed class SqlCommand : Component, IDbCommand, ICloneable
62 #endif // NET_2_0
63         {
64                 #region Fields
65
66                 const int DEFAULT_COMMAND_TIMEOUT = 30;
67
68                 int commandTimeout;
69                 bool designTimeVisible;
70                 string commandText;
71                 CommandType commandType;
72                 SqlConnection connection;
73                 SqlTransaction transaction;
74                 UpdateRowSource updatedRowSource;
75                 CommandBehavior behavior = CommandBehavior.Default;
76                 SqlParameterCollection parameters;
77                 string preparedStatement;
78 #if NET_2_0
79                 bool disposed;
80                 SqlNotificationRequest notification;
81                 bool notificationAutoEnlist;
82 #endif
83
84                 #endregion // Fields
85
86                 #region Constructors
87
88                 public SqlCommand() 
89                         : this (String.Empty, null, null)
90                 {
91                 }
92
93                 public SqlCommand (string cmdText)
94                         : this (cmdText, null, null)
95                 {
96                 }
97
98                 public SqlCommand (string cmdText, SqlConnection connection)
99                         : this (cmdText, connection, null)
100                 {
101                 }
102
103                 public SqlCommand (string cmdText, SqlConnection connection, SqlTransaction transaction) 
104                 {
105                         this.commandText = cmdText;
106                         this.connection = connection;
107                         this.transaction = transaction;
108                         this.commandType = CommandType.Text;
109                         this.updatedRowSource = UpdateRowSource.Both;
110
111                         this.commandTimeout = DEFAULT_COMMAND_TIMEOUT;
112 #if NET_2_0
113                         notificationAutoEnlist = true;
114 #endif
115                         designTimeVisible = true;
116                         parameters = new SqlParameterCollection (this);
117                 }
118
119                 private SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction, CommandType commandType, UpdateRowSource updatedRowSource, bool designTimeVisible, int commandTimeout, SqlParameterCollection parameters)
120                 {
121                         this.commandText = commandText;
122                         this.connection = connection;
123                         this.transaction = transaction;
124                         this.commandType = commandType;
125                         this.updatedRowSource = updatedRowSource;
126                         this.designTimeVisible = designTimeVisible;
127                         this.commandTimeout = commandTimeout;
128                         this.parameters = new SqlParameterCollection(this);
129                         for (int i = 0;i < parameters.Count;i++)
130                                 this.parameters.Add(((ICloneable)parameters[i]).Clone());
131                 }
132
133                 #endregion // Constructors
134
135                 #region Properties
136
137                 internal CommandBehavior CommandBehavior {
138                         get { return behavior; }
139                 }
140
141 #if !NET_2_0
142                 [DataSysDescription ("Command text to execute.")]
143 #endif
144                 [DefaultValue ("")]
145                 [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
146                 [RefreshProperties (RefreshProperties.All)]
147                 public
148 #if NET_2_0
149                 override
150 #endif //NET_2_0
151                 string CommandText {
152                         get {
153                                 if (commandText == null)
154                                         return string.Empty;
155                                 return commandText;
156                         }
157                         set {
158                                 if (value != commandText && preparedStatement != null)
159                                         Unprepare ();
160                                 commandText = value; 
161                         }
162                 }
163
164 #if !NET_2_0
165                 [DataSysDescription ("Time to wait for command to execute.")]
166                 [DefaultValue (DEFAULT_COMMAND_TIMEOUT)]
167 #endif
168                 public
169 #if NET_2_0
170                 override
171 #endif //NET_2_0
172                 int CommandTimeout {
173                         get { return commandTimeout; }
174                         set { 
175                                 if (value < 0)
176 #if NET_2_0
177                                         throw new ArgumentException ("The property value assigned is less than 0.",
178                                                 "CommandTimeout");
179 #else
180                                         throw new ArgumentException ("The property value assigned is less than 0.");
181 #endif
182                                 commandTimeout = value; 
183                         }
184                 }
185
186 #if !NET_2_0
187                 [DataSysDescription ("How to interpret the CommandText.")]
188 #endif
189                 [DefaultValue (CommandType.Text)]
190                 [RefreshProperties (RefreshProperties.All)]
191                 public
192 #if NET_2_0
193                 override
194 #endif //NET_2_0
195                 CommandType CommandType {
196                         get { return commandType; }
197                         set { 
198                                 if (value == CommandType.TableDirect)
199 #if NET_2_0
200                                         throw new ArgumentOutOfRangeException ("CommandType.TableDirect is not supported " +
201                                                 "by the Mono SqlClient Data Provider.");
202 #else
203                                         throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
204 #endif
205
206                                 ExceptionHelper.CheckEnumValue (typeof (CommandType), value);
207                                 commandType = value; 
208                         }
209                 }
210
211                 [DefaultValue (null)]
212 #if !NET_2_0
213                 [DataSysDescription ("Connection used by the command.")]
214 #endif
215                 [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]                
216                 public
217 #if NET_2_0
218                 new
219 #endif //NET_2_0
220                 SqlConnection Connection {
221                         get { return connection; }
222                         set
223                         {
224 #if ONLY_1_1
225                                 if (connection != null && connection.DataReader != null)
226                                         throw new InvalidOperationException ("The connection is busy fetching data.");
227 #endif
228                                 connection = value;
229                         }
230                 }
231
232                 [Browsable (false)]
233                 [DefaultValue (true)]
234                 [DesignOnly (true)]
235 #if NET_2_0
236                 [EditorBrowsable (EditorBrowsableState.Never)]
237 #endif
238                 public
239 #if NET_2_0
240                 override
241 #endif //NET_2_0
242                 bool DesignTimeVisible {
243                         get { return designTimeVisible; } 
244                         set { designTimeVisible = value; }
245                 }
246
247 #if !NET_2_0
248                 [DataSysDescription ("The parameters collection.")]
249 #endif
250                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
251                 public
252 #if NET_2_0
253                 new
254 #endif //NET_2_0
255                 SqlParameterCollection Parameters {
256                         get { return parameters; }
257                 }
258
259                 internal Tds Tds {
260                         get { return Connection.Tds; }
261                 }
262
263 #if !NET_2_0
264                 IDbConnection IDbCommand.Connection {
265                         get { return Connection; }
266                         set { 
267                                 if (!(value == null || value is SqlConnection))
268                                         throw new InvalidCastException ("The value was not a valid SqlConnection.");
269                                 Connection = (SqlConnection) value;
270                         }
271                 }
272
273                 IDataParameterCollection IDbCommand.Parameters {
274                         get { return Parameters; }
275                 }
276
277                 IDbTransaction IDbCommand.Transaction {
278                         get { return Transaction; }
279                         set {
280                                 if (!(value == null || value is SqlTransaction))
281                                         throw new ArgumentException ();
282                                 Transaction = (SqlTransaction) value; 
283                         }
284                 }
285 #endif
286
287                 [Browsable (false)]
288 #if !NET_2_0
289                 [DataSysDescription ("The transaction used by the command.")]
290 #endif
291                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
292                 public new SqlTransaction Transaction {
293                         get {
294                                 if (transaction != null && !transaction.IsOpen)
295                                         transaction = null;
296                                 return transaction;
297                         }
298                         set
299                         {
300 #if ONLY_1_1
301                                 if (connection != null && connection.DataReader != null)
302                                         throw new InvalidOperationException ("The connection is busy fetching data.");
303 #endif
304                                 transaction = value;
305                         }
306                 }
307
308 #if !NET_2_0
309                 [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
310 #endif
311                 [DefaultValue (UpdateRowSource.Both)]
312                 public
313 #if NET_2_0
314                 override
315 #endif // NET_2_0
316                 UpdateRowSource UpdatedRowSource {
317                         get { return updatedRowSource; }
318                         set {
319                                 ExceptionHelper.CheckEnumValue (typeof (UpdateRowSource), value);
320                                 updatedRowSource = value;
321                         }
322                 }
323
324 #if NET_2_0
325                 [Browsable (false)]
326                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
327                 public SqlNotificationRequest Notification {
328                         get { return notification; }
329                         set { notification = value; }
330                 }
331
332                 [DefaultValue (true)]
333                 public bool NotificationAutoEnlist {
334                         get { return notificationAutoEnlist; }
335                         set { notificationAutoEnlist = value; }
336                 }
337 #endif
338                 #endregion // Fields
339
340                 #region Methods
341
342                 public
343 #if NET_2_0
344                 override
345 #endif // NET_2_0
346                 void Cancel ()
347                 {
348                         if (Connection == null || Connection.Tds == null)
349                                 return;
350                         Connection.Tds.Cancel ();
351                 }
352
353 #if NET_2_0
354                 public SqlCommand Clone ()
355                 {
356                         return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
357                 }
358 #endif // NET_2_0
359
360                 internal void CloseDataReader ()
361                 {
362                         if (Connection != null) {
363                                 Connection.DataReader = null;
364
365                                 if ((behavior & CommandBehavior.CloseConnection) != 0)
366                                         Connection.Close ();
367
368                                 if (Tds != null)
369                                         Tds.SequentialAccess = false;
370                         }
371
372                         // Reset the behavior
373                         behavior = CommandBehavior.Default;
374                 }
375
376                 public new SqlParameter CreateParameter ()
377                 {
378                         return new SqlParameter ();
379                 }
380
381                 internal void DeriveParameters ()
382                 {
383                         if (commandType != CommandType.StoredProcedure)
384                                 throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
385                         ValidateCommand ("DeriveParameters", false);
386
387                         string procName = CommandText;
388                         string schemaName = String.Empty;
389                         int dotPosition = procName.IndexOf ('.');
390                         if (dotPosition >= 0) {
391                                 schemaName = procName.Substring (0, dotPosition);
392                                 procName = procName.Substring (dotPosition + 1);
393                         }
394                         
395                         SqlParameterCollection localParameters = new SqlParameterCollection (this);
396                         localParameters.Add ("@procedure_name", SqlDbType.NVarChar, procName.Length).Value = procName;
397                         if (schemaName.Length > 0)
398                                 localParameters.Add ("@procedure_schema", SqlDbType.NVarChar, schemaName.Length).Value = schemaName;
399                         
400                         string sql = "sp_procedure_params_rowset";
401
402                         try {
403                                 Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
404                         } catch (TdsTimeoutException ex) {
405                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
406                         } catch (TdsInternalException ex) {
407                                 Connection.Close ();
408                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
409                         }
410
411                         SqlDataReader reader = new SqlDataReader (this);
412                         parameters.Clear ();
413                         object[] dbValues = new object[reader.FieldCount];
414
415                         while (reader.Read ()) {
416                                 reader.GetValues (dbValues);
417                                 parameters.Add (new SqlParameter (dbValues));
418                         }
419                         reader.Close ();
420
421                         if (parameters.Count == 0)
422                                 throw new InvalidOperationException ("Stored procedure '" + procName + "' does not exist.");
423                 }
424
425                 private void Execute (bool wantResults)
426                 {
427                         int index = 0;
428                         Connection.Tds.RecordsAffected = -1;
429                         TdsMetaParameterCollection parms = Parameters.MetaParameters;
430                         foreach (TdsMetaParameter param in parms) {
431                                 param.Validate (index++);
432                         }
433
434                         if (preparedStatement == null) {
435                                 bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
436                                 bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
437
438                                 StringBuilder sql1 = new StringBuilder ();
439                                 StringBuilder sql2 = new StringBuilder ();
440
441                                 if (schemaOnly || keyInfo)
442                                         sql1.Append ("SET FMTONLY OFF;");
443                                 if (keyInfo) {
444                                         sql1.Append ("SET NO_BROWSETABLE ON;");
445                                         sql2.Append ("SET NO_BROWSETABLE OFF;");
446                                 }
447                                 if (schemaOnly) {
448                                         sql1.Append ("SET FMTONLY ON;");
449                                         sql2.Append ("SET FMTONLY OFF;");
450                                 }
451                                 
452                                 switch (CommandType) {
453                                 case CommandType.StoredProcedure:
454                                         try {
455                                                 if (keyInfo || schemaOnly)
456                                                         Connection.Tds.Execute (sql1.ToString ());
457                                                 Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
458                                                 if (keyInfo || schemaOnly)
459                                                         Connection.Tds.Execute (sql2.ToString ());
460                                         } catch (TdsTimeoutException ex) {
461                                                 // If it is a timeout exception there can be many reasons:
462                                                 // 1) Network is down/server is down/not reachable
463                                                 // 2) Somebody has an exclusive lock on Table/DB
464                                                 // In any of these cases, don't close the connection. Let the user do it
465                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
466                                         } catch (TdsInternalException ex) {
467                                                 Connection.Close ();
468                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
469                                         }
470                                         break;
471                                 case CommandType.Text:
472                                         string sql;
473                                         if (sql2.Length > 0) {
474                                                 sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
475                                         } else {
476                                                 sql = String.Format ("{0}{1}", sql1.ToString (), CommandText);
477                                         }
478                                         try {
479                                                 Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
480                                         } catch (TdsTimeoutException ex) {
481                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
482                                         } catch (TdsInternalException ex) {
483                                                 Connection.Close ();
484                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
485                                         }
486                                         break;
487                                 }
488                         }
489                         else {
490                                 try {
491                                         Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
492                                 } catch (TdsTimeoutException ex) {
493                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
494                                 } catch (TdsInternalException ex) {
495                                         Connection.Close ();
496                                         throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
497                                 }
498                         }
499                 }
500
501                 public
502 #if NET_2_0
503                 override
504 #endif // NET_2_0
505                 int ExecuteNonQuery ()
506                 {
507                         ValidateCommand ("ExecuteNonQuery", false);
508                         int result = 0;
509                         behavior = CommandBehavior.Default;
510
511                         try {
512                                 Execute (false);
513                                 result = Connection.Tds.RecordsAffected;
514                         } catch (TdsTimeoutException e) {
515                                 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
516                         }
517
518                         GetOutputParameters ();
519                         return result;
520                 }
521
522                 public new SqlDataReader ExecuteReader ()
523                 {
524                         return ExecuteReader (CommandBehavior.Default);
525                 }
526
527                 public new SqlDataReader ExecuteReader (CommandBehavior behavior)
528                 {
529                         ValidateCommand ("ExecuteReader", false);
530                         if ((behavior & CommandBehavior.SingleRow) != 0)
531                                 behavior |= CommandBehavior.SingleResult;
532                         this.behavior = behavior;
533                         if ((behavior & CommandBehavior.SequentialAccess) != 0)
534                                 Tds.SequentialAccess = true;
535                         Execute (true);
536                         Connection.DataReader = new SqlDataReader (this);
537                         
538                         return Connection.DataReader;
539                 }
540
541                 public
542 #if NET_2_0
543                 override
544 #endif // NET_2_0
545                 object ExecuteScalar ()
546                 {
547                         try {
548                                 object result = null;
549 #if NET_2_0
550                                 ValidateCommand ("ExecuteScalar", false);
551 #else
552                                 ValidateCommand ("ExecuteReader", false);
553 #endif
554                                 behavior = CommandBehavior.Default;
555                                 Execute (true);
556
557                                 try {
558                                         if (Connection.Tds.NextResult () && Connection.Tds.NextRow ())
559                                                 result = Connection.Tds.ColumnValues[0];
560
561                                         if (commandType == CommandType.StoredProcedure) {
562                                                 Connection.Tds.SkipToEnd ();
563                                                 GetOutputParameters ();
564                                         }
565                                 } catch (TdsTimeoutException ex) {
566                                         throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
567                                 } catch (TdsInternalException ex) {
568                                         Connection.Close ();
569                                         throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
570                                 }
571
572                                 return result;
573                         } finally {
574                                 CloseDataReader ();
575                         }
576                 }
577
578                 public XmlReader ExecuteXmlReader ()
579                 {
580                         ValidateCommand ("ExecuteXmlReader", false);
581                         behavior = CommandBehavior.Default;
582                         try {
583                                 Execute (true);
584                         } catch (TdsTimeoutException e) {
585                                 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
586                         }
587
588                         SqlDataReader dataReader = new SqlDataReader (this);
589                         SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
590                         XmlReader xmlReader = new XmlTextReader (textReader);
591                         return xmlReader;
592                 }
593
594                 internal void GetOutputParameters ()
595                 {
596                         IList list = Connection.Tds.OutputParameters;
597
598                         if (list != null && list.Count > 0) {
599
600                                 int index = 0;
601                                 foreach (SqlParameter parameter in parameters) {
602                                         if (parameter.Direction != ParameterDirection.Input &&
603                                             parameter.Direction != ParameterDirection.ReturnValue) {
604                                                 parameter.Value = list [index];
605                                                 index += 1;
606                                         }
607                                         if (index >= list.Count)
608                                                 break;
609                                 }
610                         }
611                 }
612
613                 object ICloneable.Clone ()
614                 {
615                         return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
616
617                 }
618
619 #if !NET_2_0
620                 IDbDataParameter IDbCommand.CreateParameter ()
621                 {
622                         return CreateParameter ();
623                 }
624
625                 IDataReader IDbCommand.ExecuteReader ()
626                 {
627                         return ExecuteReader ();
628                 }
629
630                 IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
631                 {
632                         return ExecuteReader (behavior);
633                 }
634 #endif
635
636 #if NET_2_0
637                 protected override void Dispose (bool disposing)
638                 {
639                         if (disposed) return;
640                         if (disposing) {
641                                 parameters.Clear();
642                         }
643                         base.Dispose (disposing);
644                         disposed = true;
645                 }
646 #endif
647
648                 public
649 #if NET_2_0
650                 override
651 #endif // NET_2_0
652                 void Prepare ()
653                 {
654 #if NET_2_0
655                         if (Connection == null)
656                                 throw new NullReferenceException ();
657 #endif
658
659                         if (CommandType == CommandType.StoredProcedure || CommandType == CommandType.Text && Parameters.Count == 0)
660                                 return;
661
662                         ValidateCommand ("Prepare", false);
663
664                         try {
665                                 foreach (SqlParameter param in Parameters)
666                                         param.CheckIfInitialized ();
667                         } catch (Exception e) {
668                                 throw new InvalidOperationException ("SqlCommand.Prepare requires " + e.Message);
669                         }
670
671                         preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
672                 }
673
674                 public void ResetCommandTimeout ()
675                 {
676                         commandTimeout = DEFAULT_COMMAND_TIMEOUT;
677                 }
678
679                 private void Unprepare ()
680                 {
681                         Connection.Tds.Unprepare (preparedStatement);
682                         preparedStatement = null;
683                 }
684
685                 private void ValidateCommand (string method, bool async)
686                 {
687                         if (Connection == null)
688                                 throw new InvalidOperationException (String.Format ("{0}: A Connection object is required to continue.", method));
689                         if (Transaction == null && Connection.Transaction != null)
690                                 throw new InvalidOperationException (String.Format (
691                                         "{0} requires a transaction if the command's connection is in a pending transaction.",
692 #if NET_2_0
693                                         method));
694 #else
695                                         "Execute"));
696 #endif
697                         if (Transaction != null && Transaction.Connection != Connection)
698                                 throw new InvalidOperationException ("The connection does not have the same transaction as the command.");
699                         if (Connection.State != ConnectionState.Open)
700                                 throw new InvalidOperationException (String.Format ("{0} requires an open connection to continue. This connection is closed.", method));
701                         if (CommandText.Length == 0)
702                                 throw new InvalidOperationException ("The command text for this Command has not been set.");
703                         if (Connection.DataReader != null)
704                                 throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
705                         if (Connection.XmlReader != null)
706                                 throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
707 #if NET_2_0
708                         if (async && !Connection.AsyncProcessing)
709                                 throw new InvalidOperationException ("This Connection object is not " + 
710                                         "in Asynchronous mode. Use 'Asynchronous" +
711                                         " Processing = true' to set it.");
712 #endif // NET_2_0
713                 }
714
715 #if NET_2_0
716                 protected override DbParameter CreateDbParameter ()
717                 {
718                         return CreateParameter ();
719                 }
720
721                 protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
722                 {
723                         return ExecuteReader (behavior);
724                 }
725
726                 protected override DbConnection DbConnection {
727                         get { return Connection; }
728                         set { Connection = (SqlConnection) value; }
729                 }
730
731                 protected override DbParameterCollection DbParameterCollection {
732                         get { return Parameters; }
733                 }
734
735                 protected override DbTransaction DbTransaction {
736                         get { return Transaction; }
737                         set { Transaction = (SqlTransaction) value; }
738                 }
739 #endif // NET_2_0
740
741                 #endregion // Methods
742
743 #if NET_2_0
744                 #region Asynchronous Methods
745
746                 internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior, 
747                                                                                                         bool wantResults,
748                                                                                                         AsyncCallback callback, 
749                                                                                                         object state)
750                 {
751                         IAsyncResult ar = null;
752                         Connection.Tds.RecordsAffected = -1;
753                         TdsMetaParameterCollection parms = Parameters.MetaParameters;
754                         if (preparedStatement == null) {
755                                 bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
756                                 bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
757
758                                 StringBuilder sql1 = new StringBuilder ();
759                                 StringBuilder sql2 = new StringBuilder ();
760
761                                 if (schemaOnly || keyInfo)
762                                         sql1.Append ("SET FMTONLY OFF;");
763                                 if (keyInfo) {
764                                         sql1.Append ("SET NO_BROWSETABLE ON;");
765                                         sql2.Append ("SET NO_BROWSETABLE OFF;");
766                                 }
767                                 if (schemaOnly) {
768                                         sql1.Append ("SET FMTONLY ON;");
769                                         sql2.Append ("SET FMTONLY OFF;");
770                                 }
771                                 switch (CommandType) {
772                                 case CommandType.StoredProcedure:
773                                         string prolog = "";
774                                         string epilog = "";
775                                         if (keyInfo || schemaOnly)
776                                                 prolog = sql1.ToString ();
777                                         if (keyInfo || schemaOnly)
778                                                 epilog = sql2.ToString ();
779                                         try {
780                                                 Connection.Tds.BeginExecuteProcedure (prolog,
781                                                                                       epilog,
782                                                                                       CommandText,
783                                                                                       !wantResults,
784                                                                                       parms,
785                                                                                       callback,
786                                                                                       state);
787                                         } catch (TdsTimeoutException ex) {
788                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
789                                         } catch (TdsInternalException ex) {
790                                                 Connection.Close ();
791                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
792                                         }
793                                         break;
794                                 case CommandType.Text:
795                                         string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
796                                         try {
797                                                 if (wantResults)
798                                                         ar = Connection.Tds.BeginExecuteQuery (sql, parms, callback, state);
799                                                 else
800                                                         ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
801                                         } catch (TdsTimeoutException ex) {
802                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
803                                         } catch (TdsInternalException ex) {
804                                                 Connection.Close ();
805                                                 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
806                                         }
807                                         break;
808                                 }
809                         }
810                         else {
811                                 try {
812                                         Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
813                                 } catch (TdsTimeoutException ex) {
814                                         throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
815                                 } catch (TdsInternalException ex) {
816                                         Connection.Close ();
817                                         throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
818                                 }
819                         }
820                         return ar;
821                 }
822
823                 internal void EndExecuteInternal (IAsyncResult ar)
824                 {
825                         SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
826                         Connection.Tds.WaitFor (sqlResult.InternalResult);
827                         Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
828                 }
829
830                 public IAsyncResult BeginExecuteNonQuery ()
831                 {
832                         return BeginExecuteNonQuery (null, null);
833                 }
834
835                 public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object stateObject)
836                 {
837                         ValidateCommand ("BeginExecuteNonQuery", true);
838                         SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
839                         ar.EndMethod = "EndExecuteNonQuery";
840                         ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
841                         return ar;
842                 }
843
844                 public int EndExecuteNonQuery (IAsyncResult asyncResult)
845                 {
846                         ValidateAsyncResult (asyncResult, "EndExecuteNonQuery");
847                         EndExecuteInternal (asyncResult);
848
849                         int ret = Connection.Tds.RecordsAffected;
850
851                         GetOutputParameters ();
852                         ((SqlAsyncResult) asyncResult).Ended = true;
853                         return ret;
854                 }
855
856                 public IAsyncResult BeginExecuteReader ()
857                 {
858                         return BeginExecuteReader (null, null, CommandBehavior.Default);
859                 }
860
861                 public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
862                 {
863                         return BeginExecuteReader (null, null, behavior);
864                 }
865
866                 public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject)
867                 {
868                         return BeginExecuteReader (callback, stateObject, CommandBehavior.Default);
869                 }
870
871                 public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject, CommandBehavior behavior)
872                 {
873                         ValidateCommand ("BeginExecuteReader", true);
874                         this.behavior = behavior;
875                         SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
876                         ar.EndMethod = "EndExecuteReader";
877                         IAsyncResult tdsResult = BeginExecuteInternal (behavior, true, 
878                                 ar.BubbleCallback, stateObject);
879                         ar.InternalResult = tdsResult;
880                         return ar;
881                 }
882
883                 public SqlDataReader EndExecuteReader (IAsyncResult asyncResult)
884                 {
885                         ValidateAsyncResult (asyncResult, "EndExecuteReader");
886                         EndExecuteInternal (asyncResult);
887                         SqlDataReader reader = null;
888                         try {
889                                 reader = new SqlDataReader (this);
890                         } catch (TdsTimeoutException e) {
891                                 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
892                         } catch (TdsInternalException e) {
893                                 // if behavior is closeconnection, even if it throws exception
894                                 // the connection has to be closed.
895                                 if ((behavior & CommandBehavior.CloseConnection) != 0)
896                                         Connection.Close ();
897                                 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
898                         }
899
900                         ((SqlAsyncResult) asyncResult).Ended = true;
901                         return reader;
902                 }
903
904                 public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object stateObject)
905                 {
906                         ValidateCommand ("BeginExecuteXmlReader", true);
907                         SqlAsyncResult ar = new SqlAsyncResult (callback, stateObject);
908                         ar.EndMethod = "EndExecuteXmlReader";
909                         ar.InternalResult = BeginExecuteInternal (behavior, true, 
910                                 ar.BubbleCallback, stateObject);
911                         return ar;
912                 }
913
914                 public IAsyncResult BeginExecuteXmlReader ()
915                 {
916                         return BeginExecuteXmlReader (null, null);
917                 }
918                 
919
920                 public XmlReader EndExecuteXmlReader (IAsyncResult asyncResult)
921                 {
922                         ValidateAsyncResult (asyncResult, "EndExecuteXmlReader");
923                         EndExecuteInternal (asyncResult);
924                         SqlDataReader reader = new SqlDataReader (this);
925                         SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
926                         XmlReader xmlReader = new XmlTextReader (textReader);
927                         ((SqlAsyncResult) asyncResult).Ended = true;
928                         return xmlReader;
929                 }
930
931                 internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
932                 {
933                         if (ar == null)
934                                 throw new ArgumentException ("result passed is null!");
935                         if (! (ar is SqlAsyncResult))
936                                 throw new ArgumentException (String.Format ("cannot test validity of types {0}",
937                                         ar.GetType ()));
938                         SqlAsyncResult result = (SqlAsyncResult) ar;
939                         if (result.EndMethod != endMethod)
940                                 throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " + 
941                                         "Expected call to {1} but {0} is called instead.",
942                                         endMethod, result.EndMethod));
943                         if (result.Ended)
944                                 throw new InvalidOperationException (String.Format ("The method {0} cannot be called " + 
945                                         "more than once for the same AsyncResult.", endMethod));
946                 }
947
948                 #endregion // Asynchronous Methods
949
950                 public event StatementCompletedEventHandler StatementCompleted;
951 #endif // NET_2_0
952         }
953 }