Exemple #1
0
        public void ExecuteReaderProcess
        (
            TDbConnection connection
            , string storeProcedureName
            , JToken inputsParameters = null         //string.Empty
            , Action
            <
                int                             // resultSetID
                , JArray
                , IDataReader
                , int                           // row index
            > onReadRowProcessAction      = null
            , int commandTimeoutInSeconds = 90
        )
        {
            var extensionInfo = new ExtensionInfo()
            {
                resultSetID    = 0
                , messageID    = 0
                , recordCounts = null
                , messages     = null
            };

            TDbCommand          command = null;
            List <TDbParameter> dbParameters;
            bool statisticsEnabled;
            StatementCompletedEventHandler
                onStatementCompletedEventHandlerProcessAction = null;
            SqlInfoMessageEventHandler
                    onSqlInfoMessageEventHandlerProcessAction = null;
            JObject result;

            try
            {
                (
                    command
                    , dbParameters
                    , statisticsEnabled
                    , onStatementCompletedEventHandlerProcessAction
                    , onSqlInfoMessageEventHandlerProcessAction
                    , result
                ) = ResultPreprocess
                    (
                    connection
                    , storeProcedureName
                    , inputsParameters
                    , commandTimeoutInSeconds
                    , extensionInfo
                    );
                connection
                .Open();
                var dataReader = command
                                 .ExecuteReader
                                 (
                    CommandBehavior
                    .CloseConnection
                                 );
                do
                {
                    JArray jColumns = null;
                    if (onReadRowProcessAction != null)
                    {
                        if (jColumns == null)
                        {
                            jColumns = dataReader
                                       .GetColumnsJArray();
                        }
                        dataReader
                        .ReadRows
                        (
                            jColumns
                            , (reader, columns, rowIndex) =>
                        {
                            onReadRowProcessAction
                            (
                                extensionInfo.resultSetID
                                , columns
                                , reader
                                , rowIndex
                            );
                        }
                        );
                    }
                    extensionInfo
                    .resultSetID++;
                    jColumns = null;
                }while
                (
                    dataReader
                    .NextResult()
                );
                dataReader.Close();
            }
            finally
            {
                extensionInfo.Clear();
                if (onStatementCompletedEventHandlerProcessAction != null)
                {
                    if (command is SqlCommand sqlCommand)
                    {
                        sqlCommand
                        .StatementCompleted -=
                            onStatementCompletedEventHandlerProcessAction;
                    }
                }
                if (onSqlInfoMessageEventHandlerProcessAction != null)
                {
                    if (connection is SqlConnection sqlConnection)
                    {
                        sqlConnection
                        .InfoMessage -=
                            onSqlInfoMessageEventHandlerProcessAction;
                        if (sqlConnection.StatisticsEnabled)
                        {
                            sqlConnection.StatisticsEnabled = false;
                        }
                    }
                }
                if (_needAutoRefreshExecutedTimeForSlideExpire)
                {
                    RefreshCachedExecuted
                    (
                        connection
                        , storeProcedureName
                    );
                }
                if (connection.State != ConnectionState.Closed)
                {
                    connection
                    .Close();
                }
                if (command != null)
                {
                    command
                    .Dispose();
                }
            }
        }
Exemple #2
0
        private ScriptExecutionResult DoBatchExecutionImpl(IDbConnection connection, string script)
        {
            Validate.IsNotNull(nameof(connection), connection);

            lock (this)
            {
                if (state == BatchState.Cancelling)
                {
                    state = BatchState.Initial;
                    return(ScriptExecutionResult.Cancel);
                }
            }

            ScriptExecutionResult result = ScriptExecutionResult.Success;

            // SqlClient event handlers setup
            SqlInfoMessageEventHandler     messageHandler            = new SqlInfoMessageEventHandler(OnSqlInfoMessageCallback);
            StatementCompletedEventHandler statementCompletedHandler = null;

            DbConnectionWrapper connectionWrapper = new DbConnectionWrapper(connection);

            connectionWrapper.InfoMessage += messageHandler;

            IDbCommand command = connection.CreateCommand();

            command.CommandText    = script;
            command.CommandTimeout = execTimeout;

            DbCommandWrapper commandWrapper = null;

            if (isScriptExecutionTracked && DbCommandWrapper.IsSupportedCommand(command))
            {
                statementCompletedHandler          = new StatementCompletedEventHandler(OnStatementExecutionFinished);
                commandWrapper                     = new DbCommandWrapper(command);
                commandWrapper.StatementCompleted += statementCompletedHandler;
            }

            lock (this)
            {
                state        = BatchState.Executing;
                this.command = command;
                command      = null;
            }

            try
            {
                result = this.ExecuteCommand();
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (SqlException sqlEx)
            {
                result = HandleSqlException(sqlEx);
            }
            catch (Exception ex)
            {
                result = ScriptExecutionResult.Failure;
                HandleExceptionMessage(ex);
            }
            finally
            {
                if (messageHandler == null)
                {
                    Logger.Write(TraceEventType.Error, "Expected handler to be declared");
                }

                if (null != connectionWrapper)
                {
                    connectionWrapper.InfoMessage -= messageHandler;
                }

                if (commandWrapper != null)
                {
                    if (statementCompletedHandler == null)
                    {
                        Logger.Write(TraceEventType.Error, "Expect handler to be declared if we have a command wrapper");
                    }
                    commandWrapper.StatementCompleted -= statementCompletedHandler;
                }

                lock (this)
                {
                    state = BatchState.Initial;
                    if (command != null)
                    {
                        command.Dispose();
                        command = null;
                    }
                }
            }

            return(result);
        }
        public static SqlExecutionResult[] ExecuteTest(ConnectionContext ctx, string testSql, params DbParameter[] tsqlParameters)
        {
            if (ctx == null)
            {
                throw new AssertFailedException("The ConnectionContext cannot be null");
            }
            if (ctx.Connection == null)
            {
                throw new AssertFailedException("The connection cannot be null");
            }
            if (ctx.Provider == null)
            {
                throw new AssertFailedException("The provider factory cannot be null");
            }
            if (testSql == null)
            {
                throw new AssertFailedException("The T-SQL string cannot be null");
            }
            AssertConnectionStateValid(ConnectionState.Open, ctx.Connection.State);
            DbCommand          command              = ctx.Connection.CreateCommand();
            SqlExecutionResult result               = new SqlExecutionResult();
            int           num                       = 0;
            int           num2                      = 0;
            int           rowsAffectedCount         = 0;
            List <int>    rowsAffected              = new List <int>();
            SqlCommand    command2                  = command as SqlCommand;
            SqlConnection connection                = ctx.Connection as SqlConnection;
            SqlInfoMessageEventHandler     handler  = null;
            StatementCompletedEventHandler handler2 = null;

            if (connection != null)
            {
                handler = delegate(object sender, SqlInfoMessageEventArgs e) {
                    ProcessErrors(e.Errors);
                };
                connection.InfoMessage += handler;
            }
            if (command2 != null)
            {
                handler2 = delegate(object sender, StatementCompletedEventArgs e) {
                    rowsAffectedCount += e.RecordCount;
                    rowsAffected.Add(e.RecordCount);
                };
                command2.StatementCompleted += handler2;
            }
            try
            {
                DataSet dataSet = new DataSet
                {
                    Locale = CultureInfo.CurrentCulture
                };
                command.CommandText    = testSql;
                command.CommandType    = CommandType.Text;
                command.Transaction    = ctx.Transaction;
                command.CommandTimeout = ctx.CommandTimeout;
                if (tsqlParameters != null)
                {
                    int length = tsqlParameters.Length;
                    for (int i = 0; i < length; i++)
                    {
                        DbParameter parameter = tsqlParameters[i];
                        command.Parameters.Add(parameter);
                    }
                }
                DbDataAdapter adapter1 = ctx.Provider.CreateDataAdapter();
                adapter1.SelectCommand = command;
                DateTime now = DateTime.Now;
                adapter1.Fill(dataSet);
                DateTime time2 = DateTime.Now;
                result.DataSet       = dataSet;
                result.ExecutionTime = time2.Subtract(now);
                result.RowsAffected  = rowsAffected.ToArray();
                num++;
                num2 += dataSet.Tables.Count;
            }
            catch (SqlException exception1)
            {
                ProcessErrors(exception1.Errors);
                throw;
            }
            finally
            {
                if (connection != null)
                {
                    connection.InfoMessage -= handler;
                }
                if (command2 != null)
                {
                    command2.StatementCompleted -= handler2;
                }
            }
            PrintMessage("{0} batches, {1} ResultSets, {2} rows affected", num, num2, rowsAffectedCount);
            return(new[] { result });
        }