public void ResolvesEntityInterceptorOnEachOpen() { TestSessionScopeSettings sss = Fake <TestSessionScopeSettings>(options => options .CallsBaseMethods() .WithArgumentsForConstructor(new[] { expectedSessionFactory }) ); ISession expectedSession = Fake <ISession>(); sss.DefaultFlushMode = FlushMode.Never; SessionScope sc = new SessionScope(sss, false); CallTo(() => sss.DoResolveEntityInterceptor()).Returns(expectedEntityInterceptor); CallTo(() => expectedSessionFactory.OpenSession(expectedEntityInterceptor)).Returns(expectedSession); sc.Open(); SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(expectedSessionFactory); sessionHolder.ContainsSession(null); // force opening session sc.Close(); sc.Open(); sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(expectedSessionFactory); sessionHolder.ContainsSession(null); // force opening session sc.Close(); CallToSet(() => expectedSession.FlushMode).WhenArgumentsMatch(x => x.Get <FlushMode>(0) == FlushMode.Never).MustHaveHappenedTwiceExactly(); CallTo(() => expectedSession.Close()).MustHaveHappenedTwiceExactly(); }
/// <summary> /// Get the transaction. /// </summary> /// <returns> /// The transaction. /// </returns> protected override object DoGetTransaction() { var transactionObject = new RabbitTransactionObject(); transactionObject.ResourceHolder = (RabbitResourceHolder)TransactionSynchronizationManager.GetResource(this.ConnectionFactory); return(transactionObject); }
/// <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() { HibernateTransactionObject txObject = new HibernateTransactionObject(); txObject.SavepointAllowed = NestedTransactionsAllowed; if (TransactionSynchronizationManager.HasResource(SessionFactory)) { SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(SessionFactory); if (log.IsDebugEnabled) { log.Debug("Found thread-bound Session [" + sessionHolder.Session + "] for Hibernate transaction"); } txObject.SetSessionHolder(sessionHolder, false); if (DbProvider != null) { ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.GetResource(DbProvider); txObject.ConnectionHolder = conHolder; } } txObject.PromotableTxScopeTransactionObject = new TxScopeTransactionManager.PromotableTxScopeTransactionObject(); return(txObject); }
/// <summary> /// Method DoReleaseConnection /// </summary> /// <param name="container">An ObjectContainer</param> /// <param name="dataSource">An IDb4oDataSource</param> private static void DoDisposeConnection(ObjectContainer container, IDb4oDataSource dataSource) { logger.Debug("DoDisposeConnection"); if (container == null) { logger.Debug("Container is null, doing nothing"); return; } if (dataSource != null) { logger.Debug("Data Source is not null, trying to release"); ObjectContainerHolder holder = (ObjectContainerHolder)TransactionSynchronizationManager.GetResource(dataSource); if (holder != null) { logger.Debug("holder is not null, releasing"); // should we make sure the connection is the right one ? holder.Released(); // should not go further since we are in a transactional context // => No connection closing directly return; } logger.Debug("No transaction, closing the container"); // no transactional context so // close the container container.close(); } }
public bool CommitIfNecessary(bool localTx) { if (DeliveryTags.Count == 0) { return(false); } var isLocallyTransacted = localTx || (Transactional && TransactionSynchronizationManager.GetResource(ConnectionFactory) == null); try { var ackRequired = !AcknowledgeMode.IsAutoAck() && !AcknowledgeMode.IsManual(); if (ackRequired && (!Transactional || isLocallyTransacted)) { var deliveryTag = new List <ulong>(DeliveryTags)[DeliveryTags.Count - 1]; Channel.BasicAck(deliveryTag, true); } if (isLocallyTransacted) { // For manual acks we still need to commit RabbitUtils.CommitIfNecessary(Channel); } } finally { DeliveryTags.Clear(); } return(true); }
/// <summary> /// get the <see cref="ConnectionHolder"/> from the current thread /// </summary> /// <returns>The<see cref="ConnectionHolder"/> of the current thread.</returns> protected ConnectionHolder GetConnectionHolder(IDbProvider dbProvider) { CheckDbProvider(dbProvider); var conHolder = (ConnectionHolder)TransactionSynchronizationManager.GetResource(dbProvider); return(conHolder); }
/// <summary> /// Get a new Hibernate Session from the given SessionFactory. /// Will return a new Session even if there already is a pre-bound /// Session for the given SessionFactory. /// </summary> /// <remarks> /// Within a transaction, this method will create a new Session /// that shares the transaction's ADO.NET Connection. More specifically, /// it will use the same ADO.NET Connection as the pre-bound Hibernate Session. /// </remarks> /// <param name="sessionFactory">The session factory to create the session with.</param> /// <param name="interceptor">The Hibernate entity interceptor, or <code>null</code> if none.</param> /// <returns>The new session.</returns> /// <exception cref="DataAccessResourceFailureException">If could not open Hibernate session</exception> public static ISession GetNewSession(ISessionFactory sessionFactory, IInterceptor interceptor) { try { SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(sessionFactory); if (sessionHolder != null && !sessionHolder.IsEmpty) { if (interceptor != null) { return(sessionFactory.OpenSession(sessionHolder.AnySession.Connection, interceptor)); } else { return(sessionFactory.OpenSession(sessionHolder.AnySession.Connection)); } } else { if (interceptor != null) { return(sessionFactory.OpenSession(interceptor)); } else { return(sessionFactory.OpenSession()); } } } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }
public void CanCreateAndCloseSimpleCtor() { ISession session = Fake <ISession>(); CallTo(() => expectedSessionFactory.OpenSession()).Returns(session); using (SessionScope scope = new SessionScope(expectedSessionFactory, true)) { // no op - just create & dispose Assert.AreSame(expectedSessionFactory, scope.SessionFactory); //Assert.AreSame(null, scope.EntityInterceptor); Assert.AreEqual(expectedSingleSession, scope.SingleSession); Assert.AreEqual(expectedDefaultFlushMode, scope.DefaultFlushMode); // ensure SessionHolder object is registered with TSM Assert.IsTrue(TransactionSynchronizationManager.HasResource(expectedSessionFactory)); SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(expectedSessionFactory); // by default session is lazy, so ask for it. Assert.IsNotNull(sessionHolder.Session); scope.Close(); } CallToSet(() => session.FlushMode).WhenArgumentsMatch(x => x.Get <FlushMode>(0) == FlushMode.Never).MustHaveHappenedOnceExactly(); CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); }
public void CanCreateAndCloseSimpleCtor() { using (mocks.Ordered()) { ISession session = mocks.StrictMock <ISession>(); Expect.Call(expectedSessionFactory.OpenSession()).Return(session); session.FlushMode = FlushMode.Never; Expect.Call(session.Close()).Return(null); } mocks.ReplayAll(); using (SessionScope scope = new SessionScope(expectedSessionFactory, true)) { // no op - just create & dispose Assert.AreSame(expectedSessionFactory, scope.SessionFactory); //Assert.AreSame(null, scope.EntityInterceptor); Assert.AreEqual(expectedSingleSession, scope.SingleSession); Assert.AreEqual(expectedDefaultFlushMode, scope.DefaultFlushMode); // ensure SessionHolder object is registered with TSM Assert.IsTrue(TransactionSynchronizationManager.HasResource(expectedSessionFactory)); SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(expectedSessionFactory); // by default session is lazy, so ask for it. Assert.IsNotNull(sessionHolder.Session); scope.Close(); } mocks.VerifyAll(); }
/// <summary> /// Get the EmsTransactionObject. /// </summary> /// <returns>he EmsTransactionObject.</returns> protected override object DoGetTransaction() { EmsTransactionObject txObject = new EmsTransactionObject(); txObject.ResourceHolder = (EmsResourceHolder)TransactionSynchronizationManager.GetResource(ConnectionFactory); return(txObject); }
/// <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() { MessageQueueTransactionObject txObject = new MessageQueueTransactionObject(); txObject.ResourceHolder = (MessageQueueResourceHolder)TransactionSynchronizationManager.GetResource(CURRENT_TRANSACTION_SLOTNAME); return(txObject); }
/// <summary>Obtain a RabbitMQ Channel that is synchronized with the current transaction, if any.</summary> /// <param name="connectionFactory">The connection factory.</param> /// <param name="resourceFactory">The resource factory.</param> /// <returns>The transactional Channel, or null if none found.</returns> private static RabbitResourceHolder DoGetTransactionalResourceHolder(IConnectionFactory connectionFactory, IResourceFactory resourceFactory) { AssertUtils.ArgumentNotNull(connectionFactory, "ConnectionFactory must not be null"); AssertUtils.ArgumentNotNull(resourceFactory, "ResourceFactory must not be null"); var resourceHolder = (RabbitResourceHolder)TransactionSynchronizationManager.GetResource(connectionFactory); if (resourceHolder != null) { var tempchannel = resourceFactory.GetChannel(resourceHolder); if (tempchannel != null) { return(resourceHolder); } } var resourceHolderToUse = resourceHolder; if (resourceHolderToUse == null) { resourceHolderToUse = new RabbitResourceHolder(); } var connection = resourceFactory.GetConnection(resourceHolderToUse); IModel channel = null; try { var isExistingCon = connection != null; if (!isExistingCon) { connection = resourceFactory.CreateConnection(); resourceHolderToUse.AddConnection(connection); } channel = consumerChannel.Value; if (channel == null) { channel = resourceFactory.CreateChannel(connection); } resourceHolderToUse.AddChannel(channel, connection); if (resourceHolderToUse != resourceHolder) { BindResourceToTransaction(resourceHolderToUse, connectionFactory, resourceFactory.IsSynchedLocalTransactionAllowed); } return(resourceHolderToUse); } catch (Exception ex) { RabbitUtils.CloseChannel(channel); RabbitUtils.CloseConnection(connection); throw new AmqpIOException(ex); } }
/// <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(); }
/// <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); }
/// <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> /// 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)); }
/// <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> /// 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)); }
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); }
/// <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)); }
/// <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)); }
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>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); } }
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 } } } }
/// <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); }
public static void RegisterDeliveryTag(IConnectionFactory connectionFactory, R.IModel channel, ulong tag) { if (connectionFactory == null) { throw new ArgumentNullException(nameof(connectionFactory)); } var resourceHolder = (RabbitResourceHolder)TransactionSynchronizationManager.GetResource(connectionFactory); if (resourceHolder != null) { resourceHolder.AddDeliveryTag(channel, tag); } }
public object DoInTransaction(ITransactionStatus status) { SessionHolder holder = (SessionHolder)TransactionSynchronizationManager.GetResource(sf); Assert.IsNotNull(holder, "Has thread session"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); tt.PropagationBehavior = TransactionPropagation.NotSupported; tt.Execute(new NotSupportedTxCallback(sf)); Assert.IsTrue(holder.Session == SessionFactoryUtils.GetSession(sf, false), "Same thread session as before"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); return(null); }
/// <summary> /// Applies the current transaction timeout, if any, to the given /// criteria object /// </summary> /// <param name="criteria">The Hibernate Criteria object.</param> /// <param name="sessionFactory">Hibernate SessionFactory that the Criteria was created for /// (can be <code>null</code>).</param> /// <exception cref="ArgumentNullException">If criteria argument is null.</exception> public static void ApplyTransactionTimeout(ICriteria criteria, ISessionFactory sessionFactory) { if (criteria == null) { throw new ArgumentNullException("criteria", "No Criteria object specified"); } SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(sessionFactory); if (sessionHolder != null && sessionHolder.HasTimeout) { criteria.SetTimeout(sessionHolder.TimeToLiveInSeconds); } }
public static RabbitResourceHolder BindResourceToTransaction(RabbitResourceHolder resourceHolder, IConnectionFactory connectionFactory, bool synched) { if (TransactionSynchronizationManager.HasResource(connectionFactory) || !TransactionSynchronizationManager.IsActualTransactionActive() || !synched) { return((RabbitResourceHolder)TransactionSynchronizationManager.GetResource(connectionFactory)); // NOSONAR never null } TransactionSynchronizationManager.BindResource(connectionFactory, resourceHolder); resourceHolder.SynchronizedWithTransaction = true; if (TransactionSynchronizationManager.IsSynchronizationActive()) { TransactionSynchronizationManager.RegisterSynchronization(new RabbitResourceSynchronization(resourceHolder, connectionFactory)); } return(resourceHolder); }
/// <summary> /// Applies the current transaction timeout, if any, to the given /// Hibenrate query object. /// </summary> /// <param name="query">The Hibernate Query object.</param> /// <param name="sessionFactory">Hibernate SessionFactory that the Query was created for /// (can be <code>null</code>).</param> /// <exception cref="ArgumentNullException">If query argument is null.</exception> public static void ApplyTransactionTimeout(IQuery query, ISessionFactory sessionFactory) { if (query == null) { throw new ArgumentNullException("queryObject", "No query object specified"); } if (sessionFactory != null) { SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(sessionFactory); if (sessionHolder != null && sessionHolder.HasTimeout) { query.SetTimeout(sessionHolder.TimeToLiveInSeconds); } } }