예제 #1
0
        public void Vol2_Dur1_Fail4()
        {
            IntResourceManager[] irm = new IntResourceManager[2];
            irm[0] = new IntResourceManager(1);
            irm[1] = new IntResourceManager(3);

            irm[0].Type              = ResourceManagerType.Durable;
            irm[0].FailSPC           = true;
            irm[0].FailWithException = true;

            for (int i = 0; i < 2; i++)
            {
                irm[i].UseSingle = true;
            }

            /* Durable RM irm[2] does on SPC, so
             * all volatile RMs get Rollback */
            TransactionAbortedException e = Assert.Throws <TransactionAbortedException>(() =>
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    irm[0].Value = 2;
                    irm[1].Value = 6;

                    scope.Complete();
                }
            });

            Assert.IsType <NotSupportedException>(e.InnerException);

            irm[0].Check(1, 0, 0, 0, 0, 0, 0, "irm [0]");
            irm[1].Check(0, 1, 0, 1, 0, 0, 0, "irm [1]");
        }
예제 #2
0
        public async Task NestedTransaction_InnerTransactionNotCommitted()
        {
            // arrange
            IMongoDatabase          database   = _mongoResource.CreateDatabase();
            IMongoCollection <User> collection =
                database.GetCollection <User>("users").AsTransactionCollection();

            // act
            TransactionAbortedException ex = await Assert.ThrowsAsync <TransactionAbortedException>(
                async() =>
            {
                using (var scope = new TransactionScope(Enabled))
                {
                    User user1 = new(Guid.NewGuid(), "Foo1");
                    await collection.InsertOneAsync(user1);

                    using (var innerScope =
                               new TransactionScope(Enabled))
                    {
                        User user2 =
                            new(Guid.NewGuid(), "Foo2");
                        await collection.InsertOneAsync(user2);
                    }

                    scope.Complete();
                }
            });

            // assert
            Assert.Equal("The transaction has aborted.", ex.Message);
            Assert.Empty(await collection.Find(FilterDefinition <User> .Empty).ToListAsync());
        }
예제 #3
0
        [OuterLoop] // 30 second timeout
        public void RMFail2()
        {
            IntResourceManager irm  = new IntResourceManager(1);
            IntResourceManager irm2 = new IntResourceManager(10);
            IntResourceManager irm3 = new IntResourceManager(12);

            Assert.Null(Transaction.Current);
            TransactionAbortedException e = Assert.Throws <TransactionAbortedException>(() =>
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 0, 10)))
                {
                    irm.Value  = 2;
                    irm2.Value = 20;
                    irm3.Value = 24;

                    /* irm2 won't call Prepared or ForceRollback in
                     * its Prepare (), so TransactionManager will timeout
                     * waiting for it
                     */
                    irm2.IgnorePrepare = true;
                    scope.Complete();
                }
            });

            Assert.NotNull(e.InnerException);
            Assert.IsType <TimeoutException>(e.InnerException);
            Assert.Null(Transaction.Current);
        }
        internal OletxDependentTransaction DependentClone(bool delayCommit)
        {
            OletxDependentTransaction transaction = null;

            if (DiagnosticTrace.Verbose)
            {
                MethodEnteredTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), "OletxTransaction.DependentClone");
            }
            if (TransactionStatus.Aborted == this.Status)
            {
                throw TransactionAbortedException.Create(System.Transactions.SR.GetString("TraceSourceOletx"), this.realOletxTransaction.innerException);
            }
            if (TransactionStatus.InDoubt == this.Status)
            {
                throw TransactionInDoubtException.Create(System.Transactions.SR.GetString("TraceSourceOletx"), this.realOletxTransaction.innerException);
            }
            if (this.Status != TransactionStatus.Active)
            {
                throw TransactionException.Create(System.Transactions.SR.GetString("TraceSourceOletx"), System.Transactions.SR.GetString("TransactionAlreadyOver"), null);
            }
            transaction = new OletxDependentTransaction(this.realOletxTransaction, delayCommit);
            if (DiagnosticTrace.Verbose)
            {
                MethodExitedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), "OletxTransaction.DependentClone");
            }
            return(transaction);
        }
        private void MapTxExceptionToHR(TransactionException txException, bool isInCommit)
        {
            TransactionAbortedException exception = txException as TransactionAbortedException;

            if (exception != null)
            {
                if (isInCommit)
                {
                    TransactionProxyException.ThrowTransactionProxyException(-2147164158, exception);
                }
                else
                {
                    TransactionProxyException.ThrowTransactionProxyException(-2147164157, exception);
                }
            }
            TransactionManagerCommunicationException exception2 = txException as TransactionManagerCommunicationException;

            if (exception2 != null)
            {
                TransactionProxyException.ThrowTransactionProxyException(-2147164145, exception2);
            }
            COMException baseException = txException.GetBaseException() as COMException;

            if (baseException != null)
            {
                TransactionProxyException.ThrowTransactionProxyException(baseException.ErrorCode, txException);
            }
            else
            {
                TransactionProxyException.ThrowTransactionProxyException(-2147418113, txException);
            }
        }
예제 #6
0
        public void Vol2_Dur1_Fail2b()
        {
            TransactionAbortedException exception = null;

            IntResourceManager[] irm = new IntResourceManager[4];
            irm[0] = new IntResourceManager(1);
            irm[1] = new IntResourceManager(3);
            irm[2] = new IntResourceManager(5);
            irm[3] = new IntResourceManager(7);

            irm[0].IgnoreSPC = true;
            irm[1].Type      = ResourceManagerType.Durable;

            for (int i = 0; i < 4; i++)
            {
                irm[i].UseSingle = true;
            }

            /* Durable RM irm[2] does on SPC, so
             * all volatile RMs get Rollback */
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 0, 5)))
                {
                    irm[0].Value = 2;
                    irm[1].Value = 6;
                    irm[2].Value = 10;
                    irm[3].Value = 14;

                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                irm[0].CheckSPC("irm [0]");

                /* Volatile RMs get 2PC Prepare, and then get rolled back */
                for (int i = 1; i < 4; i++)
                {
                    irm[i].Check(0, 1, 0, 1, 0, 0, 0, "irm [" + i + "]");
                }

                exception = ex;
            }

            Assert.IsNotNull(exception, "Expected TransactionAbortedException not thrown!");
            Assert.IsNotNull(exception.InnerException, "TransactionAbortedException has no inner exception!");
            Assert.AreEqual(typeof(TimeoutException), exception.InnerException.GetType());
        }
예제 #7
0
        public void Vol2_Dur1_Fail5()
        {
            CommittableTransaction ct = new CommittableTransaction();

            IntResourceManager[] irm = new IntResourceManager[2];
            irm[0] = new IntResourceManager(1);
            irm[1] = new IntResourceManager(3);

            Transaction.Current      = ct;
            irm[0].Type              = ResourceManagerType.Durable;
            irm[0].FailSPC           = true;
            irm[0].FailWithException = true;

            for (int i = 0; i < 2; i++)
            {
                irm[i].UseSingle = true;
            }

            /* Durable RM irm[2] does on SPC, so
             * all volatile RMs get Rollback */

            using (TransactionScope scope = new TransactionScope())
            {
                irm[0].Value = 2;
                irm[1].Value = 6;

                scope.Complete();
            }

            TransactionAbortedException tae = Assert.Throws <TransactionAbortedException>(() => ct.Commit());

            Assert.IsType <NotSupportedException>(tae.InnerException);

            irm[0].Check(1, 0, 0, 0, 0, 0, 0, "irm [0]");
            irm[1].Check(0, 1, 0, 1, 0, 0, 0, "irm [1]");

            InvalidOperationException ioe = Assert.Throws <InvalidOperationException>(() => ct.Commit());

            Assert.Null(ioe.InnerException);

            Transaction.Current = null;
        }
예제 #8
0
 public override void TransactionAbortedExceptionHandler(TransactionAbortedException ex)
 {
     MessageBox.Show(ex.Message, "Ошибка транзакции", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
예제 #9
0
 public abstract void TransactionAbortedExceptionHandler(TransactionAbortedException ex);
 /// <summary>
 /// IUnitOfWork instance Id: {0} with transaction Id: {1} has failed to commit due to the following exception(s): {2}
 /// </summary>
 /// <param name="unitOfWorkId">The unit of work id.</param>
 /// <param name="transactionIdentifier">The transaction identifier.</param>
 /// <param name="exception">The exception.</param>
 /// <returns>NContextPersistenceError.</returns>
 public static NContextPersistenceError CommitFailed(Guid unitOfWorkId, String transactionIdentifier, TransactionAbortedException exception)
 {
     return(new NContextPersistenceError("CommitFailed", unitOfWorkId, transactionIdentifier, String.Join(Environment.NewLine, exception.ToError().Messages)));
 }
예제 #11
0
        /// <summary>
        /// Execute um script e executa o commit somnete de todas as instruções forem executadas com sucesso.
        /// </summary>
        /// <param name="querySql"></param>
        /// <param name="taskLogDelegate">Metódo anônimo</param>
        /// <returns>true se executado com sucesso caso contrário false</returns>
        public bool ExecuteNonQueryTransaction(string querySql, Delegate taskLogDelegate)
        {
            Dictionary <string, bool> statusScripts = new Dictionary <string, bool>();

            var tso = new TransactionOptions()
            {
                IsolationLevel = System.Transactions.IsolationLevel.Serializable
            };

            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, tso))
            {
                try
                {
                    //open connection
                    OpenConnection();

                    // split script on GO command
                    List <SqlCommand> commands = SplitCommandFromGo(querySql);

                    //cria a transacao
                    this.Transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted, "myTransaction");

                    SqlException sqlException = null;

                    //executando cada script quebrado no comando GO
                    foreach (SqlCommand command in commands)
                    {
                        string commandString = command.CommandText;

                        try
                        {
                            command.Connection  = this.connection;
                            command.Transaction = this.Transaction;
                            StringBuilder queryLog = new StringBuilder();
                            queryLog.Append("Preparing Command: ...\n");
                            queryLog.Append("--============================================================================\n");
                            queryLog.Append(commandString);
                            queryLog.Append("\n");
                            queryLog.Append("--============================================================================");
                            //delay for log screen
                            Thread.Sleep(10);
                            //passa o parametro e dispara o delegate
                            taskLogDelegate.DynamicInvoke(queryLog.ToString());

                            //inicia a transação
                            var result = command.BeginExecuteNonQuery();

                            //executa do comando
                            command.EndExecuteNonQuery(result);

                            //query executed sucessful
                            if (result.IsCompleted)
                            {
                                //salva o comando executado
                                statusScripts.Add(commandString, result.IsCompleted);
                            }
                        }
                        catch (SqlException sqlex)
                        {
                            //registra o log
                            sqlException = sqlex;
                            //guarda a ref pro erro
                            statusScripts.Add(commandString, false);
                        }
                    }


                    //se tudo deu ok
                    if (statusScripts.Count(s => s.Value == false) == 0)
                    {
                        //avisa o banco da transação
                        this.Transaction.Commit();

                        //transaction complete
                        ts.Complete();

                        //encerra a conexão
                        CloseConnection();

                        //log
                        var queryLog = new StringBuilder();
                        queryLog.Append("Executing Query ...\n");

                        //limpa o log builder
                        queryLog.Clear();

                        queryLog.Append("============================================================================\n");
                        queryLog.Append("Query executed sucessfully !\n");
                        queryLog.Append("============================================================================\n");

                        //passa o parametro e dispara o delegate
                        taskLogDelegate.DynamicInvoke(queryLog.ToString());

                        return(true);
                    }
                    else
                    {
                        //desafaz as alterações
                        this.Transaction.Rollback();

                        //recupera o comando que falhou
                        string command = statusScripts.FirstOrDefault(s => s.Value == false)
                                         .ToString();

                        //message
                        string errorMessage = LoggerUtilIts.GetInnerException(sqlException);

                        //exceção interna
                        Exception innerException = new Exception(command);

                        //cria a exceção a ser lançada
                        TransactionAbortedException transactionAborted =
                            new TransactionAbortedException(errorMessage, innerException);


                        var log = new StringBuilder();
                        log.Append("****************************************************************************\n");
                        log.Append("Erro: ");
                        log.Append(errorMessage);
                        log.Append("\n****************************************************************************\n");

                        //passa o parametro e dispara o delegate
                        taskLogDelegate.DynamicInvoke(log.ToString());

                        //transaction aborted
                        throw transactionAborted;
                    }
                }
                catch (TransactionAbortedException tae)
                {
                    //transaction aborted
                    throw tae;
                }
                catch (Exception ex)
                {
                    StringBuilder logScreen = new StringBuilder("Falha durante a transação.");
                    logScreen.Append("Mensagem: " + LoggerUtilIts.GetInnerException(ex));

                    //others errors
                    throw new Exception(logScreen.ToString(), ex);
                }
            }
        }