internal InternalEnlistment(System.Transactions.Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications, InternalTransaction transaction, System.Transactions.Transaction atomicTransaction)
 {
     this.enlistment = enlistment;
     this.twoPhaseNotifications = twoPhaseNotifications;
     this.transaction = transaction;
     this.atomicTransaction = atomicTransaction;
 }
 protected InternalEnlistment(System.Transactions.Enlistment enlistment, InternalTransaction transaction, System.Transactions.Transaction atomicTransaction)
 {
     this.enlistment = enlistment;
     this.transaction = transaction;
     this.atomicTransaction = atomicTransaction;
     this.enlistmentId = transaction.enlistmentCount++;
     this.traceIdentifier = EnlistmentTraceIdentifier.Empty;
 }
 internal InternalEnlistment(System.Transactions.Enlistment enlistment, InternalTransaction transaction, IEnlistmentNotification twoPhaseNotifications, ISinglePhaseNotification singlePhaseNotifications, System.Transactions.Transaction atomicTransaction)
 {
     this.enlistment = enlistment;
     this.transaction = transaction;
     this.twoPhaseNotifications = twoPhaseNotifications;
     this.singlePhaseNotifications = singlePhaseNotifications;
     this.atomicTransaction = atomicTransaction;
     this.enlistmentId = transaction.enlistmentCount++;
     this.traceIdentifier = EnlistmentTraceIdentifier.Empty;
 }
Example #4
0
        internal Transaction(System.Transactions.Transaction transaction, bool isAmbient)
        {
            this.internalTransaction = transaction;
            this.isAmbient = isAmbient;

            this.transactionId = Interlocked.Increment(ref transactionCounter);
            this.atomicSectionLock = new LightweightSpinLock();
            this.isolationLevel = this.MapIsolationLevel(transaction.IsolationLevel);

            this.aborted = false;

            this.registeredHandlers = new HashSet<ITransactionHandler>();

            this.internalTransaction.EnlistVolatile(this, System.Transactions.EnlistmentOptions.EnlistDuringPrepareRequired);
        }
Example #5
0
 public static byte[] GetExportCookie(System.Transactions.Transaction transaction, byte[] whereabouts)
 {
     throw null;
 }
Example #6
0
        /// <include file='docs/mysqlcommand.xml' path='docs/ExecuteReader1/*'/>
        public new MySqlDataReader ExecuteReader(CommandBehavior behavior)
        {
            // give our interceptors a shot at it first
            MySqlDataReader interceptedReader = null;

            if (connection?.commandInterceptor != null && connection.commandInterceptor.ExecuteReader(CommandText, behavior, ref interceptedReader))
            {
                return(interceptedReader);
            }

            // interceptors didn't handle this so we fall through
            bool success = false;

            CheckState();
            Driver driver = connection.driver;

            cmdText = cmdText.Trim();
            if (String.IsNullOrEmpty(cmdText))
            {
                Throw(new InvalidOperationException(Resources.CommandTextNotInitialized));
            }

            string sql = cmdText.Trim(';');

#if !NETSTANDARD1_6
            // Load balancing getting a new connection
            if (connection.hasBeenOpen && !driver.HasStatus(ServerStatusFlags.InTransaction))
            {
                ReplicationManager.GetNewConnection(connection.Settings.Server, !IsReadOnlyCommand(sql), connection);
            }
#endif

            lock (driver)
            {
                // We have to recheck that there is no reader, after we got the lock
                if (connection.Reader != null)
                {
                    Throw(new MySqlException(Resources.DataReaderOpen));
                }

#if !NETSTANDARD1_6
                System.Transactions.Transaction curTrans = System.Transactions.Transaction.Current;

                if (curTrans != null)
                {
                    bool inRollback = false;
                    //TODO: ADD support for 452 and 46X
                    if (driver.currentTransaction != null)
                    {
                        inRollback = driver.currentTransaction.InRollback;
                    }
                    if (!inRollback)
                    {
                        System.Transactions.TransactionStatus status = System.Transactions.TransactionStatus.InDoubt;
                        try
                        {
                            // in some cases (during state transitions) this throws
                            // an exception. Ignore exceptions, we're only interested
                            // whether transaction was aborted or not.
                            status = curTrans.TransactionInformation.Status;
                        }
                        catch (System.Transactions.TransactionException)
                        {
                        }
                        if (status == System.Transactions.TransactionStatus.Aborted)
                        {
                            Throw(new System.Transactions.TransactionAbortedException());
                        }
                    }
                }
#endif

                commandTimer = new CommandTimer(connection, CommandTimeout);

                LastInsertedId = -1;

                if (CommandType == CommandType.TableDirect)
                {
                    sql = "SELECT * FROM " + sql;
                }
                else if (CommandType == CommandType.Text)
                {
                    // validates single word statetment (maybe is a stored procedure call)
                    if (sql.IndexOf(" ") == -1)
                    {
                        if (AddCallStatement(sql))
                        {
                            sql = "call " + sql;
                        }
                    }
                }

                // if we are on a replicated connection, we are only allow readonly statements
                if (connection.Settings.Replication && !InternallyCreated)
                {
                    EnsureCommandIsReadOnly(sql);
                }

                if (statement == null || !statement.IsPrepared)
                {
                    if (CommandType == CommandType.StoredProcedure)
                    {
                        statement = new StoredProcedure(this, sql);
                    }
                    else
                    {
                        statement = new PreparableStatement(this, sql);
                    }
                }

                // stored procs are the only statement type that need do anything during resolve
                statement.Resolve(false);

                // Now that we have completed our resolve step, we can handle our
                // command behaviors
                HandleCommandBehaviors(behavior);

                try
                {
                    MySqlDataReader reader = new MySqlDataReader(this, statement, behavior);
                    connection.Reader = reader;
                    Canceled          = false;
                    // execute the statement
                    statement.Execute();
                    // wait for data to return
                    reader.NextResult();
                    success = true;
                    return(reader);
                }
                catch (TimeoutException tex)
                {
                    connection.HandleTimeoutOrThreadAbort(tex);
                    throw; //unreached
                }
#if !NETSTANDARD1_6
                catch (ThreadAbortException taex)
                {
                    connection.HandleTimeoutOrThreadAbort(taex);
                    throw;
                }
#endif
                catch (IOException ioex)
                {
                    connection.Abort(); // Closes connection without returning it to the pool
                    throw new MySqlException(Resources.FatalErrorDuringExecute, ioex);
                }
                catch (MySqlException ex)
                {
                    if (ex.InnerException is TimeoutException)
                    {
                        throw; // already handled
                    }
                    try
                    {
                        ResetReader();
                        ResetSqlSelectLimit();
                    }
                    catch (Exception)
                    {
                        // Reset SqlLimit did not work, connection is hosed.
                        Connection.Abort();
                        throw new MySqlException(ex.Message, true, ex);
                    }

                    // if we caught an exception because of a cancel, then just return null
                    if (ex.IsQueryAborted)
                    {
                        return(null);
                    }
                    if (ex.IsFatal)
                    {
                        Connection.Close();
                    }
                    if (ex.Number == 0)
                    {
                        throw new MySqlException(Resources.FatalErrorDuringExecute, ex);
                    }
                    throw;
                }
                finally
                {
                    if (connection != null)
                    {
                        if (connection.Reader == null)
                        {
                            // Something went seriously wrong,  and reader would not
                            // be able to clear timeout on closing.
                            // So we clear timeout here.
                            ClearCommandTimer();
                        }
                        if (!success)
                        {
                            // ExecuteReader failed.Close Reader and set to null to
                            // prevent subsequent errors with DataReaderOpen
                            ResetReader();
                        }
                    }
                }
            }
        }
Example #7
0
 public virtual void EnlistTransaction(System.Transactions.Transaction transaction)
 {
     throw ADP.NotSupported();
 }
        internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource <DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
        {
            Debug.Assert(null != owningConnection, "null owningConnection?");

            DbConnectionPoolGroup poolGroup;
            DbConnectionPool      connectionPool;

            connection = null;

            // SQLBU 431251:
            //  Work around race condition with clearing the pool between GetConnectionPool obtaining pool
            //  and GetConnection on the pool checking the pool state.  Clearing the pool in this window
            //  will switch the pool into the ShuttingDown state, and GetConnection will return null.
            //  There is probably a better solution involving locking the pool/group, but that entails a major
            //  re-design of the connection pooling synchronization, so is post-poned for now.

            // VSDD 674236: use retriesLeft to prevent CPU spikes with incremental sleep
            // start with one msec, double the time every retry
            // max time is: 1 + 2 + 4 + ... + 2^(retries-1) == 2^retries -1 == 1023ms (for 10 retries)
            int retriesLeft = 10;
            int timeBetweenRetriesMilliseconds = 1;

            do
            {
                poolGroup = GetConnectionPoolGroup(owningConnection);
                // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread.
                connectionPool = GetConnectionPool(owningConnection, poolGroup);
                if (null == connectionPool)
                {
                    // If GetConnectionPool returns null, we can be certain that
                    // this connection should not be pooled via DbConnectionPool
                    // or have a disabled pool entry.
                    poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled

                    if (retry != null)
                    {
                        Task <DbConnectionInternal> newTask;
                        CancellationTokenSource     cancellationTokenSource = new CancellationTokenSource();
                        lock (s_pendingOpenNonPooled)
                        {
                            // look for an available task slot (completed or empty)
                            int idx;
                            for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++)
                            {
                                Task task = s_pendingOpenNonPooled[idx];
                                if (task == null)
                                {
                                    s_pendingOpenNonPooled[idx] = GetCompletedTask();
                                    break;
                                }
                                else if (task.IsCompleted)
                                {
                                    break;
                                }
                            }

                            // if didn't find one, pick the next one in round-robbin fashion
                            if (idx == s_pendingOpenNonPooled.Length)
                            {
                                idx = s_pendingOpenNonPooledNext++ % s_pendingOpenNonPooled.Length;
                            }

                            // now that we have an antecedent task, schedule our work when it is completed.
                            // If it is a new slot or a compelted task, this continuation will start right away.
                            // BUG? : If we have timed out task on top of running task, then new task could be started
                            // on top of that, since we are only checking the top task. This will lead to starting more threads
                            // than intended.
                            newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) =>
                            {
                                System.Transactions.Transaction originalTransaction = ADP.GetCurrentTransaction();
                                try
                                {
                                    ADP.SetCurrentTransaction(retry.Task.AsyncState as System.Transactions.Transaction);
                                    var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
                                    if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
                                    {
                                        oldConnection.PrepareForReplaceConnection();
                                        oldConnection.Dispose();
                                    }
                                    return(newConnection);
                                }
                                finally
                                {
                                    ADP.SetCurrentTransaction(originalTransaction);
                                }
                            }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default);

                            // Place this new task in the slot so any future work will be queued behind it
                            s_pendingOpenNonPooled[idx] = newTask;
                        }

                        // Set up the timeout (if needed)
                        if (owningConnection.ConnectionTimeout > 0)
                        {
                            int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000;
                            cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds);
                        }

                        // once the task is done, propagate the final results to the original caller
                        newTask.ContinueWith((task) =>
                        {
                            cancellationTokenSource.Dispose();
                            if (task.IsCanceled)
                            {
                                retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout()));
                            }
                            else if (task.IsFaulted)
                            {
                                retry.TrySetException(task.Exception.InnerException);
                            }
                            else
                            {
                                if (retry.TrySetResult(task.Result))
                                {
                                    PerformanceCounters.NumberOfNonPooledConnections.Increment();
                                }
                                else
                                {
                                    // The outer TaskCompletionSource was already completed
                                    // Which means that we don't know if someone has messed with the outer connection in the middle of creation
                                    // So the best thing to do now is to destroy the newly created connection
                                    task.Result.DoomThisConnection();
                                    task.Result.Dispose();
                                }
                            }
                        }, TaskScheduler.Default);

                        return(false);
                    }

                    connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
                    PerformanceCounters.NumberOfNonPooledConnections.Increment();
                }
                else
                {
                    if (((SqlClient.SqlConnection)owningConnection).ForceNewConnection)
                    {
                        Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection");
                        connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection);
                    }
                    else
                    {
                        if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection))
                        {
                            return(false);
                        }
                    }

                    if (connection == null)
                    {
                        // connection creation failed on semaphore waiting or if max pool reached
                        if (connectionPool.IsRunning)
                        {
                            // If GetConnection failed while the pool is running, the pool timeout occurred.
                            Bid.Trace("<prov.DbConnectionFactory.GetConnection|RES|CPOOL> %d#, GetConnection failed because a pool timeout occurred.\n", ObjectID);
                            throw ADP.PooledOpenTimeout();
                        }
                        else
                        {
                            // We've hit the race condition, where the pool was shut down after we got it from the group.
                            // Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated
                            //  before retrying.
                            System.Threading.Thread.Sleep(timeBetweenRetriesMilliseconds);
                            timeBetweenRetriesMilliseconds *= 2; // double the wait time for next iteration
                        }
                    }
                }
            } while (connection == null && retriesLeft-- > 0);

            if (connection == null)
            {
                // exhausted all retries or timed out - give up
                Bid.Trace("<prov.DbConnectionFactory.GetConnection|RES|CPOOL> %d#, GetConnection failed because a pool timeout occurred and all retries were exhausted.\n", ObjectID);
                throw ADP.PooledOpenTimeout();
            }

            return(true);
        }
Example #9
0
        public override void EnlistTransaction(System.Transactions.Transaction transaction)
        {
            CheckClosed();

            _innerConnection.EnlistTransaction(transaction);
        }
        public override void EnlistTransaction(System.Transactions.Transaction transaction)
        {
            CheckConnection();

            _internalConnection.EnlistTransaction(transaction);
        }
 public override void EnlistTransaction(System.Transactions.Transaction transaction)
 {
     throw new NotSupportedException("System.Transactions.Transaction is not supported. Use BeginTransaction instead.");
 }
Example #12
0
 public TransactionScope(System.Transactions.Transaction transaction, System.TimeSpan timeout)
 {
 }
Example #13
0
 public TransactionScope(System.Transactions.Transaction transaction, System.TimeSpan timeout, System.Transactions.EnterpriseServicesInteropOption opt)
 {
 }
Example #14
0
 public static byte[] GetExportCookie(System.Transactions.Transaction transaction, byte[] exportCookie)
 {
     throw null;
 }
Example #15
0
 public TransactionScope(System.Transactions.Transaction transactionToUse, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption)
 {
 }
        private static Transaction CreateTransaction(System.Transactions.Transaction ambient)
        {
            ambient.TransactionCompleted += OnAmbientTransactionCompleted;

            return(new Transaction(ambient, true));
        }
        public static void RemoveTransaction(System.Transactions.Transaction ambient)
        {
            Transaction removedTransaction;

            transactions.TryRemove(ambient.TransactionInformation.LocalIdentifier, out removedTransaction);
        }
 public override void EnlistTransaction(System.Transactions.Transaction transaction)
 {
 }
Example #19
0
 /// <summary>
 /// enlist the transaction.
 /// </summary>
 /// <param name="transaction">The transaction.</param>
 public override void EnlistTransaction(System.Transactions.Transaction transaction)
 {
     _connection.EnlistTransaction(transaction);
 }
Example #20
0
 public static System.Transactions.IDtcTransaction GetDtcTransaction(System.Transactions.Transaction transaction)
 {
     return(default(System.Transactions.IDtcTransaction));
 }
        public virtual void Execute(BpmnStackTrace stackTrace)
        {
            if ((operation != PvmAtomicOperationFields.ActivityStartCancelScope) &&
                (operation != PvmAtomicOperationFields.ActivityStartInterruptScope) &&
                (operation != PvmAtomicOperationFields.ActivityStartConcurrent))
            {
                // execution might be replaced in the meantime:
                ExecutionEntity replacedBy = (ExecutionEntity)execution.ReplacedBy;
                if (replacedBy != null)
                {
                    execution = replacedBy;
                }
            }

            //execution was canceled for example via terminate end event
            if (execution.Canceled &&
                (operation == PvmAtomicOperationFields.TransitionNotifyListenerEnd ||
                 operation == PvmAtomicOperationFields.ActivityNotifyListenerEnd))
            {
                return;
            }

            //// execution might have ended in the meanwhile
            if (execution.IsEnded &&
                (operation == PvmAtomicOperationFields.TransitionNotifyListenerTake ||
                 operation == PvmAtomicOperationFields.ActivityStartCreateScope))
            {
                return;
            }
            //TODO Context.CurrentProcessApplication
            var currentPa = context.Impl.Context.CurrentProcessApplication;

            if (currentPa != null)
            {
                applicationContextName = currentPa.Name;
            }
            activityId = execution.ActivityId;
            stackTrace.Add(this);

            try
            {
                Context.SetExecutionContext(execution);
                if (!performAsync)//同步
                {
                    Log.DebugExecutingAtomicOperation(operation, execution);
                    operation.Execute(execution);
                }
                else//异步
                {
                    execution.ScheduleAtomicOperationAsync(this);
                }
            }
            catch (ClassMethodDelegateException ex)
            {
                if (execution.IsInTransaction)
                {
                    System.Transactions.Transaction tr = Context.CommandContext.CurrentTransaction;
                    Log.LogDebug("外部代码异常,事务Id:", tr.TransactionInformation.LocalIdentifier);
                    if (context.Impl.Context.CommandContext.CurrentTransaction != null)
                    {
                        Log.LogDebug("移除当前外部事务,添加到待回滚中。", context.Impl.Context.CommandContext.CurrentTransaction.TransactionInformation.LocalIdentifier);
                        context.Impl.Context.CommandContext.MoveToRollBack();
                    }
                }
                else
                {
                    Log.LogDebug("外部代码不在事务范围内,ActivityId:" + execution.ActivityId, ex.Message);
                }
            }
            //debug抛异常
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                context.Impl.Context.RemoveExecutionContext();
            }
        }
Example #22
0
 public static byte[] GetExportCookie(System.Transactions.Transaction transaction, byte[] whereabouts)
 {
     return(default(byte[]));
 }
        internal void UnenlistTransaction(ImplicitTransactionBase implicitTransaction, System.Transactions.Transaction transaction)
        {
            if (!object.ReferenceEquals(implicitTransaction, m_implicitTransaction))
            {
                throw new InvalidOperationException("Active transaction is not the one being unenlisted from.");
            }
            m_implicitTransaction = null;

            if (m_shouldCloseWhenUnenlisted)
            {
                m_shouldCloseWhenUnenlisted = false;
                Close();
            }

            // NOTE: may try to remove the same Transaction multiple times (if it spans multiple connections), which is a safe no-op
            lock (s_lock)
                s_transactionConnections.Remove(transaction);
        }
Example #24
0
 public static byte[] GetTransmitterPropagationToken(System.Transactions.Transaction transaction)
 {
     return(default(byte[]));
 }
Example #25
0
 public void EnlistTransaction(System.Transactions.Transaction transaction) => throw new NotImplementedException();
Example #26
0
 public TransactionScope(System.Transactions.Transaction transactionToUse)
 {
 }
Example #27
0
 public override void EnlistTransaction(System.Transactions.Transaction transaction)
 {
     this._WrappedConnection.EnlistTransaction(transaction);
 }
Example #28
0
 public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout)
 {
 }
Example #29
0
 public static System.Transactions.IDtcTransaction GetDtcTransaction(System.Transactions.Transaction transaction)
 {
     throw null;
 }
Example #30
0
 public void EnlistTransaction(System.Transactions.Transaction transaction)
 {
 }
Example #31
0
 public static byte[] GetTransmitterPropagationToken(System.Transactions.Transaction transaction)
 {
     throw null;
 }
		public TransactionScope(System.Transactions.Transaction curr)
		{
			prev = System.Transactions.Transaction.Current;
			System.Transactions.Transaction.Current = curr;
		}
Example #33
0
 public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout, System.Transactions.EnterpriseServicesInteropOption interopOption)
 {
 }
 public static Transaction GetAmbientEnlistedTransaction(System.Transactions.Transaction ambient)
 {
     return(transactions.GetOrAdd(ambient.TransactionInformation.LocalIdentifier, x => CreateTransaction(ambient)));
 }
Example #35
0
 public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption)
 {
 }
    /// <summary>
    /// Manual distributed transaction enlistment support
    /// </summary>
    /// <param name="transaction">The distributed transaction to enlist in</param>
    public override void EnlistTransaction(System.Transactions.Transaction transaction)
    {
      if (_transactionLevel > 0 && transaction != null)
        throw new ArgumentException("Unable to enlist in transaction, a local transaction already exists");

      if (_enlistment != null && transaction != _enlistment)
        throw new ArgumentException("Already enlisted in a transaction");

      transaction.EnlistVolatile(new SQLiteEnlistment(this), System.Transactions.EnlistmentOptions.None);

      _enlistment = transaction;
    }