本文整理汇总了C#中Spring.Transaction.Support.TransactionTemplate.Execute方法的典型用法代码示例。如果您正苦于以下问题:C# TransactionTemplate.Execute方法的具体用法?C# TransactionTemplate.Execute怎么用?C# TransactionTemplate.Execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Spring.Transaction.Support.TransactionTemplate
的用法示例。
在下文中一共展示了TransactionTemplate.Execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReturnConnectionAfterCommit
public void ReturnConnectionAfterCommit()
{
var txTemplate = new TransactionTemplate(new RabbitTemplateTestsTransactionManager());
var mockConnectionFactory = new Mock<ConnectionFactory>();
var mockConnection = new Mock<IConnection>();
var mockChannel = new Mock<IModel>();
mockConnectionFactory.Setup(m => m.CreateConnection()).Returns(mockConnection.Object);
mockConnection.Setup(m => m.IsOpen).Returns(true);
mockConnection.Setup(m => m.CreateModel()).Returns(mockChannel.Object);
mockChannel.Setup(m => m.IsOpen).Returns(true);
mockChannel.Setup(m => m.CreateBasicProperties()).Returns(() => new BasicProperties());
var template = new RabbitTemplate(new CachingConnectionFactory(mockConnectionFactory.Object));
template.ChannelTransacted = true;
txTemplate.Execute(
status =>
{
template.ConvertAndSend("foo", "bar");
return null;
});
txTemplate.Execute(
status =>
{
template.ConvertAndSend("baz", "qux");
return null;
});
mockConnectionFactory.Verify(m => m.CreateConnection(), Times.Once());
// ensure we used the same channel
mockConnection.Verify(m => m.CreateModel(), Times.Once());
}
示例2: TxTemplate
public void TxTemplate()
{
IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
dbProvider.ConnectionString = @"Data Source=MARKT60\SQL2005;Initial Catalog=CreditsAndDebits;User ID=springqa; Password=springqa";
//IPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager();
//IPlatformTransactionManager tm = new TxScopeTransactionManager();
IPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
AdoTemplate adoTemplate = new AdoTemplate(dbProvider);
TransactionTemplate tt = new TransactionTemplate(tm);
tt.PropagationBehavior = TransactionPropagation.Required;
tt.Execute(delegate(ITransactionStatus status)
{
if (System.Transactions.Transaction.Current != null) Console.WriteLine("tx 1 id = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier);
Console.WriteLine("tx 1 'IsNewTransaction' = " + status.IsNewTransaction);
adoTemplate.ExecuteNonQuery(CommandType.Text, "insert into Credits (CreditAmount) VALUES (@amount)", "amount", DbType.Decimal, 0,444);
TransactionTemplate tt2 = new TransactionTemplate(tm);
tt2.PropagationBehavior = TransactionPropagation.RequiresNew;
tt2.Execute(delegate(ITransactionStatus status2)
{
if (System.Transactions.Transaction.Current != null) Console.WriteLine("tx 2 = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier);
Console.WriteLine("tx 2 'IsNewTransaction' = " + status2.IsNewTransaction);
adoTemplate.ExecuteNonQuery(CommandType.Text, "insert into dbo.Debits (DebitAmount) VALUES (@amount)", "amount", DbType.Decimal, 0,555);
//throw new ArithmeticException("can't do the math.");
status2.SetRollbackOnly();
return null;
});
if (System.Transactions.Transaction.Current != null) Console.WriteLine("tx id1 = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier);
return null;
});
}
示例3: ParticipatingTransactionWithCommit
public void ParticipatingTransactionWithCommit()
{
IConnectionFactory connectionFactory = mocks.StrictMock<IConnectionFactory>();
IConnection connection = mocks.StrictMock<IConnection>();
ISession session = mocks.StrictMock<ISession>();
using (mocks.Ordered())
{
SetupCommitExpectations(connection, connectionFactory, session);
}
mocks.ReplayAll();
NmsTransactionManager tm = new NmsTransactionManager(connectionFactory);
ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition());
NmsTemplate nt = new NmsTemplate(connectionFactory);
nt.Execute(new AssertSessionCallback(session));
TransactionTemplate tt = new TransactionTemplate(tm);
tt.Execute(delegate(ITransactionStatus status)
{
nt.Execute(new AssertSessionCallback(session));
return null;
});
tm.Commit(ts);
mocks.VerifyAll();
}
示例4: TransactionCommit
public void TransactionCommit()
{
ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter) mocks.CreateMock(typeof(ITransactionScopeAdapter));
using (mocks.Ordered())
{
Expect.Call(txAdapter.IsExistingTransaction).Return(false);
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None);
Expect.Call(txAdapter.RollbackOnly).Return(false);
txAdapter.Complete();
txAdapter.Dispose();
}
mocks.ReplayAll();
TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm);
tt.Execute(status =>
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
return null;
});
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
mocks.VerifyAll();
}
示例5: NullResult
public void NullResult()
{
MockTxnPlatformMgr mock = new MockTxnPlatformMgr();
mock.SetExpectedGetTxnCallCount(1);
mock.SetExpectedCommitCallCount(1);
TransactionTemplate temp = new TransactionTemplate(mock);
temp.AfterPropertiesSet();
Assert.AreEqual( mock, temp.PlatformTransactionManager);
Assert.IsNull( temp.Execute(new TransactionDelegate(DummyTransactionMethod) ) );
mock.Verify();
}
示例6: NullResult
public void NullResult()
{
IPlatformTransactionManager mock = MockRepository.GenerateMock<IPlatformTransactionManager>();
TransactionTemplate temp = new TransactionTemplate(mock);
temp.AfterPropertiesSet();
Assert.AreEqual(mock, temp.PlatformTransactionManager);
Assert.IsNull(temp.Execute(new TransactionDelegate(DummyTransactionMethod)));
mock.AssertWasCalled(x => x.GetTransaction(Arg<ITransactionDefinition>.Is.Anything), constraints => constraints.Repeat.Once());
mock.AssertWasCalled(x => x.Commit(Arg<ITransactionStatus>.Is.Anything), constraints => constraints.Repeat.Once());
}
示例7: ExecuteException
public void ExecuteException()
{
MockTxnPlatformMgr mock = new MockTxnPlatformMgr();
mock.SetExpectedGetTxnCallCount(1);
mock.SetExpectedRollbackCallCount(1);
TransactionTemplate temp = new TransactionTemplate(mock);
try
{
temp.Execute(new TransactionDelegate(DummyExceptionMethod));
Assert.Fail("Should throw exception");
} catch
{
}
mock.Verify();
}
示例8: ExecuteException
public void ExecuteException()
{
IPlatformTransactionManager mock = MockRepository.GenerateMock<IPlatformTransactionManager>();
TransactionTemplate temp = new TransactionTemplate(mock);
try
{
temp.Execute(new TransactionDelegate(DummyExceptionMethod));
}
catch
{
}
mock.AssertWasCalled(x => x.GetTransaction(Arg<ITransactionDefinition>.Is.Anything), constraints => constraints.Repeat.Once());
mock.AssertWasCalled(x => x.Rollback(Arg<ITransactionStatus>.Is.Anything), constraints => constraints.Repeat.Once());
}
示例9: Commit
public void Commit()
{
TxScopeTransactionManager tm = new TxScopeTransactionManager();
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm);
//tt.Name = "txName";
Assert.AreEqual(TransactionSynchronizationState.Always, tm.TransactionSynchronization);
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsNull(TransactionSynchronizationManager.CurrentTransactionName);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
tt.Execute(CommitTxDelegate);
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsNull(TransactionSynchronizationManager.CurrentTransactionName);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
}
示例10: TransactionCommit
public void TransactionCommit()
{
#region Mock Setup
IServiceDomainAdapter txAdapter = (IServiceDomainAdapter) mocks.CreateMock(typeof (IServiceDomainAdapter));
using (mocks.Ordered())
{
Expect.Call(txAdapter.IsInTransaction).Return(false);
SimpleServiceConfig serviceConfig = new SimpleServiceConfig();
ConfigureServiceConfig(serviceConfig, true);
txAdapter.Enter(serviceConfig);
//ProcessCommit - status.GlobalRollbackOnly check
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
//DoCommit - status.GlobalRollbackOnly check
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
Expect.Call(txAdapter.IsInTransaction).Return(true);
//DoCommit - check to call SetComplete or SetAbort
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
txAdapter.SetComplete();
Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited);
}
#endregion
mocks.ReplayAll();
ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter);
TransactionTemplate tt = new TransactionTemplate(tm);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
tt.Execute(new TransactionDelegate(TransactionCommitMethod));
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
mocks.VerifyAll();
}
示例11: ExecuteTemplate
public void ExecuteTemplate()
{
ITestObjectDao dao = (ITestObjectDao)ctx["NHTestObjectDao"];
TransactionTemplate tt = new TransactionTemplate(transactionManager);
object result = tt.Execute(new SimpleTransactionCallback(dbProvider, dao));
TestObject to = result as TestObject;
Assert.IsNotNull(to,"FindByName for Gabriel should not return null");
Assert.AreEqual("Gabriel", to.Name);
}
示例12: DoTransactionWithTimeout
private void DoTransactionWithTimeout(int timeout)
{
#region Mock setup
IDbProvider dbProvider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));
IDbConnection connection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection));
IDbTransaction transaction = (IDbTransaction)mocks.CreateMock(typeof(IDbTransaction));
IDbCommand command = (IDbCommand) mocks.CreateMock(typeof (IDbCommand));
using (mocks.Ordered())
{
Expect.Call(dbProvider.CreateConnection()).Return(connection);
connection.Open();
LastCall.On(connection).Repeat.Once();
Expect.Call(connection.BeginTransaction(_defaultIsolationLevel)).Return(transaction);
Expect.Call(connection.CreateCommand()).Return(command);
command.CommandText = "some SQL statement";
LastCall.On(command).Repeat.Once();
if (timeout > 1)
{
command.CommandTimeout = (timeout - 1);
transaction.Commit();
} else
{
transaction.Rollback();
}
LastCall.On(transaction).Repeat.Once();
connection.Dispose();
}
#endregion
mocks.ReplayAll();
AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm);
tt.TransactionTimeout = timeout;
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");
try
{
tt.Execute(new TransactionWithTimeoutCallback(dbProvider));
if (timeout <= 1)
{
Assert.Fail("Should have thrown TransactionTimedOutException");
}
} catch (TransactionTimedOutException)
{
if (timeout <=1 )
{
//expected
} else
{
throw;
}
}
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider");
mocks.VerifyAll();
}
示例13: SendUsingMessageTx
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;
});
}
示例14: DoTransactionCommitWithFlushFailure
/// <summary>
/// Does the test transaction commit with flush failure.
/// </summary>
/// <param name="fallbackTranslation">if set to <c>true</c> if the exception throw
/// is of the type NHibernate.ADOException, in which case HibernateTransactionManager
/// will 'fallback' to using the error codes in the underlying exception thrown by
/// the provider, ie. a SqlException, MySqlException. Otherwise, if it is
/// another subclass of HibernateException, then perform a direct maping as
/// found in SessionFactoryUtils.ConvertHibernateAccessException.</param>
private void DoTransactionCommitWithFlushFailure(bool fallbackTranslation)
{
#region Mock Setup
IDbProvider provider = new TestDbProvider();
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();
Exception rootCause = null;
using (mocks.Ordered())
{
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
transaction.Commit();
Exception sqlException = new TestSqlException("mymsg", "2627");
if (fallbackTranslation)
{
//error code 2627 will map to a DataAccessIntegrity exception in sqlserver, which is the metadata
//used by TestDbProvider.
rootCause = sqlException;
LastCall.On(transaction).Throw(new ADOException("mymsg", sqlException));
}
else
{
rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name");
LastCall.On(transaction).Throw(rootCause);
}
Expect.Call(adoTransaction.Connection).Return(connection);
LastCall.On(adoTransaction).Repeat.Once();
transaction.Rollback();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null);
}
#endregion
mocks.ReplayAll();
TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
tm.DbProvider = provider;
tm.StubbedTransactionThatReturnsExpectedConnection = adoTransaction;
TransactionTemplate tt = new TransactionTemplate(tm);
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
IList list = new ArrayList();
list.Add("test");
try
{
tt.Execute(new TransactionCommitWithFlushFailureCallback(sessionFactory, list));
Assert.Fail("Should have thrown DataIntegrityViolationException");
}
catch (DataIntegrityViolationException ex)
{
Assert.AreEqual(rootCause, ex.InnerException);
Assert.IsTrue(ex.Message.IndexOf("mymsg") != -1);
}
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
mocks.VerifyAll();
}
示例15: TransactionWithPropagationSupports
public void TransactionWithPropagationSupports()
{
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.FlushMode).Return(FlushMode.Never);
session.FlushMode = FlushMode.Auto;
LastCall.IgnoreArguments();
session.Flush();
LastCall.IgnoreArguments();
session.FlushMode = FlushMode.Never;
Expect.Call(session.FlushMode).Return(FlushMode.Never);
mocks.ReplayAll();
LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);
lsfo.AfterPropertiesSet();
ISessionFactory sfProxy = (ISessionFactory) lsfo.GetObject();
Assert.IsNotNull(sfProxy);
HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm);
tt.PropagationBehavior = TransactionPropagation.Supports;
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
tt.Execute(new TransactionWithPropagationSupportsTxCallback(sessionFactory));
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
mocks.VerifyAll();
}