public void ReturnConnectionAfterCommit()
        {
            var txTemplate = new TransactionTemplate(new RabbitTemplateTestsTransactionManager());
            var mockConnectionFactory = new Mock<ConnectionFactory>();
            var mockConnection = new Mock<IConnection>();
            var mockChannel = new Mock<IModel>();

            mockConnectionFactory.Setup(m => m.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(m => m.IsOpen).Returns(true);
            mockConnection.Setup(m => m.CreateModel()).Returns(mockChannel.Object);
            mockChannel.Setup(m => m.IsOpen).Returns(true);
            mockChannel.Setup(m => m.CreateBasicProperties()).Returns(() => new BasicProperties());

            var template = new RabbitTemplate(new CachingConnectionFactory(mockConnectionFactory.Object));
            template.ChannelTransacted = true;

            txTemplate.Execute(
                status =>
                {
                    template.ConvertAndSend("foo", "bar");
                    return null;
                });

            txTemplate.Execute(
                status =>
                {
                    template.ConvertAndSend("baz", "qux");
                    return null;
                });

            mockConnectionFactory.Verify(m => m.CreateConnection(), Times.Once());

            // ensure we used the same channel
            mockConnection.Verify(m => m.CreateModel(), Times.Once());
        }
Пример #2
0
        public void TxTemplate()
        {
            IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
            dbProvider.ConnectionString = @"Data Source=MARKT60\SQL2005;Initial Catalog=CreditsAndDebits;User ID=springqa; Password=springqa";
            //IPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager();
            //IPlatformTransactionManager tm = new TxScopeTransactionManager();
            IPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
            AdoTemplate adoTemplate = new AdoTemplate(dbProvider);

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.PropagationBehavior = TransactionPropagation.Required;
            tt.Execute(delegate(ITransactionStatus status)
                           {
                               if (System.Transactions.Transaction.Current != null) Console.WriteLine("tx 1 id = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier);
                               Console.WriteLine("tx 1 'IsNewTransaction' = " + status.IsNewTransaction);
                               adoTemplate.ExecuteNonQuery(CommandType.Text, "insert into Credits (CreditAmount) VALUES (@amount)", "amount", DbType.Decimal, 0,444);
                               TransactionTemplate tt2 = new TransactionTemplate(tm);
                               tt2.PropagationBehavior = TransactionPropagation.RequiresNew;
                               
                               tt2.Execute(delegate(ITransactionStatus status2)
                                               {
                                                   if (System.Transactions.Transaction.Current != null) Console.WriteLine("tx 2 = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier);
                                                   Console.WriteLine("tx 2 'IsNewTransaction' = " + status2.IsNewTransaction);
                                                   adoTemplate.ExecuteNonQuery(CommandType.Text, "insert into dbo.Debits (DebitAmount) VALUES (@amount)", "amount", DbType.Decimal, 0,555);
                                                   //throw new ArithmeticException("can't do the math.");
                                                   status2.SetRollbackOnly();
                                                   return null;
                                               });
                               
                               if (System.Transactions.Transaction.Current != null) Console.WriteLine("tx id1 = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier);                               
                               return null;
                           });
        }
        public void ParticipatingTransactionWithCommit()
        {
            IConnectionFactory connectionFactory = mocks.StrictMock<IConnectionFactory>();
            IConnection connection = mocks.StrictMock<IConnection>();
            ISession session = mocks.StrictMock<ISession>();

            using (mocks.Ordered())
            {
                SetupCommitExpectations(connection, connectionFactory, session);
            }

            mocks.ReplayAll();

            NmsTransactionManager tm = new NmsTransactionManager(connectionFactory);
            ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition());
            NmsTemplate nt = new NmsTemplate(connectionFactory);
            nt.Execute(new AssertSessionCallback(session));

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.Execute(delegate(ITransactionStatus status)
                           {
                               nt.Execute(new AssertSessionCallback(session));
                               return null;
                           });

            tm.Commit(ts);

            mocks.VerifyAll();
        }
        public void TransactionCommit()
        {
            ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter) mocks.CreateMock(typeof(ITransactionScopeAdapter));

            using (mocks.Ordered())
            {
                Expect.Call(txAdapter.IsExistingTransaction).Return(false);
                TransactionOptions txOptions = new TransactionOptions();
                txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
                txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None);

                Expect.Call(txAdapter.RollbackOnly).Return(false);
                txAdapter.Complete();
                txAdapter.Dispose();
            }
            mocks.ReplayAll();

            TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.Execute(status =>
                           {
                               Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
                               Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
                               return null;
                           });

            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
            Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);   

            mocks.VerifyAll();


        }
Пример #5
0
		public void NullResult()
		{
			MockTxnPlatformMgr mock = new MockTxnPlatformMgr();
			mock.SetExpectedGetTxnCallCount(1);
			mock.SetExpectedCommitCallCount(1);
			TransactionTemplate temp = new TransactionTemplate(mock);
			temp.AfterPropertiesSet();
			Assert.AreEqual( mock, temp.PlatformTransactionManager);
			Assert.IsNull( temp.Execute(new TransactionDelegate(DummyTransactionMethod) ) );
			mock.Verify();
		}
        public void NullResult()
        {
            IPlatformTransactionManager mock = MockRepository.GenerateMock<IPlatformTransactionManager>();

            TransactionTemplate temp = new TransactionTemplate(mock);
            temp.AfterPropertiesSet();
            Assert.AreEqual(mock, temp.PlatformTransactionManager);
            Assert.IsNull(temp.Execute(new TransactionDelegate(DummyTransactionMethod)));

            mock.AssertWasCalled(x => x.GetTransaction(Arg<ITransactionDefinition>.Is.Anything), constraints => constraints.Repeat.Once());
            mock.AssertWasCalled(x => x.Commit(Arg<ITransactionStatus>.Is.Anything), constraints => constraints.Repeat.Once());
        }
Пример #7
0
		public void ExecuteException()
		{
			MockTxnPlatformMgr mock = new MockTxnPlatformMgr();
			mock.SetExpectedGetTxnCallCount(1);
			mock.SetExpectedRollbackCallCount(1);
			TransactionTemplate temp = new TransactionTemplate(mock);
			try 
			{
				temp.Execute(new TransactionDelegate(DummyExceptionMethod));
				Assert.Fail("Should throw exception");
			} catch
			{
				
			}
			mock.Verify();
		}
        public void ExecuteException()
        {
            IPlatformTransactionManager mock = MockRepository.GenerateMock<IPlatformTransactionManager>();

            TransactionTemplate temp = new TransactionTemplate(mock);
            try
            {
                temp.Execute(new TransactionDelegate(DummyExceptionMethod));
            }
            catch
            {
            }

            mock.AssertWasCalled(x => x.GetTransaction(Arg<ITransactionDefinition>.Is.Anything), constraints => constraints.Repeat.Once());
            mock.AssertWasCalled(x => x.Rollback(Arg<ITransactionStatus>.Is.Anything), constraints => constraints.Repeat.Once());
        }
        public void Commit()
        {
            TxScopeTransactionManager tm = new TxScopeTransactionManager();
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);

            //tt.Name = "txName";

            Assert.AreEqual(TransactionSynchronizationState.Always, tm.TransactionSynchronization);
            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
            Assert.IsNull(TransactionSynchronizationManager.CurrentTransactionName);
            Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
            tt.Execute(CommitTxDelegate);
            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
            Assert.IsNull(TransactionSynchronizationManager.CurrentTransactionName);
            Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
        }
        public void TransactionCommit()
        {
            #region Mock Setup
            IServiceDomainAdapter txAdapter = (IServiceDomainAdapter) mocks.CreateMock(typeof (IServiceDomainAdapter));
            using (mocks.Ordered())
            {
                Expect.Call(txAdapter.IsInTransaction).Return(false);
                SimpleServiceConfig serviceConfig = new SimpleServiceConfig();
                ConfigureServiceConfig(serviceConfig, true);
                txAdapter.Enter(serviceConfig);

                //ProcessCommit - status.GlobalRollbackOnly check
                Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
                //DoCommit      - status.GlobalRollbackOnly check
                Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);

                Expect.Call(txAdapter.IsInTransaction).Return(true);
                //DoCommit      - check to call SetComplete or SetAbort
                Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
                txAdapter.SetComplete();
                Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited);

            }
            #endregion

            mocks.ReplayAll();

            ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter);
            TransactionTemplate tt = new TransactionTemplate(tm);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            tt.Execute(new TransactionDelegate(TransactionCommitMethod));

            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
            Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);

            mocks.VerifyAll();

        }
Пример #11
0
 public void ExecuteTemplate()
 {
     ITestObjectDao dao = (ITestObjectDao)ctx["NHTestObjectDao"];
     TransactionTemplate tt = new TransactionTemplate(transactionManager);
     object result = tt.Execute(new SimpleTransactionCallback(dbProvider, dao));
     TestObject to = result as TestObject;
     Assert.IsNotNull(to,"FindByName for Gabriel should not return null");
     Assert.AreEqual("Gabriel", to.Name);
 }
        private void DoTransactionWithTimeout(int timeout)
        {
            #region Mock setup

            IDbProvider dbProvider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));
            IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection));
            IDbTransaction transaction = (IDbTransaction)mocks.CreateMock(typeof(IDbTransaction));
            IDbCommand command = (IDbCommand) mocks.CreateMock(typeof (IDbCommand));

            using (mocks.Ordered())
            {
                Expect.Call(dbProvider.CreateConnection()).Return(connection);
                connection.Open();

                LastCall.On(connection).Repeat.Once();
                Expect.Call(connection.BeginTransaction(_defaultIsolationLevel)).Return(transaction);
                Expect.Call(connection.CreateCommand()).Return(command);
                command.CommandText = "some SQL statement";
                LastCall.On(command).Repeat.Once();
                if (timeout > 1)
                {
                    command.CommandTimeout = (timeout - 1);
                    transaction.Commit();
                } else
                {
                    transaction.Rollback();
                }
                LastCall.On(transaction).Repeat.Once();
                connection.Dispose();
            }

            #endregion

            mocks.ReplayAll();

            AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.TransactionTimeout = timeout;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");

            try
            {
                tt.Execute(new TransactionWithTimeoutCallback(dbProvider));
                if (timeout <= 1)
                {
                    Assert.Fail("Should have thrown TransactionTimedOutException");
                }
            } catch (TransactionTimedOutException)
            {
                if (timeout <=1 )
                {
                    //expected
                } else
                {
                    throw;
                }
            }

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");

            mocks.VerifyAll();
        }
 private static void SendUsingMessageTx(string messageQueueObjectName, MessageQueueTemplate q)
 {
     IPlatformTransactionManager txManager = new MessageQueueTransactionManager();
     TransactionTemplate transactionTemplate = new TransactionTemplate(txManager);
     transactionTemplate.Execute(status =>
                                     {
                                         if (messageQueueObjectName == null)
                                         {
                                             q.ConvertAndSend("Hello World 1");
                                             q.ConvertAndSend("Hello World 2");
                                             q.ConvertAndSend("Hello World 3");
                                         } else
                                         {
                                             q.ConvertAndSend(messageQueueObjectName, "Hello World 1");
                                             q.ConvertAndSend(messageQueueObjectName, "Hello World 2");
                                             q.ConvertAndSend(messageQueueObjectName, "Hello World 3");
                                         }
                                         return null;
                                     });
 }
        /// <summary>
        /// Does the test transaction commit with flush failure.
        /// </summary>
        /// <param name="fallbackTranslation">if set to <c>true</c> if the exception throw
        /// is of the type NHibernate.ADOException, in which case HibernateTransactionManager
        /// will 'fallback' to using the error codes in the underlying exception thrown by
        /// the provider, ie. a SqlException, MySqlException.  Otherwise, if it is 
        /// another subclass of HibernateException, then perform a direct maping as 
        /// found in SessionFactoryUtils.ConvertHibernateAccessException.</param>
        private void DoTransactionCommitWithFlushFailure(bool fallbackTranslation)
        {
            #region Mock Setup

            IDbProvider provider = new TestDbProvider();
            IDbConnection connection = mocks.StrictMock<IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session = mocks.StrictMock<ISession>();
            ITransaction transaction = mocks.StrictMock<ITransaction>();
            IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();
            
            Exception rootCause = null;
            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);
                transaction.Commit();
                Exception sqlException = new TestSqlException("mymsg", "2627");
                if (fallbackTranslation)
                {
                    //error code 2627 will map to a DataAccessIntegrity exception in sqlserver, which is the metadata
                    //used by TestDbProvider.
                    rootCause = sqlException;
                    LastCall.On(transaction).Throw(new ADOException("mymsg", sqlException));
                }
                else
                {
                    rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name");
                    LastCall.On(transaction).Throw(rootCause);
                }

                Expect.Call(adoTransaction.Connection).Return(connection);
                LastCall.On(adoTransaction).Repeat.Once();

                transaction.Rollback();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }

            #endregion

            mocks.ReplayAll();


            TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            tm.DbProvider = provider;
            tm.StubbedTransactionThatReturnsExpectedConnection = adoTransaction;

            TransactionTemplate tt = new TransactionTemplate(tm);
            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");

            IList list = new ArrayList();
            list.Add("test");
            try
            {
                tt.Execute(new TransactionCommitWithFlushFailureCallback(sessionFactory, list));
                Assert.Fail("Should have thrown DataIntegrityViolationException");
            }
            catch (DataIntegrityViolationException ex)
            {
                Assert.AreEqual(rootCause, ex.InnerException);
                Assert.IsTrue(ex.Message.IndexOf("mymsg") != -1);
            }

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");

            mocks.VerifyAll();


        }
        public void TransactionWithPropagationSupports()
        {
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session = mocks.StrictMock<ISession>();

            Expect.Call(sessionFactory.OpenSession()).Return(session);
            Expect.Call(session.FlushMode).Return(FlushMode.Never);
            session.FlushMode = FlushMode.Auto;
            LastCall.IgnoreArguments();
            session.Flush();
            LastCall.IgnoreArguments();
            session.FlushMode = FlushMode.Never;
            Expect.Call(session.FlushMode).Return(FlushMode.Never);

            mocks.ReplayAll();


            LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);
            lsfo.AfterPropertiesSet();
            ISessionFactory sfProxy = (ISessionFactory) lsfo.GetObject();
            Assert.IsNotNull(sfProxy);

            HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.PropagationBehavior = TransactionPropagation.Supports;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            tt.Execute(new TransactionWithPropagationSupportsTxCallback(sessionFactory));

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            mocks.VerifyAll();

        }
        public void ParticipatingTransactionWithRollbackOnly()
        {
            IDbConnection connection = mocks.StrictMock<IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session = mocks.StrictMock<ISession>();
            ITransaction transaction = mocks.StrictMock<ITransaction>();
            IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();

            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);

                Expect.Call(adoTransaction.Connection).Return(connection);
                LastCall.On(adoTransaction).Repeat.Once();

                transaction.Rollback();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }
            mocks.ReplayAll();


            TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            tm.StubbedTransactionThatReturnsExpectedConnection = adoTransaction;

            TransactionTemplate tt = new TransactionTemplate(tm);
            IList list = new ArrayList();
            list.Add("test");
            try
            {
                tt.Execute(new ParticipatingTransactionWithRollbackOnlyTxCallback(tt,sessionFactory,list));
                Assert.Fail("Should have thrown UnexpectedRollbackException");
            }
            catch (UnexpectedRollbackException)
            {

            }

            mocks.VerifyAll();
        }
        public void TransactionRollbackOnly()
        {            
            IDbConnection connection = mocks.StrictMock<IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session = mocks.StrictMock<ISession>();
            ITransaction transaction = mocks.StrictMock<ITransaction>();
            IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();

            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);
                Expect.Call(session.FlushMode).Return(FlushMode.Auto);
                session.Flush();
                LastCall.On(session).Repeat.Once();

                Expect.Call(adoTransaction.Connection).Return(connection);
                LastCall.On(adoTransaction).Repeat.Once();

                transaction.Rollback();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }
            mocks.ReplayAll();


            TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            tm.StubbedTransactionThatReturnsExpectedConnection = adoTransaction;

            TransactionTemplate tt = new TransactionTemplate(tm);

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Shouldn't have a thread session");

            tt.Execute(new TransactionRollbackOnlyTxCallback(sessionFactory));

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Shouldn't have a thread session");
            
            mocks.VerifyAll();
            
        }
Пример #18
0
 public void ExecuteTemplate()
 {
     TransactionTemplate tt = new TransactionTemplate(transactionManager);
     object result = tt.Execute(new SimpleTransactionCallback(dbProvider));
     Assert.AreEqual(2, (int)result);
 }
        public void TransactionRollback()
        {

            IDbProvider provider = mocks.StrictMock<IDbProvider>();
            IDbConnection connection = mocks.StrictMock<IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session = mocks.StrictMock<ISession>();
            ITransaction transaction = mocks.StrictMock<ITransaction>();
            IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();

            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);

                Expect.Call(adoTransaction.Connection).Return(connection);
                LastCall.On(adoTransaction).Repeat.Once();

                transaction.Rollback();
                LastCall.On(transaction).Repeat.Once();

                Expect.Call(session.Close()).Return(null);
            }
            mocks.ReplayAll();

            TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            tm.StubbedTransactionThatReturnsExpectedConnection = adoTransaction;

            TransactionTemplate tt = new TransactionTemplate(tm);

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");

            try
            {
                tt.Execute(new TransactionRollbackTxCallback(sessionFactory));
                Assert.Fail("Should have thrown exception");
            } catch (ArgumentException)
            {
                
            }

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
            Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
            
            mocks.VerifyAll();
        }
        public void TransactionRollback()
        {
            #region Mock Setup

            IDbProvider dbProvider = (IDbProvider) mocks.CreateMock(typeof (IDbProvider));
            IDbConnection connection = (IDbConnection) mocks.CreateMock(typeof (IDbConnection));
            IDbTransaction transaction = (IDbTransaction) mocks.CreateMock(typeof (IDbTransaction));

            using (mocks.Ordered())
            {
                Expect.Call(dbProvider.CreateConnection()).Return(connection);
                connection.Open();
                LastCall.On(connection).Repeat.Once();
                Expect.Call(connection.BeginTransaction(_defaultIsolationLevel)).Return(transaction);
                //standard tx timeout.
                transaction.Rollback();
                LastCall.On(transaction).Repeat.Once();

                connection.Dispose();
            }

            #endregion

            mocks.ReplayAll();

            AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");

            Exception ex = new ArgumentException("test exception");
            try
            {
                tt.Execute(new TransactionRollbackTxCallback(dbProvider, ex));
                Assert.Fail("Should have thrown exception");
            }
            catch (ArgumentException e)
            {
                Assert.AreEqual(ex, e);
            }

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");

            mocks.VerifyAll();
        }
        public void ParticipatingTransactionWithCommit()
        {
            IDbConnection connection = mocks.StrictMock<IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session = mocks.StrictMock<ISession>();
            ITransaction transaction = mocks.StrictMock<ITransaction>();

            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);
                Expect.Call(session.FlushMode).Return(FlushMode.Auto);
                session.Flush();
                LastCall.On(session).Repeat.Once();
                transaction.Commit();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }

            mocks.ReplayAll();

            HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            IList list = new ArrayList();
            list.Add("test");

            object result = tt.Execute(new ParticipatingTransactionWithCommitTxCallback(sessionFactory, list));
            Assert.IsTrue(result == list);

            mocks.VerifyAll();

        }
        public void TransactionWithExceptionOnBegin()
        {
            #region Mock setup
            IDbProvider dbProvider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));

            // CreateConnection is called in AdoPlatformTransactionManager.DoBegin
            Expect.Call(dbProvider.CreateConnection()).Throw(new TestSqlException("Cannot begin", "314"));

            #endregion

            mocks.ReplayAll();

            AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            try
            {
                tt.Execute(new TransactionDelegate(TransactionWithExceptionNoOp));
            } catch (CannotCreateTransactionException)
            {
                // expected
            }

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");

            mocks.VerifyAll();
        }
        public void ParticipatingTransactionWithWithNotSupported()
        {
            IDbConnection connection = mocks.StrictMock<IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session = mocks.StrictMock<ISession>();
            ITransaction transaction = mocks.StrictMock<ITransaction>();

            //using (mocks.Ordered())
            //{
                Expect.Call(sessionFactory.OpenSession()).Return(session).Repeat.Twice();
                Expect.Call(session.Connection).Return(connection);


                Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);
                Expect.Call(session.FlushMode).Return(FlushMode.Auto).Repeat.Twice();
                session.Flush();
                LastCall.On(session).Repeat.Twice();
                transaction.Commit();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null).Repeat.Once();
            //}
            mocks.ReplayAll();


            HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.PropagationBehavior = TransactionPropagation.RequiresNew;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            tt.Execute(new ParticipatingTransactionWithWithNotSupportedTxCallback(tt, sessionFactory));

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            mocks.VerifyAll();


        }
        public void TransactionWithExceptionOnRollback()
        {
            #region Mock Setup

            IDbProvider dbProvider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));
            IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection));
            IDbTransaction transaction = (IDbTransaction)mocks.CreateMock(typeof(IDbTransaction));

            using (mocks.Ordered())
            {
                Expect.Call(dbProvider.CreateConnection()).Return(connection);
                connection.Open();
                LastCall.On(connection).Repeat.Once();
                Expect.Call(connection.BeginTransaction(_defaultIsolationLevel)).Return(transaction);
                //standard tx timeout.
                transaction.Rollback();
                LastCall.On(transaction).Throw(new TestSqlException("Cannot commit", "314"));

                connection.Dispose();
            }

            #endregion

            mocks.ReplayAll();

            AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);

            try
            {
                tt.Execute(new TransactionDelegate(TransactionWithExceptionOnRollbackMethod));
            }
            catch (TransactionSystemException)
            {
                //expected
            }

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");

            mocks.VerifyAll();
        }
        public void TransactionWithPropagationSupportsAndInnerTransaction()
        {
            IDbConnection connection = mocks.StrictMock<IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session1 = mocks.StrictMock<ISession>();
            ISession session2 = mocks.StrictMock<ISession>();
            ITransaction transaction = mocks.StrictMock<ITransaction>();

            Expect.Call(sessionFactory.OpenSession()).Return(session1);
            Expect.Call(session1.Connection).Return(connection);
            Expect.Call(session1.SessionFactory).Return(sessionFactory);
            Expect.Call(session1.FlushMode).Return(FlushMode.Auto).Repeat.Twice();

            session1.Flush();
            LastCall.IgnoreArguments().Repeat.Twice();
            Expect.Call(session1.Close()).Return(null);

            Expect.Call(sessionFactory.OpenSession()).Return(session2);
            Expect.Call(session2.Connection).Return(connection).Repeat.Twice();
            Expect.Call(session2.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
            Expect.Call(session2.FlushMode).Return(FlushMode.Auto);
            session2.Flush();
            LastCall.IgnoreArguments();
            Expect.Call(session2.IsOpen).Return(true);


            transaction.Commit();
            LastCall.On(transaction).Repeat.Once();


            Expect.Call(session2.Close()).Return(null);

            mocks.ReplayAll();

            LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);
            lsfo.AfterPropertiesSet();
            ISessionFactory sfProxy = (ISessionFactory)lsfo.GetObject();
            Assert.IsNotNull(sfProxy);

            HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            
            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.PropagationBehavior = TransactionPropagation.Supports;
            TransactionTemplate tt2 = new TransactionTemplate(tm);
            tt2.PropagationBehavior = TransactionPropagation.Required;

            HibernateTemplate ht = new HibernateTemplate(sessionFactory);
            ht.TemplateFlushMode = TemplateFlushMode.Eager;
            ht.ExposeNativeSession = true;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            tt.Execute(new TransactionWithPropagationSupportsAndInnerTransactionTxCallback(tt2, sessionFactory, ht, session1, session2));

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
            
            mocks.ReplayAll();
            
        }
        public void TransactionWithIsolation()
        {
            #region Mock setup
            IDbProvider dbProvider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));
            IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection));
            IDbTransaction transaction = (IDbTransaction)mocks.CreateMock(typeof(IDbTransaction));

            using (mocks.Ordered())
            {
                Expect.Call(dbProvider.CreateConnection()).Return(connection);
                connection.Open();
                LastCall.On(connection).Repeat.Once();
                Expect.Call(connection.BeginTransaction(IsolationLevel.Serializable)).Return(transaction);
                //standard tx timeout.
                transaction.Commit();
                LastCall.On(transaction).Repeat.Once();
                connection.Dispose();
            }

            #endregion

            mocks.ReplayAll();

            AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.PropagationBehavior = TransactionPropagation.RequiresNew;
            tt.TransactionIsolationLevel = IsolationLevel.Serializable;
            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");

            tt.Execute(new TransactionCommitTxCallback(dbProvider));

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");

            mocks.VerifyAll();
        }
        public void TransactionCommit()
        {
            IDbProvider provider = mocks.StrictMock<IDbProvider>();
            IDbConnection connection = mocks.StrictMock<IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
            ISession session = mocks.StrictMock<ISession>();
            ITransaction transaction = mocks.StrictMock<ITransaction>();
            IQuery query = mocks.StrictMock<IQuery>();

            IList list = new ArrayList();
            list.Add("test");
            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.Serializable)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);
                Expect.Call(session.CreateQuery("some query string")).Return(query);
                Expect.Call(query.List()).Return(list);
                transaction.Commit();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }

            mocks.ReplayAll();


            LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);
            lsfo.AfterPropertiesSet();

            ISessionFactory sfProxy = lsfo.GetObject() as ISessionFactory;
            Assert.IsNotNull(sfProxy);

            HibernateTransactionManager tm = new HibernateTransactionManager();
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            tm.AdoExceptionTranslator = new FallbackExceptionTranslator();
            tm.SessionFactory = sfProxy;
            tm.DbProvider = provider;
            TransactionTemplate tt = new TransactionTemplate(tm);

            tt.TransactionIsolationLevel = IsolationLevel.Serializable;

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sfProxy),"Hasn't thread session");
            Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
            Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active");

            object result = tt.Execute(new TransactionCommitTxCallback(sfProxy, provider));

            Assert.IsTrue(result == list, "Incorrect result list");

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sfProxy), "Hasn't thread session");
            Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
            Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active");


            mocks.VerifyAll();

        }
        public void TransactionWithPropagationNestedAndRollback()
        {
            #region Mock setup
            IDbProvider dbProvider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));
            IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection));
            IDbTransaction transaction = (IDbTransaction)mocks.CreateMock(typeof(IDbTransaction));

            using (mocks.Ordered())
            {
                Expect.Call(dbProvider.CreateConnection()).Return(connection);
                connection.Open();
                LastCall.On(connection).Repeat.Once();
                Expect.Call(connection.BeginTransaction(_defaultIsolationLevel)).Return(transaction);
                transaction.Rollback();
                LastCall.On(transaction).Repeat.Once();
                connection.Dispose();
            }

            #endregion

            mocks.ReplayAll();

            AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.PropagationBehavior = TransactionPropagation.Nested;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");

            tt.Execute(new TransactionDelegate(TransactionWithPropagationNestedAndRollbackMethod));

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");
            mocks.VerifyAll();
        }
 private static void SendUsingMessageTxScope(MessageQueueTemplate q)
 {
     IPlatformTransactionManager txManager = new TxScopeTransactionManager();
     TransactionTemplate transactionTemplate = new TransactionTemplate(txManager);
     transactionTemplate.Execute(status =>
                                     {
                                         q.ConvertAndSend("Hello World 1");
                                         q.ConvertAndSend("Hello World 2");
                                         q.ConvertAndSend("Hello World 3");
                                         return null;
                                     });
 }
        public void TransactionWithPropagationSupports()
        {
            IDbProvider dbProvider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));

            mocks.ReplayAll();

            AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.PropagationBehavior = TransactionPropagation.Supports;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");

            tt.Execute(new TransactionWithPropagationSupportsCallback(dbProvider));

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");
            mocks.VerifyAll();
        }