public void ParticipatingTransactionWithWithRequiresNew() { IDbConnection connection = A.Fake <IDbConnection>(); 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.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); A.CallTo(() => session1.IsOpen).Returns(true); A.CallTo(() => session2.Connection).Returns(connection); A.CallTo(() => session2.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); A.CallTo(() => session2.IsOpen).Returns(true); A.CallTo(() => session2.FlushMode).Returns(FlushMode.Auto); 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 ParticipatingTransactionWithWithRequiresNewTxCallback(tt, sessionFactory)); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session"); A.CallTo(() => transaction.Commit()).MustHaveHappenedTwiceExactly(); A.CallTo(() => session2.Flush()).MustHaveHappenedOnceExactly(); A.CallTo(() => session1.Close()).MustHaveHappenedOnceExactly(); A.CallTo(() => session2.Close()).MustHaveHappenedOnceExactly(); }
public void TransactionWithPropagationSupports() { ISessionFactory sessionFactory = (ISessionFactory)mocks.CreateMock(typeof(ISessionFactory)); ISession session = (ISession)mocks.CreateMock(typeof(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 TransactionRollback() { IDbProvider provider = A.Fake <IDbProvider>(); IDbConnection connection = A.Fake <IDbConnection>(); ISessionFactory sessionFactory = A.Fake <ISessionFactory>(); ISession session = A.Fake <ISession>(); ITransaction transaction = A.Fake <ITransaction>(); IDbTransaction adoTransaction = A.Fake <IDbTransaction>(); A.CallTo(() => sessionFactory.OpenSession()).Returns(session).Once(); A.CallTo(() => session.Connection).Returns(connection).Once(); A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction).Once(); A.CallTo(() => session.IsOpen).Returns(true).Once(); A.CallTo(() => adoTransaction.Connection).Returns(connection).Once(); 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"); A.CallTo(() => transaction.Rollback()).MustHaveHappened(); A.CallTo(() => session.Close()).MustHaveHappened(); }
public void DoRequestUpdate(AccountAuthorizationRequest request, string adminName, bool doAccept) { request.Response.AuthorizationGeneratedOn = DateTime.Now; AuthorizationResponse response = GetAuthorizationResponse(request, doAccept); byte[] authorizationResponsContent = _serializationHelper.Serialize(response); Document document = new Document(response.GetType().Name + ".xml", CommonContentType.XML, authorizationResponsContent); string statusDetail = string.Format("{0} {1} authorization request from user \"{2} ({3})\"", adminName, doAccept ? "accepted" : "rejected", request.FullName, request.NaasAccount); TransactionTemplate.Execute(delegate { Save(request); _documentManager.AddDocument(request.TransactionId, CommonTransactionStatusCode.Completed, statusDetail, document); _transactionDao.SetTransactionStatus(request.TransactionId, CommonTransactionStatusCode.Completed, statusDetail, true); return(null); }); }
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); }); }
private void ExecuteListenerInTransaction(Message message, ulong deliveryTag) { if (IsRabbitTxManager) { ConsumerChannelRegistry.RegisterConsumerChannel(Model, ConnectionFactory); } if (TransactionTemplate == null) { TransactionTemplate = new TransactionTemplate(TransactionManager, TransactionAttribute); } TransactionTemplate.Execute <object>(s => { var resourceHolder = ConnectionFactoryUtils.BindResourceToTransaction(new RabbitResourceHolder(Model, false), ConnectionFactory, true); if (resourceHolder != null) { resourceHolder.AddDeliveryTag(Model, deliveryTag); } // unbound in ResourceHolderSynchronization.beforeCompletion() try { CallExecuteListener(message, deliveryTag); } catch (Exception e1) { _container.PrepareHolderForRollback(resourceHolder, e1); throw; } // catch (Throwable e2) // { // //NOSONAR ok to catch Throwable here because we re-throw it below // throw new WrappedTransactionException(e2); // } return(null); }); }
public void TransactionRollback() { #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); Expect.Call(txAdapter.IsInTransaction).Return(true); txAdapter.SetAbort(); Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited); } #endregion mocks.ReplayAll(); IPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); TransactionTemplate tt = new TransactionTemplate(tm); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); Exception ex = new ArgumentException("test exception"); try { tt.Execute(new TransactionRollbackTxCallback(ex)); Assert.Fail("Should have thrown exception"); } catch (ArgumentException e) { Assert.AreEqual(ex, e); } Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); mocks.VerifyAll(); }
public void PropagationRequiresNewWithExistingTransaction() { IServiceDomainAdapter txAdapter = A.Fake <IServiceDomainAdapter>(); A.CallTo(() => txAdapter.IsInTransaction) .Returns(false).Once() .Then.Returns(true).NumberOfTimes(3); A.CallTo(() => txAdapter.Leave()) .Returns(TransactionStatus.Aborted).Once() .Then.Returns(TransactionStatus.Commited).Once(); A.CallTo(() => txAdapter.MyTransactionVote).Returns(TransactionVote.Commit).NumberOfTimes(3); ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); tm.TransactionSynchronization = TransactionSynchronizationState.Always; TransactionTemplate tt = new TransactionTemplate(tm); tt.PropagationBehavior = TransactionPropagation.RequiresNew; tt.Execute(new PropagationRequiresNewWithExistingTransactionCallbackSD(tt)); SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); ConfigureServiceConfig(serviceConfig, false); serviceConfig.TransactionOption = TransactionOption.RequiresNew; serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted; A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappened(); ConfigureServiceConfig(serviceConfig, false); serviceConfig.TransactionOption = TransactionOption.RequiresNew; serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted; A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappened(); A.CallTo(() => txAdapter.SetAbort()).MustHaveHappenedOnceExactly(); A.CallTo(() => txAdapter.SetComplete()).MustHaveHappenedOnceExactly(); }
public void ParticipatingTransactionWithCommit() { IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection)); ISessionFactory sessionFactory = (ISessionFactory)mocks.CreateMock(typeof(ISessionFactory)); ISession session = (ISession)mocks.CreateMock(typeof(ISession)); ITransaction transaction = (ITransaction)mocks.CreateMock(typeof(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(); }
/// <summary> /// Create a new data request according to the input parameters and return the /// data request id. /// </summary> public string CreateDataRequest(string transactionId, string serviceId, int rowIndex, int maxRowCount, RequestType type, string userCreatorId, ByIndexOrNameDictionary <string> parameters) { string requestId = IdProvider.Get(); TransactionTemplate.Execute(delegate { DoInsert(TABLE_NAME, "Id;TransactionId;ServiceId;RowIndex;MaxRowCount;RequestType;ModifiedBy;ModifiedOn;ParamsByName", requestId, transactionId, serviceId, rowIndex, maxRowCount, type.ToString(), userCreatorId, DateTime.Now, DbUtils.ToDbBool((parameters == null) ? true : parameters.IsByName)); if (!CollectionUtils.IsNullOrEmpty(parameters)) { object[] insertValues = new object[4]; DoBulkInsert(ARGS_TABLE_NAME, "Id;RequestId;ArgName;ArgValue", delegate(int currentInsertIndex) { if (currentInsertIndex < parameters.Count) { insertValues[0] = IdProvider.Get(); insertValues[1] = requestId; if (parameters.IsByName) { insertValues[2] = parameters.KeyAtIndex(currentInsertIndex); } else { insertValues[2] = currentInsertIndex.ToString("D3"); } insertValues[3] = parameters[currentInsertIndex]; return(insertValues); } return(null); }); } return(null); }); return(requestId); }
public bool CacheData(byte[] data, string name, DateTime expirationTime) { try { DateTime now = DateTime.Now; if (data == null) { throw new ArgumentNullException("data"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (expirationTime == DbUtils.DB_MIN_DATE) { DoSimpleQueryForObjectDelegate <string>( TABLE_NAME, "Name", name, "Expiration", delegate(IDataReader reader, int rowNum) { expirationTime = reader.GetDateTime(0); return(null); }); } TransactionTemplate.Execute(delegate { DoSimpleDelete(TABLE_NAME, "Name", name); DoInsert(TABLE_NAME, "Name;Data;ModifiedOn;Expiration", name, data, now, expirationTime); return(null); }); return(true); } catch (Exception e) { LOG.Error("Failed to cache object \"{0}\"", e, name); return(false); } }
public void ParticipatingTransactionWithRollbackOnly() { IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection)); ISessionFactory sessionFactory = (ISessionFactory)mocks.CreateMock(typeof(ISessionFactory)); ISession session = (ISession)mocks.CreateMock(typeof(ISession)); ITransaction transaction = (ITransaction)mocks.CreateMock(typeof(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); transaction.Rollback(); LastCall.On(transaction).Repeat.Once(); Expect.Call(session.Close()).Return(null); } mocks.ReplayAll(); HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory); 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 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(); }
public void ParticipatingTransactionWithRollback() { IConnectionFactory connectionFactory = (IConnectionFactory)mocks.CreateMock(typeof(IConnectionFactory)); IConnection connection = (IConnection)mocks.CreateMock(typeof(IConnection)); ISession session = (ISession)mocks.CreateMock(typeof(ISession)); using (mocks.Ordered()) { SetupRollbackExpectations(connection, connectionFactory, session); } mocks.ReplayAll(); EmsTransactionManager tm = new EmsTransactionManager(connectionFactory); ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition()); EmsTemplate nt = new EmsTemplate(connectionFactory); nt.Execute(new AssertSessionCallback(session)); TransactionTemplate tt = new TransactionTemplate(tm); tt.Execute(delegate(ITransactionStatus status) { nt.Execute(new AssertSessionCallback(session)); status.SetRollbackOnly(); return(null); }); try { tm.Commit(ts); Assert.Fail("Should have thrown UnexpectedRollbackException"); } catch (UnexpectedRollbackException) { } mocks.VerifyAll(); }
public void Rollback() { ITransactionSynchronization sync = (ITransactionSynchronization)mocks.DynamicMock(typeof(ITransactionSynchronization)); sync.BeforeCompletion(); LastCall.On(sync).Repeat.Once(); sync.AfterCompletion(TransactionSynchronizationStatus.Rolledback); LastCall.On(sync).Repeat.Once(); mocks.ReplayAll(); TxScopeTransactionManager tm = new TxScopeTransactionManager(); tm.TransactionSynchronization = TransactionSynchronizationState.Always; TransactionTemplate tt = new TransactionTemplate(tm); tt.TransactionTimeout = 10; tt.Name = "txName"; Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive); Assert.IsNull(TransactionSynchronizationManager.CurrentTransactionName); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); tt.Execute(delegate(ITransactionStatus status) { Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); TransactionSynchronizationManager.RegisterSynchronization(sync); Assert.AreEqual("txName", TransactionSynchronizationManager.CurrentTransactionName); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); status.SetRollbackOnly(); return(null); } ); mocks.VerifyAll(); }
private void SaveServiceDataSources(DataService item) { TransactionTemplate.Execute(delegate { DoSimpleDelete(SOURCES_TABLE_NAME, "ServiceId", new object[] { item.Id }); if (CollectionUtils.IsNullOrEmpty(item.DataSources)) { return(null); } using (IEnumerator <KeyValuePair <string, DataProviderInfo> > enumeratorObj = item.DataSources.GetEnumerator()) { object[] insertValues = new object[4]; object enumeratorObject = enumeratorObj; // NOTE: Boxing here so that value-type enumerator works // in anonymous delegate DoBulkInsert(SOURCES_TABLE_NAME, "Id;ServiceId;ConnectionId;KeyName", delegate(int currentInsertIndex) { IEnumerator <KeyValuePair <string, DataProviderInfo> > enumerator = (IEnumerator <KeyValuePair <string, DataProviderInfo> >)enumeratorObject; if (enumerator.MoveNext()) { insertValues[0] = IdProvider.Get(); insertValues[1] = item.Id; insertValues[2] = enumerator.Current.Value.Id; insertValues[3] = enumerator.Current.Key; enumeratorObject = enumerator; return(insertValues); } else { return(null); } }); } return(null); }); }
private void SaveScheduleSourceArgs(string scheduleId, ByIndexOrNameDictionary <string> args) { TransactionTemplate.Execute(delegate { DoSimpleDelete(SOURCE_ARGS_TABLE_NAME, "ScheduleId", new object[] { scheduleId }); if (CollectionUtils.IsNullOrEmpty(args)) { return(null); } object[] insertValues = new object[4]; DoBulkInsert(SOURCE_ARGS_TABLE_NAME, "Id;ScheduleId;Name;Value", delegate(int currentInsertIndex) { if (currentInsertIndex < args.Count) { insertValues[0] = IdProvider.Get(); insertValues[1] = scheduleId; if (args.IsByName) { insertValues[2] = currentInsertIndex.ToString(cIndexFormatString) + args.KeyAtIndex(currentInsertIndex); } else { insertValues[2] = currentInsertIndex.ToString(cIndexFormatString); } insertValues[3] = string.IsNullOrEmpty(args[currentInsertIndex]) ? (object)DBNull.Value : (object)args[currentInsertIndex]; return(insertValues); } else { return(null); } }); return(null); }); }
public void UpdateScheduleSourceArgs(string scheduleId, IDictionary <string, string> updateScheduleParams) { if (CollectionUtils.IsNullOrEmpty(updateScheduleParams)) { return; } TransactionTemplate.Execute(delegate { foreach (var pair in updateScheduleParams) { int count = DoSimpleUpdate(SOURCE_ARGS_TABLE_NAME, "ScheduleId;Name LIKE '%'p", new object[] { scheduleId, pair.Key }, "Value", 1, pair.Value); if (count == 0) { throw new ArgumentException(string.Format("The schedule with id \"{0}\" does not have any schedule parameters matching the name \"{0}\"", pair.Key)); } else if (count > 1) { throw new ArgumentException(string.Format("The schedule with id \"{0}\" has more than one schedule parameter matching the name \"{0}\"", pair.Key)); } } return(null); }); }
public void ParticipatingTransactionWithRollbackOnly() { DbConnection connection = A.Fake <DbConnection>(); ISessionFactory sessionFactory = A.Fake <ISessionFactory>(); ISession session = A.Fake <ISession>(); ITransaction transaction = A.Fake <ITransaction>(); IDbTransaction adoTransaction = A.Fake <IDbTransaction>(); A.CallTo(() => sessionFactory.OpenSession()).Returns(session); A.CallTo(() => session.Connection).Returns(connection); A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); A.CallTo(() => session.IsOpen).Returns(true); A.CallTo(() => adoTransaction.Connection).Returns(connection).Once(); 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) { } A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); }
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()); }
public void TransactionRollback() { SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); ConfigureServiceConfig(serviceConfig, standardIsolationAndProp: true); IServiceDomainAdapter txAdapter = A.Fake <IServiceDomainAdapter>(); A.CallTo(() => txAdapter.IsInTransaction).Returns(false).Once().Then.Returns(true); A.CallTo(() => txAdapter.Leave()).Returns(TransactionStatus.Commited); ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); tm.TransactionSynchronization = TransactionSynchronizationState.Always; TransactionTemplate tt = new TransactionTemplate(tm); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); Exception ex = new ArgumentException("test exception"); try { tt.Execute(new TransactionRollbackTxCallback(ex)); Assert.Fail("Should have thrown exception"); } catch (ArgumentException e) { Assert.AreEqual(ex, e); } Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); A.CallTo(() => txAdapter.SetAbort()).MustHaveHappenedOnceExactly(); A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappenedOnceExactly(); }
public PropagationRequiresNewWithExistingTransactionCallbackSD(TransactionTemplate tt) { this.tt = tt; }
public ParticipatingTransactionWithWithNotSupportedTxCallback(TransactionTemplate tt, ISessionFactory sf) { this.tt = tt; this.sf = sf; }
public ParticipatingTransactionWithWithRequiresNewTxCallback(TransactionTemplate tt, ISessionFactory sf) { this.tt = tt; this.sf = sf; }
public ParticipatingTransactionWithRollbackOnlyTxCallback(TransactionTemplate tt, ISessionFactory sf, IList list) { this.tt = tt; this.sf = sf; this.list = list; }
public void TransactionCommit() { IDbProvider provider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider)); IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection)); ISessionFactory sessionFactory = (ISessionFactory)mocks.CreateMock(typeof(ISessionFactory)); ISession session = (ISession)mocks.CreateMock(typeof(ISession)); ITransaction transaction = (ITransaction)mocks.CreateMock(typeof(ITransaction)); IQuery query = (IQuery)mocks.CreateMock(typeof(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(); }
/// <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 = (IDbConnection)mocks.CreateMock(typeof(IDbConnection)); ISessionFactory sessionFactory = (ISessionFactory)mocks.CreateMock(typeof(ISessionFactory)); ISession session = (ISession)mocks.CreateMock(typeof(ISession)); ITransaction transaction = (ITransaction)mocks.CreateMock(typeof(ITransaction)); IDbTransaction adoTransaction = (IDbTransaction)mocks.CreateMock(typeof(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 { #if NH_2_0 || NH_2_1 rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name"); #else rootCause = new PropertyValueException("mymsg", typeof(string), "Name"); #endif 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 TransactionWithPropagationSupportsAndInnerTransaction() { IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection)); ISessionFactory sessionFactory = (ISessionFactory)mocks.CreateMock(typeof(ISessionFactory)); ISession session1 = (ISession)mocks.CreateMock(typeof(ISession)); ISession session2 = (ISession)mocks.CreateMock(typeof(ISession)); ITransaction transaction = (ITransaction)mocks.CreateMock(typeof(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(); }
/// <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) { IDbProvider provider = new TestDbProvider(); DbConnection connection = A.Fake <DbConnection>(); ISessionFactory sessionFactory = A.Fake <ISessionFactory>(); ISession session = A.Fake <ISession>(); ITransaction transaction = A.Fake <ITransaction>(); IDbTransaction adoTransaction = A.Fake <IDbTransaction>(); Exception rootCause; A.CallTo(() => sessionFactory.OpenSession()).Returns(session); A.CallTo(() => session.Connection).Returns(connection); A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); A.CallTo(() => session.IsOpen).Returns(true); 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; A.CallTo(() => transaction.Commit()).Throws(new ADOException("mymsg", sqlException)); } else { rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name"); A.CallTo(() => transaction.Commit()).Throws(rootCause); } A.CallTo(() => adoTransaction.Connection).Returns(connection).Once(); 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"); A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); }
public SaveTransactionTemplateRequest(int ledgerId, TransactionTemplate transactionTemplate) { LedgerId = ledgerId; TransactionTemplate = transactionTemplate; }