Esempio n. 1
0
        private object TransactionMethod(ITransactionStatus status)
        {
            Assert.IsTrue(TransactionSynchronizationManager.HasResource(sf), "Has thread session");
            HibernateTemplate ht          = new HibernateTemplate(sf);
            object            returnValue = ht.Execute(new HibernateDelegate(Del));

            status.SetRollbackOnly();
            return(null);
        }
Esempio n. 2
0
        /// <summary>The do cleanup after completion.</summary>
        /// <param name="transaction">The transaction.</param>
        protected override void DoCleanupAfterCompletion(object transaction)
        {
            var list      = (Stack <object>)TransactionSynchronizationManager.GetResource(this);
            var resources = list;

            resources.Clear();
            TransactionSynchronizationManager.UnbindResource(this);
            ((ResourcelessTransaction)transaction).Clear();
        }
Esempio n. 3
0
        /// <summary>
        /// Suspend this synchronization.
        /// </summary>
        /// <remarks>
        ///     <p>
        /// Supposed to unbind resources from
        /// <see cref="Spring.Transaction.Support.TransactionSynchronizationManager"/>
        /// if managing any.
        /// </p>
        /// </remarks>
        public override void Suspend()
        {
            if (holderActive)
            {
                TransactionSynchronizationManager.UnbindResource(dbProvider);

                //TODO do we need to reset the connection inside the conHolder to null?
            }
        }
        /// <summary>
        /// Return the current transaction object.
        /// </summary>
        /// <returns>The current transaction object.</returns>
        /// <exception cref="Spring.Transaction.CannotCreateTransactionException">
        /// If transaction support is not available.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// In the case of lookup or system errors.
        /// </exception>
        protected override Object DoGetTransaction()
        {
            logger.Debug("Do Get Transaction");
            Db4oTransactionObject txObject   = new Db4oTransactionObject();
            ObjectContainerHolder contHolder = (ObjectContainerHolder)TransactionSynchronizationManager.GetResource(_DataSource);

            txObject.ObjectContainerHolder = contHolder;
            return(txObject);
        }
Esempio n. 5
0
 public override void BeforeCompletion()
 {
     TransactionSynchronizationManager.UnbindResource(resourceKey);
     holderActive = false;
     if (!transacted)
     {
         resourceHolder.CloseAll();
     }
 }
Esempio n. 6
0
 /// <summary>
 /// Invoked before transaction commit/rollback (after
 /// <see cref="Spring.Transaction.Support.ITransactionSynchronization.BeforeCommit"/>,
 /// even if
 /// <see cref="Spring.Transaction.Support.ITransactionSynchronization.BeforeCommit"/>
 /// threw an exception).
 /// </summary>
 /// <remarks>
 ///     <p>
 /// Can e.g. perform resource cleanup.
 /// </p>
 ///     <p>
 /// Note that exceptions will get propagated to the commit caller
 /// and cause a rollback of the transaction.
 /// </p>
 /// </remarks>
 public override void BeforeCompletion()
 {
     if (connectionHolder.IsOpen)
     {
         TransactionSynchronizationManager.UnbindResource(dbProvider);
         holderActive = false;
         ConnectionUtils.DisposeConnection(connectionHolder.Connection, dbProvider);
     }
 }
        /// <summary>
        /// Suspend the resources of the current transaction.
        /// </summary>
        /// <param name="transaction">Transaction object returned by
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
        /// <returns>
        /// An object that holds suspended resources (will be kept unexamined for passing it into
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoResume"/>.)
        /// </returns>
        /// <remarks>
        /// Transaction synchronization will already have been suspended.
        /// </remarks>
        /// <exception cref="Spring.Transaction.IllegalTransactionStateException">
        /// If suspending is not supported by the transaction manager implementation.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// in case of system errors.
        /// </exception>
        protected override object DoSuspend(object transaction)
        {
            DbProviderTransactionObject txMgrStateObject = (DbProviderTransactionObject)transaction;

            txMgrStateObject.ConnectionHolder = null;
            ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.UnbindResource(DbProvider);

            return(conHolder);
        }
Esempio n. 8
0
 /// <summary>
 /// Invoked after transaction commit/rollback.
 /// </summary>
 /// <param name="status">Status according to <see cref="Spring.Transaction.Support.TransactionSynchronizationStatus"/></param>
 /// <remarks>
 /// Can e.g. perform resource cleanup, in this case after transaction completion.
 /// <p>
 /// Note that exceptions will get propagated to the commit or rollback
 /// caller, although they will not influence the outcome of the transaction.
 /// </p>
 /// </remarks>
 public override void AfterCompletion(TransactionSynchronizationStatus status)
 {
     if (TransactionSynchronizationManager.HasResource(dbProvider))
     {
         TransactionSynchronizationManager.UnbindResource(dbProvider);
         holderActive = false;
         ConnectionUtils.DisposeConnection(connectionHolder.Connection, dbProvider);
     }
 }
        protected override object DoGetTransaction()
        {
            IbatisTransactionObject obj = new IbatisTransactionObject();

            obj.savepointAllowed = base.NestedTransactionsAllowed;
            SqlMapperHolder sqlMapperHolder = (SqlMapperHolder)TransactionSynchronizationManager.GetResource(this.sqlMapper);

            obj.SetSqlMapHolder(sqlMapperHolder, false);
            return(obj);
        }
Esempio n. 10
0
        public object DoInTransaction(ITransactionStatus status)
        {
            Assert.IsTrue(TransactionSynchronizationManager.HasResource(sf), "Has thread session");
            HibernateTemplate ht = new HibernateTemplate(sf);

            ht.TemplateFlushMode = TemplateFlushMode.Eager;
            ht.Execute(new HibernateDelegate(Del));
            status.SetRollbackOnly();
            return(null);
        }
Esempio n. 11
0
        /// <summary>The is existing transaction.</summary>
        /// <param name="transaction">The transaction.</param>
        /// <returns>The System.Boolean.</returns>
        protected override bool IsExistingTransaction(object transaction)
        {
            if (TransactionSynchronizationManager.HasResource(this))
            {
                var stack = (Stack <object>)TransactionSynchronizationManager.GetResource(this);
                return(stack.Count > 1);
            }

            return(((ResourcelessTransaction)transaction).Active);
        }
        /// <summary>
        /// Suspend the resources of the current transaction.
        /// </summary>
        /// <param name="transaction">
        /// Transaction object returned by
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.
        /// </param>
        /// <returns>
        /// An object that holds suspended resources (will be kept unexamined for passing it into
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoResume"/>.)
        /// </returns>
        /// <remarks>
        /// Transaction synchronization will already have been suspended.
        /// </remarks>
        /// <exception cref="Spring.Transaction.IllegalTransactionStateException">
        /// If suspending is not supported by the transaction manager implementation.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// in case of system errors.
        /// </exception>
        protected override Object DoSuspend(Object transaction)
        {
            logger.Debug("Do Suspend");
            Db4oTransactionObject txObject = (Db4oTransactionObject)transaction;

            txObject.ObjectContainerHolder = null;
            ObjectContainerHolder containerHolder = (ObjectContainerHolder)TransactionSynchronizationManager.GetResource(_DataSource);

            return(new SuspendedResourcesHolder(containerHolder));
        }
Esempio n. 13
0
        public object DoInTransaction(ITransactionStatus status)
        {
            Assert.IsTrue(TransactionSynchronizationManager.HasResource(sfProxy), "Has thread session");
            Assert.IsTrue(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
            Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
            Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
            HibernateTemplate ht = new HibernateTemplate(sfProxy);

            return(ht.Find("some query string"));
        }
Esempio n. 14
0
        /// <summary>
        /// Determines whether the given JMS Session is transactional, that is,
        /// bound to the current thread by Spring's transaction facilities.
        /// </summary>
        /// <param name="session">The session to check.</param>
        /// <param name="cf">The ConnectionFactory that the Session originated from</param>
        /// <returns>
        ///     <c>true</c> if is session transactional, bound to current thread; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsSessionTransactional(ISession session, IConnectionFactory cf)
        {
            if (session == null || cf == null)
            {
                return(false);
            }
            EmsResourceHolder resourceHolder = (EmsResourceHolder)TransactionSynchronizationManager.GetResource(cf);

            return(resourceHolder != null && resourceHolder.ContainsSession(session));
        }
        /// <summary>
        /// Return whether the given DB instance is transactional, that is, bound to the current thread by Spring's transaction
        /// facilities.
        /// </summary>
        /// <param name="db">the Database to check</param>
        /// <param name="mongo">the Mongo instance that the DB was created with (may be <code>null</code>)</param>
        /// <returns>whether the DB is transactional</returns>
        public static bool IsDbTransactional(MongoDatabase db, MongoServer mongo)
        {
            if (mongo == null)
            {
                return(false);
            }
            var dbHolder = (DatabaseHolder)TransactionSynchronizationManager.GetResource(mongo);

            return(dbHolder != null && dbHolder.ContainsDatabase(db));
        }
Esempio n. 16
0
        public void TransactionWithPropagationSupportsAndInnerTransaction()
        {
            DbConnection    connection     = A.Fake <DbConnection>();
            ISessionFactory sessionFactory = A.Fake <ISessionFactory>();
            ISession        session1       = A.Fake <ISession>();
            ISession        session2       = A.Fake <ISession>();
            ITransaction    transaction    = A.Fake <ITransaction>();

            A.CallTo(() => sessionFactory.OpenSession()).Returns(session1).Once()
            .Then.Returns(session2).Once();

            A.CallTo(() => session1.Connection).Returns(connection);
            A.CallTo(() => session1.SessionFactory).Returns(sessionFactory);
            A.CallTo(() => session1.FlushMode).Returns(FlushMode.Auto);

            A.CallTo(() => session2.Connection).Returns(connection);
            A.CallTo(() => session2.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
            A.CallTo(() => session2.FlushMode).Returns(FlushMode.Auto);
            A.CallTo(() => session2.IsOpen).Returns(true);

            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");

            A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly();
            A.CallTo(() => session1.Flush()).MustHaveHappenedTwiceExactly();
            A.CallTo(() => session2.Flush()).MustHaveHappenedOnceExactly();
            A.CallTo(() => session2.Close()).MustHaveHappenedOnceExactly();
        }
        /// <summary>
        /// Return whether the given Hibernate Session is transactional, that is,
        /// bound to the current thread by Spring's transaction facilities.
        /// </summary>
        /// <param name="session">The hibernate session to check</param>
        /// <param name="sessionFactory">The session factory that the session
        /// was created with, can be null.</param>
        /// <returns>
        ///     <c>true</c> if the session transactional; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsSessionTransactional(ISession session, ISessionFactory sessionFactory)
        {
            if (sessionFactory == null)
            {
                return(false);
            }
            SessionHolder sessionHolder =
                (SessionHolder)TransactionSynchronizationManager.GetResource(sessionFactory);

            return(sessionHolder != null && sessionHolder.ContainsSession(session));
        }
Esempio n. 18
0
            private void CallExecuteListener(Message message, ulong deliveryTag)
            {
                var channelLocallyTransacted = _container.IsChannelLocallyTransacted;

                try
                {
                    _container.ExecuteListener(Model, message);
                    HandleAck(deliveryTag, channelLocallyTransacted);
                }
                catch (ImmediateAcknowledgeAmqpException e)
                {
                    _logger?.LogDebug("User requested ack for failed delivery '" + e.Message + "': " + deliveryTag);
                    HandleAck(deliveryTag, channelLocallyTransacted);
                }
                catch (Exception e)
                {
                    if (_container.CauseChainHasImmediateAcknowledgeAmqpException(e))
                    {
                        _logger?.LogDebug("User requested ack for failed delivery: " + deliveryTag);
                        HandleAck(deliveryTag, channelLocallyTransacted);
                    }
                    else
                    {
                        _logger?.LogError("Failed to invoke listener", e);
                        if (TransactionManager != null)
                        {
                            if (TransactionAttribute.RollbackOn(e))
                            {
                                var resourceHolder = (RabbitResourceHolder)TransactionSynchronizationManager.GetResource(ConnectionFactory);
                                if (resourceHolder == null)
                                {
                                    /*
                                     * If we don't actually have a transaction, we have to roll back
                                     * manually. See prepareHolderForRollback().
                                     */
                                    Rollback(deliveryTag, e);
                                }

                                throw; // encompassing transaction will handle the rollback.
                            }
                            else
                            {
                                _logger?.LogDebug("No rollback for " + e);
                            }
                        }
                        else
                        {
                            Rollback(deliveryTag, e);

                            // no need to rethrow e - we'd ignore it anyway, not throw to client
                        }
                    }
                }
            }
Esempio n. 19
0
        /// <summary>
        /// Get a ADO.NET Connection/Transaction Pair for the given IDbProvider.
        /// Same as <see cref="GetConnection"/> but throwing original provider
        /// exception.
        /// </summary>
        /// <remarks>
        /// Is aware of a corresponding Connection/Transaction bound to the current thread, for example
        /// when using AdoPlatformTransactionManager. Will bind a IDbConnection to the thread
        /// if transaction synchronization is active
        /// </remarks>
        /// <param name="provider">The provider.</param>
        /// <returns></returns>
        public static ConnectionTxPair DoGetConnection(IDbProvider provider)
        {
            AssertUtils.ArgumentNotNull(provider, "provider");
            ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.GetResource(provider);

            if (conHolder != null && (conHolder.HasConnection || conHolder.SynchronizedWithTransaction))
            {
                conHolder.Requested();
                if (!conHolder.HasConnection)
                {
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug("Fetching resumed ADO.NET connection from DbProvider");
                    }
                    conHolder.Connection = provider.CreateConnection();
                }
                return(new ConnectionTxPair(conHolder.Connection, conHolder.Transaction));
            }

            // Else we either got no holder or an empty thread-bound holder here.
            if (LOG.IsDebugEnabled)
            {
                LOG.Debug("Fetching Connection from DbProvider");
            }
            IDbConnection conn = provider.CreateConnection();

            conn.Open();

            if (TransactionSynchronizationManager.SynchronizationActive)
            {
                LOG.Debug("Registering transaction synchronization for IDbConnection");
                //Use same connection for further ADO.NET actions with the transaction.
                //Thread-bound object will get removed by manager at transaction completion.

                ConnectionHolder holderToUse = conHolder;
                if (holderToUse == null)
                {
                    holderToUse = new ConnectionHolder(conn, null);
                }
                else
                {
                    holderToUse.Connection = conn;
                }
                holderToUse.Requested();
                TransactionSynchronizationManager.RegisterSynchronization(
                    new ConnectionSynchronization(holderToUse, provider));
                holderToUse.SynchronizedWithTransaction = true;
                if (holderToUse != conHolder)
                {
                    TransactionSynchronizationManager.BindResource(provider, holderToUse);
                }
            }
            return(new ConnectionTxPair(conn, null));
        }
Esempio n. 20
0
        public void TestResourceHolder()
        {
            var h1 = new RabbitResourceHolder();
            var h2 = new RabbitResourceHolder();
            var connectionFactory = new Mock <IConnectionFactory>();

            TransactionSynchronizationManager.SetActualTransactionActive(true);
            ConnectionFactoryUtils.BindResourceToTransaction(h1, connectionFactory.Object, true);
            Assert.Same(h1, ConnectionFactoryUtils.BindResourceToTransaction(h2, connectionFactory.Object, true));
            TransactionSynchronizationManager.Clear();
        }
        /// <summary>Register a delivery tag.</summary>
        /// <param name="connectionFactory">The connection factory.</param>
        /// <param name="channel">The channel.</param>
        /// <param name="tag">The tag.</param>
        public static void RegisterDeliveryTag(IConnectionFactory connectionFactory, IModel channel, long tag)
        {
            AssertUtils.ArgumentNotNull(connectionFactory, "ConnectionFactory must not be null");

            var resourceHolder = (RabbitResourceHolder)TransactionSynchronizationManager.GetResource(connectionFactory);

            if (resourceHolder != null)
            {
                resourceHolder.AddDeliveryTag(channel, tag);
            }
        }
Esempio n. 22
0
        public void TransactionCommit()
        {
            IDbProvider     provider       = A.Fake <IDbProvider>();
            DbConnection    connection     = A.Fake <DbConnection>();
            ISessionFactory sessionFactory = A.Fake <ISessionFactory>();
            ISession        session        = A.Fake <ISession>();
            ITransaction    transaction    = A.Fake <ITransaction>();
            IQuery          query          = A.Fake <IQuery>();

            IList list = new ArrayList();

            list.Add("test");
            A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
            A.CallTo(() => session.Connection).Returns(connection);
            A.CallTo(() => session.BeginTransaction(IsolationLevel.Serializable)).Returns(transaction);
            A.CallTo(() => session.IsOpen).Returns(true);
            A.CallTo(() => session.CreateQuery("some query string")).Returns(query);
            A.CallTo(() => query.List()).Returns(list);

            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");

            A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly();
            A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
        }
Esempio n. 23
0
        public object DoInTransaction(ITransactionStatus status)
        {
            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sf), "Hasn't thread session");
            Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
            Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive);

            HibernateTemplate ht = new HibernateTemplate(sf);

            ht.TemplateFlushMode = TemplateFlushMode.Eager;
            return(ht.ExecuteFind(new NotSupportedTxCallbackInner()));
        }
Esempio n. 24
0
        /// <summary>
        /// Opens a new session or participates in an existing session and
        /// registers with spring's <see cref="TransactionSynchronizationManager"/>.
        /// </summary>
        public void Open()
        {
            if (IsParticipating || IsOpen)
            {
                throw new InvalidOperationException("This scope is already open");
            }

            bool isDebugEnabled = log.IsDebugEnabled;

            if (SingleSession)
            {
                // single session mode
                if (TransactionSynchronizationManager.HasResource(SessionFactory))
                {
                    // Do not modify the Session: just set the participate flag.
                    if (isDebugEnabled)
                    {
                        log.Debug("Participating in existing Hibernate SessionFactory");
                    }
                    SetParticipating(true);
                }
                else
                {
                    if (isDebugEnabled)
                    {
                        log.Debug("Opening single Hibernate Session in SessionScope");
                    }
                    TransactionSynchronizationManager.BindResource(SessionFactory, new LazySessionHolder(this));
                }
            }
            else
            {
                // deferred close mode
                if (SessionFactoryUtils.IsDeferredCloseActive(SessionFactory))
                {
                    // Do not modify deferred close: just set the participate flag.
                    if (isDebugEnabled)
                    {
                        log.Debug("Participating in active deferred close mode");
                    }
                    SetParticipating(true);
                }
                else
                {
                    if (isDebugEnabled)
                    {
                        log.Debug("Initializing deferred close mode");
                    }
                    SessionFactoryUtils.InitDeferredClose(SessionFactory);
                }
            }

            SetOpen(true);
        }
Esempio n. 25
0
        public static bool IsChannelTransactional(R.IModel channel, IConnectionFactory connectionFactory)
        {
            if (channel == null || connectionFactory == null)
            {
                return(false);
            }

            var resourceHolder = (RabbitResourceHolder)TransactionSynchronizationManager.GetResource(connectionFactory);

            return(resourceHolder != null && resourceHolder.ContainsChannel(channel));
        }
 /// <summary>
 /// Invoked before transaction commit/rollback (after
 /// <see cref="Spring.Transaction.Support.ITransactionSynchronization.BeforeCommit"/>,
 /// even if
 /// <see cref="Spring.Transaction.Support.ITransactionSynchronization.BeforeCommit"/>
 /// threw an exception).
 /// </summary>
 /// <remarks>
 /// <p>
 /// Can e.g. perform resource cleanup.
 /// </p>
 /// <p>
 /// Note that exceptions will get propagated to the commit caller
 /// and cause a rollback of the transaction.
 /// </p>
 /// </remarks>
 public void BeforeCompletion()
 {
     if (ShouldUnbindAtCompletion())
     {
         TransactionSynchronizationManager.UnbindResource(_resourceKey);
         _holderActive = false;
         if (ShouldReleaseBeforeCompletion())
         {
             ReleaseResource(_resourceHolder, _resourceKey);
         }
     }
 }
 /// <summary>The before completion.</summary>
 public virtual void BeforeCompletion()
 {
     if (this.ShouldUnbindAtCompletion())
     {
         TransactionSynchronizationManager.UnbindResource(this.resourceKey);
         this.holderActive = false;
         if (this.ShouldReleaseBeforeCompletion())
         {
             this.ReleaseResource(this.resourceHolder, this.resourceKey);
         }
     }
 }
        /// <summary>
        /// Return the current transaction object.
        /// </summary>
        /// <returns>The current transaction object.</returns>
        /// <exception cref="Spring.Transaction.CannotCreateTransactionException">
        /// If transaction support is not available.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// In the case of lookup or system errors.
        /// </exception>
        protected override object DoGetTransaction()
        {
            DbProviderTransactionObject txMgrStateObject =
                new DbProviderTransactionObject();

            txMgrStateObject.SavepointAllowed = NestedTransactionsAllowed;
            ConnectionHolder conHolder =
                (ConnectionHolder)TransactionSynchronizationManager.GetResource(DbProvider);

            txMgrStateObject.SetConnectionHolder(conHolder, false);
            return(txMgrStateObject);
        }
        /// <summary>
        /// Cleanup resources after transaction completion.
        /// </summary>
        /// <param name="transaction">Transaction object returned by
        /// <see cref="M:Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
        /// <remarks>
        /// <note>
        /// This implemenation unbinds the SessionFactory and
        /// DbProvider from thread local storage and closes the
        /// ISession.
        /// </note>
        ///     <p>
        /// Called after <see cref="M:Spring.Transaction.Support.AbstractPlatformTransactionManager.DoCommit(Spring.Transaction.Support.DefaultTransactionStatus)"/>
        /// and
        /// <see cref="M:Spring.Transaction.Support.AbstractPlatformTransactionManager.DoRollback(Spring.Transaction.Support.DefaultTransactionStatus)"/>
        /// execution on any outcome.
        /// </p>
        ///     <p>
        /// Should not throw any exceptions but just issue warnings on errors.
        /// </p>
        /// </remarks>
        protected override void DoCleanupAfterCompletion(object transaction)
        {
            HibernateTransactionObject txObject = (HibernateTransactionObject)transaction;

            // Remove the session holder from the thread.
            if (txObject.NewSessionHolder)
            {
                TransactionSynchronizationManager.UnbindResource(SessionFactory);
            }
            // Remove the ADO.NET connection holder from the thread, if exposed.
            if (DbProvider != null)
            {
                TransactionSynchronizationManager.UnbindResource(DbProvider);
            }

            /*
             * try
             * {
             *  //TODO investigate isolation level settings...
             *  //IDbConnection con = txObject.SessionHolder.Session.Connection;
             *  //AdoUtils.ResetConnectionAfterTransaction(con, txObject.PreviousIsolationLevel);
             * }
             * catch (HibernateException ex)
             * {
             *  log.Info("Could not access ADO.NET IDbConnection of Hibernate Session", ex);
             * }
             */
            ISession session = txObject.SessionHolder.Session;

            if (txObject.NewSessionHolder)
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("Closing Hibernate Session [" + session + "] after transaction");
                }

                SessionFactoryUtils.CloseSessionOrRegisterDeferredClose(session, SessionFactory);
            }
            else
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("Not closing pre-bound Hibernate Session [" + session + "] after transaction");
                }
                if (txObject.SessionHolder.AssignedPreviousFlushMode)
                {
                    session.FlushMode = txObject.SessionHolder.PreviousFlushMode;
                }
            }

            txObject.SessionHolder.Clear();
        }
Esempio n. 30
0
 /// <summary>
 /// Invoked before transaction commit (before
 /// <see cref="Spring.Transaction.Support.ITransactionSynchronization.BeforeCompletion"/>)
 /// Can e.g. flush transactional O/R Mapping sessions to the database
 /// </summary>
 /// <remarks>
 /// <para>
 /// This callback does not mean that the transaction will actually be
 /// commited.  A rollback decision can still occur after this method
 /// has been called.  This callback is rather meant to perform work
 /// that's only relevant if a commit still has a chance
 /// to happen, such as flushing SQL statements to the database.
 /// </para>
 /// <para>
 /// Note that exceptions will get propagated to the commit caller and cause a
 /// rollback of the transaction.</para>
 /// <para>
 /// (note: do not throw TransactionException subclasses here!)
 /// </para>
 /// </remarks>
 public override void BeforeCompletion()
 {
     if (this.newSession)
     {
         // Default behavior: unbind and close the thread-bound Hibernate Session.
         TransactionSynchronizationManager.UnbindResource(this.sessionFactory);
         this.holderActive = false;
     }
     else if (this.sessionHolder.AssignedPreviousFlushMode == true)
     {
         // In case of pre-bound Session, restore previous flush mode.
         this.sessionHolder.Session.FlushMode = (this.sessionHolder.PreviousFlushMode);
     }
 }