public void ExplicitTransaction1() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; try { IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; using (TransactionScope scope = new TransactionScope()) { Assert.Equal(ct, Transaction.Current); irm.Value = 4; scope.Complete(); } Assert.Equal(ct, Transaction.Current); Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); Assert.Equal(1, irm.Actual); ct.Commit(); Assert.Equal(4, irm.Actual); Assert.Equal(TransactionStatus.Committed, Transaction.Current.TransactionInformation.Status); } finally { Transaction.Current = oldTransaction; } }
// TODO: Issue #10353 - These variations need to be added once we have promotion support. /* [InlineData(CloneType.Normal, true, true, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.RepeatableRead, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.ReadCommitted, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.ReadUncommitted, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Snapshot, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Chaos, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Unspecified, false, false, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Serializable, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.RepeatableRead, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadCommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadUncommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Snapshot, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Chaos, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Unspecified, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Serializable, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.RepeatableRead, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadCommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadUncommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Snapshot, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Chaos, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Unspecified, true, true, TransactionStatus.Committed)] */ public void Run(CloneType cloneType, IsolationLevel isoLevel, bool forcePromote, bool completeClone, TransactionStatus expectedStatus ) { TransactionOptions options = new TransactionOptions { IsolationLevel = isoLevel, // Shorten the delay before a timeout for blocking clones. Timeout = TimeSpan.FromSeconds(1) }; CommittableTransaction tx = new CommittableTransaction(options); Transaction clone; switch (cloneType) { case CloneType.Normal: { clone = tx.Clone(); break; } case CloneType.BlockingDependent: { clone = tx.DependentClone(DependentCloneOption.BlockCommitUntilComplete); break; } case CloneType.RollbackDependent: { clone = tx.DependentClone(DependentCloneOption.RollbackIfNotComplete); break; } default: { throw new Exception("Unexpected CloneType - " + cloneType.ToString()); } } if (forcePromote) { HelperFunctions.PromoteTx(tx); } Assert.Equal(clone.IsolationLevel, tx.IsolationLevel); Assert.Equal(clone.TransactionInformation.Status, tx.TransactionInformation.Status); Assert.Equal(clone.TransactionInformation.LocalIdentifier, tx.TransactionInformation.LocalIdentifier); Assert.Equal(clone.TransactionInformation.DistributedIdentifier, tx.TransactionInformation.DistributedIdentifier); CommittableTransaction cloneCommittable = clone as CommittableTransaction; Assert.Null(cloneCommittable); try { tx.Commit(); } catch (TransactionAbortedException) { Assert.Equal(expectedStatus, TransactionStatus.Aborted); } Assert.Equal(expectedStatus, tx.TransactionInformation.Status); }
public void AsyncFail1() { Assert.Throws<InvalidOperationException>(() => { IntResourceManager irm = new IntResourceManager(1); CommittableTransaction ct = new CommittableTransaction(); /* Set ambient Tx */ Transaction.Current = ct; /* Enlist */ irm.Value = 2; IAsyncResult ar = ct.BeginCommit(null, null); IAsyncResult ar2 = ct.BeginCommit(null, null); }); }
public void AsyncFail2() { Assert.Throws<TransactionAbortedException>(() => { IntResourceManager irm = new IntResourceManager(1); CommittableTransaction ct = new CommittableTransaction(); /* Set ambient Tx */ Transaction.Current = ct; /* Enlist */ irm.Value = 2; irm.FailPrepare = true; IAsyncResult ar = ct.BeginCommit(null, null); ct.EndCommit(ar); }); }
public void ExplicitTransaction10() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { irm.Value = 2; TransactionScope scope = new TransactionScope(ct); Assert.Equal(ct, Transaction.Current); Assert.Throws<TransactionAbortedException>(() => ct.Commit()); irm.Check(0, 0, 1, 0, "irm"); } finally { Transaction.Current = null; } }
public static void TestCase_OutcomeRegistration(bool promote) { string testCaseDescription = string.Format( "TestCase_OutcomeRegistration promote={0}", promote ); Trace("**** " + testCaseDescription + " ****"); AutoResetEvent pspeCompleted = new AutoResetEvent(false); NonMSDTCPromoterEnlistment pspe = null; int numberOfCompletions = 0; CommittableTransaction tx = null; try { tx = new CommittableTransaction(TimeSpan.FromSeconds(5)); tx.TransactionCompleted += delegate (object sender, TransactionEventArgs completedArgs) { Trace("Completed event registered before PSPE"); numberOfCompletions++; Assert.Equal(TransactionStatus.Committed, completedArgs.Transaction.TransactionInformation.Status); }; pspe = (NonMSDTCPromoterEnlistment)CreatePSPEEnlistment(NonMsdtcPromoterTests.PromoterType1, NonMsdtcPromoterTests.PromotedToken1, pspeCompleted, /*nonMSDTC = */ true, tx, /*spcResponse=*/ TransactionStatus.Committed, /*expectRejection=*/ false ); tx.TransactionCompleted += delegate (object sender, TransactionEventArgs completedArgs) { Trace("Completed event registered after PSPE"); numberOfCompletions++; Assert.Equal(TransactionStatus.Committed, completedArgs.Transaction.TransactionInformation.Status); }; if (promote) { Promote(testCaseDescription, NonMsdtcPromoterTests.PromotedToken1, tx); tx.TransactionCompleted += delegate (object sender, TransactionEventArgs completedArgs) { Trace("Completed event registered after promote"); numberOfCompletions++; Assert.Equal(TransactionStatus.Committed, completedArgs.Transaction.TransactionInformation.Status); }; } tx.Commit(); } catch (Exception ex) { Assert.Null(ex); } tx.TransactionCompleted += delegate (object sender, TransactionEventArgs completedArgs) { Trace("Completed event registered after commit"); numberOfCompletions++; Assert.Equal(TransactionStatus.Committed, completedArgs.Transaction.TransactionInformation.Status); }; Assert.True(pspeCompleted.WaitOne(TimeSpan.FromSeconds(5))); if (promote) { Assert.True(pspe.Promoted); } else { Assert.False(pspe.Promoted); } Assert.Equal((promote ? 4 : 3), numberOfCompletions); TestPassed(); }
public void ExplicitTransaction7() { Assert.Throws<TransactionException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; ct.Commit(); /* Cannot accept any new work now, so TransactionException */ ct.Rollback(); }); }
public void ExplicitTransaction6() { Assert.Throws<InvalidOperationException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; ct.Commit(); ct.Commit(); }); }
public void ExplicitTransactionRollback() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; try { IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; Assert.Equal(TransactionStatus.Active, ct.TransactionInformation.Status); ct.Rollback(); Assert.Equal(1, irm.Value); Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status); } finally { Transaction.Current = oldTransaction; } }
public TxnBatch(IBTTransportProxy transportProxy, ControlledTermination control, IDtcTransaction comTxn, CommittableTransaction transaction, ManualResetEvent orderedEvent, bool makeSuccessCall) : base(transportProxy, makeSuccessCall) { this.control = control; this.comTxn = comTxn; this.transaction = transaction; this.orderedEvent = orderedEvent; }
public PromotedTx(CommittableTransaction commitTx) { DtcTxCreator.Trace("PromotedTx constructor"); _commitTx = commitTx; }
public DurableResourceManager(NpgsqlResourceManager rm, INpgsqlTransactionCallbacks callbacks, CommittableTransaction tx) { _callbacks = callbacks; }
public TxnBatch(IBTTransportProxy transportProxy, ControlledTermination control, CommittableTransaction transaction, ManualResetEvent orderedEvent, bool makeSuccessCall) : base(transportProxy, makeSuccessCall) { this.control = control; this.comTxn = TransactionInterop.GetDtcTransaction(transaction); // the System.Transactions transaction - must be the original transaction - only that can be used to commit this.transaction = transaction; this.orderedEvent = orderedEvent; }
public override void SendToEndpoint(global::Neuron.Esb.ESBMessage message, CommittableTransaction tx) { RaiseAdapterInfo(ErrorLevel.Info, string.Format("MESSAGE ID: {0} ~ TOPIC: {1}", message.Header.MessageId, message.Header.Topic)); TweetStatus(message); }
/// <summary> /// The Reciever always needs a transaction to protect its conversation, but a Service may wish to enlist other work /// in the transaction. TakeTransaction will detach the transaction that the conversation uses from the reciever and allow /// the server to enlist other work in it and control its fate. /// </summary> /// <returns></returns> public CommittableTransaction TakeTransaction() { CommittableTransaction tran = this.tx; tx = null; return tran; }
internal void EmployWorker(WorkerCard workerCard, WorkAssignment workAssignment, CommittableTransaction committableTransaction) { WorkerRunner workerRunner = null; switch (workAssignment.WorkRequest.WorkerIsolationLevel) { case WorkerIsolationLevel.SeparateAppDomain: workerRunner = new WorkerRunnerAppDomain(workerCard, workAssignment, committableTransaction); break; case WorkerIsolationLevel.SeparateProcess: workerRunner = new WorkerRunnerProcess(workerCard, workAssignment, committableTransaction); // Debug //workerRunner = new WorkerRunnerThread(workerCard, WorkAssignment, committableTransaction); break; case WorkerIsolationLevel.SeparateThread: case WorkerIsolationLevel.Default: default: workerRunner = new WorkerRunnerThread(workerCard, workAssignment, committableTransaction); break; } try { AllWorkerRunners.Add(workAssignment.WorkerId, workerRunner); } catch (Exception ex) { Tracer.Error("AllWorkerRunners.Add({0}) caused exception: {1}", workAssignment.WorkerId, ex); foreach (string workerId in AllWorkerRunners.Keys) { Tracer.Error("AllWorkerRunners contains worker {0}", workerId); } throw; } workerRunner.Run(); }
public static void TestCase_TransactionTimeout(bool promote) { string testCaseDescription = string.Format( "TestCase_TransactionTimeout promote={0}", promote ); Trace("**** " + testCaseDescription + " ****"); AutoResetEvent pspeCompleted = new AutoResetEvent(false); NonMSDTCPromoterEnlistment pspe = null; try { CommittableTransaction tx = new CommittableTransaction(TimeSpan.FromSeconds(3)); pspe = (NonMSDTCPromoterEnlistment)CreatePSPEEnlistment(NonMsdtcPromoterTests.PromoterType1, NonMsdtcPromoterTests.PromotedToken1, pspeCompleted, /*nonMSDTC = */ true, tx, /*spcResponse=*/ TransactionStatus.Committed, /*expectRejection=*/ false ); if (promote) { Promote(testCaseDescription, NonMsdtcPromoterTests.PromotedToken1, tx); } NoStressTrace(string.Format("There will be a 7 second delay here - {0}", DateTime.Now.ToString())); Task.Delay(TimeSpan.FromSeconds(7)).Wait(); NoStressTrace(string.Format("Woke up from sleep. Attempting Commit - {0}", DateTime.Now.ToString())); tx.Commit(); } catch (Exception ex) { if (ex.GetType() != typeof(TransactionAbortedException)) { TestFailed(testCaseDescription, string.Format("Unexpected exception {0}: {1}", ex.GetType().ToString(), ex.ToString())); return; } } if (pspeCompleted.WaitOne(TimeSpan.FromSeconds(5))) { if (!promote && pspe.Promoted) { TestFailed(testCaseDescription, "The enlistment promoted"); return; } if (promote && !pspe.Promoted) { TestFailed(testCaseDescription, "The enlistment was not promoted"); return; } if (!(pspe.Aborted)) { TestFailed(testCaseDescription, "The enlistment did not abort"); return; } TestPassed(true); } else { TestFailed(testCaseDescription, "Timeout waiting for enlistment outcomes"); } }
public SingleMessageReceiveTxnBatch(IBTTransportProxy transportProxy, ControlledTermination control, CommittableTransaction transaction, ManualResetEvent orderedEvent) : base(transportProxy, control, transaction, orderedEvent, true) { }
public static void TestCase_OutcomeRegistration(bool promote) { string testCaseDescription = string.Format( "TestCase_OutcomeRegistration promote={0}", promote ); Trace("**** " + testCaseDescription + " ****"); AutoResetEvent pspeCompleted = new AutoResetEvent(false); NonMSDTCPromoterEnlistment pspe = null; int numberOfCompletions = 0; CommittableTransaction tx = null; try { tx = new CommittableTransaction(TimeSpan.FromSeconds(5)); tx.TransactionCompleted += delegate (object sender, TransactionEventArgs completedArgs) { Trace("Completed event registered before PSPE"); numberOfCompletions++; if (completedArgs.Transaction.TransactionInformation.Status != TransactionStatus.Committed) { TestFailed(testCaseDescription, "Completed event registered before PSPE did not receive committed"); return; } }; pspe = (NonMSDTCPromoterEnlistment)CreatePSPEEnlistment(NonMsdtcPromoterTests.PromoterType1, NonMsdtcPromoterTests.PromotedToken1, pspeCompleted, /*nonMSDTC = */ true, tx, /*spcResponse=*/ TransactionStatus.Committed, /*expectRejection=*/ false ); tx.TransactionCompleted += delegate (object sender, TransactionEventArgs completedArgs) { Trace("Completed event registered after PSPE"); numberOfCompletions++; if (completedArgs.Transaction.TransactionInformation.Status != TransactionStatus.Committed) { TestFailed(testCaseDescription, "Completed event registered after PSPE did not receive committed"); return; } }; if (promote) { Promote(testCaseDescription, NonMsdtcPromoterTests.PromotedToken1, tx); tx.TransactionCompleted += delegate (object sender, TransactionEventArgs completedArgs) { Trace("Completed event registered after promote"); numberOfCompletions++; if (completedArgs.Transaction.TransactionInformation.Status != TransactionStatus.Committed) { TestFailed(testCaseDescription, "Completed event registered after promote did not receive committed"); return; } }; } tx.Commit(); } catch (Exception ex) { TestFailed(testCaseDescription, string.Format("Unexpected exception {0}: {1}", ex.GetType().ToString(), ex.ToString())); return; } tx.TransactionCompleted += delegate (object sender, TransactionEventArgs completedArgs) { Trace("Completed event registered after commit"); numberOfCompletions++; if (completedArgs.Transaction.TransactionInformation.Status != TransactionStatus.Committed) { TestFailed(testCaseDescription, "Completed event registered after commit did not receive committed"); return; } }; if (pspeCompleted.WaitOne(TimeSpan.FromSeconds(5))) { if (!promote && pspe.Promoted) { TestFailed(testCaseDescription, "The enlistment promoted"); return; } if (promote && !pspe.Promoted) { TestFailed(testCaseDescription, "The enlistment was not promoted"); return; } if (numberOfCompletions != (promote ? 4 : 3)) { TestFailed(testCaseDescription, string.Format("Unexpected number of completion event firings - {0}", numberOfCompletions)); return; } TestPassed(); } else { TestFailed(testCaseDescription, "Timeout waiting for enlistment outcomes"); } }
public AbortOnFailureReceiveTxnBatch(IBTTransportProxy transportProxy, ControlledTermination control, IDtcTransaction comTxn, CommittableTransaction transaction, ManualResetEvent orderedEvent, TxnAborted txnAborted) : base(transportProxy, control, comTxn, transaction, orderedEvent, false) { this.txnAborted = txnAborted; }
public void Rollback() { DtcTxCreator.Trace("PromotedTx.Rollback"); _commitTx.Rollback(); _commitTx = null; }
public AbortOnAllFailureReceiveTxnBatch(IBTTransportProxy transportProxy, ControlledTermination control, CommittableTransaction transaction, ManualResetEvent orderedEvent, StopProcessing stopProcessing) : base(transportProxy, control, transaction, orderedEvent, false) { this.stopProcessing = stopProcessing; }
public virtual async Task SaveChanges_uses_enlisted_transaction(bool async, bool autoTransactionsEnabled) { using (var transaction = new CommittableTransaction(TimeSpan.FromMinutes(10))) { using (var context = CreateContext()) { context.Database.EnlistTransaction(transaction); context.Database.AutoTransactionsEnabled = autoTransactionsEnabled; context.Add( new TransactionCustomer { Id = 77, Name = "Bobble" }); context.Entry(context.Set <TransactionCustomer>().OrderBy(c => c.Id).Last()).State = EntityState.Added; if (async) { await Assert.ThrowsAsync <DbUpdateException>(() => context.SaveChangesAsync()); } else { Assert.Throws <DbUpdateException>(() => context.SaveChanges()); } context.Database.AutoTransactionsEnabled = true; } if (AmbientTransactionsSupported) { Assert.Equal( RelationalResources.LogExplicitTransactionEnlisted(new TestLogger <TestRelationalLoggingDefinitions>()).GenerateMessage("Serializable"), Fixture.ListLoggerFactory.Log.First().Message); } else { Assert.Equal( RelationalResources.LogAmbientTransaction(new TestLogger <TestRelationalLoggingDefinitions>()).GenerateMessage(), Fixture.ListLoggerFactory.Log.First().Message); if (!autoTransactionsEnabled) { using (var context = CreateContext()) { context.Entry(context.Set <TransactionCustomer>().Single(c => c.Id == 77)).State = EntityState.Deleted; if (async) { await context.SaveChangesAsync(); } else { context.SaveChanges(); } } } } } AssertStoreInitialState(); }
void ProcessOpen() { CommittableTransaction tx = new CommittableTransaction(); txscope = new TransactionScope(tx); }
public void ExplicitTransaction3() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; try { IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { Assert.True(ct != Transaction.Current, "Scope with RequiresNew should have a new ambient transaction"); irm.Value = 3; scope.Complete(); } irm.Value = 2; Assert.Equal(3, irm.Actual); Assert.Equal(ct, Transaction.Current); ct.Commit(); Assert.Equal(2, irm.Actual); } finally { Transaction.Current = oldTransaction; } }
public async Task <IActionResult> Create(OrderViewModel viewModel) { if (ModelState.IsValid) { using (var transaction = new CommittableTransaction(new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })) { var user = await _dataContext.Users.Where(u => u.UserName == User.Identity.Name).FirstOrDefaultAsync(); try { var order = new Order { Id = viewModel.Id, StartDate = viewModel.StartDate.ToUniversalTime(), EndDate = viewModel.EndDate.ToUniversalTime(), Payment = viewModel.Payment, Deposit = viewModel.Deposit, Remarks = viewModel.Remarks, Pending = viewModel.Pending, Customer = await _dataContext.Customers.FindAsync(viewModel.CustomerId), Warehouse = await _dataContext.Warehouses.FindAsync(viewModel.WarehouseId), House = await _dataContext.Houses.FindAsync(viewModel.HouseId), DayPayment = await _dataContext.DayPayments.FindAsync(viewModel.DayPaymentId), TypePayment = await _dataContext.TypePayments.FindAsync(viewModel.TypePaymentId), Seller = await _dataContext.Sellers.FindAsync(viewModel.SellerId), Helper = await _dataContext.Helpers.FindAsync(viewModel.HelperId), Collector = await _dataContext.Collectors.FindAsync(viewModel.CollectorId), State = await _dataContext.States.FindAsync(viewModel.StateId), }; var details2 = _dataContext.OrderTmps.Where(pt => pt.Username == User.Identity.Name).ToList(); foreach (var detail2 in details2) { order = new Order { Id = viewModel.Id, StartDate = viewModel.StartDate.ToUniversalTime(), EndDate = viewModel.EndDate.ToUniversalTime(), Payment = viewModel.Payment, Deposit = viewModel.Deposit, Remarks = viewModel.Remarks, Pending = viewModel.Pending, Customer = await _dataContext.Customers.FindAsync(detail2.Customer.Id), Warehouse = await _dataContext.Warehouses.FindAsync(viewModel.WarehouseId), House = await _dataContext.Houses.FindAsync(viewModel.HouseId), DayPayment = await _dataContext.DayPayments.FindAsync(viewModel.DayPaymentId), TypePayment = await _dataContext.TypePayments.FindAsync(viewModel.TypePaymentId), Seller = await _dataContext.Sellers.FindAsync(viewModel.SellerId), Helper = await _dataContext.Helpers.FindAsync(viewModel.HelperId), Collector = await _dataContext.Collectors.FindAsync(detail2.Customer.Collector.Id), State = await _dataContext.States.FindAsync(viewModel.StateId), }; _dataContext.Orders.Add(order); _dataContext.OrderTmps.Remove(detail2); } _dataContext.Orders.Add(order); await _dataContext.SaveChangesAsync(); var details = _dataContext.OrderDetailTmps.Include(odt => odt.Product).Where(odt => odt.Username == User.Identity.Name).ToList(); foreach (var detail in details) { var orderDetail = new OrderDetail { Name = detail.Name, Price = detail.Price, Quantity = detail.Quantity, Order = await _dataContext.Orders.FindAsync(order.Id), Product = await _dataContext.Products.FindAsync(detail.Product.Id), }; _dataContext.OrderDetails.Add(orderDetail); _dataContext.OrderDetailTmps.Remove(detail); } await _dataContext.SaveChangesAsync(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); } } return(RedirectToAction(nameof(Index))); } viewModel.Houses = _combosHelper.GetComboHouses(); viewModel.TypePayments = _combosHelper.GetComboTypePayments(); viewModel.DayPayments = _combosHelper.GetComboDayPayments(); viewModel.Sellers = _combosHelper.GetComboSellers(); viewModel.Helpers = _combosHelper.GetComboHelpers(); viewModel.States = _combosHelper.GetComboStates(); viewModel.Warehouses = _combosHelper.GetComboWarehouses(); viewModel.Details = _dataContext.OrderDetailTmps.Where(odt => odt.Username == User.Identity.Name).ToList(); viewModel.Details2 = _dataContext.OrderTmps.Include(ot => ot.Customer).Where(ot => ot.Username == User.Identity.Name).ToList(); return(View(viewModel)); }
public void ExplicitTransaction6b() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { TransactionScope scope1 = new TransactionScope(); /* Enlist */ irm.Value = 2; scope1.Complete(); Assert.Throws<TransactionAbortedException>(() => ct.Commit()); irm.Check(0, 0, 1, 0, "irm"); scope1.Dispose(); } finally { Transaction.Current = null; } }
public async Task CrossEntityTransactionSendsFirstRollback() { await using var client = CreateCrossEntityTxnClient(); await using var queueA = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false); await using var queueB = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false); await using var queueC = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false); await using var noTxClient = CreateClient(); var senderA = noTxClient.CreateSender(queueA.QueueName); var receiverA = client.CreateReceiver(queueA.QueueName); var receiverB = client.CreateReceiver(queueB.QueueName); var senderB = client.CreateSender(queueB.QueueName); var senderC = client.CreateSender(queueC.QueueName); var receiverC = noTxClient.CreateReceiver(queueC.QueueName); var message = new ServiceBusMessage(); // B is the send via entity since it is first await senderB.SendMessageAsync(message); await senderA.SendMessageAsync(message); // you can't use a receiver after a sender (for a different entity) when using a Transaction Group because it would be // saying that you want to receive via the sender entity which isn't possible Assert.ThrowsAsync <InvalidOperationException>(async() => await receiverA.ReceiveMessageAsync()); // After the above throws, the session gets closed by the AMQP lib, so we are testing whether the fault tolerant session/controller // objects get re-created correctly. ServiceBusReceivedMessage receivedMessageB = await receiverB.ReceiveMessageAsync(); // If the transaction succeeds, then all the operations occurred on the same partition. var transaction = new CommittableTransaction(); using (var ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) { // this is allowed because it is on B await receiverB.CompleteMessageAsync(receivedMessageB); // send to C via B - this is allowed because we are sending await senderC.SendMessageAsync(message); ts.Complete(); } transaction.Rollback(); // Adding delay since transaction Commit/Rollback is an asynchronous operation. await Task.Delay(TimeSpan.FromSeconds(2)); await receiverB.AbandonMessageAsync(receivedMessageB); receivedMessageB = await receiverB.ReceiveMessageAsync(); Assert.IsNotNull(receivedMessageB); await receiverB.AbandonMessageAsync(receivedMessageB); var receivedMessageC = await receiverC.ReceiveMessageAsync(); Assert.IsNull(receivedMessageC); // If the transaction succeeds, then all the operations occurred on the same partition. using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { receivedMessageB = await receiverB.ReceiveMessageAsync(); // this is allowed because it is on B await receiverB.CompleteMessageAsync(receivedMessageB); // this will fail because it is not part of txn group Assert.ThrowsAsync <ServiceBusException>(async() => await senderA.SendMessageAsync(message)); ts.Complete(); } receivedMessageB = await receiverB.ReceiveMessageAsync(); Assert.IsNull(receivedMessageB); }
public void ExplicitTransaction9() { Assert.Throws<InvalidOperationException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); ct.BeginCommit(null, null); ct.BeginCommit(null, null); }); }
/// <summary>DB批次作業 /// </summary> public bool DBExec(string connstr, string SQL, List <List <SqlParameter> > dbParametersList, ref string errmsg) { bool result = true; SqlCommand dbCmd = new SqlCommand(); SqlConnection dbConn = new SqlConnection(connstr); dbConn.Open(); CommittableTransaction cTra = new CommittableTransaction(); dbConn.EnlistTransaction(cTra); dbCmd.Connection = dbConn; dbCmd.CommandTimeout = 10; try { dbCmd.CommandType = CommandType.Text; dbCmd.CommandText = SQL; if (dbParametersList != null) { errmsg = ""; foreach (List <SqlParameter> dbParameters in dbParametersList) { dbCmd.Parameters.Clear(); dbCmd.Parameters.AddRange(dbParameters.ToArray()); try { dbCmd.ExecuteNonQuery(); } catch (Exception ex) { errmsg = ex.Message; cTra.Rollback(); result = false; break; } } } //全部成功才 commit if (errmsg.Trim().Length == 0) { cTra.Commit(); } } catch (TransactionException tex) { if (!cTra.TransactionInformation.Status.Equals(TransactionStatus.Aborted)) { errmsg = tex.Message; cTra.Rollback(tex); result = false; } } catch (Exception ex) { errmsg = ex.Message; cTra.Rollback(); result = false; } finally { cTra.Dispose(); dbCmd.Dispose(); dbConn.Close(); dbConn.Dispose(); } return(result); }
public async Task TransactionThrowsWhenOperationsOfDifferentPartitionsAreInSameTransaction() { var queueName = TestConstants.PartitionedQueueName; var sender = new MessageSender(ConnectionString, queueName); var receiver = new MessageReceiver(ConnectionString, queueName); try { string body = Guid.NewGuid().ToString("N"); var message1 = new Message((body + "1").GetBytes()) { PartitionKey = "1" }; var message2 = new Message((body + "2").GetBytes()) { PartitionKey = "2" }; // Two send operations to different partitions. var transaction = new CommittableTransaction(); using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) { await sender.SendAsync(message1); await Assert.ThrowsAsync <InvalidOperationException>( async() => await sender.SendAsync(message2)); ts.Complete(); } transaction.Rollback(); // Adding delay since transaction Commit/Rollback is an asynchronous operation. // Operating on the same message should not be done. await Task.Delay(TimeSpan.FromSeconds(2)); // Two complete operations to different partitions. await sender.SendAsync(message1); await sender.SendAsync(message2); var receivedMessage1 = await receiver.ReceiveAsync(ReceiveTimeout); Assert.NotNull(receivedMessage1); var receivedMessage2 = await receiver.ReceiveAsync(ReceiveTimeout); Assert.NotNull(receivedMessage2); transaction = new CommittableTransaction(); using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) { await receiver.CompleteAsync(receivedMessage1.SystemProperties.LockToken); await Assert.ThrowsAsync <InvalidOperationException>( async() => await receiver.CompleteAsync(receivedMessage2.SystemProperties.LockToken)); ts.Complete(); } transaction.Rollback(); // Adding delay since transaction Commit/Rollback is an asynchronous operation. // Operating on the same message should not be done. await Task.Delay(TimeSpan.FromSeconds(2)); await receiver.CompleteAsync(receivedMessage1.SystemProperties.LockToken); await receiver.CompleteAsync(receivedMessage2.SystemProperties.LockToken); } catch (Exception e) { Console.WriteLine(e); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }
/// <summary> /// Initializes a new instance of the PSTransaction class. /// </summary> internal PSTransaction(RollbackSeverity rollbackPreference, TimeSpan timeout) { _transaction = new CommittableTransaction(timeout); RollbackPreference = rollbackPreference; _subscriberCount = 1; }
public static void TestCase_TransactionTimeout(bool promote) { string testCaseDescription = string.Format( "TestCase_TransactionTimeout promote={0}", promote ); Trace("**** " + testCaseDescription + " ****"); AutoResetEvent pspeCompleted = new AutoResetEvent(false); NonMSDTCPromoterEnlistment pspe = null; Assert.Throws<TransactionAbortedException>(() => { CommittableTransaction tx = new CommittableTransaction(TimeSpan.FromSeconds(1)); pspe = (NonMSDTCPromoterEnlistment)CreatePSPEEnlistment(NonMsdtcPromoterTests.PromoterType1, NonMsdtcPromoterTests.PromotedToken1, pspeCompleted, /*nonMSDTC = */ true, tx, /*spcResponse=*/ TransactionStatus.Committed, /*expectRejection=*/ false ); if (promote) { Promote(testCaseDescription, NonMsdtcPromoterTests.PromotedToken1, tx); } NoStressTrace(string.Format("There will be a 3 second delay here - {0}", DateTime.Now.ToString())); Task.Delay(TimeSpan.FromSeconds(3)).Wait(); NoStressTrace(string.Format("Woke up from sleep. Attempting Commit - {0}", DateTime.Now.ToString())); tx.Commit(); }); Assert.True(pspeCompleted.WaitOne(TimeSpan.FromSeconds(5))); if (promote) { Assert.True(pspe.Promoted); } else { Assert.False(pspe.Promoted); } Assert.True(pspe.Aborted); TestPassed(true); }
/// <summary> /// Initializes a new instance of the PSTransaction class using a CommittableTransaction. /// </summary> internal PSTransaction(CommittableTransaction transaction, RollbackSeverity severity) { _transaction = transaction; RollbackPreference = severity; _subscriberCount = 1; }
public static void TestCase_DisposeCommittableTransaction(bool promote) { string testCaseDescription = string.Format( "TestCase_DisposeCommittableTransaction promote={0}", promote ); Trace("**** " + testCaseDescription + " ****"); AutoResetEvent pspeCompleted = new AutoResetEvent(false); NonMSDTCPromoterEnlistment pspe = null; Transaction savedTransaction = null; try { CommittableTransaction tx = new CommittableTransaction(TimeSpan.FromMinutes(1)); savedTransaction = tx.Clone(); pspe = (NonMSDTCPromoterEnlistment)CreatePSPEEnlistment(NonMsdtcPromoterTests.PromoterType1, NonMsdtcPromoterTests.PromotedToken1, pspeCompleted, /*nonMSDTC = */ true, tx, /*spcResponse=*/ TransactionStatus.Committed, /*expectRejection=*/ false ); if (promote) { Promote(testCaseDescription, NonMsdtcPromoterTests.PromotedToken1, tx); } tx.Dispose(); tx.Commit(); } catch (Exception ex) { if (ex.GetType() != typeof(ObjectDisposedException)) { TestFailed(testCaseDescription, string.Format("Unexpected exception {0}: {1}", ex.GetType().ToString(), ex.ToString())); return; } } if (pspeCompleted.WaitOne(TimeSpan.FromSeconds(5))) { if (!promote && pspe.Promoted) { TestFailed(testCaseDescription, "The enlistment promoted"); return; } if (promote && !pspe.Promoted) { TestFailed(testCaseDescription, "The enlistment was not promoted"); return; } if (!(pspe.Aborted)) { TestFailed(testCaseDescription, "The enlistment did not abort"); return; } if (savedTransaction.TransactionInformation.Status != TransactionStatus.Aborted) { TestFailed(testCaseDescription, "The transaction did not abort"); return; } TestPassed(); } else { TestFailed(testCaseDescription, "Timeout waiting for enlistment outcomes"); } }
public async Task <BE_ResultadoTransaccion> Create(BE_TxExamenFisicoPollito value) { BE_ResultadoTransaccion vResultadoTransaccion = new BE_ResultadoTransaccion(); _metodoName = regex.Match(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name).Groups[1].Value.ToString(); vResultadoTransaccion.ResultadoMetodo = _metodoName; vResultadoTransaccion.ResultadoAplicacion = _aplicacionName; try { using (SqlConnection conn = new SqlConnection(context.DevuelveConnectionSQL())) { using (CommittableTransaction transaction = new CommittableTransaction()) { await conn.OpenAsync(); conn.EnlistTransaction(transaction); try { using (SqlCommand cmd = new SqlCommand(SP_INSERT, conn)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; SqlParameter oParam = new SqlParameter("@IdExamenFisico", value.IdExamenFisico); oParam.SqlDbType = SqlDbType.Int; oParam.Direction = ParameterDirection.Output; cmd.Parameters.Add(oParam); cmd.Parameters.Add(new SqlParameter("@CodigoEmpresa", value.CodigoEmpresa)); cmd.Parameters.Add(new SqlParameter("@CodigoPlanta", value.CodigoPlanta)); cmd.Parameters.Add(new SqlParameter("@FecRegistro", value.FecRegistro)); cmd.Parameters.Add(new SqlParameter("@ResponsableInvetsa", value.ResponsableInvetsa)); cmd.Parameters.Add(new SqlParameter("@ResponsablePlanta", value.ResponsablePlanta)); cmd.Parameters.Add(new SqlParameter("@NumeroNacedora", value.NumeroNacedora)); cmd.Parameters.Add(new SqlParameter("@Lote", value.Lote)); cmd.Parameters.Add(new SqlParameter("@PesoPromedio", value.PesoPromedio)); cmd.Parameters.Add(new SqlParameter("@EdadReproductora", value.EdadReproductora)); cmd.Parameters.Add(new SqlParameter("@Sexo", value.Sexo)); cmd.Parameters.Add(new SqlParameter("@LineaGenetica", value.LineaGenetica)); cmd.Parameters.Add(new SqlParameter("@Calificacion", value.Calificacion)); cmd.Parameters.Add(new SqlParameter("@Uniformidad", value.Uniformidad)); cmd.Parameters.Add(new SqlParameter("@IdCalidad", value.IdCalidad)); cmd.Parameters.Add(new SqlParameter("@FirmaInvetsa", value.FirmaInvetsa)); cmd.Parameters.Add(new SqlParameter("@FirmaPlanta", value.FirmaPlanta)); cmd.Parameters.Add(new SqlParameter("@EmailFrom", value.EmailFrom)); cmd.Parameters.Add(new SqlParameter("@EmailTo", value.EmailTo)); cmd.Parameters.Add(new SqlParameter("@FlgCerrado", value.FlgCerrado)); cmd.Parameters.Add(new SqlParameter("@IdUsuarioCierre", value.IdUsuarioCierre)); cmd.Parameters.Add(new SqlParameter("@FecCierre", value.FecCierre)); cmd.Parameters.Add(new SqlParameter("@RegUsuario", value.RegUsuario)); cmd.Parameters.Add(new SqlParameter("@RegEstacion", value.RegEstacion)); await cmd.ExecuteNonQueryAsync(); value.IdExamenFisico = (int)cmd.Parameters["@IdExamenFisico"].Value; } using (SqlCommand cmd = new SqlCommand(SP_MERGE_DETALLE, conn)) { foreach (BE_TxExamenFisicoPollitoDetalleNew item in value.ListDetalleNew) { cmd.Parameters.Clear(); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@IdExamenFisicoDetalle", item.IdExamenFisicoDetalle)); cmd.Parameters.Add(new SqlParameter("@IdExamenFisico", value.IdExamenFisico)); cmd.Parameters.Add(new SqlParameter("@NumeroPollito", item.NumeroPollito)); if (item.Factor == 0) { cmd.Parameters.Add(new SqlParameter("@IdProcesoDetalle", item.IdProcesoDetalle)); } else { cmd.Parameters.Add(new SqlParameter("@IdProcesoDetalle", item.Valor)); } cmd.Parameters.Add(new SqlParameter("@Valor", item.Valor)); cmd.Parameters.Add(new SqlParameter("@RegUsuario", value.RegUsuario)); cmd.Parameters.Add(new SqlParameter("@RegEstacion", value.RegEstacion)); await cmd.ExecuteNonQueryAsync(); } } using (SqlCommand cmd = new SqlCommand(SP_MERGE_DETALLE_RESUMEN, conn)) { foreach (BE_TxExamenFisicoPollitoResumen item in value.ListDetalleResumen) { cmd.Parameters.Clear(); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@IdExamenFisicoDetalle", item.IdExamenFisicoDetalle)); cmd.Parameters.Add(new SqlParameter("@IdExamenFisico", value.IdExamenFisico)); cmd.Parameters.Add(new SqlParameter("@IdProceso", item.IdProceso)); cmd.Parameters.Add(new SqlParameter("@Esperado", item.Esperado)); cmd.Parameters.Add(new SqlParameter("@Obtenido", item.Obtenido)); cmd.Parameters.Add(new SqlParameter("@RegUsuario", value.RegUsuario)); cmd.Parameters.Add(new SqlParameter("@RegEstacion", value.RegEstacion)); await cmd.ExecuteNonQueryAsync(); } } if (value.ListDetalleFotos != null) { if (value.ListDetalleFotos.Count() > 0) { using (SqlCommand cmd = new SqlCommand(SP_MERGE_DETALLE_FOTO, conn)) { foreach (BE_TxExamenFisicoPollitoDetalleFotos item in value.ListDetalleFotos) { cmd.Parameters.Clear(); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@IdExamenFisicoDetalle", item.IdExamenFisicoDetalle)); cmd.Parameters.Add(new SqlParameter("@IdExamenFisico", value.IdExamenFisico)); cmd.Parameters.Add(new SqlParameter("@Foto", item.Foto)); cmd.Parameters.Add(new SqlParameter("@RegUsuario", value.RegUsuario)); cmd.Parameters.Add(new SqlParameter("@RegEstacion", value.RegEstacion)); await cmd.ExecuteNonQueryAsync(); } } } } transaction.Commit(); vResultadoTransaccion.IdRegistro = (int)value.IdExamenFisico; vResultadoTransaccion.ResultadoCodigo = 0; vResultadoTransaccion.ResultadoDescripcion = "Se realizo correctamente"; } catch (Exception ex) { transaction.Rollback(); vResultadoTransaccion.ResultadoCodigo = -1; vResultadoTransaccion.ResultadoDescripcion = ex.Message.ToString(); return(vResultadoTransaccion); } } } } catch (Exception ex) { vResultadoTransaccion.ResultadoCodigo = -1; vResultadoTransaccion.ResultadoDescripcion = ex.Message.ToString(); return(vResultadoTransaccion); } return(vResultadoTransaccion); }
public byte[] CreatePromotedTx(ref PromotedTx promotedTx) { DtcTxCreator.Trace("DtcTxCreator.CreatePromotedTx"); byte[] propagationToken; CommittableTransaction commitTx = new CommittableTransaction(); promotedTx = new PromotedTx(commitTx); propagationToken = TransactionInterop.GetTransmitterPropagationToken(commitTx); return propagationToken; }
protected internal override void CommitWorkBatch(WorkflowCommitWorkBatchService.CommitWorkBatchCallback commitWorkBatchCallback) { ManualResetEvent event2; DbRetry retry = new DbRetry(this._enableRetries); short maxRetries = retry.MaxRetries; Label_0013: event2 = new ManualResetEvent(false); Transaction transaction = null; SharedConnectionInfo connectionInfo = null; try { if (null == Transaction.Current) { maxRetries = 0; transaction = new CommittableTransaction(); connectionInfo = new SharedConnectionInfo(this.dbResourceAllocator, transaction, false, event2); } else { transaction = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete); connectionInfo = new SharedConnectionInfo(this.dbResourceAllocator, transaction, true, event2); } this.AddToConnectionInfoTable(transaction, connectionInfo); using (TransactionScope scope = new TransactionScope(transaction)) { try { commitWorkBatchCallback(); scope.Complete(); } finally { this.RemoveConnectionFromInfoTable(transaction); event2.Set(); } } CommittableTransaction transaction2 = transaction as CommittableTransaction; if (transaction2 != null) { transaction2.Commit(); } DependentTransaction transaction3 = transaction as DependentTransaction; if (transaction3 != null) { transaction3.Complete(); } } catch (Exception exception) { transaction.Rollback(); WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SharedConnectionWorkflowCommitWorkBatchService caught exception from commitWorkBatchCallback: " + exception.ToString()); if (!retry.TryDoRetry(ref maxRetries)) { throw; } WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SharedConnectionWorkflowCommitWorkBatchService retrying commitWorkBatchCallback (retry attempt " + maxRetries.ToString(CultureInfo.InvariantCulture) + ")"); goto Label_0013; } finally { event2.Close(); if (transaction != null) { transaction.Dispose(); } } }
public void Commit() { DtcTxCreator.Trace("PromotedTx.Commit"); _commitTx.Commit(); _commitTx = null; }
public void ExplicitTransaction14() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); Transaction.Current = ct; try { irm.Value = 2; ct.Commit(); Assert.Equal(TransactionStatus.Committed, ct.TransactionInformation.Status); Assert.Throws<InvalidOperationException>(() => ct.BeginCommit(null, null)); } finally { Transaction.Current = null; } }
public SystemTransactionContext(TransactionOptions options) { _transaction = new CommittableTransaction(options); }
public void ExplicitTransaction16() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm0 = new IntResourceManager(3); IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); Transaction.Current = ct; try { irm.FailPrepare = true; irm.FailWithException = true; irm.Value = 2; irm0.Value = 6; var e = Assert.Throws<TransactionAbortedException>(() => ct.Commit()); Assert.NotNull(e.InnerException); Assert.IsType<NotSupportedException>(e.InnerException); irm.Check(1, 0, 0, 0, "irm"); irm0.Check(0, 0, 1, 0, "irm0"); } finally { Transaction.Current = null; } }
protected void btnInitAkcionnieCeny_Click(object sender, EventArgs e) { string ret = ""; SaalutDataClasses1DataContext context = new SaalutDataClasses1DataContext(); //------------------------------- var delStoreInfo = (from d in context.StoreInfos select d).FirstOrDefault(); string jurCo = delStoreInfo.Company; string jurF = delStoreInfo.AddressFact; context.StoreInfos.DeleteOnSubmit(delStoreInfo); context.SubmitChanges(); UKMDataBaseConnects utl = new UKMDataBaseConnects(); utl.InitialStoreInfoIns(); var newStoreInfo = (from d in context.StoreInfos select d).FirstOrDefault(); newStoreInfo.Company = jurCo; newStoreInfo.AddressFact = jurF; context.SubmitChanges(); //--------------------------------- var pricesAkcion = (from p in context.PricesAkcionnies select p).FirstOrDefault(); if (pricesAkcion != null) { return; } var store = (from s in context.StoreInfos where s.Active == true select s).FirstOrDefault(); CommittableTransaction tx = new CommittableTransaction(); // Create a connection object and data adapter MySqlConnection cnx = null; try { cnx = new MySqlConnection(connStr); MySqlDataAdapter adapter = new MySqlDataAdapter(); // = делаем текущий прайс лист магазина // Выбираем магазин string cmdText = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ; select item, price, version, deleted from ukmserver.trm_in_pricelist_items where pricelist_id = '" + store.ActPriceList_ID_UKM.ToString() + "' and deleted = 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ; "; MySqlCommand cmd = new MySqlCommand(cmdText, cnx); cmd.CommandTimeout = 30000; // Create a fill a Dataset DataSet ds = new DataSet(); adapter.SelectCommand = cmd; adapter.Fill(ds); DataTable pricesAkcionnie = ds.Tables[0]; if (pricesAkcionnie != null) { foreach (DataRow row1 in pricesAkcionnie.Rows) { string artikulA = (string)row1[0]; decimal priceA = (decimal)row1[1]; int version_priceA = (int)row1[2]; bool delete_priceA = (bool)row1[3]; double newPriceA = Double.Parse(priceA.ToString()); var good = (from g in context.Goods where g.Articul == artikulA select g).FirstOrDefault(); if (good == null) { continue; } //+ PricesAkcionnie npr1 = new PricesAkcionnie(); npr1.GoodID = good.ID; npr1.Price = newPriceA; npr1.Version_UKM = version_priceA; npr1.TimeStamp = DateTime.Now; npr1.Active = true; context.PricesAkcionnies.InsertOnSubmit(npr1); context.SubmitChanges(); //- } } tx.Commit(); } catch (MySqlException ex) { ret += "Error: " + ex.ToString(); tx.Rollback(); } finally { if (cnx != null) { cnx.Close(); } } return; }
public async Task <bool> Execute(UpdateResourcePermissionsParameter updateResourcePermissionsParameter) { if (updateResourcePermissionsParameter == null) { throw new ArgumentNullException(nameof(updateResourcePermissionsParameter)); } if (string.IsNullOrWhiteSpace(updateResourcePermissionsParameter.ResourceId)) { throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheResourceIdMustBeSpecified); } var resource = await _resourceSetRepository.Get(updateResourcePermissionsParameter.ResourceId).ConfigureAwait(false); if (resource == null) { throw new UmaResourceNotFoundException(); } if (updateResourcePermissionsParameter.Subject != resource.Owner) { throw new UmaNotAuthorizedException(); } var policiesToBeUpdated = resource.AuthPolicies.ToList(); var policiesToBeRemoved = new List <string>(); var length = policiesToBeUpdated.Count(); for (int i = length - 1; i >= 0; i--) { var policy = policiesToBeUpdated.ElementAt(i); var policyParameter = updateResourcePermissionsParameter.PolicyIds.FirstOrDefault(p => p == policy.Id); if (policyParameter == null) { policiesToBeUpdated.Remove(policy); policiesToBeRemoved.Add(policy.Id); } } using (var transaction = new CommittableTransaction(new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })) { try { var operations = new List <Task <bool> >(); foreach (var policyId in policiesToBeRemoved) { operations.Add(_policyRepository.Delete(policyId)); } await Task.WhenAll(operations).ConfigureAwait(false); transaction.Commit(); return(true); } catch { transaction.Rollback(); throw; } } }
public void ExplicitTransaction15() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(3); Assert.Null(Transaction.Current); Transaction.Current = ct; try { Assert.Throws<InvalidOperationException>(() => { using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; Transaction.Current = new CommittableTransaction(); irm2.Value = 6; } }); irm.Check(0, 0, 1, 0, "irm"); irm2.Check(0, 0, 1, 0, "irm2"); } finally { Transaction.Current = null; } }
// TODO: Issue #10353 - These variations need to be added once we have promotion support. /* * [InlineData(CloneType.Normal, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.RepeatableRead, false, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.ReadCommitted, false, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.ReadUncommitted, false, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.Snapshot, false, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.Chaos, false, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.Unspecified, false, false, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.Serializable, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.RepeatableRead, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadCommitted, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadUncommitted, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.Snapshot, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.Chaos, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.Unspecified, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.Serializable, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.RepeatableRead, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadCommitted, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadUncommitted, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.Snapshot, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.Chaos, true, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.Unspecified, true, true, TransactionStatus.Committed)] */ public void Run(CloneType cloneType, IsolationLevel isoLevel, bool forcePromote, bool completeClone, TransactionStatus expectedStatus) { TransactionOptions options = new TransactionOptions { IsolationLevel = isoLevel, // Shorten the delay before a timeout for blocking clones. Timeout = TimeSpan.FromSeconds(1) }; CommittableTransaction tx = new CommittableTransaction(options); Transaction clone; switch (cloneType) { case CloneType.Normal: { clone = tx.Clone(); break; } case CloneType.BlockingDependent: { clone = tx.DependentClone(DependentCloneOption.BlockCommitUntilComplete); break; } case CloneType.RollbackDependent: { clone = tx.DependentClone(DependentCloneOption.RollbackIfNotComplete); break; } default: { throw new Exception("Unexpected CloneType - " + cloneType.ToString()); } } if (forcePromote) { HelperFunctions.PromoteTx(tx); } Assert.Equal(clone.IsolationLevel, tx.IsolationLevel); Assert.Equal(clone.TransactionInformation.Status, tx.TransactionInformation.Status); Assert.Equal(clone.TransactionInformation.LocalIdentifier, tx.TransactionInformation.LocalIdentifier); Assert.Equal(clone.TransactionInformation.DistributedIdentifier, tx.TransactionInformation.DistributedIdentifier); CommittableTransaction cloneCommittable = clone as CommittableTransaction; Assert.Null(cloneCommittable); try { tx.Commit(); } catch (TransactionAbortedException) { Assert.Equal(expectedStatus, TransactionStatus.Aborted); } Assert.Equal(expectedStatus, tx.TransactionInformation.Status); }
public void ExplicitTransactionCommit() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; ct.Commit(); Assert.Equal(2, irm.Value); Assert.Equal(TransactionStatus.Committed, ct.TransactionInformation.Status); Transaction.Current = oldTransaction; }
public async Task TransactionThrowsWhenOperationsOfDifferentPartitionsAreInSameTransaction() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: false)) { var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusSender sender = client.CreateSender(scope.QueueName); ServiceBusReceiver receiver = client.CreateReceiver(scope.QueueName); string body = Guid.NewGuid().ToString("N"); ServiceBusMessage message1 = GetMessage(partitionKey: "1"); ServiceBusMessage message2 = GetMessage(partitionKey: "2"); // Two send operations to different partitions. var transaction = new CommittableTransaction(); using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) { await sender.SendMessageAsync(message1); Assert.ThrowsAsync <InvalidOperationException>( async() => await sender.SendMessageAsync(message2)); ts.Complete(); } transaction.Rollback(); // Adding delay since transaction Commit/Rollback is an asynchronous operation. // Operating on the same message should not be done. await Task.Delay(TimeSpan.FromSeconds(2)); // Two complete operations to different partitions. await sender.SendMessageAsync(message1); await sender.SendMessageAsync(message2); ServiceBusReceivedMessage receivedMessage1 = await receiver.ReceiveMessageAsync(); Assert.NotNull(receivedMessage1); ServiceBusReceivedMessage receivedMessage2 = await receiver.ReceiveMessageAsync(); Assert.NotNull(receivedMessage2); transaction = new CommittableTransaction(); using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) { await receiver.CompleteMessageAsync(receivedMessage1); Assert.ThrowsAsync <InvalidOperationException>( async() => await receiver.CompleteMessageAsync(receivedMessage2)); ts.Complete(); } transaction.Rollback(); // Adding delay since transaction Commit/Rollback is an asynchronous operation. // Operating on the same message should not be done. await Task.Delay(TimeSpan.FromSeconds(2)); await receiver.CompleteMessageAsync(receivedMessage1); // the service seems to abandon the message that // triggered the InvalidOperationException // in the transaction Assert.That( async() => await receiver.CompleteMessageAsync(receivedMessage2), Throws.InstanceOf <ServiceBusException>() .And.Property(nameof(ServiceBusException.Reason)) .EqualTo(ServiceBusException.FailureReason.MessageLockLost)); } }
public void ExplicitTransaction2() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; try { IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; using (TransactionScope scope = new TransactionScope()) { Assert.Equal(ct, Transaction.Current); /* Not calling scope.Complete scope.Complete ();*/ } Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status); Assert.Equal(ct, Transaction.Current); Assert.Equal(1, irm.Actual); Assert.Equal(1, irm.NumRollback); irm.Check(0, 0, 1, 0, "irm"); } finally { Transaction.Current = oldTransaction; } Assert.Throws<TransactionAbortedException>(() => ct.Commit()); }
public static void ListenerThreadProc(object queueListenerConfig) { QueueListenerConfig config = (QueueListenerConfig)queueListenerConfig; while (!stopping) { TransactionOptions to = new TransactionOptions(); to.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; to.Timeout = TimeSpan.MaxValue; CommittableTransaction tran = new CommittableTransaction(to); try { using (var con = new SqlConnection(config.ConnectionString)) { con.Open(); con.EnlistTransaction(tran); byte[] message = ServiceBrokerUtils.GetMessage(config.QueueName, con, TimeSpan.FromSeconds(10)); if (message == null) //no message available { tran.Commit(); con.Close(); continue; } try { if (config.EnlistMessageProcessor) { using (var ts = new TransactionScope(tran)) { config.MessageProcessor(message); ts.Complete(); } } else { config.MessageProcessor(message); } } catch (SqlException ex) //catch selected exceptions thrown by the MessageProcessor { config.FailedMessageProcessor(message, con, ex); } tran.Commit(); // the message processing succeeded or the FailedMessageProcessor ran so commit the RECEIVE con.Close(); } } catch (SqlException ex) { System.Diagnostics.Trace.Write("Error processing message from " + config.QueueName + ": " + ex.Message); tran.Rollback(); tran.Dispose(); Thread.Sleep(1000); } ///catch any other non-fatal exceptions that should not stop the listener loop. catch (Exception ex) { Trace.WriteLine("Unexpected Exception in Thread Proc for " + config.QueueName + ". Thread Proc is exiting: " + ex.Message); tran.Rollback(); tran.Dispose(); return; } } }
public void ExplicitTransaction5() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; /* Not setting ambient transaction Transaction.Current = ct; */ IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope(ct)) { Assert.Equal(ct, Transaction.Current); irm.Value = 2; /* Not completing this scope scope.Complete (); */ } Assert.Equal(oldTransaction, Transaction.Current); Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status); Assert.Equal(1, irm.Actual); irm.Check(0, 0, 1, 0, "irm"); }
//----------------------------------- //Genera Cargo Solicitud Colegiado //----------------------------------- public bool Ins_GenerarCargoSolicitud(string CodEmpresa, long TipoPrograma, long TipoSolicitud, string cPerCodigo, int nPeriodo, DateTime dFechaSys, string NroSolicitud) { bool exito = false; string NroRecibo = ""; long nLinea = 0; //double nImporte = 0; //para Tipo de cambio double nTC = 0; BL_Sistema daTC = new BL_Sistema(); //para CtaCteItem BL_CtaCteItem blCCItem = new BL_CtaCteItem(); BL_CtaCteIteLine blCCItemLine = new BL_CtaCteIteLine(); BL_CtaCteIteLinRetencion blCCRetencion = new BL_CtaCteIteLinRetencion(); BL_ImpuestoServicio blImpServ = new BL_ImpuestoServicio(); //para Obtener Serv. Configurado BE_ReqCtaCteSysConfigParamterServicio ReqServConfig = new BE_ReqCtaCteSysConfigParamterServicio(); BL_CtaCteSysConfigParamterServicio daServConfig = new BL_CtaCteSysConfigParamterServicio(); //actuliza solicitud con el recibo de cargo BL_Solicitud DaSolAdm = new BL_Solicitud(); //---------------------- //CommittableTransaction //---------------------- Transaction oldAmbient = Transaction.Current; CommittableTransaction committableTransaction; committableTransaction = oldAmbient as CommittableTransaction; if (committableTransaction == null) { committableTransaction = new CommittableTransaction(); Transaction.Current = committableTransaction; } try { //using (TransactionScope tx = new TransactionScope(TransactionScopeOption.Required)) //{ // ReqServConfig.cPerJurCodigo = CodEmpresa; ReqServConfig.nSisModulo = 7001; //default aun falta definir interface ReqServConfig.nParCodigo_nProCodigo = TipoSolicitud; //CLng(CboPrograma.SelectedValue) ReqServConfig.cFLag = "FEC"; if (daServConfig.Get_SysConfParametrosServ(ReqServConfig).Rows.Count > 0) { DataRow row = daServConfig.Get_SysConfParametrosServ(ReqServConfig).Rows[0]; //-------------- //Tipo de cambio //-------------- if (Convert.ToInt32(row["nMonCodigo"]) == 2) //Dolar { if (daTC.Get_TipodeCambio(Convert.ToInt32(row["nMonCodigo"]), "TCD", String.Format("{0:dd/MM/yyyy}", dFechaSys), 0, 0).Rows.Count > 0) { //DataRow row = daTC.Get_TipodeCambio(ReqTC).Rows[0]; nTC = Convert.ToDouble(daTC.Get_TipodeCambio(Convert.ToInt32(row["nMonCodigo"]), "TCD", String.Format("{0:dd/MM/yyyy}", dFechaSys), 0, 0).Rows[0]["nCompra"]); } else { throw new ApplicationException("No se ha registrado el Tipo de Cambio del dia: " + String.Format("{0:ddd, MMM d, yyyy}", dFechaSys)); } } else { nTC = 1.0; } //---------- //CtaCteItem //---------- //se comente esto porque la Actualizacion 28/01/2014 no se necesita esta variable //foreach (DataRow fila in daServConfig.Get_SysConfParametrosServ(ReqServConfig).Rows) //{ // //Obteniendo el total del importe de recibo (cabezera) // nImporte = nImporte + Convert.ToDouble(fila["nSysValor"]); //} //Actualizacion 28/01/2014: //porque necesitan que cada concepto salga en diferente recibo //NroRecibo = blCCItem.Ins_CtaCteItem(CodEmpresa, cPerCodigo, nPeriodo, row["nCtaCteTipoCta"].ToString(), dFechaSys.Year, nImporte, dFechaSys, 1); //-------------- //CtaCteIteLine //-------------- //Recorro SysConfParametrosServ foreach (DataRow fila in daServConfig.Get_SysConfParametrosServ(ReqServConfig).Rows) { //aqui se cambio Actualizacion 28/01/2014: NroRecibo = blCCItem.Ins_CtaCteItem(CodEmpresa, cPerCodigo, nPeriodo, row["nCtaCteTipoCta"].ToString(), dFechaSys.Year, Convert.ToDouble(fila["nSysValor"]), dFechaSys, 1); nLinea = blCCItemLine.Ins_CtaCteIteLine(CodEmpresa, cPerCodigo, NroRecibo, Convert.ToInt32(fila["nParCodigo_nCtaCteSerCodigo"]), Convert.ToInt32(fila["nMonCodigo"]), 1, Convert.ToDouble(fila["nSysValor"]), Convert.ToDouble(fila["nSysValor"]), nTC, 1); if (nLinea != 0) { //--------------------- //CtaCteIteLinRetencion //--------------------- foreach (DataRow posicion in blImpServ.Get_ImpuestoServicio(CodEmpresa, cPerCodigo, NroRecibo, Convert.ToInt32(fila["nParCodigo_nCtaCteSerCodigo"]), 9256).Rows) //9256.- Perú { if (!blCCRetencion.Ins_CtaCteIteLinRetencion(CodEmpresa, cPerCodigo, NroRecibo, nLinea, Convert.ToInt32(posicion["nSysTasCodigo"]), Convert.ToDouble(fila["nSysValor"]), Convert.ToInt32(posicion["fSysTasValor"]), dFechaSys)) { throw new ApplicationException("Se encontraron errores en la transaccion: Ins_CtaCteIteLinRetencion.!"); } } } else { throw new ApplicationException("Se encontraron errores en la transaccion: Ins_CtaCteIteLine.!"); } } //------------------------------------------------------------------------------ //update AdmSolicitud (cCtaCteRecibo) - Referenciando recibo en "AdmSolicitud" ? //------------------------------------------------------------------------------ if (!DaSolAdm.Upd_AdmSol_cCtaCteRecibo(CodEmpresa, TipoPrograma, NroSolicitud, NroRecibo)) { throw new ApplicationException("Se encontraron errores en la transaccion: AdmSolicitud.! " + CodEmpresa + ' ' + TipoPrograma + ' ' + NroSolicitud + ' ' + NroRecibo); } //exito = true; //tx.Complete(); /* Perform transactional work here */ //No errors - commit transaction committableTransaction.Commit(); exito = true; } else { throw new ApplicationException("Configuracion de parametros no establecida.!"); } } //} catch (Exception) { committableTransaction.Rollback(); throw; } finally { committableTransaction.Dispose(); //Restore the ambient transaction Transaction.Current = oldAmbient; } return(exito); }
public void ExplicitTransaction6a() { Assert.Throws<InvalidOperationException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; ct.Commit(); /* Using a already committed transaction in a new * TransactionScope */ TransactionScope scope = new TransactionScope(ct); }); }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // thread per endpoint batch private void BatchWorker(string outboundTransportLocation, ArrayList messages) { // we did an enter for every message - so we should ensure we have a correspending leave int leaveCount = messages.Count; try { // all the messages in this batch should have the same properties - so just take the first one IBaseMessage firstMessage = (IBaseMessage)messages[0]; SystemMessageContext firstMessageContext = new SystemMessageContext(firstMessage.Context); TransactionalTransmitProperties properties = new TransactionalTransmitProperties(firstMessageContext.OutboundTransportLocation); string config = (string)firstMessage.Context.Read("AdapterConfig", this.propertyNamespace); if (config != null) { // There is a configuration DOM so we are doing a Static Send XmlDocument locationConfigDom = new XmlDocument(); locationConfigDom.LoadXml(config); properties.LocationConfiguration(locationConfigDom); } else { // Add dynamic send here } foreach (IBaseMessage message in messages) { CommittableTransaction transaction = null; try { // create the System.Transactions transaction - this is not yet a DTC transaction transaction = new CommittableTransaction(); // give the CommittableTransaction to the batch and it will take the responsibility to Commit it. // the TransactionInterop.GetDtcTransaction call inside the base TxnBase class actually causes the // DTC transaction to be created - this can be observed in the COM+ Explorer while debugging this code using (Batch batch = new TransactionalDeleteBatch(this.transportProxy, this.control, transaction)) { // note the options EnterpriseServicesInteropOption.Full in the future when resource managers // understand light weight transactions this might not be necessary but we need it for now using (TransactionScope ts = new TransactionScope(transaction, TimeSpan.FromHours(1), EnterpriseServicesInteropOption.Full)) { SendMessage(message, properties); // an exception will skip this next line ts.Complete(); } // IMPORTANT: a Delete is part of the same transaction as the send operation batch.DeleteMessage(message); // IMPORTANT: if there was a response to submit it would be added here // - in the same batch and same transaction as the Delete batch.Done(); } } catch (Exception e) { // in this scenario we will explicitly Rollback the transaction on failure if (transaction != null) { transaction.Rollback(); } // Remember to set the exception on the message itself - this will now appear in tracking in addition to the EventLog message.SetErrorInfo(e); // Any failures need to be retried - but the change of state back on BizTalk is outside of the transaction // that has been used to attempt to send the message - after all that transaction will undoubtedly get rollback with the failure. // We say this batch is "non-transactional" from the adapter's point of view - though internally in BizTalk its still a transaction. using (TransmitResponseBatch batch = new TransmitResponseBatch(this.transportProxy, new TransmitResponseBatch.AllWorkDoneDelegate(AllWorkDone))) { batch.Resubmit(message, false, null); batch.Done(); } } // an exception will skip this line - an exception means the Done hasn't been called or was successful so we have a leave to do leaveCount--; } } catch (Exception e) { this.transportProxy.SetErrorInfo(e); } finally { // perform any remain leaves - hopefully none - if everything was successful then leaveCount will be 0 for (int i = 0; i < leaveCount; i++) { this.control.Leave(); } } }
public void ExplicitTransaction6e() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { TransactionScope scope1 = new TransactionScope(); /* Enlist */ irm.Value = 2; TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress); Assert.Throws<InvalidOperationException>(() => scope1.Dispose()); scope2.Dispose(); } finally { Transaction.Current = null; } }
public void CanUseSessionWithManyDependentTransaction(bool explicitFlush) { if (!TestDialect.SupportsDependentTransaction) { Assert.Ignore("Dialect does not support dependent transactions"); } IgnoreIfUnsupported(explicitFlush); try { using (var s = Sfi.WithOptions().ConnectionReleaseMode(ConnectionReleaseMode.OnClose).OpenSession()) { using (var committable = new CommittableTransaction()) { System.Transactions.Transaction.Current = committable; using (var clone = committable.DependentClone(DependentCloneOption.RollbackIfNotComplete)) { System.Transactions.Transaction.Current = clone; if (!AutoJoinTransaction) { s.JoinTransaction(); } // Acquire the connection var count = s.Query <Person>().Count(); Assert.That(count, Is.EqualTo(0), "Unexpected initial entity count."); clone.Complete(); } using (var clone = committable.DependentClone(DependentCloneOption.RollbackIfNotComplete)) { System.Transactions.Transaction.Current = clone; if (!AutoJoinTransaction) { s.JoinTransaction(); } s.Save(new Person()); if (explicitFlush) { s.Flush(); } clone.Complete(); } using (var clone = committable.DependentClone(DependentCloneOption.RollbackIfNotComplete)) { System.Transactions.Transaction.Current = clone; if (!AutoJoinTransaction) { s.JoinTransaction(); } var count = s.Query <Person>().Count(); Assert.That(count, Is.EqualTo(1), "Unexpected entity count after committed insert."); clone.Complete(); } System.Transactions.Transaction.Current = committable; committable.Commit(); } } } finally { System.Transactions.Transaction.Current = null; } DodgeTransactionCompletionDelayIfRequired(); using (var s = OpenSession()) { using (var tx = new TransactionScope()) { if (!AutoJoinTransaction) { s.JoinTransaction(); } var count = s.Query <Person>().Count(); Assert.That(count, Is.EqualTo(1), "Unexpected entity count after global commit."); tx.Complete(); } } }
public void ExplicitTransaction8a() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope(ct)) { irm.Value = 2; scope.Complete(); Assert.Throws<TransactionAbortedException>(() => ct.Commit()); /* FIXME: Why TransactionAbortedException ?? */ irm.Check(0, 0, 1, 0, "irm"); } }
/// <summary> /// /// </summary> public void ReSet() { _ct = new CommittableTransaction(_ops); _done = false; }
public void ExplicitTransaction12() { Assert.Throws<ArgumentException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.FailPrepare = true; ct.BeginCommit(null, null); ct.EndCommit(null); }); }
// These variations need to be added once we have promotion support. /* * [InlineData(CloneType.Normal, true, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.RepeatableRead, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.ReadCommitted, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.ReadUncommitted, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.Snapshot, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.Chaos, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, IsolationLevel.Unspecified, false, TransactionStatus.Committed)] * [InlineData(CloneType.Normal, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.Serializable, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.RepeatableRead, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadCommitted, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadUncommitted, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.Snapshot, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.Chaos, true, TransactionStatus.Committed)] * [InlineData(CloneType.BlockingDependent, IsolationLevel.Unspecified, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.Serializable, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.RepeatableRead, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadCommitted, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadUncommitted, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.Snapshot, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.Chaos, true, TransactionStatus.Committed)] * [InlineData(CloneType.RollbackDependent, IsolationLevel.Unspecified, true, TransactionStatus.Committed)] */ public void Run(CloneType cloneType, IsolationLevel isoLevel, bool forcePromote, TransactionStatus expectedStatus) { TransactionOptions options = new TransactionOptions { IsolationLevel = isoLevel, // Shorten the delay before a timeout for blocking clones. Timeout = TimeSpan.FromSeconds(1) }; // If we are dealing with a "normal" clone, we fully expect the transaction to commit successfully. // But a timeout of 1 seconds may not be enough for that to happen. So increase the timeout // for "normal" clones. This will not increase the test execution time in the "passing" scenario. if (cloneType == CloneType.Normal) { options.Timeout = TimeSpan.FromSeconds(10); } CommittableTransaction tx = new CommittableTransaction(options); Transaction clone; switch (cloneType) { case CloneType.Normal: { clone = tx.Clone(); break; } case CloneType.BlockingDependent: { clone = tx.DependentClone(DependentCloneOption.BlockCommitUntilComplete); break; } case CloneType.RollbackDependent: { clone = tx.DependentClone(DependentCloneOption.RollbackIfNotComplete); break; } default: { throw new Exception("Unexpected CloneType - " + cloneType.ToString()); } } if (forcePromote) { HelperFunctions.PromoteTx(tx); } Assert.Equal(tx.IsolationLevel, clone.IsolationLevel); Assert.Equal(tx.TransactionInformation.Status, clone.TransactionInformation.Status); Assert.Equal(tx.TransactionInformation.LocalIdentifier, clone.TransactionInformation.LocalIdentifier); Assert.Equal(tx.TransactionInformation.DistributedIdentifier, clone.TransactionInformation.DistributedIdentifier); CommittableTransaction cloneCommittable = clone as CommittableTransaction; Assert.Null(cloneCommittable); try { tx.Commit(); } catch (TransactionAbortedException ex) { Assert.Equal(TransactionStatus.Aborted, expectedStatus); switch (cloneType) { case CloneType.Normal: { // We shouldn't be getting TransactionAbortedException for "normal" clones, // so we have these two Asserts to possibly help determine what went wrong. Assert.Null(ex.InnerException); Assert.Equal("There shouldn't be any exception with this Message property", ex.Message); break; } case CloneType.BlockingDependent: { Assert.IsType <TimeoutException>(ex.InnerException); break; } case CloneType.RollbackDependent: { Assert.Null(ex.InnerException); break; } default: { throw new Exception("Unexpected CloneType - " + cloneType.ToString()); } } } Assert.Equal(expectedStatus, tx.TransactionInformation.Status); }