Exemplo n.º 1
0
 public static void Transaction(Action action)
 {
     using (GlobalTransactionManager.BeginTransaction())
     {
         action();
     }
 }
Exemplo n.º 2
0
 public void BasicTransactionCommitt()
 {
     using (GlobalTransactionManager.BeginTransaction())
     {
         Int32 count = DataAccess.CreateQuery("Insert into FirstTable (field1, field2) values (1, 'test')").ExecuteNonQuery();
         Assert.That(count, Is.EqualTo(1));
     }
     DbAssert.OnQuery("Select count(*) cnt from FirstTable").That("cnt", Is.EqualTo(1)).ExecuteAssert();
 }
        public void ContextNestedWithTwoTransactionLast()
        {
            GlobalTransactionManager.BeginTransaction();
            GlobalTransactionManager.BeginTransaction();

            GlobalTransactionManager.TransactionToken token = GlobalTransactionManager.Enlist(Nope);
            GlobalTransactionManager.TransactionContext.Set("key", "test", 1);
            Assert.That(token.GetFromTransactionContext("key"), Is.EqualTo("test"));
        }
        public void VerifyThatSessionIsDisposedWhenRollbackOccurredEvenIfCreatedOutsideTransaction()
        {
            ISession session1 = NHibernateSessionManager.GetSessionFor("files\\NhConfigFile1.cfg.xml");

            using (GlobalTransactionManager.BeginTransaction())
            {
                GlobalTransactionManager.DoomCurrentTransaction();
            }
            Assert.That(session1.IsOpen, Is.False);
        }
Exemplo n.º 5
0
        /// <summary>
        /// This is the Connetion creation function, this function should enlist in the
        /// current transaction as well reusing the same connection for all the call
        /// inside a global transaction to consume less resources.
        /// </summary>
        /// <param name="connectionName"></param>
        /// <returns></returns>
        internal static GlobalTransactionManager.TransactionToken CreateConnection(string connectionName)
        {
            ConnectionData newConnData = null;

            if (GlobalTransactionManager.IsInTransaction)
            {
                //We are in a transaction, check if at current connection stack level there is  a connection data.
                Object connData = GlobalTransactionManager.TransactionContext.Get(GetKeyFromConnName(connectionName));
                if (null != connData)
                {
                    //We already created the connection for this database in this transaction.
                    return(GlobalTransactionManager.Enlist(DoNothing));
                }
                //There is not a transaction in the current transaction stack level, are we in nested transaction?
                if (GlobalTransactionManager.TransactionsCount > 1)
                {
                    //The only connection data valid is the one at the first level, lets check if it is present.
                    connData = GlobalTransactionManager.TransactionContext.Get(GetKeyFromConnName(connectionName), 0);
                    if (null == connData)
                    {
                        //We never created the connection data
                        newConnData = new ConnectionData(connectionName);
                        GlobalTransactionManager.TransactionContext.Set(GetKeyFromConnName(connectionName), newConnData, 0);
                        GlobalTransactionManager.Enlist(newConnData.CloseConnection, 0);
                    }
                    else
                    {
                        newConnData = (ConnectionData)connData;
                    }

                    GlobalTransactionManager.TransactionToken lasttoken = null;
                    //Now we have the connection data, we need to store this connection data in each connection that is active and
                    //that still not have start a transaction
                    for (Int32 Ix = 1; Ix < GlobalTransactionManager.TransactionsCount; ++Ix)
                    {
                        if (GlobalTransactionManager.TransactionContext.Get(GetKeyFromConnName(connectionName), Ix) == null)
                        {
                            //In this step of the stack there is no ConnectionData, store and increase the transaction
                            newConnData.BeginNestedTransaction();
                            lasttoken = GlobalTransactionManager.Enlist(newConnData.CloseConnection, Ix);
                            lasttoken.SetInTransactionContext(GetKeyFromConnName(connectionName), newConnData);
                        }
                    }
                    //Return the last token, the one corresponding to the current transaction level.
                    return(lasttoken);
                }
            }

            //We are not in nested transaction and there is not connection data, create for the first time
            newConnData = new ConnectionData(connectionName);
            GlobalTransactionManager.TransactionToken token =
                GlobalTransactionManager.Enlist(newConnData.CloseConnection);
            token.SetInTransactionContext(GetKeyFromConnName(connectionName), newConnData);
            return(token);
        }
        public void GoodTransactionIsCommitted()
        {
            Action <Boolean> mock = mockRepository.CreateMock <Action <Boolean> >();

            mock(true);             //Sets the expectation
            mockRepository.ReplayAll();
            using (GlobalTransactionManager.BeginTransaction())
            {
                GlobalTransactionManager.Enlist(mock);
            }
        }
        public void VerifyTransactionClosedDoomedFalse()
        {
            ITranEvSink mock = mockRepository.CreateMock <ITranEvSink>();

            Expect.Call(() => mock.Handle(null, null))
            .Constraints(RhinoIs.Null(), RhinoIs.Matching <TransactionClosedEventArgs>(args => args.IsDoomed == false));
            GlobalTransactionManager.TransactionClosed += mock.Handle;
            ExecuteAtTheEndOfTest(() => GlobalTransactionManager.TransactionClosed -= mock.Handle);
            mockRepository.ReplayAll();
            GlobalTransactionManager.BeginTransaction().Dispose();
        }
        public void DoomedTransactionIsRollbacked()
        {
            Action <Boolean> mock = mockRepository.CreateMock <Action <Boolean> >();

            mock(false);             //Sets the expectation
            mockRepository.ReplayAll();
            using (GlobalTransactionManager.BeginTransaction())
            {
                GlobalTransactionManager.Enlist(mock);
                GlobalTransactionManager.DoomCurrentTransaction();
            }
        }
        public void VerifyTransactionClosed()
        {
            ITranEvSink mock = mockRepository.CreateMock <ITranEvSink>();

            Expect.Call(() => mock.Handle(null, EventArgs.Empty))
            .IgnoreArguments()
            .Callback(new Func <Object, EventArgs, Boolean>((sender, e) => GlobalTransactionManager.TransactionsCount == 0));
            GlobalTransactionManager.TransactionClosed += mock.Handle;
            ExecuteAtTheEndOfTest(() => GlobalTransactionManager.TransactionClosed -= mock.Handle);
            mockRepository.ReplayAll();
            GlobalTransactionManager.BeginTransaction().Dispose();
        }
        public void EnlistWithoutATransaction()
        {
            Action <Boolean> mock = mockRepository.CreateMock <Action <Boolean> >();

            mock(true);             //Sets the expectation
            mockRepository.ReplayAll();
            using (GlobalTransactionManager.Enlist(mock))
            {
                //Do something, the important thing is that the delegate is called because we have
                //not a transaction active.
            }
        }
        public void EnlistNestedWithTwoTransactionDisposeTwo()
        {
            Action <Boolean> mock = mockRepository.CreateMock <Action <Boolean> >();

            Expect.Call(() => mock(true)).Repeat.Once();             //Sets the expectation
            mockRepository.ReplayAll();
            IDisposable first  = GlobalTransactionManager.BeginTransaction();
            IDisposable second = GlobalTransactionManager.BeginTransaction();

            GlobalTransactionManager.Enlist(mock, 0);
            GlobalTransactionManager.Enlist(mock, 1);
            second.Dispose();
        }
        public void VerifyTransactionClosingDoomedTrue()
        {
            ITranEvSink mock = mockRepository.CreateMock <ITranEvSink>();

            Expect.Call(() => mock.Handle(null, null))
            .Constraints(RhinoIs.Null(), RhinoIs.Matching <TransactionClosingEventArgs>(args => args.IsDoomed == true));
            GlobalTransactionManager.TransactionClosing += mock.Handle;
            ExecuteAtTheEndOfTest(() => GlobalTransactionManager.TransactionClosing -= mock.Handle);
            mockRepository.ReplayAll();
            using (GlobalTransactionManager.BeginTransaction())
            {
                GlobalTransactionManager.DoomCurrentTransaction();
            }
        }
        public void EnlistNestedWithTwoTransaction()
        {
            Action <Boolean> mock = mockRepository.CreateMock <Action <Boolean> >();

            Expect.Call(() => mock(true)).Repeat.Twice();             //Sets the expectation
            mockRepository.ReplayAll();
            using (GlobalTransactionManager.BeginTransaction())
            {
                using (GlobalTransactionManager.BeginTransaction())
                {
                    GlobalTransactionManager.Enlist(mock, 0);
                    GlobalTransactionManager.Enlist(mock, 1);
                }
            }
        }
Exemplo n.º 14
0
 public void DistinctDbTransactionAccessInTransaction()
 {
     using (GlobalTransactionManager.BeginTransaction())
     {
         DataAccess.CreateQuery("Insert into FirstTable (field1, field2) values (1, 'test')")
         .ExecuteNonQuery();
         DataAccess.OnDb("secondary")
         .CreateQuery("Insert into SecondaryFirstTable (field1, field2) values (1, 'test')")
         .ExecuteNonQuery();
         //VErify that in transaction all data is queryable
         DbAssert.OnQuery("Select count(*) cnt from FirstTable").That("cnt", Is.EqualTo(1)).ExecuteAssert();
         DbAssert.OnDb("secondary").WithQuery("Select count(*) cnt from SecondaryFirstTable").That("cnt", Is.EqualTo(1)).ExecuteAssert();
         GlobalTransactionManager.DoomCurrentTransaction();
     }
 }
        public void IgnoreExceptionWhenCommitt()
        {
            Action <Boolean> mock1 = mockRepository.CreateMock <Action <Boolean> >();

            mock1(true);             //Sets the expectation
            LastCall.Throw(new ApplicationException());
            Action <Boolean> mock2 = mockRepository.CreateMock <Action <Boolean> >();

            mock2(true);             //Sets the expectation
            mockRepository.ReplayAll();
            using (GlobalTransactionManager.BeginTransaction())
            {
                GlobalTransactionManager.Enlist(mock1);
                GlobalTransactionManager.Enlist(mock2);
            }
        }
        public void TestEnlistInGlobalTransaction()
        {
            Int32 insertedId;

            using (GlobalTransactionManager.BeginTransaction())
            {
                using (ISession session = NHibernateSessionManager.GetSessionFor("files\\NhConfigFile1.cfg.xml"))
                {
                    AnEntity e = AnEntity.CreateSome();
                    insertedId = (Int32)session.Save(e);
                }
                GlobalTransactionManager.DoomCurrentTransaction();
            }
            DbAssert.OnQuery("select count(*) cnt from AnEntity where id = {id}")
            .SetInt32Param("id", insertedId)
            .That("cnt", Is.EqualTo(0)).ExecuteAssert();
        }
Exemplo n.º 17
0
 public void MultipleTransactionRollbackAndCommit()
 {
     using (GlobalTransactionManager.BeginTransaction())
     {
         using (GlobalTransactionManager.BeginTransaction())
         {
             DataAccess.CreateQuery("Insert into FirstTable (field1, field2) values (1, 'test1')").ExecuteNonQuery();
             GlobalTransactionManager.DoomCurrentTransaction();
         }
         DataAccess.CreateQuery("Insert into FirstTable (field1, field2) values (1, 'test2')").ExecuteNonQuery();
     }
     //inner transaction is rollbacked, but the external one no, so I should see second row
     DbAssert.OnQuery("Select count(*) cnt from FirstTable")
     .That("cnt", Is.EqualTo(1)).ExecuteAssert();
     DbAssert.OnQuery("Select field2 from FirstTable")
     .That("field2", Is.EqualTo("test2")).ExecuteAssert();
 }
        public void TestEnlistInGlobalTransactionRead()
        {
            Int32 insertedId;

            using (GlobalTransactionManager.BeginTransaction())
            {
                using (ISession session = NHibernateSessionManager.GetSessionFor("files\\NhConfigFile1.cfg.xml"))
                {
                    AnEntity e = AnEntity.CreateSome();
                    insertedId = (Int32)session.Save(e);
                }
                //We are still in the transaction, ensure we can read the db in the same transaction
                DbAssert.OnDb("main").WithQuery("select count(*) cnt from AnEntity where id = {id}")
                .SetInt32Param("id", insertedId)
                .That("cnt", Is.EqualTo(1)).ExecuteAssert();
            }
        }
Exemplo n.º 19
0
 public void MultipleTransactionBothRollback()
 {
     using (GlobalTransactionManager.BeginTransaction())
     {
         using (GlobalTransactionManager.BeginTransaction())
         {
             Int32 count = DataAccess.CreateQuery("Insert into FirstTable (field1, field2) values (1, 'test1')").ExecuteNonQuery();
             Assert.That(count, Is.EqualTo(1));
         }
         using (GlobalTransactionManager.BeginTransaction())
         {
             Int32 count = DataAccess.CreateQuery("Insert into FirstTable (field1, field2) values (2, 'test2')").ExecuteNonQuery();
             Assert.That(count, Is.EqualTo(1));
         }
         GlobalTransactionManager.DoomCurrentTransaction();
     }
     DbAssert.OnQuery("Select count(*) cnt from FirstTable").That("cnt", Is.EqualTo(0)).ExecuteAssert();
 }
Exemplo n.º 20
0
 public void MultipleTransactionSeeDataCommittedInNested()
 {
     using (GlobalTransactionManager.BeginTransaction())
     {
         using (GlobalTransactionManager.BeginTransaction())
         {
             Int32 count = DataAccess.CreateQuery("Insert into FirstTable (field1, field2) values (1, 'test1')").ExecuteNonQuery();
             Assert.That(count, Is.EqualTo(1));
         }
         //First transaction is committed I should see data into db
         GlobalTransactionManager.DoomCurrentTransaction();
         DbAssert.OnQuery("Select count(*) cnt from FirstTable")
         .That("cnt", Is.EqualTo(1)).ExecuteAssert();
     }
     //Transaction is doomed, so the row disappeared
     DbAssert.OnQuery("Select count(*) cnt from FirstTable")
     .That("cnt", Is.EqualTo(0)).ExecuteAssert();
 }
        public void ImplicitTransactionIsDoomedIfExceptionIsThrown()
        {
            Action <Boolean> mock = mockRepository.CreateMock <Action <Boolean> >();

            mock(false);             //Sets the expectation
            mockRepository.ReplayAll();
            try
            {
                using (GlobalTransactionManager.BeginTransaction())
                {
                    GlobalTransactionManager.Enlist(mock);
                    throw new ApplicationException();
                }
            }
            catch (ApplicationException)
            {
                //Ok we catch the exception but the inner using is exited inside an application handler.
            }
        }
        public void LogExceptionWhenCommitt()
        {
            Action <Boolean> mock1 = mockRepository.CreateMock <Action <Boolean> >();
            Exception        ex    = new ArgumentException();

            Expect.Call(() => mock1(true)).Throw(ex);             //Sets the expectation
            ILogger mockLogger = mockRepository.CreateMock <ILogger>();

            Expect.Call(mockLogger.ActualLevel).Repeat.Any().Return(LogLevel.Info);
            Expect.Call(() => mockLogger.LogError("", ex))
            .Constraints(RhinoIs.Anything(), RhinoIs.Equal(ex));
            mockRepository.ReplayAll();
            using (Logger.Override(mockLogger))
            {
                using (GlobalTransactionManager.BeginTransaction())
                {
                    GlobalTransactionManager.Enlist(mock1);
                }
            }
        }
        public void TestEnlistInGlobalTransactionReadDataAccessWrittenData()
        {
            Int32 insertedId;

            using (GlobalTransactionManager.BeginTransaction())
            {
                Int32 newId = GetNewId();
                DataAccess.OnDb("main")
                .CreateQuery("insert into AnEntity (id, name, value) values ({pid}, {pname}, {pvalue})")
                .SetInt32Param("pid", newId)
                .SetStringParam("pname", "xxx")
                .SetInt32Param("pvalue", 108)
                .ExecuteNonQuery();
                using (ISession session = NHibernateSessionManager.GetSessionFor("files\\NhConfigFile1.cfg.xml"))
                {
                    AnEntity e = session.Load <AnEntity>(newId);
                    Assert.That(e.Name, Is.EqualTo("xxx"));
                    Assert.That(e.Value, Is.EqualTo(108));
                }
            }
        }
Exemplo n.º 24
0
        public void DistinctDbTransactionExceptionRollback()
        {
            try
            {
                using (GlobalTransactionManager.BeginTransaction())
                {
                    Int32 count = DataAccess.CreateQuery("Insert into FirstTable (field1, field2) values (1, 'test')").ExecuteNonQuery();
                    Assert.That(count, Is.EqualTo(1));
                    count = DataAccess.OnDb("secondary")
                            .CreateQuery("Insert into SecondaryFirstTable (field1, field2) values (1, 'test')")
                            .ExecuteNonQuery();
                    Assert.That(count, Is.EqualTo(1));
                    throw new ApplicationException();
                }
            } catch
            {
            }

            DbAssert.OnQuery("Select count(*) cnt from FirstTable").That("cnt", Is.EqualTo(0)).ExecuteAssert();
            DbAssert.OnDb("secondary").WithQuery("Select count(*) cnt from SecondaryFirstTable").That("cnt", Is.EqualTo(0)).ExecuteAssert();
        }
        public void TestSessionCanWorkWhenTransactionIsClosed()
        {
            Int32 insertedId;

            using (ISession session = NHibernateSessionManager.GetSessionFor("files\\NhConfigFile1.cfg.xml"))
            {
                using (GlobalTransactionManager.BeginTransaction())
                {
                    AnEntity e = AnEntity.CreateSome();
                    session.Save(e);
                    session.Flush();
                }
                //Now the transaction is closed, session still need to work correctly
                AnEntity e1 = AnEntity.CreateSome();
                insertedId = (Int32)session.Save(e1);
                session.Flush();
            }
            //Need to see the second entity
            DbAssert.OnQuery("select count(*) cnt from AnEntity where id = {id}")
            .SetInt32Param("id", insertedId)
            .That("cnt", Is.EqualTo(1)).ExecuteAssert();
        }
 public void TransactionInContext()
 {
     GlobalTransactionManager.BeginTransaction();
     Assert.That(overrideContext.storage.Count, Is.EqualTo(1));
 }
 public void TransactionIsInTransaction()
 {
     GlobalTransactionManager.BeginTransaction();
     Assert.That(GlobalTransactionManager.IsInTransaction);
 }
Exemplo n.º 28
0
 protected virtual void OnTestSetUp()
 {
     scope = GlobalTransactionManager.BeginTransaction();
 }