This source code has been disassembled from System.Data.dll assembly.

Click on a class, interface or delegate name to go to definition. Also, let us your feedback on this class using the comment feed aside.

If any source code presented here does not respect license rules applied to related product, please signal it right now.

Examples containing SqlCommand

  • No example yet.

SqlCommand.cs

Namespace
System.Data.SqlClient
Assembly
System.Data v4.0.0.0
CPU architecture
X86
.NET Runtime
v4.0.30319

Source Code

Versions (3)

.NET Runtimes

// Assembly: System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Runtime: v4.0.30319
// Architecture: X86
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Remoting.Messaging;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using System.Xml;
namespace System.Data.SqlClient
{
	[ToolboxItem(true), Designer("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), DefaultEvent("RecordsAffected")]
	public sealed class SqlCommand : DbCommand, ICloneable
	{
		private enum EXECTYPE
		{
			UNPREPARED,
			PREPAREPENDING,
			PREPARED
		}
		private class CachedAsyncState
		{
			private int _cachedAsyncCloseCount = -1;
			private TaskCompletionSource<object> _cachedAsyncResult;
			private SqlConnection _cachedAsyncConnection;
			private SqlDataReader _cachedAsyncReader;
			private RunBehavior _cachedRunBehavior = RunBehavior.ReturnImmediately;
			private string _cachedSetOptions;
			private string _cachedEndMethod;
			internal SqlDataReader CachedAsyncReader
			{
				get
				{
					return this._cachedAsyncReader;
				}
			}
			internal RunBehavior CachedRunBehavior
			{
				get
				{
					return this._cachedRunBehavior;
				}
			}
			internal string CachedSetOptions
			{
				get
				{
					return this._cachedSetOptions;
				}
			}
			internal bool PendingAsyncOperation
			{
				get
				{
					return null != this._cachedAsyncResult;
				}
			}
			internal string EndMethodName
			{
				get
				{
					return this._cachedEndMethod;
				}
			}
			internal CachedAsyncState()
			{
			}
			internal bool IsActiveConnectionValid(SqlConnection activeConnection)
			{
				return this._cachedAsyncConnection == activeConnection && this._cachedAsyncCloseCount == activeConnection.CloseCount;
			}
			[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
			internal void ResetAsyncState()
			{
				this._cachedAsyncCloseCount = -1;
				this._cachedAsyncResult = null;
				if (this._cachedAsyncConnection != null)
				{
					this._cachedAsyncConnection.AsyncCommandInProgress = false;
					this._cachedAsyncConnection = null;
				}
				this._cachedAsyncReader = null;
				this._cachedRunBehavior = RunBehavior.ReturnImmediately;
				this._cachedSetOptions = null;
				this._cachedEndMethod = null;
			}
			internal void SetActiveConnectionAndResult(TaskCompletionSource<object> completion, string endMethod, SqlConnection activeConnection)
			{
				TdsParser parser = activeConnection.Parser;
				if (parser == null || parser.State == TdsParserState.Closed || parser.State == TdsParserState.Broken)
				{
					throw ADP.ClosedConnectionError();
				}
				this._cachedAsyncCloseCount = activeConnection.CloseCount;
				this._cachedAsyncResult = completion;
				if (activeConnection != null && !parser.MARSOn && activeConnection.AsyncCommandInProgress)
				{
					throw SQL.MARSUnspportedOnConnection();
				}
				this._cachedAsyncConnection = activeConnection;
				this._cachedAsyncConnection.AsyncCommandInProgress = true;
				this._cachedEndMethod = endMethod;
			}
			internal void SetAsyncReaderState(SqlDataReader ds, RunBehavior runBehavior, string optionSettings)
			{
				this._cachedAsyncReader = ds;
				this._cachedRunBehavior = runBehavior;
				this._cachedSetOptions = optionSettings;
			}
		}
		private sealed class CommandEventSink : SmiEventSink_Default
		{
			private SqlCommand _command;
			internal CommandEventSink(SqlCommand command)
			{
				this._command = command;
			}
			internal override void StatementCompleted(int rowsAffected)
			{
				if (Bid.AdvancedOn)
				{
					Bid.Trace("<sc.SqlCommand.CommandEventSink.StatementCompleted|ADV> %d#, rowsAffected=%d.\n", this._command.ObjectID, rowsAffected);
				}
				this._command.InternalRecordsAffected = rowsAffected;
			}
			internal override void BatchCompleted()
			{
				if (Bid.AdvancedOn)
				{
					Bid.Trace("<sc.SqlCommand.CommandEventSink.BatchCompleted|ADV> %d#.\n", this._command.ObjectID);
				}
			}
			internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues)
			{
				if (Bid.AdvancedOn)
				{
					Bid.Trace("<sc.SqlCommand.CommandEventSink.ParametersAvailable|ADV> %d# metaData.Length=%d.\n", this._command.ObjectID, (metaData != null) ? metaData.Length : -1);
					if (metaData != null)
					{
						for (int i = 0; i < metaData.Length; i++)
						{
							Bid.Trace("<sc.SqlCommand.CommandEventSink.ParametersAvailable|ADV> %d#, metaData[%d] is %ls%ls\n", this._command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString());
						}
					}
				}
				this._command.OnParametersAvailableSmi(metaData, parameterValues);
			}
			internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal)
			{
				if (Bid.AdvancedOn && metaData != null)
				{
					Bid.Trace("<sc.SqlCommand.CommandEventSink.ParameterAvailable|ADV> %d#, metaData[%d] is %ls%ls\n", this._command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString());
				}
				this._command.OnParameterAvailableSmi(metaData, parameterValues, ordinal);
			}
		}
		private static int _objectTypeCount;
		internal readonly int ObjectID = Interlocked.Increment(ref SqlCommand._objectTypeCount);
		private string _commandText;
		private CommandType _commandType;
		private int _commandTimeout = 30;
		private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
		private bool _designTimeInvisible;
		internal SqlDependency _sqlDep;
		private bool _inPrepare;
		private int _prepareHandle = -1;
		private bool _hiddenPrepare;
		private SqlParameterCollection _parameters;
		private SqlConnection _activeConnection;
		private bool _dirty;
		private SqlCommand.EXECTYPE _execType;
		private _SqlRPC[] _rpcArrayOf1;
		private _SqlMetaDataSet _cachedMetaData;
		private SqlCommand.CachedAsyncState _cachedAsyncState;
		internal int _rowsAffected = -1;
		private SqlNotificationRequest _notification;
		private bool _notificationAutoEnlist = true;
		private SqlTransaction _transaction;
		private StatementCompletedEventHandler _statementCompletedEventHandler;
		private TdsParserStateObject _stateObj;
		private bool _pendingCancel;
		private bool _batchRPCMode;
		private List<_SqlRPC> _RPCList;
		private _SqlRPC[] _SqlRPCBatchArray;
		private List<SqlParameterCollection> _parameterCollectionList;
		private int _currentlyExecutingBatch;
		private SmiContext _smiRequestContext;
		private SqlCommand.CommandEventSink _smiEventSink;
		private SmiEventSink_DeferedProcessing _outParamEventSink;
		internal static readonly string[] PreKatmaiProcParamsNames;
		internal static readonly string[] KatmaiProcParamsNames;
		[ResCategory("DataCategory_StatementCompleted"), ResDescription("DbCommand_StatementCompleted")]
		public event StatementCompletedEventHandler StatementCompleted
		{
			add
			{
				this._statementCompletedEventHandler = (StatementCompletedEventHandler)Delegate.Combine(this._statementCompletedEventHandler, value);
			}
			remove
			{
				this._statementCompletedEventHandler = (StatementCompletedEventHandler)Delegate.Remove(this._statementCompletedEventHandler, value);
			}
		}
		internal bool InPrepare
		{
			get
			{
				return this._inPrepare;
			}
		}
		private SqlCommand.CachedAsyncState cachedAsyncState
		{
			get
			{
				if (this._cachedAsyncState == null)
				{
					this._cachedAsyncState = new SqlCommand.CachedAsyncState();
				}
				return this._cachedAsyncState;
			}
		}
		private SqlCommand.CommandEventSink EventSink
		{
			get
			{
				if (this._smiEventSink == null)
				{
					this._smiEventSink = new SqlCommand.CommandEventSink(this);
				}
				this._smiEventSink.Parent = this.InternalSmiConnection.CurrentEventSink;
				return this._smiEventSink;
			}
		}
		private SmiEventSink_DeferedProcessing OutParamEventSink
		{
			get
			{
				if (this._outParamEventSink == null)
				{
					this._outParamEventSink = new SmiEventSink_DeferedProcessing(this.EventSink);
				}
				else
				{
					this._outParamEventSink.Parent = this.EventSink;
				}
				return this._outParamEventSink;
			}
		}
		[ResCategory("DataCategory_Data"), Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), DefaultValue(null), ResDescription("DbCommand_Connection")]
		public new SqlConnection Connection
		{
			get
			{
				return this._activeConnection;
			}
			set
			{
				if (this._activeConnection != value && this._activeConnection != null && this.cachedAsyncState.PendingAsyncOperation)
				{
					throw SQL.CannotModifyPropertyAsyncOperationInProgress("Connection");
				}
				if (this._transaction != null && this._transaction.Connection == null)
				{
					this._transaction = null;
				}
				this._smiRequestContext = null;
				if (this.IsPrepared && this._activeConnection != value && this._activeConnection != null)
				{
					RuntimeHelpers.PrepareConstrainedRegions();
					try
					{
						this.Unprepare(false, null, null);
					}
					catch (OutOfMemoryException)
					{
						this._activeConnection.InnerConnection.DoomThisConnection();
						throw;
					}
					catch (StackOverflowException)
					{
						this._activeConnection.InnerConnection.DoomThisConnection();
						throw;
					}
					catch (ThreadAbortException)
					{
						this._activeConnection.InnerConnection.DoomThisConnection();
						throw;
					}
					catch (Exception)
					{
					}
					finally
					{
						this._prepareHandle = -1;
						this._execType = SqlCommand.EXECTYPE.UNPREPARED;
					}
				}
				this._activeConnection = value;
				Bid.Trace("<sc.SqlCommand.set_Connection|API> %d#, %d#\n", this.ObjectID, (value != null) ? value.ObjectID : -1);
			}
		}
		protected override DbConnection DbConnection
		{
			get
			{
				return this.Connection;
			}
			set
			{
				this.Connection = (SqlConnection)value;
			}
		}
		private SqlInternalConnectionSmi InternalSmiConnection
		{
			get
			{
				return (SqlInternalConnectionSmi)this._activeConnection.InnerConnection;
			}
		}
		private SqlInternalConnectionTds InternalTdsConnection
		{
			get
			{
				return (SqlInternalConnectionTds)this._activeConnection.InnerConnection;
			}
		}
		private bool IsShiloh
		{
			get
			{
				return this._activeConnection != null && this._activeConnection.IsShiloh;
			}
		}
		[DefaultValue(true), ResDescription("SqlCommand_NotificationAutoEnlist"), ResCategory("DataCategory_Notification")]
		public bool NotificationAutoEnlist
		{
			get
			{
				return this._notificationAutoEnlist;
			}
			set
			{
				this._notificationAutoEnlist = value;
			}
		}
		[Browsable(false), ResCategory("DataCategory_Notification"), ResDescription("SqlCommand_Notification"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public SqlNotificationRequest Notification
		{
			get
			{
				return this._notification;
			}
			set
			{
				Bid.Trace("<sc.SqlCommand.set_Notification|API> %d#\n", this.ObjectID);
				this._sqlDep = null;
				this._notification = value;
			}
		}
		internal SqlStatistics Statistics
		{
			get
			{
				if (this._activeConnection != null && this._activeConnection.StatisticsEnabled)
				{
					return this._activeConnection.Statistics;
				}
				return null;
			}
		}
		[Browsable(false), ResDescription("DbCommand_Transaction"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public new SqlTransaction Transaction
		{
			get
			{
				if (this._transaction != null && this._transaction.Connection == null)
				{
					this._transaction = null;
				}
				return this._transaction;
			}
			set
			{
				if (this._transaction != value && this._activeConnection != null && this.cachedAsyncState.PendingAsyncOperation)
				{
					throw SQL.CannotModifyPropertyAsyncOperationInProgress("Transaction");
				}
				Bid.Trace("<sc.SqlCommand.set_Transaction|API> %d#\n", this.ObjectID);
				this._transaction = value;
			}
		}
		protected override DbTransaction DbTransaction
		{
			get
			{
				return this.Transaction;
			}
			set
			{
				this.Transaction = (SqlTransaction)value;
			}
		}
		[ResCategory("DataCategory_Data"), Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), RefreshProperties(RefreshProperties.All), ResDescription("DbCommand_CommandText"), DefaultValue("")]
		public override string CommandText
		{
			get
			{
				string commandText = this._commandText;
				if (commandText == null)
				{
					return ADP.StrEmpty;
				}
				return commandText;
			}
			set
			{
				if (Bid.TraceOn)
				{
					Bid.Trace("<sc.SqlCommand.set_CommandText|API> %d#, '", this.ObjectID);
					Bid.PutStr(value);
					Bid.Trace("'\n");
				}
				if (ADP.SrcCompare(this._commandText, value) != 0)
				{
					this.PropertyChanging();
					this._commandText = value;
				}
			}
		}
		[ResDescription("DbCommand_CommandTimeout"), ResCategory("DataCategory_Data")]
		public override int CommandTimeout
		{
			get
			{
				return this._commandTimeout;
			}
			set
			{
				Bid.Trace("<sc.SqlCommand.set_CommandTimeout|API> %d#, %d\n", this.ObjectID, value);
				if (value < 0)
				{
					throw ADP.InvalidCommandTimeout(value);
				}
				if (value != this._commandTimeout)
				{
					this.PropertyChanging();
					this._commandTimeout = value;
				}
			}
		}
		[RefreshProperties(RefreshProperties.All), DefaultValue(CommandType.Text), ResDescription("DbCommand_CommandType"), ResCategory("DataCategory_Data")]
		public override CommandType CommandType
		{
			get
			{
				CommandType commandType = this._commandType;
				if (commandType == (CommandType)0)
				{
					return CommandType.Text;
				}
				return commandType;
			}
			set
			{
				Bid.Trace("<sc.SqlCommand.set_CommandType|API> %d#, %d{ds.CommandType}\n", this.ObjectID, (int)value);
				if (this._commandType == value)
				{
					return;
				}
				if (value == CommandType.Text || value == CommandType.StoredProcedure)
				{
					this.PropertyChanging();
					this._commandType = value;
					return;
				}
				if (value != CommandType.TableDirect)
				{
					throw ADP.InvalidCommandType(value);
				}
				throw SQL.NotSupportedCommandType(value);
			}
		}
		[EditorBrowsable(EditorBrowsableState.Never), DefaultValue(true), DesignOnly(true), Browsable(false)]
		public override bool DesignTimeVisible
		{
			get
			{
				return !this._designTimeInvisible;
			}
			set
			{
				this._designTimeInvisible = !value;
				TypeDescriptor.Refresh(this);
			}
		}
		[ResDescription("DbCommand_Parameters"), ResCategory("DataCategory_Data"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		public new SqlParameterCollection Parameters
		{
			get
			{
				if (this._parameters == null)
				{
					this._parameters = new SqlParameterCollection();
				}
				return this._parameters;
			}
		}
		protected override DbParameterCollection DbParameterCollection
		{
			get
			{
				return this.Parameters;
			}
		}
		[ResCategory("DataCategory_Update"), ResDescription("DbCommand_UpdatedRowSource"), DefaultValue(UpdateRowSource.Both)]
		public override UpdateRowSource UpdatedRowSource
		{
			get
			{
				return this._updatedRowSource;
			}
			set
			{
				switch (value)
				{
					case UpdateRowSource.None:
					case UpdateRowSource.OutputParameters:
					case UpdateRowSource.FirstReturnedRecord:
					case UpdateRowSource.Both:
					{
						this._updatedRowSource = value;
						return;
					}
					default:
					{
						throw ADP.InvalidUpdateRowSource(value);
					}
				}
			}
		}
		internal _SqlMetaDataSet MetaData
		{
			get
			{
				return this._cachedMetaData;
			}
		}
		internal TdsParserStateObject StateObject
		{
			get
			{
				return this._stateObj;
			}
		}
		private bool IsPrepared
		{
			get
			{
				return this._execType != SqlCommand.EXECTYPE.UNPREPARED;
			}
		}
		private bool IsUserPrepared
		{
			get
			{
				return this.IsPrepared && !this._hiddenPrepare && !this.IsDirty;
			}
		}
		internal bool IsDirty
		{
			get
			{
				return this.IsPrepared && (this._dirty || (this._parameters != null && this._parameters.IsDirty));
			}
			set
			{
				this._dirty = (value && this.IsPrepared);
				if (this._parameters != null)
				{
					this._parameters.IsDirty = this._dirty;
				}
				this._cachedMetaData = null;
			}
		}
		internal int InternalRecordsAffected
		{
			get
			{
				return this._rowsAffected;
			}
			set
			{
				if (-1 == this._rowsAffected)
				{
					this._rowsAffected = value;
					return;
				}
				if (0 < value)
				{
					this._rowsAffected += value;
				}
			}
		}
		internal bool BatchRPCMode
		{
			get
			{
				return this._batchRPCMode;
			}
			set
			{
				this._batchRPCMode = value;
				if (!this._batchRPCMode)
				{
					this.ClearBatchCommand();
					return;
				}
				if (this._RPCList == null)
				{
					this._RPCList = new List<_SqlRPC>();
				}
				if (this._parameterCollectionList == null)
				{
					this._parameterCollectionList = new List<SqlParameterCollection>();
				}
			}
		}
		public SqlCommand()
		{
			GC.SuppressFinalize(this);
		}
		public SqlCommand(string cmdText) : this()
		{
			this.CommandText = cmdText;
		}
		public SqlCommand(string cmdText, SqlConnection connection) : this()
		{
			this.CommandText = cmdText;
			this.Connection = connection;
		}
		public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction) : this()
		{
			this.CommandText = cmdText;
			this.Connection = connection;
			this.Transaction = transaction;
		}
		private SqlCommand(SqlCommand from) : this()
		{
			this.CommandText = from.CommandText;
			this.CommandTimeout = from.CommandTimeout;
			this.CommandType = from.CommandType;
			this.Connection = from.Connection;
			this.DesignTimeVisible = from.DesignTimeVisible;
			this.Transaction = from.Transaction;
			this.UpdatedRowSource = from.UpdatedRowSource;
			SqlParameterCollection parameters = this.Parameters;
			foreach (object current in from.Parameters)
			{
				parameters.Add((current is ICloneable) ? (current as ICloneable).Clone() : current);
			}
		}
		public void ResetCommandTimeout()
		{
			if (30 != this._commandTimeout)
			{
				this.PropertyChanging();
				this._commandTimeout = 30;
			}
		}
		private bool ShouldSerializeCommandTimeout()
		{
			return 30 != this._commandTimeout;
		}
		internal void OnStatementCompleted(int recordCount)
		{
			if (0 <= recordCount)
			{
				StatementCompletedEventHandler statementCompletedEventHandler = this._statementCompletedEventHandler;
				if (statementCompletedEventHandler != null)
				{
					try
					{
						Bid.Trace("<sc.SqlCommand.OnStatementCompleted|INFO> %d#, recordCount=%d\n", this.ObjectID, recordCount);
						statementCompletedEventHandler(this, new StatementCompletedEventArgs(recordCount));
					}
					catch (Exception e)
					{
						if (!ADP.IsCatchableOrSecurityExceptionType(e))
						{
							throw;
						}
						ADP.TraceExceptionWithoutRethrow(e);
					}
				}
			}
		}
		private void PropertyChanging()
		{
			this.IsDirty = true;
		}
		public override void Prepare()
		{
			SqlConnection.ExecutePermission.Demand();
			this._pendingCancel = false;
			if (this._activeConnection != null && this._activeConnection.IsContextConnection)
			{
				return;
			}
			SqlStatistics statistics = null;
			SqlDataReader sqlDataReader = null;
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<sc.SqlCommand.Prepare|API> %d#", this.ObjectID);
			Bid.CorrelationTrace("<sc.SqlCommand.Prepare|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			statistics = SqlStatistics.StartTimer(this.Statistics);
			if ((this.IsPrepared && !this.IsDirty) || this.CommandType == CommandType.StoredProcedure || (CommandType.Text == this.CommandType && this.GetParameterCount(this._parameters) == 0))
			{
				if (this.Statistics != null)
				{
					this.Statistics.SafeIncrement(ref this.Statistics._prepares);
				}
				this._hiddenPrepare = false;
			}
			else
			{
				bool flag = true;
				TdsParser target = null;
				RuntimeHelpers.PrepareConstrainedRegions();
				try
				{
					target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
					this.ValidateCommand("Prepare", false);
					this.GetStateObject(null);
					if (this._parameters != null)
					{
						int count = this._parameters.Count;
						for (int i = 0; i < count; i++)
						{
							this._parameters[i].Prepare(this);
						}
					}
					sqlDataReader = this.InternalPrepare(CommandBehavior.Default);
				}
				catch (OutOfMemoryException e)
				{
					flag = false;
					this._activeConnection.Abort(e);
					throw;
				}
				catch (StackOverflowException e2)
				{
					flag = false;
					this._activeConnection.Abort(e2);
					throw;
				}
				catch (ThreadAbortException e3)
				{
					flag = false;
					this._activeConnection.Abort(e3);
					SqlInternalConnection.BestEffortCleanup(target);
					throw;
				}
				catch (Exception e4)
				{
					flag = ADP.IsCatchableExceptionType(e4);
					throw;
				}
				finally
				{
					if (flag)
					{
						this._hiddenPrepare = false;
						if (sqlDataReader != null)
						{
							this._cachedMetaData = sqlDataReader.MetaData;
							sqlDataReader.Close();
						}
						this.PutStateObject();
					}
				}
			}
			SqlStatistics.StopTimer(statistics);
			Bid.ScopeLeave(ref intPtr);
		}
		private SqlDataReader InternalPrepare(CommandBehavior behavior)
		{
			SqlDataReader sqlDataReader = null;
			if (this.IsDirty)
			{
				this.Unprepare(false, null, null);
				this.IsDirty = false;
			}
			if (this._activeConnection.IsShiloh)
			{
				this._execType = SqlCommand.EXECTYPE.PREPAREPENDING;
			}
			else
			{
				this.BuildPrepare(behavior);
				this._inPrepare = true;
				sqlDataReader = new SqlDataReader(this, behavior);
				try
				{
					this._stateObj.Parser.TdsExecuteRPC(this._rpcArrayOf1, this.CommandTimeout, false, null, this._stateObj, CommandType.StoredProcedure == this.CommandType, true, null, 0, 0);
					bool flag;
					if (!this._stateObj.Parser.TryRun(RunBehavior.UntilDone, this, sqlDataReader, null, this._stateObj, out flag))
					{
						throw SQL.SynchronousCallMayNotPend();
					}
				}
				catch
				{
					this._inPrepare = false;
					throw;
				}
				sqlDataReader.Bind(this._stateObj);
				this._execType = SqlCommand.EXECTYPE.PREPARED;
				Bid.Trace("<sc.SqlCommand.Prepare|INFO> %d#, Command prepared.\n", this.ObjectID);
			}
			if (this.Statistics != null)
			{
				this.Statistics.SafeIncrement(ref this.Statistics._prepares);
			}
			this._activeConnection.AddPreparedCommand(this);
			return sqlDataReader;
		}
		internal void Unprepare(bool isClosing, TdsParser parser = null, bool? isShiloh = null)
		{
			if (this._activeConnection.IsContextConnection)
			{
				return;
			}
			if (isClosing)
			{
				this._pendingCancel = false;
			}
			bool flag = false;
			bool flag2 = true;
			try
			{
				if (this._stateObj == null)
				{
					this.GetStateObject(parser);
					flag = true;
				}
				bool? flag3 = isShiloh;
				this.InternalUnprepare(isClosing, flag3.HasValue ? flag3.GetValueOrDefault() : this.IsShiloh);
			}
			catch (Exception e)
			{
				flag2 = ADP.IsCatchableExceptionType(e);
				throw;
			}
			finally
			{
				if (flag2 && flag)
				{
					this.PutStateObject();
				}
			}
		}
		private void InternalUnprepare(bool isClosing, bool isShiloh)
		{
			if (isShiloh)
			{
				this._execType = SqlCommand.EXECTYPE.PREPAREPENDING;
				if (isClosing)
				{
					this._prepareHandle = -1;
				}
			}
			else
			{
				if (this._prepareHandle != -1)
				{
					this.BuildUnprepare();
					this._stateObj.Parser.TdsExecuteRPC(this._rpcArrayOf1, this.CommandTimeout, false, null, this._stateObj, CommandType.StoredProcedure == this.CommandType, true, null, 0, 0);
					bool flag;
					if (!this._stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, this._stateObj, out flag))
					{
						throw SQL.SynchronousCallMayNotPend();
					}
					this._prepareHandle = -1;
				}
				this._execType = SqlCommand.EXECTYPE.UNPREPARED;
			}
			this._cachedMetaData = null;
			if (!isClosing)
			{
				this._activeConnection.RemovePreparedCommand(this);
			}
			Bid.Trace("<sc.SqlCommand.Prepare|INFO> %d#, Command unprepared.\n", this.ObjectID);
		}
		public override void Cancel()
		{
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<sc.SqlCommand.Cancel|API> %d#", this.ObjectID);
			Bid.CorrelationTrace("<sc.SqlCommand.Cancel|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			SqlStatistics statistics = null;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				if (this._activeConnection != null)
				{
					SqlInternalConnectionTds sqlInternalConnectionTds = this._activeConnection.InnerConnection as SqlInternalConnectionTds;
					if (sqlInternalConnectionTds != null)
					{
						lock (sqlInternalConnectionTds)
						{
							if (sqlInternalConnectionTds == this._activeConnection.InnerConnection as SqlInternalConnectionTds)
							{
								if (sqlInternalConnectionTds.Parser != null)
								{
									TdsParser target = null;
									RuntimeHelpers.PrepareConstrainedRegions();
									try
									{
										target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
										if (!this._pendingCancel)
										{
											this._pendingCancel = true;
											TdsParserStateObject stateObj = this._stateObj;
											if (stateObj != null)
											{
												stateObj.Cancel(this.ObjectID);
											}
											else
											{
												SqlDataReader sqlDataReader = sqlInternalConnectionTds.FindLiveReader(this);
												if (sqlDataReader != null)
												{
													sqlDataReader.Cancel(this.ObjectID);
												}
											}
										}
									}
									catch (OutOfMemoryException e)
									{
										this._activeConnection.Abort(e);
										throw;
									}
									catch (StackOverflowException e2)
									{
										this._activeConnection.Abort(e2);
										throw;
									}
									catch (ThreadAbortException e3)
									{
										this._activeConnection.Abort(e3);
										SqlInternalConnection.BestEffortCleanup(target);
										throw;
									}
								}
							}
						}
					}
				}
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
				Bid.ScopeLeave(ref intPtr);
			}
		}
		public new SqlParameter CreateParameter()
		{
			return new SqlParameter();
		}
		protected override DbParameter CreateDbParameter()
		{
			return this.CreateParameter();
		}
		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				this._cachedMetaData = null;
			}
			base.Dispose(disposing);
		}
		public override object ExecuteScalar()
		{
			SqlConnection.ExecutePermission.Demand();
			this._pendingCancel = false;
			SqlStatistics statistics = null;
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<sc.SqlCommand.ExecuteScalar|API> %d#", this.ObjectID);
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteScalar|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			object result;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				SqlDataReader ds = this.RunExecuteReader(CommandBehavior.Default, RunBehavior.ReturnImmediately, true, "ExecuteScalar");
				result = this.CompleteExecuteScalar(ds, false);
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
				Bid.ScopeLeave(ref intPtr);
			}
			return result;
		}
		private object CompleteExecuteScalar(SqlDataReader ds, bool returnSqlValue)
		{
			object result = null;
			try
			{
				if (ds.Read() && ds.FieldCount > 0)
				{
					if (returnSqlValue)
					{
						result = ds.GetSqlValue(0);
					}
					else
					{
						result = ds.GetValue(0);
					}
				}
			}
			finally
			{
				ds.Close();
			}
			return result;
		}
		public override int ExecuteNonQuery()
		{
			SqlConnection.ExecutePermission.Demand();
			this._pendingCancel = false;
			SqlStatistics statistics = null;
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<sc.SqlCommand.ExecuteNonQuery|API> %d#", this.ObjectID);
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			int rowsAffected;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				this.InternalExecuteNonQuery(null, "ExecuteNonQuery", false, this.CommandTimeout, false);
				rowsAffected = this._rowsAffected;
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
				Bid.ScopeLeave(ref intPtr);
			}
			return rowsAffected;
		}
		internal void ExecuteToPipe(SmiContext pipeContext)
		{
			SqlConnection.ExecutePermission.Demand();
			this._pendingCancel = false;
			SqlStatistics statistics = null;
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<sc.SqlCommand.ExecuteToPipe|INFO> %d#", this.ObjectID);
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				this.InternalExecuteNonQuery(null, "ExecuteNonQuery", true, this.CommandTimeout, false);
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
				Bid.ScopeLeave(ref intPtr);
			}
		}
		[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
		public IAsyncResult BeginExecuteNonQuery()
		{
			return this.BeginExecuteNonQuery(null, null);
		}
		[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
		public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			SqlConnection.ExecutePermission.Demand();
			return this.BeginExecuteNonQueryInternal(callback, stateObject, 0, false);
		}
		private IAsyncResult BeginExecuteNonQueryAsync(AsyncCallback callback, object stateObject)
		{
			return this.BeginExecuteNonQueryInternal(callback, stateObject, this.CommandTimeout, true);
		}
		private IAsyncResult BeginExecuteNonQueryInternal(AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false)
		{
			this._pendingCancel = false;
			this.ValidateAsyncCommand();
			SqlStatistics statistics = null;
			IAsyncResult task2;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
				try
				{
					Task task = this.InternalExecuteNonQuery(completion, "BeginExecuteNonQuery", false, timeout, asyncWrite);
					if (task != null)
					{
						AsyncHelper.ContinueTask(task, completion, delegate
						{
							this.BeginExecuteNonQueryInternalReadStage(completion);
						}
						, null, null, null);
					}
					else
					{
						this.BeginExecuteNonQueryInternalReadStage(completion);
					}
				}
				catch (Exception e)
				{
					if (!ADP.IsCatchableOrSecurityExceptionType(e))
					{
						throw;
					}
					this.PutStateObject();
					throw;
				}
				if (callback != null)
				{
					completion.Task.ContinueWith(delegate(Task<object> t)
					{
						callback(t);
					}
					, TaskScheduler.Default);
				}
				task2 = completion.Task;
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
			}
			return task2;
		}
		private void BeginExecuteNonQueryInternalReadStage(TaskCompletionSource<object> completion)
		{
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				this.cachedAsyncState.SetActiveConnectionAndResult(completion, "EndExecuteNonQuery", this._activeConnection);
				this._stateObj.ReadSni(completion);
			}
			catch (OutOfMemoryException e)
			{
				this._activeConnection.Abort(e);
				throw;
			}
			catch (StackOverflowException e2)
			{
				this._activeConnection.Abort(e2);
				throw;
			}
			catch (ThreadAbortException e3)
			{
				this._activeConnection.Abort(e3);
				SqlInternalConnection.BestEffortCleanup(target);
				throw;
			}
			catch (Exception)
			{
				if (this._cachedAsyncState != null)
				{
					this._cachedAsyncState.ResetAsyncState();
				}
				this.PutStateObject();
				throw;
			}
		}
		private void VerifyEndExecuteState(Task completionTask, string endMethod)
		{
			if (completionTask == null)
			{
				throw ADP.ArgumentNull("asyncResult");
			}
			if (completionTask.IsCanceled)
			{
				this._stateObj.Parser.State = TdsParserState.Broken;
				this._stateObj.Parser.Connection.BreakConnection();
				this._stateObj.Parser.ThrowExceptionAndWarning(this._stateObj, false, false);
			}
			else
			{
				if (completionTask.IsFaulted)
				{
					throw completionTask.Exception.InnerException;
				}
			}
			if (this.cachedAsyncState.EndMethodName == null)
			{
				throw ADP.MethodCalledTwice(endMethod);
			}
			if (endMethod != this.cachedAsyncState.EndMethodName)
			{
				throw ADP.MismatchedAsyncResult(this.cachedAsyncState.EndMethodName, endMethod);
			}
			if (this._activeConnection.State != ConnectionState.Open || !this.cachedAsyncState.IsActiveConnectionValid(this._activeConnection))
			{
				throw ADP.ClosedConnectionError();
			}
		}
		private void WaitForAsyncResults(IAsyncResult asyncResult)
		{
			Task arg_06_0 = (Task)asyncResult;
			if (!asyncResult.IsCompleted)
			{
				asyncResult.AsyncWaitHandle.WaitOne();
			}
			this._stateObj._networkPacketTaskSource = null;
			this._activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
		}
		public int EndExecuteNonQuery(IAsyncResult asyncResult)
		{
			int result;
			try
			{
				result = this.EndExecuteNonQueryInternal(asyncResult);
			}
			finally
			{
				Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteNonQuery|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			}
			return result;
		}
		private int EndExecuteNonQueryAsync(IAsyncResult asyncResult)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteNonQueryAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			Exception exception = ((Task)asyncResult).Exception;
			if (exception != null)
			{
				this.PutStateObject();
				throw exception.InnerException;
			}
			int result;
			lock (this._stateObj)
			{
				result = this.EndExecuteNonQueryInternal(asyncResult);
			}
			return result;
		}
		private int EndExecuteNonQueryInternal(IAsyncResult asyncResult)
		{
			SqlStatistics statistics = null;
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			int rowsAffected;
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				statistics = SqlStatistics.StartTimer(this.Statistics);
				this.VerifyEndExecuteState((Task)asyncResult, "EndExecuteNonQuery");
				this.WaitForAsyncResults(asyncResult);
				bool flag = true;
				try
				{
					this.NotifyDependency();
					this.CheckThrowSNIException();
					if (CommandType.Text == this.CommandType && this.GetParameterCount(this._parameters) == 0)
					{
						try
						{
							bool flag2;
							if (!this._stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, this._stateObj, out flag2))
							{
								throw SQL.SynchronousCallMayNotPend();
							}
							goto IL_A4;
						}
						finally
						{
							this.cachedAsyncState.ResetAsyncState();
						}
					}
					SqlDataReader sqlDataReader = this.CompleteAsyncExecuteReader();
					if (sqlDataReader != null)
					{
						sqlDataReader.Close();
					}
					IL_A4:;
				}
				catch (Exception e)
				{
					flag = ADP.IsCatchableExceptionType(e);
					throw;
				}
				finally
				{
					if (flag)
					{
						this.PutStateObject();
					}
				}
				rowsAffected = this._rowsAffected;
			}
			catch (OutOfMemoryException e2)
			{
				this._activeConnection.Abort(e2);
				throw;
			}
			catch (StackOverflowException e3)
			{
				this._activeConnection.Abort(e3);
				throw;
			}
			catch (ThreadAbortException e4)
			{
				this._activeConnection.Abort(e4);
				SqlInternalConnection.BestEffortCleanup(target);
				throw;
			}
			catch (Exception e5)
			{
				if (this.cachedAsyncState != null)
				{
					this.cachedAsyncState.ResetAsyncState();
				}
				if (ADP.IsCatchableExceptionType(e5))
				{
					this.PutStateObject();
				}
				throw;
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
			}
			return rowsAffected;
		}
		private Task InternalExecuteNonQuery(TaskCompletionSource<object> completion, string methodName, bool sendToPipe, int timeout, bool asyncWrite = false)
		{
			bool async = null != completion;
			SqlStatistics statistics = this.Statistics;
			this._rowsAffected = -1;
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			Task result;
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				this.ValidateCommand(methodName, async);
				this.CheckNotificationStateAndAutoEnlist();
				Task task = null;
				if (this._activeConnection.IsContextConnection)
				{
					if (statistics != null)
					{
						statistics.SafeIncrement(ref statistics._unpreparedExecs);
					}
					this.RunExecuteNonQuerySmi(sendToPipe);
				}
				else
				{
					if (!this.BatchRPCMode && CommandType.Text == this.CommandType && this.GetParameterCount(this._parameters) == 0)
					{
						if (statistics != null)
						{
							if (!this.IsDirty && this.IsPrepared)
							{
								statistics.SafeIncrement(ref statistics._preparedExecs);
							}
							else
							{
								statistics.SafeIncrement(ref statistics._unpreparedExecs);
							}
						}
						this.RunExecuteNonQueryTds(methodName, async, timeout);
					}
					else
					{
						Bid.Trace("<sc.SqlCommand.ExecuteNonQuery|INFO> %d#, Command executed as RPC.\n", this.ObjectID);
						SqlDataReader reader = this.RunExecuteReader(CommandBehavior.Default, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, asyncWrite);
						if (reader != null)
						{
							if (task != null)
							{
								task = AsyncHelper.CreateContinuationTask(task, delegate
								{
									reader.Close();
								}
								, null, null);
							}
							else
							{
								reader.Close();
							}
						}
					}
				}
				result = task;
			}
			catch (OutOfMemoryException e)
			{
				this._activeConnection.Abort(e);
				throw;
			}
			catch (StackOverflowException e2)
			{
				this._activeConnection.Abort(e2);
				throw;
			}
			catch (ThreadAbortException e3)
			{
				this._activeConnection.Abort(e3);
				SqlInternalConnection.BestEffortCleanup(target);
				throw;
			}
			return result;
		}
		public XmlReader ExecuteXmlReader()
		{
			SqlConnection.ExecutePermission.Demand();
			this._pendingCancel = false;
			SqlStatistics statistics = null;
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<sc.SqlCommand.ExecuteXmlReader|API> %d#", this.ObjectID);
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			XmlReader result;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				SqlDataReader ds = this.RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, "ExecuteXmlReader");
				result = this.CompleteXmlReader(ds);
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
				Bid.ScopeLeave(ref intPtr);
			}
			return result;
		}
		[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
		public IAsyncResult BeginExecuteXmlReader()
		{
			return this.BeginExecuteXmlReader(null, null);
		}
		[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
		public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			SqlConnection.ExecutePermission.Demand();
			return this.BeginExecuteXmlReaderInternal(callback, stateObject, 0, false);
		}
		private IAsyncResult BeginExecuteXmlReaderAsync(AsyncCallback callback, object stateObject)
		{
			return this.BeginExecuteXmlReaderInternal(callback, stateObject, this.CommandTimeout, true);
		}
		private IAsyncResult BeginExecuteXmlReaderInternal(AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false)
		{
			this._pendingCancel = false;
			this.ValidateAsyncCommand();
			SqlStatistics statistics = null;
			IAsyncResult task2;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
				Task task;
				try
				{
					this.RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, "BeginExecuteXmlReader", completion, timeout, out task, asyncWrite);
				}
				catch (Exception e)
				{
					if (!ADP.IsCatchableOrSecurityExceptionType(e))
					{
						throw;
					}
					this.PutStateObject();
					throw;
				}
				if (task != null)
				{
					AsyncHelper.ContinueTask(task, completion, delegate
					{
						this.BeginExecuteXmlReaderInternalReadStage(completion);
					}
					, null, null, null);
				}
				else
				{
					this.BeginExecuteXmlReaderInternalReadStage(completion);
				}
				if (callback != null)
				{
					completion.Task.ContinueWith(delegate(Task<object> t)
					{
						callback(t);
					}
					, TaskScheduler.Default);
				}
				task2 = completion.Task;
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
			}
			return task2;
		}
		private void BeginExecuteXmlReaderInternalReadStage(TaskCompletionSource<object> completion)
		{
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				this.cachedAsyncState.SetActiveConnectionAndResult(completion, "EndExecuteXmlReader", this._activeConnection);
				this._stateObj.ReadSni(completion);
			}
			catch (OutOfMemoryException ex)
			{
				this._activeConnection.Abort(ex);
				completion.TrySetException(ex);
				throw;
			}
			catch (StackOverflowException ex2)
			{
				this._activeConnection.Abort(ex2);
				completion.TrySetException(ex2);
				throw;
			}
			catch (ThreadAbortException ex3)
			{
				this._activeConnection.Abort(ex3);
				SqlInternalConnection.BestEffortCleanup(target);
				completion.TrySetException(ex3);
				throw;
			}
			catch (Exception exception)
			{
				if (this._cachedAsyncState != null)
				{
					this._cachedAsyncState.ResetAsyncState();
				}
				this.PutStateObject();
				completion.TrySetException(exception);
			}
		}
		public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult)
		{
			XmlReader result;
			try
			{
				result = this.EndExecuteXmlReaderInternal(asyncResult);
			}
			finally
			{
				Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteXmlReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			}
			return result;
		}
		private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteXmlReaderAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			Exception exception = ((Task)asyncResult).Exception;
			if (exception != null)
			{
				this.PutStateObject();
				throw exception.InnerException;
			}
			XmlReader result;
			lock (this._stateObj)
			{
				result = this.EndExecuteXmlReaderInternal(asyncResult);
			}
			return result;
		}
		private XmlReader EndExecuteXmlReaderInternal(IAsyncResult asyncResult)
		{
			XmlReader result;
			try
			{
				result = this.CompleteXmlReader(this.InternalEndExecuteReader(asyncResult, "EndExecuteXmlReader"));
			}
			catch (Exception e)
			{
				if (this.cachedAsyncState != null)
				{
					this.cachedAsyncState.ResetAsyncState();
				}
				if (ADP.IsCatchableExceptionType(e))
				{
					this.PutStateObject();
				}
				throw;
			}
			return result;
		}
		private XmlReader CompleteXmlReader(SqlDataReader ds)
		{
			XmlReader xmlReader = null;
			SmiExtendedMetaData[] internalSmiMetaData = ds.GetInternalSmiMetaData();
			bool flag = internalSmiMetaData != null && internalSmiMetaData.Length == 1 && (internalSmiMetaData[0].SqlDbType == SqlDbType.NText || internalSmiMetaData[0].SqlDbType == SqlDbType.NVarChar || internalSmiMetaData[0].SqlDbType == SqlDbType.Xml);
			if (flag)
			{
				try
				{
					SqlStream sqlStream = new SqlStream(ds, true, internalSmiMetaData[0].SqlDbType != SqlDbType.Xml);
					xmlReader = sqlStream.ToXmlReader();
				}
				catch (Exception e)
				{
					if (ADP.IsCatchableExceptionType(e))
					{
						ds.Close();
					}
					throw;
				}
			}
			if (xmlReader == null)
			{
				ds.Close();
				throw SQL.NonXmlResult();
			}
			return xmlReader;
		}
		[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
		public IAsyncResult BeginExecuteReader()
		{
			return this.BeginExecuteReader(null, null, CommandBehavior.Default);
		}
		[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
		public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject)
		{
			return this.BeginExecuteReader(callback, stateObject, CommandBehavior.Default);
		}
		protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteDbDataReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			return this.ExecuteReader(behavior, "ExecuteReader");
		}
		public new SqlDataReader ExecuteReader()
		{
			SqlStatistics statistics = null;
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<sc.SqlCommand.ExecuteReader|API> %d#", this.ObjectID);
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			SqlDataReader result;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				result = this.ExecuteReader(CommandBehavior.Default, "ExecuteReader");
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
				Bid.ScopeLeave(ref intPtr);
			}
			return result;
		}
		public new SqlDataReader ExecuteReader(CommandBehavior behavior)
		{
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<sc.SqlCommand.ExecuteReader|API> %d#, behavior=%d{ds.CommandBehavior}", this.ObjectID, (int)behavior);
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReader|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", this.ObjectID, (int)behavior);
			SqlDataReader result;
			try
			{
				result = this.ExecuteReader(behavior, "ExecuteReader");
			}
			finally
			{
				Bid.ScopeLeave(ref intPtr);
			}
			return result;
		}
		[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
		public IAsyncResult BeginExecuteReader(CommandBehavior behavior)
		{
			return this.BeginExecuteReader(null, null, behavior);
		}
		[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
		public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.BeginExecuteReader|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", this.ObjectID, (int)behavior);
			SqlConnection.ExecutePermission.Demand();
			return this.BeginExecuteReaderInternal(behavior, callback, stateObject, 0, false);
		}
		internal SqlDataReader ExecuteReader(CommandBehavior behavior, string method)
		{
			SqlConnection.ExecutePermission.Demand();
			this._pendingCancel = false;
			SqlStatistics statistics = null;
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			SqlDataReader result;
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				statistics = SqlStatistics.StartTimer(this.Statistics);
				result = this.RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, method);
			}
			catch (OutOfMemoryException e)
			{
				this._activeConnection.Abort(e);
				throw;
			}
			catch (StackOverflowException e2)
			{
				this._activeConnection.Abort(e2);
				throw;
			}
			catch (ThreadAbortException e3)
			{
				this._activeConnection.Abort(e3);
				SqlInternalConnection.BestEffortCleanup(target);
				throw;
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
			}
			return result;
		}
		public SqlDataReader EndExecuteReader(IAsyncResult asyncResult)
		{
			SqlDataReader result;
			try
			{
				result = this.EndExecuteReaderInternal(asyncResult);
			}
			finally
			{
				Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteReader|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			}
			return result;
		}
		private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.EndExecuteReaderAsync|Info|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			Exception exception = ((Task)asyncResult).Exception;
			if (exception != null)
			{
				this.PutStateObject();
				throw exception.InnerException;
			}
			SqlDataReader result;
			lock (this._stateObj)
			{
				result = this.EndExecuteReaderInternal(asyncResult);
			}
			return result;
		}
		private SqlDataReader EndExecuteReaderInternal(IAsyncResult asyncResult)
		{
			SqlStatistics statistics = null;
			SqlDataReader result;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				result = this.InternalEndExecuteReader(asyncResult, "EndExecuteReader");
			}
			catch (Exception e)
			{
				if (this.cachedAsyncState != null)
				{
					this.cachedAsyncState.ResetAsyncState();
				}
				if (ADP.IsCatchableExceptionType(e))
				{
					this.PutStateObject();
				}
				throw;
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
			}
			return result;
		}
		private IAsyncResult BeginExecuteReaderAsync(CommandBehavior behavior, AsyncCallback callback, object stateObject)
		{
			return this.BeginExecuteReaderInternal(behavior, callback, stateObject, this.CommandTimeout, true);
		}
		private IAsyncResult BeginExecuteReaderInternal(CommandBehavior behavior, AsyncCallback callback, object stateObject, int timeout, bool asyncWrite = false)
		{
			this._pendingCancel = false;
			SqlStatistics statistics = null;
			IAsyncResult task2;
			try
			{
				statistics = SqlStatistics.StartTimer(this.Statistics);
				TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
				this.ValidateAsyncCommand();
				Task task = null;
				try
				{
					this.RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, "BeginExecuteReader", completion, timeout, out task, asyncWrite);
				}
				catch (Exception e)
				{
					if (!ADP.IsCatchableOrSecurityExceptionType(e))
					{
						throw;
					}
					this.PutStateObject();
					throw;
				}
				if (task != null)
				{
					AsyncHelper.ContinueTask(task, completion, delegate
					{
						this.BeginExecuteReaderInternalReadStage(completion);
					}
					, null, null, null);
				}
				else
				{
					this.BeginExecuteReaderInternalReadStage(completion);
				}
				if (callback != null)
				{
					completion.Task.ContinueWith(delegate(Task<object> t)
					{
						callback(t);
					}
					, TaskScheduler.Default);
				}
				task2 = completion.Task;
			}
			finally
			{
				SqlStatistics.StopTimer(statistics);
			}
			return task2;
		}
		private void BeginExecuteReaderInternalReadStage(TaskCompletionSource<object> completion)
		{
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				this.cachedAsyncState.SetActiveConnectionAndResult(completion, "EndExecuteReader", this._activeConnection);
				this._stateObj.ReadSni(completion);
			}
			catch (OutOfMemoryException ex)
			{
				this._activeConnection.Abort(ex);
				completion.TrySetException(ex);
				throw;
			}
			catch (StackOverflowException ex2)
			{
				this._activeConnection.Abort(ex2);
				completion.TrySetException(ex2);
				throw;
			}
			catch (ThreadAbortException ex3)
			{
				this._activeConnection.Abort(ex3);
				SqlInternalConnection.BestEffortCleanup(target);
				completion.TrySetException(ex3);
				throw;
			}
			catch (Exception exception)
			{
				if (this._cachedAsyncState != null)
				{
					this._cachedAsyncState.ResetAsyncState();
				}
				this.PutStateObject();
				completion.TrySetException(exception);
			}
		}
		private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string endMethod)
		{
			this.VerifyEndExecuteState((Task)asyncResult, endMethod);
			this.WaitForAsyncResults(asyncResult);
			this.CheckThrowSNIException();
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			SqlDataReader result;
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				SqlDataReader sqlDataReader = this.CompleteAsyncExecuteReader();
				result = sqlDataReader;
			}
			catch (OutOfMemoryException e)
			{
				this._activeConnection.Abort(e);
				throw;
			}
			catch (StackOverflowException e2)
			{
				this._activeConnection.Abort(e2);
				throw;
			}
			catch (ThreadAbortException e3)
			{
				this._activeConnection.Abort(e3);
				SqlInternalConnection.BestEffortCleanup(target);
				throw;
			}
			return result;
		}
		public override Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteNonQueryAsync|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			SqlConnection.ExecutePermission.Demand();
			TaskCompletionSource<int> source = new TaskCompletionSource<int>();
			CancellationTokenRegistration registration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					source.SetCanceled();
					return source.Task;
				}
				registration = cancellationToken.Register(new Action(base.CancelIgnoreFailure));
			}
			Task<int> task = source.Task;
			try
			{
				this.RegisterForConnectionCloseNotification<int>(ref task);
				Task<int>.Factory.FromAsync(new Func<AsyncCallback, object, IAsyncResult>(this.BeginExecuteNonQueryAsync), new Func<IAsyncResult, int>(this.EndExecuteNonQueryAsync), null).ContinueWith(delegate(Task<int> t)
				{
					registration.Dispose();
					if (t.IsFaulted)
					{
						Exception innerException = t.Exception.InnerException;
						source.SetException(innerException);
						return;
					}
					if (t.IsCanceled)
					{
						source.SetCanceled();
						return;
					}
					source.SetResult(t.Result);
				}
				, TaskScheduler.Default);
			}
			catch (Exception exception)
			{
				source.SetException(exception);
			}
			return task;
		}
		protected override Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
		{
			return this.ExecuteReaderAsync(behavior, cancellationToken).ContinueWith<DbDataReader>(delegate(Task<SqlDataReader> result)
			{
				if (result.IsFaulted)
				{
					throw result.Exception.InnerException;
				}
				return result.Result;
			}
			, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
		}
		public new Task<SqlDataReader> ExecuteReaderAsync()
		{
			return this.ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None);
		}
		public new Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior)
		{
			return this.ExecuteReaderAsync(behavior, CancellationToken.None);
		}
		public new Task<SqlDataReader> ExecuteReaderAsync(CancellationToken cancellationToken)
		{
			return this.ExecuteReaderAsync(CommandBehavior.Default, cancellationToken);
		}
		public new Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteReaderAsync|API|Correlation> ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", this.ObjectID, (int)behavior);
			SqlConnection.ExecutePermission.Demand();
			TaskCompletionSource<SqlDataReader> source = new TaskCompletionSource<SqlDataReader>();
			CancellationTokenRegistration registration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					source.SetCanceled();
					return source.Task;
				}
				registration = cancellationToken.Register(new Action(base.CancelIgnoreFailure));
			}
			Task<SqlDataReader> task = source.Task;
			try
			{
				this.RegisterForConnectionCloseNotification<SqlDataReader>(ref task);
				Task<SqlDataReader>.Factory.FromAsync<CommandBehavior>(new Func<CommandBehavior, AsyncCallback, object, IAsyncResult>(this.BeginExecuteReaderAsync), new Func<IAsyncResult, SqlDataReader>(this.EndExecuteReaderAsync), behavior, null).ContinueWith(delegate(Task<SqlDataReader> t)
				{
					registration.Dispose();
					if (t.IsFaulted)
					{
						Exception innerException = t.Exception.InnerException;
						source.SetException(innerException);
						return;
					}
					if (t.IsCanceled)
					{
						source.SetCanceled();
						return;
					}
					source.SetResult(t.Result);
				}
				, TaskScheduler.Default);
			}
			catch (Exception exception)
			{
				source.SetException(exception);
			}
			return task;
		}
		public override Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
		{
			return this.ExecuteReaderAsync(cancellationToken).ContinueWith<Task<object>>(delegate(Task<SqlDataReader> executeTask)
			{
				TaskCompletionSource<object> source = new TaskCompletionSource<object>();
				if (executeTask.IsCanceled)
				{
					source.SetCanceled();
				}
				else
				{
					if (executeTask.IsFaulted)
					{
						source.SetException(executeTask.Exception.InnerException);
					}
					else
					{
						SqlDataReader reader = executeTask.Result;
						reader.ReadAsync(cancellationToken).ContinueWith(delegate(Task<bool> readTask)
						{
							try
							{
								if (readTask.IsCanceled)
								{
									reader.Dispose();
									source.SetCanceled();
								}
								else
								{
									if (readTask.IsFaulted)
									{
										reader.Dispose();
										source.SetException(readTask.Exception.InnerException);
									}
									else
									{
										Exception ex = null;
										object result = null;
										try
										{
											bool result2 = readTask.Result;
											if (result2 && reader.FieldCount > 0)
											{
												try
												{
													result = reader.GetValue(0);
												}
												catch (Exception ex2)
												{
													ex = ex2;
												}
											}
										}
										finally
										{
											reader.Dispose();
										}
										if (ex != null)
										{
											source.SetException(ex);
										}
										else
										{
											source.SetResult(result);
										}
									}
								}
							}
							catch (Exception exception)
							{
								source.SetException(exception);
							}
						}
						, TaskScheduler.Default);
					}
				}
				return source.Task;
			}
			, TaskScheduler.Default).Unwrap<object>();
		}
		public Task<XmlReader> ExecuteXmlReaderAsync()
		{
			return this.ExecuteXmlReaderAsync(CancellationToken.None);
		}
		public Task<XmlReader> ExecuteXmlReaderAsync(CancellationToken cancellationToken)
		{
			Bid.CorrelationTrace("<sc.SqlCommand.ExecuteXmlReaderAsync|API|Correlation> ObjectID%d#, ActivityID %ls\n", this.ObjectID);
			SqlConnection.ExecutePermission.Demand();
			TaskCompletionSource<XmlReader> source = new TaskCompletionSource<XmlReader>();
			CancellationTokenRegistration registration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					source.SetCanceled();
					return source.Task;
				}
				registration = cancellationToken.Register(new Action(base.CancelIgnoreFailure));
			}
			Task<XmlReader> task = source.Task;
			try
			{
				this.RegisterForConnectionCloseNotification<XmlReader>(ref task);
				Task<XmlReader>.Factory.FromAsync(new Func<AsyncCallback, object, IAsyncResult>(this.BeginExecuteXmlReaderAsync), new Func<IAsyncResult, XmlReader>(this.EndExecuteXmlReaderAsync), null).ContinueWith(delegate(Task<XmlReader> t)
				{
					registration.Dispose();
					if (t.IsFaulted)
					{
						Exception innerException = t.Exception.InnerException;
						source.SetException(innerException);
						return;
					}
					if (t.IsCanceled)
					{
						source.SetCanceled();
						return;
					}
					source.SetResult(t.Result);
				}
				, TaskScheduler.Default);
			}
			catch (Exception exception)
			{
				source.SetException(exception);
			}
			return task;
		}
		private static string UnquoteProcedurePart(string part)
		{
			if (part != null && 2 <= part.Length && '[' == part[0] && ']' == part[part.Length - 1])
			{
				part = part.Substring(1, part.Length - 2);
				part = part.Replace("]]", "]");
			}
			return part;
		}
		private static string UnquoteProcedureName(string name, out object groupNumber)
		{
			groupNumber = null;
			string text = name;
			if (text != null)
			{
				if (char.IsDigit(text[text.Length - 1]))
				{
					int num = text.LastIndexOf(';');
					if (num != -1)
					{
						string s = text.Substring(num + 1);
						int num2 = 0;
						if (int.TryParse(s, out num2))
						{
							groupNumber = num2;
							text = text.Substring(0, num);
						}
					}
				}
				text = SqlCommand.UnquoteProcedurePart(text);
			}
			return text;
		}
		internal void DeriveParameters()
		{
			CommandType commandType = this.CommandType;
			if (commandType == CommandType.Text)
			{
				throw ADP.DeriveParametersNotSupported(this);
			}
			if (commandType != CommandType.StoredProcedure)
			{
				if (commandType != CommandType.TableDirect)
				{
					throw ADP.InvalidCommandType(this.CommandType);
				}
				throw ADP.DeriveParametersNotSupported(this);
			}
			else
			{
				this.ValidateCommand("DeriveParameters", false);
				string[] array = MultipartIdentifier.ParseMultipartIdentifier(this.CommandText, "[\"", "]\"", "SQL_SqlCommandCommandText", false);
				if (array[3] == null || ADP.IsEmpty(array[3]))
				{
					throw ADP.NoStoredProcedureExists(this.CommandText);
				}
				SqlCommand sqlCommand = null;
				StringBuilder stringBuilder = new StringBuilder();
				if (!ADP.IsEmpty(array[0]))
				{
					SqlCommandSet.BuildStoredProcedureName(stringBuilder, array[0]);
					stringBuilder.Append(".");
				}
				if (ADP.IsEmpty(array[1]))
				{
					array[1] = this.Connection.Database;
				}
				SqlCommandSet.BuildStoredProcedureName(stringBuilder, array[1]);
				stringBuilder.Append(".");
				string[] array2;
				bool flag;
				if (this.Connection.IsKatmaiOrNewer)
				{
					stringBuilder.Append("[sys].[").Append("sp_procedure_params_100_managed").Append("]");
					array2 = SqlCommand.KatmaiProcParamsNames;
					flag = true;
				}
				else
				{
					if (this.Connection.IsYukonOrNewer)
					{
						stringBuilder.Append("[sys].[").Append("sp_procedure_params_managed").Append("]");
					}
					else
					{
						stringBuilder.Append(".[").Append("sp_procedure_params_rowset").Append("]");
					}
					array2 = SqlCommand.PreKatmaiProcParamsNames;
					flag = false;
				}
				sqlCommand = new SqlCommand(stringBuilder.ToString(), this.Connection, this.Transaction);
				sqlCommand.CommandType = CommandType.StoredProcedure;
				sqlCommand.Parameters.Add(new SqlParameter("@procedure_name", SqlDbType.NVarChar, 255));
				object obj;
				sqlCommand.Parameters[0].Value = SqlCommand.UnquoteProcedureName(array[3], out obj);
				if (obj != null)
				{
					SqlParameter sqlParameter = sqlCommand.Parameters.Add(new SqlParameter("@group_number", SqlDbType.Int));
					sqlParameter.Value = obj;
				}
				if (!ADP.IsEmpty(array[2]))
				{
					SqlParameter sqlParameter2 = sqlCommand.Parameters.Add(new SqlParameter("@procedure_schema", SqlDbType.NVarChar, 255));
					sqlParameter2.Value = SqlCommand.UnquoteProcedurePart(array[2]);
				}
				SqlDataReader sqlDataReader = null;
				List<SqlParameter> list = new List<SqlParameter>();
				bool flag2 = true;
				try
				{
					sqlDataReader = sqlCommand.ExecuteReader();
					while (sqlDataReader.Read())
					{
						SqlParameter sqlParameter3 = new SqlParameter();
						sqlParameter3.ParameterName = (string)sqlDataReader[array2[0]];
						if (flag)
						{
							sqlParameter3.SqlDbType = (SqlDbType)((short)sqlDataReader[array2[3]]);
							SqlDbType sqlDbType = sqlParameter3.SqlDbType;
							if (sqlDbType != SqlDbType.Image)
							{
								if (sqlDbType == SqlDbType.NText)
								{
									sqlParameter3.SqlDbType = SqlDbType.NVarChar;
									goto IL_2F3;
								}
								switch (sqlDbType)
								{
									case SqlDbType.Text:
									{
										sqlParameter3.SqlDbType = SqlDbType.VarChar;
										goto IL_2F3;
									}
									case SqlDbType.Timestamp:
									{
										break;
									}
									default:
									{
										goto IL_2F3;
									}
								}
							}
							sqlParameter3.SqlDbType = SqlDbType.VarBinary;
						}
						else
						{
							sqlParameter3.SqlDbType = MetaType.GetSqlDbTypeFromOleDbType((short)sqlDataReader[array2[2]], ADP.IsNull(sqlDataReader[array2[9]]) ? ADP.StrEmpty : ((string)sqlDataReader[array2[9]]));
						}
						IL_2F3:
						object obj2 = sqlDataReader[array2[4]];
						if (obj2 is int)
						{
							int num = (int)obj2;
							if (num == 0 && (sqlParameter3.SqlDbType == SqlDbType.NVarChar || sqlParameter3.SqlDbType == SqlDbType.VarBinary || sqlParameter3.SqlDbType == SqlDbType.VarChar))
							{
								num = -1;
							}
							sqlParameter3.Size = num;
						}
						sqlParameter3.Direction = this.ParameterDirectionFromOleDbDirection((short)sqlDataReader[array2[1]]);
						if (sqlParameter3.SqlDbType == SqlDbType.Decimal)
						{
							sqlParameter3.ScaleInternal = (byte)((short)sqlDataReader[array2[6]] & 255);
							sqlParameter3.PrecisionInternal = (byte)((short)sqlDataReader[array2[5]] & 255);
						}
						if (SqlDbType.Udt == sqlParameter3.SqlDbType)
						{
							string text;
							if (flag)
							{
								text = (string)sqlDataReader[array2[9]];
							}
							else
							{
								text = (string)sqlDataReader[array2[13]];
							}
							sqlParameter3.UdtTypeName = string.Concat(new object[]
							{
								sqlDataReader[array2[7]], 
								".", 
								sqlDataReader[array2[8]], 
								".", 
								text
							});
						}
						if (SqlDbType.Structured == sqlParameter3.SqlDbType)
						{
							sqlParameter3.TypeName = string.Concat(new object[]
							{
								sqlDataReader[array2[7]], 
								".", 
								sqlDataReader[array2[8]], 
								".", 
								sqlDataReader[array2[9]]
							});
						}
						if (SqlDbType.Xml == sqlParameter3.SqlDbType)
						{
							object obj3 = sqlDataReader[array2[10]];
							sqlParameter3.XmlSchemaCollectionDatabase = (ADP.IsNull(obj3) ? string.Empty : ((string)obj3));
							obj3 = sqlDataReader[array2[11]];
							sqlParameter3.XmlSchemaCollectionOwningSchema = (ADP.IsNull(obj3) ? string.Empty : ((string)obj3));
							obj3 = sqlDataReader[array2[12]];
							sqlParameter3.XmlSchemaCollectionName = (ADP.IsNull(obj3) ? string.Empty : ((string)obj3));
						}
						if (MetaType._IsVarTime(sqlParameter3.SqlDbType))
						{
							object obj4 = sqlDataReader[array2[14]];
							if (obj4 is int)
							{
								sqlParameter3.ScaleInternal = (byte)((int)obj4 & 255);
							}
						}
						list.Add(sqlParameter3);
					}
				}
				catch (Exception e)
				{
					flag2 = ADP.IsCatchableExceptionType(e);
					throw;
				}
				finally
				{
					if (flag2)
					{
						if (sqlDataReader != null)
						{
							sqlDataReader.Close();
						}
						sqlCommand.Connection = null;
					}
				}
				if (list.Count == 0)
				{
					throw ADP.NoStoredProcedureExists(this.CommandText);
				}
				this.Parameters.Clear();
				foreach (SqlParameter current in list)
				{
					this._parameters.Add(current);
				}
				return;
			}
		}
		private ParameterDirection ParameterDirectionFromOleDbDirection(short oledbDirection)
		{
			switch (oledbDirection)
			{
				case 2:
				{
					return ParameterDirection.InputOutput;
				}
				case 3:
				{
					return ParameterDirection.Output;
				}
				case 4:
				{
					return ParameterDirection.ReturnValue;
				}
				default:
				{
					return ParameterDirection.Input;
				}
			}
		}
		private void CheckNotificationStateAndAutoEnlist()
		{
			if (this.NotificationAutoEnlist && this._activeConnection.IsYukonOrNewer)
			{
				string text = SqlCommand.SqlNotificationContext();
				if (!ADP.IsEmpty(text))
				{
					SqlDependency sqlDependency = SqlDependencyPerAppDomainDispatcher.SingletonInstance.LookupDependencyEntry(text);
					if (sqlDependency != null)
					{
						sqlDependency.AddCommandDependency(this);
					}
				}
			}
			if (this.Notification != null && this._sqlDep != null)
			{
				if (this._sqlDep.Options == null)
				{
					SqlDependency.IdentityUserNamePair identityUser = null;
					SqlInternalConnectionTds sqlInternalConnectionTds = this._activeConnection.InnerConnection as SqlInternalConnectionTds;
					if (sqlInternalConnectionTds.Identity != null)
					{
						identityUser = new SqlDependency.IdentityUserNamePair(sqlInternalConnectionTds.Identity, null);
					}
					else
					{
						identityUser = new SqlDependency.IdentityUserNamePair(null, sqlInternalConnectionTds.ConnectionOptions.UserID);
					}
					this.Notification.Options = SqlDependency.GetDefaultComposedOptions(this._activeConnection.DataSource, this.InternalTdsConnection.ServerProvidedFailOverPartner, identityUser, this._activeConnection.Database);
				}
				this.Notification.UserData = this._sqlDep.ComputeHashAndAddToDispatcher(this);
				this._sqlDep.AddToServerList(this._activeConnection.DataSource);
			}
		}
		[SecurityPermission(SecurityAction.Assert, Infrastructure = true)]
		internal static string SqlNotificationContext()
		{
			return CallContext.GetData("MS.SqlDependencyCookie") as string;
		}
		private void RunExecuteNonQueryTds(string methodName, bool async, int timeout)
		{
			bool flag = true;
			try
			{
				this.GetStateObject(null);
				Bid.Trace("<sc.SqlCommand.ExecuteNonQuery|INFO> %d#, Command executed as SQLBATCH.\n", this.ObjectID);
				this._stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, this._stateObj, true, false);
				this.NotifyDependency();
				if (async)
				{
					this._activeConnection.GetOpenTdsConnection(methodName).IncrementAsyncCount();
				}
				else
				{
					bool flag2;
					if (!this._stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, this._stateObj, out flag2))
					{
						throw SQL.SynchronousCallMayNotPend();
					}
				}
			}
			catch (Exception e)
			{
				flag = ADP.IsCatchableExceptionType(e);
				throw;
			}
			finally
			{
				if (flag && !async)
				{
					this.PutStateObject();
				}
			}
		}
		private void RunExecuteNonQuerySmi(bool sendToPipe)
		{
			SqlInternalConnectionSmi internalSmiConnection = this.InternalSmiConnection;
			SmiRequestExecutor smiRequestExecutor = null;
			try
			{
				smiRequestExecutor = this.SetUpSmiRequest(internalSmiConnection);
				SmiExecuteType executeType;
				if (sendToPipe)
				{
					executeType = SmiExecuteType.ToPipe;
				}
				else
				{
					executeType = SmiExecuteType.NonQuery;
				}
				SmiEventStream smiEventStream = null;
				bool flag = true;
				try
				{
					long num;
					Transaction associatedTransaction;
					internalSmiConnection.GetCurrentTransactionPair(out num, out associatedTransaction);
					if (Bid.AdvancedOn)
					{
						Bid.Trace("<sc.SqlCommand.RunExecuteNonQuerySmi|ADV> %d#, innerConnection=%d#, transactionId=0x%I64x, cmdBehavior=%d.\n", this.ObjectID, internalSmiConnection.ObjectID, num, 0);
					}
					if (SmiContextFactory.Instance.NegotiatedSmiVersion >= 210uL)
					{
						smiEventStream = smiRequestExecutor.Execute(internalSmiConnection.SmiConnection, num, associatedTransaction, CommandBehavior.Default, executeType);
					}
					else
					{
						smiEventStream = smiRequestExecutor.Execute(internalSmiConnection.SmiConnection, num, CommandBehavior.Default, executeType);
					}
					while (smiEventStream.HasEvents)
					{
						smiEventStream.ProcessEvent(this.EventSink);
					}
				}
				catch (Exception e)
				{
					flag = ADP.IsCatchableExceptionType(e);
					throw;
				}
				finally
				{
					if (smiEventStream != null && flag)
					{
						smiEventStream.Close(this.EventSink);
					}
				}
				this.EventSink.ProcessMessagesAndThrow();
			}
			finally
			{
				if (smiRequestExecutor != null)
				{
					smiRequestExecutor.Close(this.EventSink);
					this.EventSink.ProcessMessagesAndThrow(true);
				}
			}
		}
		internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method)
		{
			Task task;
			return this.RunExecuteReader(cmdBehavior, runBehavior, returnStream, method, null, this.CommandTimeout, out task, false);
		}
		internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method, TaskCompletionSource<object> completion, int timeout, out Task task, bool asyncWrite = false)
		{
			bool flag = null != completion;
			task = null;
			this._rowsAffected = -1;
			if ((CommandBehavior.SingleRow & cmdBehavior) != CommandBehavior.Default)
			{
				cmdBehavior |= CommandBehavior.SingleResult;
			}
			this.ValidateCommand(method, flag);
			this.CheckNotificationStateAndAutoEnlist();
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			SqlDataReader result;
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				SqlStatistics statistics = this.Statistics;
				if (statistics != null)
				{
					if ((!this.IsDirty && this.IsPrepared && !this._hiddenPrepare) || (this.IsPrepared && this._execType == SqlCommand.EXECTYPE.PREPAREPENDING))
					{
						statistics.SafeIncrement(ref statistics._preparedExecs);
					}
					else
					{
						statistics.SafeIncrement(ref statistics._unpreparedExecs);
					}
				}
				if (this._activeConnection.IsContextConnection)
				{
					result = this.RunExecuteReaderSmi(cmdBehavior, runBehavior, returnStream);
				}
				else
				{
					result = this.RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, flag, timeout, out task, asyncWrite && flag);
				}
			}
			catch (OutOfMemoryException e)
			{
				this._activeConnection.Abort(e);
				throw;
			}
			catch (StackOverflowException e2)
			{
				this._activeConnection.Abort(e2);
				throw;
			}
			catch (ThreadAbortException e3)
			{
				this._activeConnection.Abort(e3);
				SqlInternalConnection.BestEffortCleanup(target);
				throw;
			}
			return result;
		}
		private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, bool async, int timeout, out Task task, bool asyncWrite)
		{
			bool inSchema = CommandBehavior.Default != (cmdBehavior & CommandBehavior.SchemaOnly);
			SqlDataReader ds = null;
			_SqlRPC sqlRPC = null;
			task = null;
			string optionSettings = null;
			bool flag = true;
			bool flag2 = false;
			if (async)
			{
				this._activeConnection.GetOpenTdsConnection().IncrementAsyncCount();
				flag2 = true;
			}
			try
			{
				this.GetStateObject(null);
				Task task2 = null;
				if (this.BatchRPCMode)
				{
					task2 = this._stateObj.Parser.TdsExecuteRPC(this._SqlRPCBatchArray, timeout, inSchema, this.Notification, this._stateObj, CommandType.StoredProcedure == this.CommandType, !asyncWrite, null, 0, 0);
				}
				else
				{
					if (CommandType.Text == this.CommandType && this.GetParameterCount(this._parameters) == 0)
					{
						if (returnStream)
						{
							Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as SQLBATCH.\n", this.ObjectID);
						}
						string text = this.GetCommandText(cmdBehavior) + this.GetResetOptionsString(cmdBehavior);
						task2 = this._stateObj.Parser.TdsExecuteSQLBatch(text, timeout, this.Notification, this._stateObj, !asyncWrite, false);
					}
					else
					{
						if (CommandType.Text == this.CommandType)
						{
							if (this.IsDirty)
							{
								if (this._execType == SqlCommand.EXECTYPE.PREPARED)
								{
									this._hiddenPrepare = true;
								}
								this.InternalUnprepare(false, this.IsShiloh);
								this.IsDirty = false;
							}
							if (this._execType == SqlCommand.EXECTYPE.PREPARED)
							{
								sqlRPC = this.BuildExecute(inSchema);
							}
							else
							{
								if (this._execType == SqlCommand.EXECTYPE.PREPAREPENDING)
								{
									sqlRPC = this.BuildPrepExec(cmdBehavior);
									this._execType = SqlCommand.EXECTYPE.PREPARED;
									this._activeConnection.AddPreparedCommand(this);
									this._inPrepare = true;
								}
								else
								{
									this.BuildExecuteSql(cmdBehavior, null, this._parameters, ref sqlRPC);
								}
							}
							if (this._activeConnection.IsShiloh)
							{
								sqlRPC.options = 2;
							}
							if (returnStream)
							{
								Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as RPC.\n", this.ObjectID);
							}
							task2 = this._stateObj.Parser.TdsExecuteRPC(this._rpcArrayOf1, this.CommandTimeout, inSchema, this.Notification, this._stateObj, CommandType.StoredProcedure == this.CommandType, !asyncWrite, null, 0, 0);
						}
						else
						{
							this.BuildRPC(inSchema, this._parameters, ref sqlRPC);
							optionSettings = this.GetSetOptionsString(cmdBehavior);
							if (returnStream)
							{
								Bid.Trace("<sc.SqlCommand.ExecuteReader|INFO> %d#, Command executed as RPC.\n", this.ObjectID);
							}
							if (optionSettings != null)
							{
								this._stateObj.Parser.TdsExecuteSQLBatch(optionSettings, timeout, this.Notification, this._stateObj, true, false);
								bool flag3;
								if (!this._stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, this._stateObj, out flag3))
								{
									throw SQL.SynchronousCallMayNotPend();
								}
								optionSettings = this.GetResetOptionsString(cmdBehavior);
							}
							this._activeConnection.CheckSQLDebug();
							task2 = this._stateObj.Parser.TdsExecuteRPC(this._rpcArrayOf1, this.CommandTimeout, inSchema, this.Notification, this._stateObj, CommandType.StoredProcedure == this.CommandType, !asyncWrite, null, 0, 0);
						}
					}
				}
				if (returnStream)
				{
					ds = new SqlDataReader(this, cmdBehavior);
				}
				if (async)
				{
					flag2 = false;
					if (task2 != null)
					{
						task = AsyncHelper.CreateContinuationTask(task2, delegate
						{
							this._activeConnection.GetOpenTdsConnection();
							this.cachedAsyncState.SetAsyncReaderState(ds, runBehavior, optionSettings);
						}
						, null, delegate(Exception exc)
						{
							this._activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
						}
						);
					}
					else
					{
						this.cachedAsyncState.SetAsyncReaderState(ds, runBehavior, optionSettings);
					}
				}
				else
				{
					this.FinishExecuteReader(ds, runBehavior, optionSettings);
				}
			}
			catch (Exception e)
			{
				flag = ADP.IsCatchableExceptionType(e);
				if (flag2)
				{
					this._activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
				}
				throw;
			}
			finally
			{
				if (flag && !async)
				{
					this.PutStateObject();
				}
			}
			return ds;
		}
		private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream)
		{
			SqlInternalConnectionSmi internalSmiConnection = this.InternalSmiConnection;
			SmiEventStream smiEventStream = null;
			SqlDataReader sqlDataReader = null;
			SmiRequestExecutor smiRequestExecutor = null;
			try
			{
				smiRequestExecutor = this.SetUpSmiRequest(internalSmiConnection);
				long num;
				Transaction associatedTransaction;
				internalSmiConnection.GetCurrentTransactionPair(out num, out associatedTransaction);
				if (Bid.AdvancedOn)
				{
					Bid.Trace("<sc.SqlCommand.RunExecuteReaderSmi|ADV> %d#, innerConnection=%d#, transactionId=0x%I64x, commandBehavior=%d.\n", this.ObjectID, internalSmiConnection.ObjectID, num, (int)cmdBehavior);
				}
				if (SmiContextFactory.Instance.NegotiatedSmiVersion >= 210uL)
				{
					smiEventStream = smiRequestExecutor.Execute(internalSmiConnection.SmiConnection, num, associatedTransaction, cmdBehavior, SmiExecuteType.Reader);
				}
				else
				{
					smiEventStream = smiRequestExecutor.Execute(internalSmiConnection.SmiConnection, num, cmdBehavior, SmiExecuteType.Reader);
				}
				if ((runBehavior & RunBehavior.UntilDone) != (RunBehavior)0)
				{
					while (smiEventStream.HasEvents)
					{
						smiEventStream.ProcessEvent(this.EventSink);
					}
					smiEventStream.Close(this.EventSink);
				}
				if (returnStream)
				{
					sqlDataReader = new SqlDataReaderSmi(smiEventStream, this, cmdBehavior, internalSmiConnection, this.EventSink, smiRequestExecutor);
					sqlDataReader.NextResult();
					this._activeConnection.AddWeakReference(sqlDataReader, 1);
				}
				this.EventSink.ProcessMessagesAndThrow();
			}
			catch (Exception e)
			{
				if (!ADP.IsCatchableOrSecurityExceptionType(e))
				{
					throw;
				}
				if (smiEventStream != null)
				{
					smiEventStream.Close(this.EventSink);
				}
				if (smiRequestExecutor != null)
				{
					smiRequestExecutor.Close(this.EventSink);
					this.EventSink.ProcessMessagesAndThrow(true);
				}
				throw;
			}
			return sqlDataReader;
		}
		private SqlDataReader CompleteAsyncExecuteReader()
		{
			SqlDataReader cachedAsyncReader = this.cachedAsyncState.CachedAsyncReader;
			bool flag = true;
			try
			{
				this.FinishExecuteReader(cachedAsyncReader, this.cachedAsyncState.CachedRunBehavior, this.cachedAsyncState.CachedSetOptions);
			}
			catch (Exception e)
			{
				flag = ADP.IsCatchableExceptionType(e);
				throw;
			}
			finally
			{
				if (flag)
				{
					this.cachedAsyncState.ResetAsyncState();
					this.PutStateObject();
				}
			}
			return cachedAsyncReader;
		}
		private void FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, string resetOptionsString)
		{
			this.NotifyDependency();
			if (runBehavior == RunBehavior.UntilDone)
			{
				try
				{
					bool flag;
					if (!this._stateObj.Parser.TryRun(RunBehavior.UntilDone, this, ds, null, this._stateObj, out flag))
					{
						throw SQL.SynchronousCallMayNotPend();
					}
				}
				catch (Exception e)
				{
					if (ADP.IsCatchableExceptionType(e))
					{
						if (this._inPrepare)
						{
							this._inPrepare = false;
							this.IsDirty = true;
							this._execType = SqlCommand.EXECTYPE.PREPAREPENDING;
						}
						if (ds != null)
						{
							ds.Close();
						}
					}
					throw;
				}
			}
			if (ds != null)
			{
				ds.Bind(this._stateObj);
				this._stateObj = null;
				ds.ResetOptionsString = resetOptionsString;
				this._activeConnection.AddWeakReference(ds, 1);
				try
				{
					this._cachedMetaData = ds.MetaData;
					ds.IsInitialized = true;
				}
				catch (Exception e2)
				{
					if (ADP.IsCatchableExceptionType(e2))
					{
						if (this._inPrepare)
						{
							this._inPrepare = false;
							this.IsDirty = true;
							this._execType = SqlCommand.EXECTYPE.PREPAREPENDING;
						}
						ds.Close();
					}
					throw;
				}
			}
		}
		private void NotifyDependency()
		{
			if (this._sqlDep != null)
			{
				this._sqlDep.StartTimer(this.Notification);
			}
		}
		public SqlCommand Clone()
		{
			SqlCommand sqlCommand = new SqlCommand(this);
			Bid.Trace("<sc.SqlCommand.Clone|API> %d#, clone=%d#\n", this.ObjectID, sqlCommand.ObjectID);
			return sqlCommand;
		}
		object ICloneable.Clone()
		{
			return this.Clone();
		}
		private void RegisterForConnectionCloseNotification<T>(ref Task<T> outterTask)
		{
			SqlConnection activeConnection = this._activeConnection;
			if (activeConnection == null)
			{
				throw ADP.ClosedConnectionError();
			}
			activeConnection.RegisterForConnectionCloseNotification<T>(ref outterTask, this, 2);
		}
		private void ValidateCommand(string method, bool async)
		{
			if (this._activeConnection == null)
			{
				throw ADP.ConnectionRequired(method);
			}
			SqlInternalConnectionTds sqlInternalConnectionTds = this._activeConnection.InnerConnection as SqlInternalConnectionTds;
			if (sqlInternalConnectionTds != null)
			{
				TdsParser parser = sqlInternalConnectionTds.Parser;
				if (parser == null || parser.State == TdsParserState.Closed)
				{
					throw ADP.OpenConnectionRequired(method, ConnectionState.Closed);
				}
				if (parser.State != TdsParserState.OpenLoggedIn)
				{
					throw ADP.OpenConnectionRequired(method, ConnectionState.Broken);
				}
			}
			else
			{
				if (this._activeConnection.State == ConnectionState.Closed)
				{
					throw ADP.OpenConnectionRequired(method, ConnectionState.Closed);
				}
				if (this._activeConnection.State == ConnectionState.Broken)
				{
					throw ADP.OpenConnectionRequired(method, ConnectionState.Broken);
				}
			}
			this.ValidateAsyncCommand();
			TdsParser target = null;
			RuntimeHelpers.PrepareConstrainedRegions();
			try
			{
				target = SqlInternalConnection.GetBestEffortCleanupTarget(this._activeConnection);
				this._activeConnection.ValidateConnectionForExecute(method, this);
			}
			catch (OutOfMemoryException e)
			{
				this._activeConnection.Abort(e);
				throw;
			}
			catch (StackOverflowException e2)
			{
				this._activeConnection.Abort(e2);
				throw;
			}
			catch (ThreadAbortException e3)
			{
				this._activeConnection.Abort(e3);
				SqlInternalConnection.BestEffortCleanup(target);
				throw;
			}
			if (this._transaction != null && this._transaction.Connection == null)
			{
				this._transaction = null;
			}
			if (this._activeConnection.HasLocalTransactionFromAPI && this._transaction == null)
			{
				throw ADP.TransactionRequired(method);
			}
			if (this._transaction != null && this._activeConnection != this._transaction.Connection)
			{
				throw ADP.TransactionConnectionMismatch();
			}
			if (ADP.IsEmpty(this.CommandText))
			{
				throw ADP.CommandTextRequired(method);
			}
			if (this.Notification != null && !this._activeConnection.IsYukonOrNewer)
			{
				throw SQL.NotificationsRequireYukon();
			}
			if (async && this._activeConnection.IsContextConnection)
			{
				throw SQL.NotAvailableOnContextConnection();
			}
		}
		private void ValidateAsyncCommand()
		{
			if (this.cachedAsyncState.PendingAsyncOperation)
			{
				if (this.cachedAsyncState.IsActiveConnectionValid(this._activeConnection))
				{
					throw SQL.PendingBeginXXXExists();
				}
				this._stateObj = null;
				this.cachedAsyncState.ResetAsyncState();
			}
		}
		private void GetStateObject(TdsParser parser = null)
		{
			if (this._pendingCancel)
			{
				this._pendingCancel = false;
				throw SQL.OperationCancelled();
			}
			if (parser == null)
			{
				parser = this._activeConnection.Parser;
				if (parser == null || parser.State == TdsParserState.Broken || parser.State == TdsParserState.Closed)
				{
					throw ADP.ClosedConnectionError();
				}
			}
			TdsParserStateObject session = parser.GetSession(this);
			session.StartSession(this.ObjectID);
			this._stateObj = session;
			if (this._pendingCancel)
			{
				this._pendingCancel = false;
				throw SQL.OperationCancelled();
			}
		}
		private void PutStateObject()
		{
			TdsParserStateObject stateObj = this._stateObj;
			this._stateObj = null;
			if (stateObj != null)
			{
				stateObj.CloseSession();
			}
		}
		internal void OnDoneProc()
		{
			if (this.BatchRPCMode)
			{
				this._SqlRPCBatchArray[this._currentlyExecutingBatch].cumulativeRecordsAffected = this._rowsAffected;
				this._SqlRPCBatchArray[this._currentlyExecutingBatch].recordsAffected = new int?((0 < this._currentlyExecutingBatch && 0 <= this._rowsAffected) ? (this._rowsAffected - Math.Max(this._SqlRPCBatchArray[this._currentlyExecutingBatch - 1].cumulativeRecordsAffected, 0)) : this._rowsAffected);
				this._SqlRPCBatchArray[this._currentlyExecutingBatch].errorsIndexStart = ((0 < this._currentlyExecutingBatch) ? this._SqlRPCBatchArray[this._currentlyExecutingBatch - 1].errorsIndexEnd : 0);
				this._SqlRPCBatchArray[this._currentlyExecutingBatch].errorsIndexEnd = this._stateObj.ErrorCount;
				this._SqlRPCBatchArray[this._currentlyExecutingBatch].errors = this._stateObj._errors;
				this._SqlRPCBatchArray[this._currentlyExecutingBatch].warningsIndexStart = ((0 < this._currentlyExecutingBatch) ? this._SqlRPCBatchArray[this._currentlyExecutingBatch - 1].warningsIndexEnd : 0);
				this._SqlRPCBatchArray[this._currentlyExecutingBatch].warningsIndexEnd = this._stateObj.WarningCount;
				this._SqlRPCBatchArray[this._currentlyExecutingBatch].warnings = this._stateObj._warnings;
				this._currentlyExecutingBatch++;
			}
		}
		internal void OnReturnStatus(int status)
		{
			if (this._inPrepare)
			{
				return;
			}
			SqlParameterCollection sqlParameterCollection = this._parameters;
			if (this.BatchRPCMode)
			{
				if (this._parameterCollectionList.Count > this._currentlyExecutingBatch)
				{
					sqlParameterCollection = this._parameterCollectionList[this._currentlyExecutingBatch];
				}
				else
				{
					sqlParameterCollection = null;
				}
			}
			int parameterCount = this.GetParameterCount(sqlParameterCollection);
			int i = 0;
			while (i < parameterCount)
			{
				SqlParameter sqlParameter = sqlParameterCollection[i];
				if (sqlParameter.Direction == ParameterDirection.ReturnValue)
				{
					object value = sqlParameter.Value;
					if (value != null && value.GetType() == typeof(SqlInt32))
					{
						sqlParameter.Value = new SqlInt32(status);
						return;
					}
					sqlParameter.Value = status;
					return;
				}
				else
				{
					i++;
				}
			}
		}
		internal void OnReturnValue(SqlReturnValue rec)
		{
			if (this._inPrepare)
			{
				if (!rec.value.IsNull)
				{
					this._prepareHandle = rec.value.Int32;
				}
				this._inPrepare = false;
				return;
			}
			SqlParameterCollection currentParameterCollection = this.GetCurrentParameterCollection();
			int parameterCount = this.GetParameterCount(currentParameterCollection);
			SqlParameter parameterForOutputValueExtraction = this.GetParameterForOutputValueExtraction(currentParameterCollection, rec.parameter, parameterCount);
			if (parameterForOutputValueExtraction != null)
			{
				object arg_5A_0 = parameterForOutputValueExtraction.Value;
				if (SqlDbType.Udt == parameterForOutputValueExtraction.SqlDbType)
				{
					object value = null;
					try
					{
						this.Connection.CheckGetExtendedUDTInfo(rec, true);
						if (rec.value.IsNull)
						{
							value = DBNull.Value;
						}
						else
						{
							value = rec.value.ByteArray;
						}
						parameterForOutputValueExtraction.Value = this.Connection.GetUdtValue(value, rec, false);
					}
					catch (FileNotFoundException udtLoadError)
					{
						parameterForOutputValueExtraction.SetUdtLoadError(udtLoadError);
					}
					catch (FileLoadException udtLoadError2)
					{
						parameterForOutputValueExtraction.SetUdtLoadError(udtLoadError2);
					}
					return;
				}
				parameterForOutputValueExtraction.SetSqlBuffer(rec.value);
				MetaType metaTypeFromSqlDbType = MetaType.GetMetaTypeFromSqlDbType(rec.type, rec.isMultiValued);
				if (rec.type == SqlDbType.Decimal)
				{
					parameterForOutputValueExtraction.ScaleInternal = rec.scale;
					parameterForOutputValueExtraction.PrecisionInternal = rec.precision;
				}
				else
				{
					if (metaTypeFromSqlDbType.IsVarTime)
					{
						parameterForOutputValueExtraction.ScaleInternal = rec.scale;
					}
					else
					{
						if (rec.type == SqlDbType.Xml)
						{
							SqlCachedBuffer sqlCachedBuffer = parameterForOutputValueExtraction.Value as SqlCachedBuffer;
							if (sqlCachedBuffer != null)
							{
								parameterForOutputValueExtraction.Value = sqlCachedBuffer.ToString();
							}
						}
					}
				}
				if (rec.collation != null)
				{
					parameterForOutputValueExtraction.Collation = rec.collation;
				}
			}
		}
		internal void OnParametersAvailableSmi(SmiParameterMetaData[] paramMetaData, ITypedGettersV3 parameterValues)
		{
			for (int i = 0; i < paramMetaData.Length; i++)
			{
				this.OnParameterAvailableSmi(paramMetaData[i], parameterValues, i);
			}
		}
		internal void OnParameterAvailableSmi(SmiParameterMetaData metaData, ITypedGettersV3 parameterValues, int ordinal)
		{
			if (ParameterDirection.Input != metaData.Direction)
			{
				string paramName = null;
				if (ParameterDirection.ReturnValue != metaData.Direction)
				{
					paramName = metaData.Name;
				}
				SqlParameterCollection currentParameterCollection = this.GetCurrentParameterCollection();
				int parameterCount = this.GetParameterCount(currentParameterCollection);
				SqlParameter parameterForOutputValueExtraction = this.GetParameterForOutputValueExtraction(currentParameterCollection, paramName, parameterCount);
				if (parameterForOutputValueExtraction != null)
				{
					parameterForOutputValueExtraction.LocaleId = (int)metaData.LocaleId;
					parameterForOutputValueExtraction.CompareInfo = metaData.CompareOptions;
					SqlBuffer sqlBuffer = new SqlBuffer();
					object obj;
					if (this._activeConnection.IsKatmaiOrNewer)
					{
						obj = ValueUtilsSmi.GetOutputParameterV200Smi(this.OutParamEventSink, (SmiTypedGetterSetter)parameterValues, ordinal, metaData, this._smiRequestContext, sqlBuffer);
					}
					else
					{
						obj = ValueUtilsSmi.GetOutputParameterV3Smi(this.OutParamEventSink, parameterValues, ordinal, metaData, this._smiRequestContext, sqlBuffer);
					}
					if (obj != null)
					{
						parameterForOutputValueExtraction.Value = obj;
						return;
					}
					parameterForOutputValueExtraction.SetSqlBuffer(sqlBuffer);
				}
			}
		}
		private SqlParameterCollection GetCurrentParameterCollection()
		{
			if (!this.BatchRPCMode)
			{
				return this._parameters;
			}
			if (this._parameterCollectionList.Count > this._currentlyExecutingBatch)
			{
				return this._parameterCollectionList[this._currentlyExecutingBatch];
			}
			return null;
		}
		private SqlParameter GetParameterForOutputValueExtraction(SqlParameterCollection parameters, string paramName, int paramCount)
		{
			SqlParameter sqlParameter = null;
			bool flag = false;
			if (paramName == null)
			{
				for (int i = 0; i < paramCount; i++)
				{
					sqlParameter = parameters[i];
					if (sqlParameter.Direction == ParameterDirection.ReturnValue)
					{
						flag = true;
						break;
					}
				}
			}
			else
			{
				for (int j = 0; j < paramCount; j++)
				{
					sqlParameter = parameters[j];
					if (sqlParameter.Direction != ParameterDirection.Input && sqlParameter.Direction != ParameterDirection.ReturnValue && paramName == sqlParameter.ParameterNameFixed)
					{
						flag = true;
						break;
					}
				}
			}
			if (flag)
			{
				return sqlParameter;
			}
			return null;
		}
		private void GetRPCObject(int paramCount, ref _SqlRPC rpc)
		{
			if (rpc == null)
			{
				if (this._rpcArrayOf1 == null)
				{
					this._rpcArrayOf1 = new _SqlRPC[1];
					this._rpcArrayOf1[0] = new _SqlRPC();
				}
				rpc = this._rpcArrayOf1[0];
			}
			rpc.ProcID = 0;
			rpc.rpcName = null;
			rpc.options = 0;
			rpc.recordsAffected = null;
			rpc.cumulativeRecordsAffected = -1;
			rpc.errorsIndexStart = 0;
			rpc.errorsIndexEnd = 0;
			rpc.errors = null;
			rpc.warningsIndexStart = 0;
			rpc.warningsIndexEnd = 0;
			rpc.warnings = null;
			if (rpc.parameters == null || rpc.parameters.Length < paramCount)
			{
				rpc.parameters = new SqlParameter[paramCount];
			}
			else
			{
				if (rpc.parameters.Length > paramCount)
				{
					rpc.parameters[paramCount] = null;
				}
			}
			if (rpc.paramoptions == null || rpc.paramoptions.Length < paramCount)
			{
				rpc.paramoptions = new byte[paramCount];
				return;
			}
			for (int i = 0; i < paramCount; i++)
			{
				rpc.paramoptions[i] = 0;
			}
		}
		private void SetUpRPCParameters(_SqlRPC rpc, int startCount, bool inSchema, SqlParameterCollection parameters)
		{
			int parameterCount = this.GetParameterCount(parameters);
			int num = startCount;
			TdsParser parser = this._activeConnection.Parser;
			bool isYukonOrNewer = parser.IsYukonOrNewer;
			for (int i = 0; i < parameterCount; i++)
			{
				SqlParameter sqlParameter = parameters[i];
				sqlParameter.Validate(i, CommandType.StoredProcedure == this.CommandType);
				if (!sqlParameter.ValidateTypeLengths(isYukonOrNewer).IsPlp && sqlParameter.Direction != ParameterDirection.Output)
				{
					sqlParameter.FixStreamDataForNonPLP();
				}
				if (SqlCommand.ShouldSendParameter(sqlParameter))
				{
					rpc.parameters[num] = sqlParameter;
					if (sqlParameter.Direction == ParameterDirection.InputOutput || sqlParameter.Direction == ParameterDirection.Output)
					{
						rpc.paramoptions[num] = 1;
					}
					if (sqlParameter.Direction != ParameterDirection.Output && sqlParameter.Value == null && (!inSchema || SqlDbType.Structured == sqlParameter.SqlDbType))
					{
						byte[] expr_B4_cp_0 = rpc.paramoptions;
						int expr_B4_cp_1 = num;
						expr_B4_cp_0[expr_B4_cp_1] |= 2;
					}
					num++;
				}
			}
		}
		private _SqlRPC BuildPrepExec(CommandBehavior behavior)
		{
			int num = 3;
			int num2 = this.CountSendableParameters(this._parameters);
			_SqlRPC sqlRPC = null;
			this.GetRPCObject(num2 + num, ref sqlRPC);
			sqlRPC.ProcID = 13;
			sqlRPC.rpcName = "sp_prepexec";
			SqlParameter sqlParameter = new SqlParameter(null, SqlDbType.Int);
			sqlParameter.Direction = ParameterDirection.InputOutput;
			sqlParameter.Value = this._prepareHandle;
			sqlRPC.parameters[0] = sqlParameter;
			sqlRPC.paramoptions[0] = 1;
			string text = this.BuildParamList(this._stateObj.Parser, this._parameters);
			sqlParameter = new SqlParameter(null, (text.Length << 1 <= 8000) ? SqlDbType.NVarChar : SqlDbType.NText, text.Length);
			sqlParameter.Value = text;
			sqlRPC.parameters[1] = sqlParameter;
			string commandText = this.GetCommandText(behavior);
			sqlParameter = new SqlParameter(null, (commandText.Length << 1 <= 8000) ? SqlDbType.NVarChar : SqlDbType.NText, commandText.Length);
			sqlParameter.Value = commandText;
			sqlRPC.parameters[2] = sqlParameter;
			this.SetUpRPCParameters(sqlRPC, num, false, this._parameters);
			return sqlRPC;
		}
		private static bool ShouldSendParameter(SqlParameter p)
		{
			switch (p.Direction)
			{
				case ParameterDirection.Input:
				case ParameterDirection.Output:
				case ParameterDirection.InputOutput:
				{
					return true;
				}
				case ParameterDirection.ReturnValue:
				{
					return false;
				}
			}
			return false;
		}
		private int CountSendableParameters(SqlParameterCollection parameters)
		{
			int num = 0;
			if (parameters != null)
			{
				int count = parameters.Count;
				for (int i = 0; i < count; i++)
				{
					if (SqlCommand.ShouldSendParameter(parameters[i]))
					{
						num++;
					}
				}
			}
			return num;
		}
		private int GetParameterCount(SqlParameterCollection parameters)
		{
			if (parameters == null)
			{
				return 0;
			}
			return parameters.Count;
		}
		private void BuildRPC(bool inSchema, SqlParameterCollection parameters, ref _SqlRPC rpc)
		{
			int paramCount = this.CountSendableParameters(parameters);
			this.GetRPCObject(paramCount, ref rpc);
			rpc.rpcName = this.CommandText;
			this.SetUpRPCParameters(rpc, 0, inSchema, parameters);
		}
		private _SqlRPC BuildUnprepare()
		{
			_SqlRPC sqlRPC = null;
			this.GetRPCObject(1, ref sqlRPC);
			sqlRPC.ProcID = 15;
			sqlRPC.rpcName = "sp_unprepare";
			SqlParameter sqlParameter = new SqlParameter(null, SqlDbType.Int);
			sqlParameter.Value = this._prepareHandle;
			sqlRPC.parameters[0] = sqlParameter;
			return sqlRPC;
		}
		private _SqlRPC BuildExecute(bool inSchema)
		{
			int num = 1;
			int num2 = this.CountSendableParameters(this._parameters);
			_SqlRPC sqlRPC = null;
			this.GetRPCObject(num2 + num, ref sqlRPC);
			sqlRPC.ProcID = 12;
			sqlRPC.rpcName = "sp_execute";
			SqlParameter sqlParameter = new SqlParameter(null, SqlDbType.Int);
			sqlParameter.Value = this._prepareHandle;
			sqlRPC.parameters[0] = sqlParameter;
			this.SetUpRPCParameters(sqlRPC, num, inSchema, this._parameters);
			return sqlRPC;
		}
		private void BuildExecuteSql(CommandBehavior behavior, string commandText, SqlParameterCollection parameters, ref _SqlRPC rpc)
		{
			int num = this.CountSendableParameters(parameters);
			int num2;
			if (num > 0)
			{
				num2 = 2;
			}
			else
			{
				num2 = 1;
			}
			this.GetRPCObject(num + num2, ref rpc);
			rpc.ProcID = 10;
			rpc.rpcName = "sp_executesql";
			if (commandText == null)
			{
				commandText = this.GetCommandText(behavior);
			}
			SqlParameter sqlParameter = new SqlParameter(null, (commandText.Length << 1 <= 8000) ? SqlDbType.NVarChar : SqlDbType.NText, commandText.Length);
			sqlParameter.Value = commandText;
			rpc.parameters[0] = sqlParameter;
			if (num > 0)
			{
				string text = this.BuildParamList(this._stateObj.Parser, this.BatchRPCMode ? parameters : this._parameters);
				sqlParameter = new SqlParameter(null, (text.Length << 1 <= 8000) ? SqlDbType.NVarChar : SqlDbType.NText, text.Length);
				sqlParameter.Value = text;
				rpc.parameters[1] = sqlParameter;
				bool inSchema = CommandBehavior.Default != (behavior & CommandBehavior.SchemaOnly);
				this.SetUpRPCParameters(rpc, num2, inSchema, parameters);
			}
		}
		internal string BuildParamList(TdsParser parser, SqlParameterCollection parameters)
		{
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = false;
			bool isYukonOrNewer = parser.IsYukonOrNewer;
			int count = parameters.Count;
			for (int i = 0; i < count; i++)
			{
				SqlParameter sqlParameter = parameters[i];
				sqlParameter.Validate(i, CommandType.StoredProcedure == this.CommandType);
				if (SqlCommand.ShouldSendParameter(sqlParameter))
				{
					if (flag)
					{
						stringBuilder.Append(',');
					}
					stringBuilder.Append(sqlParameter.ParameterNameFixed);
					MetaType metaType = sqlParameter.InternalMetaType;
					stringBuilder.Append(" ");
					if (metaType.SqlDbType == SqlDbType.Udt)
					{
						string udtTypeName = sqlParameter.UdtTypeName;
						if (ADP.IsEmpty(udtTypeName))
						{
							throw SQL.MustSetUdtTypeNameForUdtParams();
						}
						stringBuilder.Append(this.ParseAndQuoteIdentifier(udtTypeName, true));
					}
					else
					{
						if (metaType.SqlDbType == SqlDbType.Structured)
						{
							string typeName = sqlParameter.TypeName;
							if (ADP.IsEmpty(typeName))
							{
								throw SQL.MustSetTypeNameForParam(metaType.TypeName, sqlParameter.ParameterNameFixed);
							}
							stringBuilder.Append(this.ParseAndQuoteIdentifier(typeName, false));
							stringBuilder.Append(" READONLY");
						}
						else
						{
							metaType = sqlParameter.ValidateTypeLengths(isYukonOrNewer);
							if (!metaType.IsPlp && sqlParameter.Direction != ParameterDirection.Output)
							{
								sqlParameter.FixStreamDataForNonPLP();
							}
							stringBuilder.Append(metaType.TypeName);
						}
					}
					flag = true;
					if (metaType.SqlDbType == SqlDbType.Decimal)
					{
						byte b = sqlParameter.GetActualPrecision();
						byte actualScale = sqlParameter.GetActualScale();
						stringBuilder.Append('(');
						if (b == 0)
						{
							if (this.IsShiloh)
							{
								b = 29;
							}
							else
							{
								b = 28;
							}
						}
						stringBuilder.Append(b);
						stringBuilder.Append(',');
						stringBuilder.Append(actualScale);
						stringBuilder.Append(')');
					}
					else
					{
						if (metaType.IsVarTime)
						{
							byte actualScale2 = sqlParameter.GetActualScale();
							stringBuilder.Append('(');
							stringBuilder.Append(actualScale2);
							stringBuilder.Append(')');
						}
						else
						{
							if (!metaType.IsFixed && !metaType.IsLong && metaType.SqlDbType != SqlDbType.Timestamp && metaType.SqlDbType != SqlDbType.Udt && SqlDbType.Structured != metaType.SqlDbType)
							{
								int num = sqlParameter.Size;
								stringBuilder.Append('(');
								if (metaType.IsAnsiType)
								{
									object coercedValue = sqlParameter.GetCoercedValue();
									string text = null;
									if (coercedValue != null && DBNull.Value != coercedValue)
									{
										text = (coercedValue as string);
										if (text == null)
										{
											SqlString sqlString = (coercedValue is SqlString) ? ((SqlString)coercedValue) : SqlString.Null;
											if (!sqlString.IsNull)
											{
												text = sqlString.Value;
											}
										}
									}
									if (text != null)
									{
										int encodingCharLength = parser.GetEncodingCharLength(text, sqlParameter.GetActualSize(), sqlParameter.Offset, null);
										if (encodingCharLength > num)
										{
											num = encodingCharLength;
										}
									}
								}
								if (num == 0)
								{
									num = (metaType.IsSizeInCharacters ? 4000 : 8000);
								}
								stringBuilder.Append(num);
								stringBuilder.Append(')');
							}
							else
							{
								if (metaType.IsPlp && metaType.SqlDbType != SqlDbType.Xml && metaType.SqlDbType != SqlDbType.Udt)
								{
									stringBuilder.Append("(max) ");
								}
							}
						}
					}
					if (sqlParameter.Direction != ParameterDirection.Input)
					{
						stringBuilder.Append(" output");
					}
				}
			}
			return stringBuilder.ToString();
		}
		private string ParseAndQuoteIdentifier(string identifier, bool isUdtTypeName)
		{
			string[] array = SqlParameter.ParseTypeName(identifier, isUdtTypeName);
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < array.Length; i++)
			{
				if (0 < stringBuilder.Length)
				{
					stringBuilder.Append('.');
				}
				if (array[i] != null && array[i].Length != 0)
				{
					stringBuilder.Append(ADP.BuildQuotedString("[", "]", array[i]));
				}
			}
			return stringBuilder.ToString();
		}
		private string GetSetOptionsString(CommandBehavior behavior)
		{
			string text = null;
			if (CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly) || CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo))
			{
				text = " SET FMTONLY OFF;";
				if (CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo))
				{
					text += " SET NO_BROWSETABLE ON;";
				}
				if (CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly))
				{
					text += " SET FMTONLY ON;";
				}
			}
			return text;
		}
		private string GetResetOptionsString(CommandBehavior behavior)
		{
			string text = null;
			if (CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly))
			{
				text += " SET FMTONLY OFF;";
			}
			if (CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo))
			{
				text += " SET NO_BROWSETABLE OFF;";
			}
			return text;
		}
		private string GetCommandText(CommandBehavior behavior)
		{
			return this.GetSetOptionsString(behavior) + this.CommandText;
		}
		private _SqlRPC BuildPrepare(CommandBehavior behavior)
		{
			_SqlRPC sqlRPC = null;
			this.GetRPCObject(3, ref sqlRPC);
			sqlRPC.ProcID = 11;
			sqlRPC.rpcName = "sp_prepare";
			SqlParameter sqlParameter = new SqlParameter(null, SqlDbType.Int);
			sqlParameter.Direction = ParameterDirection.Output;
			sqlRPC.parameters[0] = sqlParameter;
			sqlRPC.paramoptions[0] = 1;
			string text = this.BuildParamList(this._stateObj.Parser, this._parameters);
			sqlParameter = new SqlParameter(null, (text.Length << 1 <= 8000) ? SqlDbType.NVarChar : SqlDbType.NText, text.Length);
			sqlParameter.Value = text;
			sqlRPC.parameters[1] = sqlParameter;
			string commandText = this.GetCommandText(behavior);
			sqlParameter = new SqlParameter(null, (commandText.Length << 1 <= 8000) ? SqlDbType.NVarChar : SqlDbType.NText, commandText.Length);
			sqlParameter.Value = commandText;
			sqlRPC.parameters[2] = sqlParameter;
			return sqlRPC;
		}
		internal void CheckThrowSNIException()
		{
			TdsParserStateObject stateObj = this._stateObj;
			if (stateObj != null)
			{
				stateObj.CheckThrowSNIException();
			}
		}
		internal void OnConnectionClosed()
		{
			TdsParserStateObject stateObj = this._stateObj;
			if (stateObj != null)
			{
				stateObj.OnConnectionClosed();
			}
		}
		internal void ClearBatchCommand()
		{
			List<_SqlRPC> rPCList = this._RPCList;
			if (rPCList != null)
			{
				rPCList.Clear();
			}
			if (this._parameterCollectionList != null)
			{
				this._parameterCollectionList.Clear();
			}
			this._SqlRPCBatchArray = null;
			this._currentlyExecutingBatch = 0;
		}
		internal void AddBatchCommand(string commandText, SqlParameterCollection parameters, CommandType cmdType)
		{
			_SqlRPC item = new _SqlRPC();
			this.CommandText = commandText;
			this.CommandType = cmdType;
			this.GetStateObject(null);
			if (cmdType == CommandType.StoredProcedure)
			{
				this.BuildRPC(false, parameters, ref item);
			}
			else
			{
				this.BuildExecuteSql(CommandBehavior.Default, commandText, parameters, ref item);
			}
			this._RPCList.Add(item);
			this._parameterCollectionList.Add(parameters);
			this.PutStateObject();
		}
		internal int ExecuteBatchRPCCommand()
		{
			this._SqlRPCBatchArray = this._RPCList.ToArray();
			this._currentlyExecutingBatch = 0;
			return this.ExecuteNonQuery();
		}
		internal int? GetRecordsAffected(int commandIndex)
		{
			return this._SqlRPCBatchArray[commandIndex].recordsAffected;
		}
		internal SqlException GetErrors(int commandIndex)
		{
			SqlException result = null;
			int num = this._SqlRPCBatchArray[commandIndex].errorsIndexEnd - this._SqlRPCBatchArray[commandIndex].errorsIndexStart;
			if (0 < num)
			{
				SqlErrorCollection sqlErrorCollection = new SqlErrorCollection();
				for (int i = this._SqlRPCBatchArray[commandIndex].errorsIndexStart; i < this._SqlRPCBatchArray[commandIndex].errorsIndexEnd; i++)
				{
					sqlErrorCollection.Add(this._SqlRPCBatchArray[commandIndex].errors[i]);
				}
				for (int j = this._SqlRPCBatchArray[commandIndex].warningsIndexStart; j < this._SqlRPCBatchArray[commandIndex].warningsIndexEnd; j++)
				{
					sqlErrorCollection.Add(this._SqlRPCBatchArray[commandIndex].warnings[j]);
				}
				result = SqlException.CreateException(sqlErrorCollection, this.Connection.ServerVersion, this.Connection.ClientConnectionId);
			}
			return result;
		}
		private SmiRequestExecutor SetUpSmiRequest(SqlInternalConnectionSmi innerConnection)
		{
			if (this.Notification != null)
			{
				throw SQL.NotificationsNotAvailableOnContextConnection();
			}
			SmiParameterMetaData[] array = null;
			ParameterPeekAheadValue[] array2 = null;
			int parameterCount = this.GetParameterCount(this.Parameters);
			if (0 < parameterCount)
			{
				array = new SmiParameterMetaData[parameterCount];
				array2 = new ParameterPeekAheadValue[parameterCount];
				for (int i = 0; i < parameterCount; i++)
				{
					SqlParameter sqlParameter = this.Parameters[i];
					sqlParameter.Validate(i, CommandType.StoredProcedure == this.CommandType);
					array[i] = sqlParameter.MetaDataForSmi(out array2[i]);
					if (!innerConnection.IsKatmaiOrNewer)
					{
						MetaType metaTypeFromSqlDbType = MetaType.GetMetaTypeFromSqlDbType(array[i].SqlDbType, array[i].IsMultiValued);
						if (!metaTypeFromSqlDbType.Is90Supported)
						{
							throw ADP.VersionDoesNotSupportDataType(metaTypeFromSqlDbType.TypeName);
						}
					}
				}
			}
			CommandType commandType = this.CommandType;
			this._smiRequestContext = innerConnection.InternalContext;
			SmiRequestExecutor smiRequestExecutor = this._smiRequestContext.CreateRequestExecutor(this.CommandText, commandType, array, this.EventSink);
			this.EventSink.ProcessMessagesAndThrow();
			for (int j = 0; j < parameterCount; j++)
			{
				if (ParameterDirection.Output != array[j].Direction && ParameterDirection.ReturnValue != array[j].Direction)
				{
					SqlParameter sqlParameter2 = this.Parameters[j];
					object obj = sqlParameter2.GetCoercedValue();
					if (obj is XmlDataFeed && array[j].SqlDbType != SqlDbType.Xml)
					{
						obj = MetaType.GetStringFromXml(((XmlDataFeed)obj)._source);
					}
					ExtendedClrTypeCode extendedClrTypeCode = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(array[j].SqlDbType, array[j].IsMultiValued, obj, null, SmiContextFactory.Instance.NegotiatedSmiVersion);
					if (CommandType.StoredProcedure == commandType && ExtendedClrTypeCode.Empty == extendedClrTypeCode)
					{
						smiRequestExecutor.SetDefault(j);
					}
					else
					{
						int size = sqlParameter2.Size;
						if (size != 0 && (long)size != -1L && !sqlParameter2.SizeInferred)
						{
							SqlDbType sqlDbType = array[j].SqlDbType;
							if (sqlDbType != SqlDbType.Image)
							{
								switch (sqlDbType)
								{
									case SqlDbType.NText:
									{
										if (size != 1073741823)
										{
											throw SQL.ParameterSizeRestrictionFailure(j);
										}
										goto IL_2EC;
									}
									case SqlDbType.NVarChar:
									{
										if (size > 0 && size != 1073741823 && array[j].MaxLength == -1L)
										{
											throw SQL.ParameterSizeRestrictionFailure(j);
										}
										goto IL_2EC;
									}
									case SqlDbType.Real:
									case SqlDbType.UniqueIdentifier:
									case SqlDbType.SmallDateTime:
									case SqlDbType.SmallInt:
									case SqlDbType.SmallMoney:
									case SqlDbType.TinyInt:
									case (SqlDbType)24:
									{
										goto IL_2EC;
									}
									case SqlDbType.Text:
									{
										break;
									}
									case SqlDbType.Timestamp:
									{
										if ((long)size < SmiMetaData.DefaultTimestamp.MaxLength)
										{
											throw SQL.ParameterSizeRestrictionFailure(j);
										}
										goto IL_2EC;
									}
									case SqlDbType.VarBinary:
									case SqlDbType.VarChar:
									{
										if (size > 0 && size != 2147483647 && array[j].MaxLength == -1L)
										{
											throw SQL.ParameterSizeRestrictionFailure(j);
										}
										goto IL_2EC;
									}
									case SqlDbType.Variant:
									{
										if (obj == null)
										{
											goto IL_2EC;
										}
										MetaType metaTypeFromValue = MetaType.GetMetaTypeFromValue(obj, true);
										if ((metaTypeFromValue.IsNCharType && (long)size < 4000L) || (metaTypeFromValue.IsBinType && (long)size < 8000L) || (metaTypeFromValue.IsAnsiType && (long)size < 8000L))
										{
											throw SQL.ParameterSizeRestrictionFailure(j);
										}
										goto IL_2EC;
									}
									case SqlDbType.Xml:
									{
										if (obj != null && ExtendedClrTypeCode.SqlXml != extendedClrTypeCode)
										{
											throw SQL.ParameterSizeRestrictionFailure(j);
										}
										goto IL_2EC;
									}
									default:
									{
										goto IL_2EC;
									}
								}
							}
							if (size != 2147483647)
							{
								throw SQL.ParameterSizeRestrictionFailure(j);
							}
						}
						IL_2EC:
						if (innerConnection.IsKatmaiOrNewer)
						{
							ValueUtilsSmi.SetCompatibleValueV200(this.EventSink, smiRequestExecutor, j, array[j], obj, extendedClrTypeCode, sqlParameter2.Offset, sqlParameter2.Size, array2[j]);
						}
						else
						{
							ValueUtilsSmi.SetCompatibleValue(this.EventSink, smiRequestExecutor, j, array[j], obj, extendedClrTypeCode, sqlParameter2.Offset);
						}
					}
				}
			}
			return smiRequestExecutor;
		}
		static SqlCommand()
		{
			// Note: this type is marked as 'beforefieldinit'.
			string[] array = new string[15];
			array[0] = "PARAMETER_NAME";
			array[1] = "PARAMETER_TYPE";
			array[2] = "DATA_TYPE";
			array[4] = "CHARACTER_MAXIMUM_LENGTH";
			array[5] = "NUMERIC_PRECISION";
			array[6] = "NUMERIC_SCALE";
			array[7] = "UDT_CATALOG";
			array[8] = "UDT_SCHEMA";
			array[9] = "TYPE_NAME";
			array[10] = "XML_CATALOGNAME";
			array[11] = "XML_SCHEMANAME";
			array[12] = "XML_SCHEMACOLLECTIONNAME";
			array[13] = "UDT_NAME";
			SqlCommand.PreKatmaiProcParamsNames = array;
			SqlCommand.KatmaiProcParamsNames = new string[]
			{
				"PARAMETER_NAME", 
				"PARAMETER_TYPE", 
				null, 
				"MANAGED_DATA_TYPE", 
				"CHARACTER_MAXIMUM_LENGTH", 
				"NUMERIC_PRECISION", 
				"NUMERIC_SCALE", 
				"TYPE_CATALOG_NAME", 
				"TYPE_SCHEMA_NAME", 
				"TYPE_NAME", 
				"XML_CATALOGNAME", 
				"XML_SCHEMANAME", 
				"XML_SCHEMACOLLECTIONNAME", 
				null, 
				"SS_DATETIME_PRECISION"
			};
		}
	}
} 
// Assembly: System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
using Mono.Data.Tds;
using Mono.Data.Tds.Protocol;
using System;
using System.Collections;
using System.ComponentModel;
using System.Data.Common;
using System.Data.Sql;
using System.Text;
using System.Threading;
using System.Xml;
namespace System.Data.SqlClient
{
	[DefaultEvent("RecordsAffected"), Designer("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.IDesigner"), ToolboxItem("System.Drawing.Design.ToolboxItem, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
	public sealed class SqlCommand : DbCommand, IDbCommand, IDisposable, ICloneable
	{
		private const int DEFAULT_COMMAND_TIMEOUT = 30;
		private int commandTimeout;
		private bool designTimeVisible;
		private string commandText;
		private CommandType commandType;
		private SqlConnection connection;
		private SqlTransaction transaction;
		private UpdateRowSource updatedRowSource;
		private CommandBehavior behavior;
		private SqlParameterCollection parameters;
		private string preparedStatement;
		private bool disposed;
		private SqlNotificationRequest notification;
		private bool notificationAutoEnlist;
		public event StatementCompletedEventHandler StatementCompleted
		{
			add
			{
				StatementCompletedEventHandler statementCompletedEventHandler = this.StatementCompleted;
				StatementCompletedEventHandler statementCompletedEventHandler2;
				do
				{
					statementCompletedEventHandler2 = statementCompletedEventHandler;
					statementCompletedEventHandler = Interlocked.CompareExchange<StatementCompletedEventHandler>(ref this.StatementCompleted, (StatementCompletedEventHandler)Delegate.Combine(statementCompletedEventHandler2, value), statementCompletedEventHandler);
				}
				while (statementCompletedEventHandler != statementCompletedEventHandler2);
			}
			remove
			{
				StatementCompletedEventHandler statementCompletedEventHandler = this.StatementCompleted;
				StatementCompletedEventHandler statementCompletedEventHandler2;
				do
				{
					statementCompletedEventHandler2 = statementCompletedEventHandler;
					statementCompletedEventHandler = Interlocked.CompareExchange<StatementCompletedEventHandler>(ref this.StatementCompleted, (StatementCompletedEventHandler)Delegate.Remove(statementCompletedEventHandler2, value), statementCompletedEventHandler);
				}
				while (statementCompletedEventHandler != statementCompletedEventHandler2);
			}
		}
		internal CommandBehavior CommandBehavior
		{
			get
			{
				return this.behavior;
			}
		}
		[DefaultValue(""), Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), RefreshProperties(RefreshProperties.All)]
		public override string CommandText
		{
			get
			{
				if (this.commandText == null)
				{
					return string.Empty;
				}
				return this.commandText;
			}
			set
			{
				if (value != this.commandText && this.preparedStatement != null)
				{
					this.Unprepare();
				}
				this.commandText = value;
			}
		}
		public override int CommandTimeout
		{
			get
			{
				return this.commandTimeout;
			}
			set
			{
				if (value < 0)
				{
					throw new ArgumentException("The property value assigned is less than 0.", "CommandTimeout");
				}
				this.commandTimeout = value;
			}
		}
		[DefaultValue(CommandType.Text), RefreshProperties(RefreshProperties.All)]
		public override CommandType CommandType
		{
			get
			{
				return this.commandType;
			}
			set
			{
				if (value == CommandType.TableDirect)
				{
					throw new ArgumentOutOfRangeException("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
				}
				ExceptionHelper.CheckEnumValue(typeof(CommandType), value);
				this.commandType = value;
			}
		}
		[DefaultValue(null), Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
		public new SqlConnection Connection
		{
			get
			{
				return this.connection;
			}
			set
			{
				this.connection = value;
			}
		}
		[Browsable(false), DefaultValue(true), DesignOnly(true), EditorBrowsable(EditorBrowsableState.Never)]
		public override bool DesignTimeVisible
		{
			get
			{
				return this.designTimeVisible;
			}
			set
			{
				this.designTimeVisible = value;
			}
		}
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		public new SqlParameterCollection Parameters
		{
			get
			{
				return this.parameters;
			}
		}
		internal Tds Tds
		{
			get
			{
				return this.Connection.Tds;
			}
		}
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public new SqlTransaction Transaction
		{
			get
			{
				if (this.transaction != null && !this.transaction.IsOpen)
				{
					this.transaction = null;
				}
				return this.transaction;
			}
			set
			{
				this.transaction = value;
			}
		}
		[DefaultValue(UpdateRowSource.Both)]
		public override UpdateRowSource UpdatedRowSource
		{
			get
			{
				return this.updatedRowSource;
			}
			set
			{
				ExceptionHelper.CheckEnumValue(typeof(UpdateRowSource), value);
				this.updatedRowSource = value;
			}
		}
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public SqlNotificationRequest Notification
		{
			get
			{
				return this.notification;
			}
			set
			{
				this.notification = value;
			}
		}
		[DefaultValue(true)]
		public bool NotificationAutoEnlist
		{
			get
			{
				return this.notificationAutoEnlist;
			}
			set
			{
				this.notificationAutoEnlist = value;
			}
		}
		protected override DbConnection DbConnection
		{
			get
			{
				return this.Connection;
			}
			set
			{
				this.Connection = (SqlConnection)value;
			}
		}
		protected override DbParameterCollection DbParameterCollection
		{
			get
			{
				return this.Parameters;
			}
		}
		protected override DbTransaction DbTransaction
		{
			get
			{
				return this.Transaction;
			}
			set
			{
				this.Transaction = (SqlTransaction)value;
			}
		}
		object ICloneable.Clone()
		{
			return new SqlCommand(this.commandText, this.connection, this.transaction, this.commandType, this.updatedRowSource, this.designTimeVisible, this.commandTimeout, this.parameters);
		}
		public SqlCommand() : this(string.Empty, null, null)
		{
		}
		public SqlCommand(string cmdText) : this(cmdText, null, null)
		{
		}
		public SqlCommand(string cmdText, SqlConnection connection) : this(cmdText, connection, null)
		{
		}
		public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction)
		{
			this.commandText = cmdText;
			this.connection = connection;
			this.transaction = transaction;
			this.commandType = CommandType.Text;
			this.updatedRowSource = UpdateRowSource.Both;
			this.commandTimeout = 30;
			this.notificationAutoEnlist = true;
			this.designTimeVisible = true;
			this.parameters = new SqlParameterCollection(this);
		}
		private SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction, CommandType commandType, UpdateRowSource updatedRowSource, bool designTimeVisible, int commandTimeout, SqlParameterCollection parameters)
		{
			this.commandText = commandText;
			this.connection = connection;
			this.transaction = transaction;
			this.commandType = commandType;
			this.updatedRowSource = updatedRowSource;
			this.designTimeVisible = designTimeVisible;
			this.commandTimeout = commandTimeout;
			this.parameters = new SqlParameterCollection(this);
			for (int i = 0; i < parameters.Count; i++)
			{
				this.parameters.Add(((ICloneable)parameters[i]).Clone());
			}
		}
		public override void Cancel()
		{
			if (this.Connection == null || this.Connection.Tds == null)
			{
				return;
			}
			this.Connection.Tds.Cancel();
		}
		public SqlCommand Clone()
		{
			return new SqlCommand(this.commandText, this.connection, this.transaction, this.commandType, this.updatedRowSource, this.designTimeVisible, this.commandTimeout, this.parameters);
		}
		internal void CloseDataReader()
		{
			if (this.Connection != null)
			{
				this.Connection.DataReader = null;
				if ((this.behavior & CommandBehavior.CloseConnection) != CommandBehavior.Default)
				{
					this.Connection.Close();
				}
				if (this.Tds != null)
				{
					this.Tds.set_SequentialAccess(false);
				}
			}
			this.behavior = CommandBehavior.Default;
		}
		public new SqlParameter CreateParameter()
		{
			return new SqlParameter();
		}
		private string EscapeProcName(string name, bool schema)
		{
			string text = name.Trim();
			int length = text.Length;
			char[] anyOf = new char[]
			{
				'[',
				']'
			};
			int startIndex = 0;
			int length2 = length;
			string result;
			if (length > 1)
			{
				int num;
				bool flag = (num = text.IndexOf('[')) <= 0;
				if (flag && num > -1)
				{
					int num2 = text.IndexOf(']');
					if (num > num2 && num2 != -1)
					{
						flag = false;
					}
					else
					{
						if (num2 == length - 1)
						{
							if (text.IndexOfAny(anyOf, 1, length - 2) != -1)
							{
								flag = false;
							}
							else
							{
								startIndex = 1;
								length2 = length - 2;
							}
						}
						else
						{
							flag = (num2 == -1 && schema);
						}
					}
				}
				if (!flag)
				{
					throw new ArgumentException(string.Format("SqlCommand.CommandText property value is an invalid multipart name {0}, incorrect usage of quotes", this.CommandText));
				}
				result = text.Substring(startIndex, length2);
			}
			else
			{
				result = text;
			}
			return result;
		}
		internal void DeriveParameters()
		{
			if (this.commandType != CommandType.StoredProcedure)
			{
				throw new InvalidOperationException(string.Format("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", this.commandType));
			}
			this.ValidateCommand("DeriveParameters", false);
			string text = this.CommandText;
			string text2 = string.Empty;
			int num = text.LastIndexOf('.');
			if (num >= 0)
			{
				text2 = text.Substring(0, num);
				text = text.Substring(num + 1);
				if ((num = text2.LastIndexOf('.')) >= 0)
				{
					text2 = text2.Substring(num + 1);
				}
			}
			text = this.EscapeProcName(text, false);
			text2 = this.EscapeProcName(text2, true);
			SqlParameterCollection sqlParameterCollection = new SqlParameterCollection(this);
			sqlParameterCollection.Add("@procedure_name", SqlDbType.NVarChar, text.Length).Value = text;
			if (text2.Length > 0)
			{
				sqlParameterCollection.Add("@procedure_schema", SqlDbType.NVarChar, text2.Length).Value = text2;
			}
			string text3 = "sp_procedure_params_rowset";
			try
			{
				this.Connection.Tds.ExecProc(text3, sqlParameterCollection.MetaParameters, 0, true);
			}
			catch (TdsTimeoutException e)
			{
				this.Connection.Tds.Reset();
				throw SqlException.FromTdsInternalException(e);
			}
			catch (TdsInternalException e2)
			{
				this.Connection.Close();
				throw SqlException.FromTdsInternalException(e2);
			}
			SqlDataReader sqlDataReader = new SqlDataReader(this);
			this.parameters.Clear();
			object[] array = new object[sqlDataReader.FieldCount];
			while (sqlDataReader.Read())
			{
				sqlDataReader.GetValues(array);
				this.parameters.Add(new SqlParameter(array));
			}
			sqlDataReader.Close();
			if (this.parameters.Count == 0)
			{
				throw new InvalidOperationException("Stored procedure '" + text + "' does not exist.");
			}
		}
		private void Execute(bool wantResults)
		{
			int num = 0;
			this.Connection.Tds.set_RecordsAffected(-1);
			TdsMetaParameterCollection metaParameters = this.Parameters.MetaParameters;
			IEnumerator enumerator = metaParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TdsMetaParameter tdsMetaParameter = (TdsMetaParameter)enumerator.Current;
					tdsMetaParameter.Validate(num++);
				}
			}
			finally
			{
				IDisposable disposable;
				if ((disposable = (enumerator as IDisposable)) != null)
				{
					disposable.Dispose();
				}
			}
			if (this.preparedStatement == null)
			{
				bool flag = (this.behavior & CommandBehavior.SchemaOnly) > CommandBehavior.Default;
				bool flag2 = (this.behavior & CommandBehavior.KeyInfo) > CommandBehavior.Default;
				StringBuilder stringBuilder = new StringBuilder();
				StringBuilder stringBuilder2 = new StringBuilder();
				if (flag || flag2)
				{
					stringBuilder.Append("SET FMTONLY OFF;");
				}
				if (flag2)
				{
					stringBuilder.Append("SET NO_BROWSETABLE ON;");
					stringBuilder2.Append("SET NO_BROWSETABLE OFF;");
				}
				if (flag)
				{
					stringBuilder.Append("SET FMTONLY ON;");
					stringBuilder2.Append("SET FMTONLY OFF;");
				}
				CommandType commandType = this.CommandType;
				if (commandType == CommandType.StoredProcedure)
				{
					try
					{
						if (flag2 || flag)
						{
							this.Connection.Tds.Execute(stringBuilder.ToString());
						}
						this.Connection.Tds.ExecProc(this.CommandText, metaParameters, this.CommandTimeout, wantResults);
						if (flag2 || flag)
						{
							this.Connection.Tds.Execute(stringBuilder2.ToString());
						}
					}
					catch (TdsTimeoutException e)
					{
						this.Connection.Tds.Reset();
						throw SqlException.FromTdsInternalException(e);
					}
					catch (TdsInternalException e2)
					{
						this.Connection.Close();
						throw SqlException.FromTdsInternalException(e2);
					}
				}
				else
				{
					if (commandType == CommandType.Text)
					{
						string text;
						if (stringBuilder2.Length > 0)
						{
							text = string.Format("{0}{1};{2}", stringBuilder.ToString(), this.CommandText, stringBuilder2.ToString());
						}
						else
						{
							text = string.Format("{0}{1}", stringBuilder.ToString(), this.CommandText);
						}
						try
						{
							this.Connection.Tds.Execute(text, metaParameters, this.CommandTimeout, wantResults);
						}
						catch (TdsTimeoutException e3)
						{
							this.Connection.Tds.Reset();
							throw SqlException.FromTdsInternalException(e3);
						}
						catch (TdsInternalException e4)
						{
							this.Connection.Close();
							throw SqlException.FromTdsInternalException(e4);
						}
					}
				}
			}
			else
			{
				try
				{
					this.Connection.Tds.ExecPrepared(this.preparedStatement, metaParameters, this.CommandTimeout, wantResults);
				}
				catch (TdsTimeoutException e5)
				{
					this.Connection.Tds.Reset();
					throw SqlException.FromTdsInternalException(e5);
				}
				catch (TdsInternalException e6)
				{
					this.Connection.Close();
					throw SqlException.FromTdsInternalException(e6);
				}
			}
		}
		public override int ExecuteNonQuery()
		{
			this.ValidateCommand("ExecuteNonQuery", false);
			int result = 0;
			this.behavior = CommandBehavior.Default;
			try
			{
				this.Execute(false);
				result = this.Connection.Tds.get_RecordsAffected();
			}
			catch (TdsTimeoutException e)
			{
				this.Connection.Tds.Reset();
				throw SqlException.FromTdsInternalException(e);
			}
			this.GetOutputParameters();
			return result;
		}
		public new SqlDataReader ExecuteReader()
		{
			return this.ExecuteReader(CommandBehavior.Default);
		}
		public new SqlDataReader ExecuteReader(CommandBehavior behavior)
		{
			this.ValidateCommand("ExecuteReader", false);
			if ((behavior & CommandBehavior.SingleRow) != CommandBehavior.Default)
			{
				behavior |= CommandBehavior.SingleResult;
			}
			this.behavior = behavior;
			if ((behavior & CommandBehavior.SequentialAccess) != CommandBehavior.Default)
			{
				this.Tds.set_SequentialAccess(true);
			}
			SqlDataReader dataReader;
			try
			{
				this.Execute(true);
				this.Connection.DataReader = new SqlDataReader(this);
				dataReader = this.Connection.DataReader;
			}
			catch
			{
				if ((behavior & CommandBehavior.CloseConnection) != CommandBehavior.Default)
				{
					this.Connection.Close();
				}
				throw;
			}
			return dataReader;
		}
		public override object ExecuteScalar()
		{
			object result;
			try
			{
				object obj = null;
				this.ValidateCommand("ExecuteScalar", false);
				this.behavior = CommandBehavior.Default;
				this.Execute(true);
				try
				{
					if (this.Connection.Tds.NextResult() && this.Connection.Tds.NextRow())
					{
						obj = this.Connection.Tds.get_ColumnValues().get_Item(0);
					}
					if (this.commandType == CommandType.StoredProcedure)
					{
						this.Connection.Tds.SkipToEnd();
						this.GetOutputParameters();
					}
				}
				catch (TdsTimeoutException e)
				{
					this.Connection.Tds.Reset();
					throw SqlException.FromTdsInternalException(e);
				}
				catch (TdsInternalException e2)
				{
					this.Connection.Close();
					throw SqlException.FromTdsInternalException(e2);
				}
				result = obj;
			}
			finally
			{
				this.CloseDataReader();
			}
			return result;
		}
		public XmlReader ExecuteXmlReader()
		{
			this.ValidateCommand("ExecuteXmlReader", false);
			this.behavior = CommandBehavior.Default;
			try
			{
				this.Execute(true);
			}
			catch (TdsTimeoutException e)
			{
				this.Connection.Tds.Reset();
				throw SqlException.FromTdsInternalException(e);
			}
			SqlDataReader reader = new SqlDataReader(this);
			SqlXmlTextReader input = new SqlXmlTextReader(reader);
			return new XmlTextReader(input);
		}
		internal void GetOutputParameters()
		{
			IList outputParameters = this.Connection.Tds.get_OutputParameters();
			if (outputParameters != null && outputParameters.Count > 0)
			{
				int num = 0;
				IEnumerator enumerator = this.parameters.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						SqlParameter sqlParameter = (SqlParameter)enumerator.Current;
						if (sqlParameter.Direction != ParameterDirection.Input && sqlParameter.Direction != ParameterDirection.ReturnValue)
						{
							sqlParameter.Value = outputParameters[num];
							num++;
						}
						if (num >= outputParameters.Count)
						{
							break;
						}
					}
				}
				finally
				{
					IDisposable disposable;
					if ((disposable = (enumerator as IDisposable)) != null)
					{
						disposable.Dispose();
					}
				}
			}
		}
		protected override void Dispose(bool disposing)
		{
			if (this.disposed)
			{
				return;
			}
			if (disposing)
			{
				this.parameters.Clear();
				if (this.Connection != null)
				{
					this.Connection.DataReader = null;
				}
			}
			base.Dispose(disposing);
			this.disposed = true;
		}
		public override void Prepare()
		{
			if (this.Connection == null)
			{
				throw new NullReferenceException();
			}
			if (this.CommandType == CommandType.StoredProcedure || (this.CommandType == CommandType.Text && this.Parameters.Count == 0))
			{
				return;
			}
			this.ValidateCommand("Prepare", false);
			try
			{
				IEnumerator enumerator = this.Parameters.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						SqlParameter sqlParameter = (SqlParameter)enumerator.Current;
						sqlParameter.CheckIfInitialized();
					}
				}
				finally
				{
					IDisposable disposable;
					if ((disposable = (enumerator as IDisposable)) != null)
					{
						disposable.Dispose();
					}
				}
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException("SqlCommand.Prepare requires " + ex.Message);
			}
			this.preparedStatement = this.Connection.Tds.Prepare(this.CommandText, this.Parameters.MetaParameters);
		}
		public void ResetCommandTimeout()
		{
			this.commandTimeout = 30;
		}
		private void Unprepare()
		{
			this.Connection.Tds.Unprepare(this.preparedStatement);
			this.preparedStatement = null;
		}
		private void ValidateCommand(string method, bool async)
		{
			if (this.Connection == null)
			{
				throw new InvalidOperationException(string.Format("{0}: A Connection object is required to continue.", method));
			}
			if (this.Transaction == null && this.Connection.Transaction != null)
			{
				throw new InvalidOperationException(string.Format("{0} requires a transaction if the command's connection is in a pending transaction.", method));
			}
			if (this.Transaction != null && this.Transaction.Connection != this.Connection)
			{
				throw new InvalidOperationException("The connection does not have the same transaction as the command.");
			}
			if (this.Connection.State != ConnectionState.Open)
			{
				throw new InvalidOperationException(string.Format("{0} requires an open connection to continue. This connection is closed.", method));
			}
			if (this.CommandText.Length == 0)
			{
				throw new InvalidOperationException(string.Format("{0}: CommandText has not been set for this Command.", method));
			}
			if (this.Connection.DataReader != null)
			{
				throw new InvalidOperationException("There is already an open DataReader associated with this Connection which must be closed first.");
			}
			if (this.Connection.XmlReader != null)
			{
				throw new InvalidOperationException("There is already an open XmlReader associated with this Connection which must be closed first.");
			}
			if (async && !this.Connection.AsyncProcessing)
			{
				throw new InvalidOperationException("This Connection object is not in Asynchronous mode. Use 'Asynchronous Processing = true' to set it.");
			}
		}
		protected override DbParameter CreateDbParameter()
		{
			return this.CreateParameter();
		}
		protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
		{
			return this.ExecuteReader(behavior);
		}
		internal IAsyncResult BeginExecuteInternal(CommandBehavior behavior, bool wantResults, AsyncCallback callback, object state)
		{
			IAsyncResult result = null;
			this.Connection.Tds.set_RecordsAffected(-1);
			TdsMetaParameterCollection metaParameters = this.Parameters.MetaParameters;
			if (this.preparedStatement == null)
			{
				bool flag = (behavior & CommandBehavior.SchemaOnly) > CommandBehavior.Default;
				bool flag2 = (behavior & CommandBehavior.KeyInfo) > CommandBehavior.Default;
				StringBuilder stringBuilder = new StringBuilder();
				StringBuilder stringBuilder2 = new StringBuilder();
				if (flag || flag2)
				{
					stringBuilder.Append("SET FMTONLY OFF;");
				}
				if (flag2)
				{
					stringBuilder.Append("SET NO_BROWSETABLE ON;");
					stringBuilder2.Append("SET NO_BROWSETABLE OFF;");
				}
				if (flag)
				{
					stringBuilder.Append("SET FMTONLY ON;");
					stringBuilder2.Append("SET FMTONLY OFF;");
				}
				CommandType commandType = this.CommandType;
				if (commandType == CommandType.StoredProcedure)
				{
					string text = string.Empty;
					string text2 = string.Empty;
					if (flag2 || flag)
					{
						text = stringBuilder.ToString();
					}
					if (flag2 || flag)
					{
						text2 = stringBuilder2.ToString();
					}
					try
					{
						this.Connection.Tds.BeginExecuteProcedure(text, text2, this.CommandText, !wantResults, metaParameters, callback, state);
					}
					catch (TdsTimeoutException e)
					{
						this.Connection.Tds.Reset();
						throw SqlException.FromTdsInternalException(e);
					}
					catch (TdsInternalException e2)
					{
						this.Connection.Close();
						throw SqlException.FromTdsInternalException(e2);
					}
				}
				else
				{
					if (commandType == CommandType.Text)
					{
						string text3 = string.Format("{0}{1};{2}", stringBuilder.ToString(), this.CommandText, stringBuilder2.ToString());
						try
						{
							if (wantResults)
							{
								result = this.Connection.Tds.BeginExecuteQuery(text3, metaParameters, callback, state);
							}
							else
							{
								result = this.Connection.Tds.BeginExecuteNonQuery(text3, metaParameters, callback, state);
							}
						}
						catch (TdsTimeoutException e3)
						{
							this.Connection.Tds.Reset();
							throw SqlException.FromTdsInternalException(e3);
						}
						catch (TdsInternalException e4)
						{
							this.Connection.Close();
							throw SqlException.FromTdsInternalException(e4);
						}
					}
				}
			}
			else
			{
				try
				{
					this.Connection.Tds.ExecPrepared(this.preparedStatement, metaParameters, this.CommandTimeout, wantResults);
				}
				catch (TdsTimeoutException e5)
				{
					this.Connection.Tds.Reset();
					throw SqlException.FromTdsInternalException(e5);
				}
				catch (TdsInternalException e6)
				{
					this.Connection.Close();
					throw SqlException.FromTdsInternalException(e6);
				}
			}
			return result;
		}
		internal void EndExecuteInternal(IAsyncResult ar)
		{
			SqlAsyncResult sqlAsyncResult = (SqlAsyncResult)ar;
			this.Connection.Tds.WaitFor(sqlAsyncResult.InternalResult);
			this.Connection.Tds.CheckAndThrowException(sqlAsyncResult.InternalResult);
		}
		public IAsyncResult BeginExecuteNonQuery()
		{
			return this.BeginExecuteNonQuery(null, null);
		}
		public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject)
		{
			this.ValidateCommand("BeginExecuteNonQuery", true);
			SqlAsyncResult sqlAsyncResult = new SqlAsyncResult(callback, stateObject);
			sqlAsyncResult.EndMethod = "EndExecuteNonQuery";
			sqlAsyncResult.InternalResult = this.BeginExecuteInternal(CommandBehavior.Default, false, sqlAsyncResult.BubbleCallback, sqlAsyncResult);
			return sqlAsyncResult;
		}
		public int EndExecuteNonQuery(IAsyncResult asyncResult)
		{
			this.ValidateAsyncResult(asyncResult, "EndExecuteNonQuery");
			this.EndExecuteInternal(asyncResult);
			int recordsAffected = this.Connection.Tds.get_RecordsAffected();
			this.GetOutputParameters();
			((SqlAsyncResult)asyncResult).Ended = true;
			return recordsAffected;
		}
		public IAsyncResult BeginExecuteReader()
		{
			return this.BeginExecuteReader(null, null, CommandBehavior.Default);
		}
		public IAsyncResult BeginExecuteReader(CommandBehavior behavior)
		{
			return this.BeginExecuteReader(null, null, behavior);
		}
		public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject)
		{
			return this.BeginExecuteReader(callback, stateObject, CommandBehavior.Default);
		}
		public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior)
		{
			this.ValidateCommand("BeginExecuteReader", true);
			this.behavior = behavior;
			SqlAsyncResult sqlAsyncResult = new SqlAsyncResult(callback, stateObject);
			sqlAsyncResult.EndMethod = "EndExecuteReader";
			IAsyncResult internalResult = this.BeginExecuteInternal(behavior, true, sqlAsyncResult.BubbleCallback, stateObject);
			sqlAsyncResult.InternalResult = internalResult;
			return sqlAsyncResult;
		}
		public SqlDataReader EndExecuteReader(IAsyncResult asyncResult)
		{
			this.ValidateAsyncResult(asyncResult, "EndExecuteReader");
			this.EndExecuteInternal(asyncResult);
			SqlDataReader result = null;
			try
			{
				result = new SqlDataReader(this);
			}
			catch (TdsTimeoutException e)
			{
				throw SqlException.FromTdsInternalException(e);
			}
			catch (TdsInternalException e2)
			{
				if ((this.behavior & CommandBehavior.CloseConnection) != CommandBehavior.Default)
				{
					this.Connection.Close();
				}
				throw SqlException.FromTdsInternalException(e2);
			}
			((SqlAsyncResult)asyncResult).Ended = true;
			return result;
		}
		public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject)
		{
			this.ValidateCommand("BeginExecuteXmlReader", true);
			SqlAsyncResult sqlAsyncResult = new SqlAsyncResult(callback, stateObject);
			sqlAsyncResult.EndMethod = "EndExecuteXmlReader";
			sqlAsyncResult.InternalResult = this.BeginExecuteInternal(this.behavior, true, sqlAsyncResult.BubbleCallback, stateObject);
			return sqlAsyncResult;
		}
		public IAsyncResult BeginExecuteXmlReader()
		{
			return this.BeginExecuteXmlReader(null, null);
		}
		public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult)
		{
			this.ValidateAsyncResult(asyncResult, "EndExecuteXmlReader");
			this.EndExecuteInternal(asyncResult);
			SqlDataReader reader = new SqlDataReader(this);
			SqlXmlTextReader input = new SqlXmlTextReader(reader);
			XmlReader result = new XmlTextReader(input);
			((SqlAsyncResult)asyncResult).Ended = true;
			return result;
		}
		internal void ValidateAsyncResult(IAsyncResult ar, string endMethod)
		{
			if (ar == null)
			{
				throw new ArgumentException("result passed is null!");
			}
			if (!(ar is SqlAsyncResult))
			{
				throw new ArgumentException(string.Format("cannot test validity of types {0}", ar.GetType()));
			}
			SqlAsyncResult sqlAsyncResult = (SqlAsyncResult)ar;
			if (sqlAsyncResult.EndMethod != endMethod)
			{
				throw new InvalidOperationException(string.Format("Mismatched {0} called for AsyncResult. Expected call to {1} but {0} is called instead.", endMethod, sqlAsyncResult.EndMethod));
			}
			if (sqlAsyncResult.Ended)
			{
				throw new InvalidOperationException(string.Format("The method {0} cannot be called more than once for the same AsyncResult.", endMethod));
			}
		}
	}
}