internal void Success_ReturnsCorrectResult(TransactionStatus transactionStatus, bool statusSuccess, bool expected) { Status status = Factory.CreateStatus(statusSuccess); CreditResult creditResult = new CreditResult { Status = status, TransactionStatus = transactionStatus }; Assert.AreEqual(expected, creditResult.Success); }
private TransactionInformation(TransactionInformation other) { this.local_id = other.local_id; this.dtcId = other.dtcId; this.creation_time = other.creation_time; this.status = other.status; }
private void InvokeOutcomeFunction(TransactionStatus status) { WeakReference weakRealTransaction = null; lock (this) { if (this.haveIssuedOutcome) { return; } this.haveIssuedOutcome = true; this.savedStatus = status; weakRealTransaction = this.weakRealTransaction; } if (weakRealTransaction != null) { RealOletxTransaction target = weakRealTransaction.Target as RealOletxTransaction; if (target != null) { target.FireOutcome(status); if (target.phase0EnlistVolatilementContainerList != null) { foreach (OletxPhase0VolatileEnlistmentContainer container in target.phase0EnlistVolatilementContainerList) { container.OutcomeFromTransaction(status); } } if (((TransactionStatus.Aborted == status) || (TransactionStatus.InDoubt == status)) && (target.phase1EnlistVolatilementContainer != null)) { target.phase1EnlistVolatilementContainer.OutcomeFromTransaction(status); } } weakRealTransaction.Target = null; } }
private TransactionInformation (TransactionInformation other) { local_id = other.local_id; dtcId = other.dtcId; creation_time = other.creation_time; status = other.status; }
public void Success_ReturnsCorrectResult(TransactionStatus transactionStatus, bool statusSuccess, bool expected) { Status status = Factory.CreateStatus(statusSuccess); CompleteResult completeResult = new CompleteResult { Status = status, TransactionStatus = transactionStatus }; Assert.AreEqual(expected, completeResult.Success); }
// 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 Constructor_Empty() { var actual = new TransactionStatus(); Assert.AreEqual(TransactionStatusCode.NotExecuted, actual.StatusCode); Assert.AreEqual("", actual.ErrorMessage); Assert.AreEqual("", actual.TransactionInfo); }
public IList<OutgoingSingleCredit> GetAllOutgoingSingleCredit(TransactionStatus transactionStatus) { using (var db = new RTGSGen2DBContext(connectionString)) { IList<OutgoingSingleCredit> outgoingSingleCreditList = db.GetAllOutgoingSingleCredit().ToList(); return outgoingSingleCreditList .Where(o => o.Status == transactionStatus.ToString()).ToList(); } }
/// <summary> /// Creates a response message confirming delivery of transaction result /// </summary> /// <param name="status">Result of delivery (note this is to confirm that you have received the result, not the result itself)</param> /// <param name="message">Optional message for example, any exceptions that may have occurred</param> /// <returns>String</returns> public string CreateServerResponseString(TransactionStatus status, string message = "") { var response = new NameValueCollection(); response.Add("StatusCode", (int)status); if (!string.IsNullOrEmpty(message)) { response.Add("Message", message); } return response.ToQueryString(); }
/// <summary> /// /// </summary> /// <param name="documentName">the name of the Document</param> protected Document(string documentName) { this.documentName = documentName; //this.hasNoTransactionStatus = true; this.hasNoLogStatus = true; this.status = TransactionStatus.Success; this.message = ""; this.properties = new Dictionary<string, Property>(); this.collections = new Dictionary<string, DocumentCollection>(); }
public TransactionInfo(Guid txnJobId, TransactionStatus txnStatus, TransactionType txnType, ulong dataStart, ulong dataLength, DateTime txnStartTime) { VersionNumber = 1; JobId = txnJobId; TransactionStatus = txnStatus; TransactionType = txnType; DataStartPosition = dataStart; DataLength = dataLength; TransactionStartTime = txnStartTime.ToUniversalTime(); }
internal OletxVolatileEnlistment(IEnlistmentNotificationInternal enlistmentNotification, EnlistmentOptions enlistmentOptions, OletxTransaction oletxTransaction) : base(null, oletxTransaction) { this.iEnlistmentNotification = enlistmentNotification; this.enlistDuringPrepareRequired = (enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != EnlistmentOptions.None; this.container = null; this.pendingOutcome = TransactionStatus.Active; if (DiagnosticTrace.Information) { EnlistmentTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), base.InternalTraceIdentifier, EnlistmentType.Volatile, enlistmentOptions); } }
public void Constructor_DataTableWithColumnsButBadRows() { // Arrange var dt = new DataTable(); dt.Columns.Add(new DataColumn("ErrorCode")); dt.Columns.Add(new DataColumn("ErrorMessage")); dt.Columns.Add(new DataColumn("TransactionInfo")); var test = new TransactionStatus(dt); Assert.IsNotNull(test); }
public Result<List<CreditTransaction>> SetExchangeStatus(IDbConnection db, string orderId, TransactionStatus newStatus) { // TODO // Step 1: Find and Update CoinTransaction 's status to "failure" // Step 2: If not found, try on FreeCoinTransaction. Status to "failure" // Step 3: CreditTransaction status also mark as "failure" // TEST // return Result<List<CreditTransaction>>.Null(); }
internal void InDoubt() { OletxVolatileEnlistmentState active = OletxVolatileEnlistmentState.Active; IEnlistmentNotificationInternal iEnlistmentNotification = null; lock (this) { if (OletxVolatileEnlistmentState.Prepared == this.state) { active = this.state = OletxVolatileEnlistmentState.InDoubt; iEnlistmentNotification = this.iEnlistmentNotification; } else { if (OletxVolatileEnlistmentState.Preparing == this.state) { this.pendingOutcome = TransactionStatus.InDoubt; } active = this.state; } } if (OletxVolatileEnlistmentState.InDoubt == active) { if (iEnlistmentNotification != null) { if (DiagnosticTrace.Verbose) { EnlistmentNotificationCallTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), base.InternalTraceIdentifier, NotificationCall.InDoubt); } iEnlistmentNotification.InDoubt(this); return; } if (DiagnosticTrace.Critical) { InternalErrorTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), ""); } throw new InvalidOperationException(System.Transactions.SR.GetString("InternalError")); } if ((OletxVolatileEnlistmentState.Preparing != active) && (OletxVolatileEnlistmentState.Done != active)) { if (DiagnosticTrace.Critical) { InternalErrorTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), ""); } throw new InvalidOperationException(System.Transactions.SR.GetString("InternalError")); } }
public void TwoPhaseDurable(int volatileCount, EnlistmentOptions volatileEnlistmentOption, EnlistmentOptions durableEnlistmentOption, Phase1Vote volatilePhase1Vote, Phase1Vote durablePhase1Vote, bool commit, EnlistmentOutcome expectedVolatileOutcome, EnlistmentOutcome expectedDurableOutcome, TransactionStatus expectedTxStatus) { Transaction tx = null; try { using (TransactionScope ts = new TransactionScope()) { tx = Transaction.Current.Clone(); if (volatileCount > 0) { TestEnlistment[] volatiles = new TestEnlistment[volatileCount]; for (int i = 0; i < volatileCount; i++) { // It doesn't matter what we specify for SinglePhaseVote. volatiles[i] = new TestEnlistment(volatilePhase1Vote, expectedVolatileOutcome); tx.EnlistVolatile(volatiles[i], volatileEnlistmentOption); } } TestEnlistment durable = new TestEnlistment(Phase1Vote.Prepared, expectedDurableOutcome); // TODO: Issue #10353 - This needs to change once we have promotion support. Assert.Throws<PlatformNotSupportedException>(() => // Creation of two phase durable enlistment attempts to promote to MSDTC { tx.EnlistDurable(Guid.NewGuid(), durable, durableEnlistmentOption); }); if (commit) { ts.Complete(); } } } catch (TransactionInDoubtException) { Assert.Equal(expectedTxStatus, TransactionStatus.InDoubt); } catch (TransactionAbortedException) { Assert.Equal(expectedTxStatus, TransactionStatus.Aborted); } Assert.NotNull(tx); Assert.Equal(expectedTxStatus, tx.TransactionInformation.Status); }
public Result<FreeCoinTransaction> GetFreeCoinTransaction(IDbConnection db, string orderId, TransactionStatus? statusFilter = null) { var trans = db.Query<FreeCoinTransaction>("SELECT * FROM free_coin_transaction WHERE order_id=@orderId", new { orderId }).FirstOrDefault(); if (trans == null) return Result<FreeCoinTransaction>.Null(ErrorCodes.InvalidTransactionId); if (statusFilter.HasValue) { if (statusFilter.Value.ToString() != trans.status) { bool accepted = (trans.status == ConstantValues.S_ACCEPTED); return Result<FreeCoinTransaction>.Null(accepted ? ErrorCodes.TransactionAlreadyProcessed : ErrorCodes.TransactionNotFound); } } // TODO: Need a collection data structure in FreeCoinTransaction to hold packages // return Result<FreeCoinTransaction>.Make(trans); }
public void SinglePhaseDurable(int volatileCount, EnlistmentOptions volatileEnlistmentOption, Phase1Vote volatilePhase1Vote, SinglePhaseVote singlePhaseVote, bool commit, EnlistmentOutcome expectedVolatileOutcome, TransactionStatus expectedTxStatus) { Transaction tx = null; try { using (TransactionScope ts = new TransactionScope()) { tx = Transaction.Current.Clone(); if (volatileCount > 0) { TestSinglePhaseEnlistment[] volatiles = new TestSinglePhaseEnlistment[volatileCount]; for (int i = 0; i < volatileCount; i++) { // It doesn't matter what we specify for SinglePhaseVote. volatiles[i] = new TestSinglePhaseEnlistment(volatilePhase1Vote, SinglePhaseVote.InDoubt, expectedVolatileOutcome); tx.EnlistVolatile(volatiles[i], volatileEnlistmentOption); } } // Doesn't really matter what we specify for EnlistmentOutcome here. This is an SPC, so Phase2 won't happen for this enlistment. TestSinglePhaseEnlistment durable = new TestSinglePhaseEnlistment(Phase1Vote.Prepared, singlePhaseVote, EnlistmentOutcome.Committed); tx.EnlistDurable(Guid.NewGuid(), durable, EnlistmentOptions.None); if (commit) { ts.Complete(); } } } catch (TransactionInDoubtException) { Assert.Equal(expectedTxStatus, TransactionStatus.InDoubt); } catch (TransactionAbortedException) { Assert.Equal(expectedTxStatus, TransactionStatus.Aborted); } Assert.NotNull(tx); Assert.Equal(expectedTxStatus, tx.TransactionInformation.Status); }
internal RealOletxTransaction(OletxTransactionManager transactionManager, ITransactionShim transactionShim, OutcomeEnlistment outcomeEnlistment, Guid identifier, OletxTransactionIsolationLevel oletxIsoLevel, bool isRoot) { bool flag = false; try { this.oletxTransactionManager = transactionManager; this.transactionShim = transactionShim; this.outcomeEnlistment = outcomeEnlistment; this.txGuid = identifier; this.isolationLevel = OletxTransactionManager.ConvertIsolationLevelFromProxyValue(oletxIsoLevel); this.status = TransactionStatus.Active; this.undisposedOletxTransactionCount = 0; this.phase0EnlistVolatilementContainerList = null; this.phase1EnlistVolatilementContainer = null; this.tooLateForEnlistments = false; this.internalTransaction = null; this.creationTime = DateTime.UtcNow; this.lastStateChangeTime = this.creationTime; this.internalClone = new OletxTransaction(this); if (this.outcomeEnlistment != null) { this.outcomeEnlistment.SetRealTransaction(this); } else { this.status = TransactionStatus.InDoubt; } if (DiagnosticTrace.HaveListeners) { DiagnosticTrace.TraceTransfer(this.txGuid); } flag = true; } finally { if (!flag && (this.outcomeEnlistment != null)) { this.outcomeEnlistment.UnregisterOutcomeCallback(); this.outcomeEnlistment = null; } } }
// TODO: Incomplete & Not Tested // public Result<List<CreditTransaction>> GetExchange(IDbConnection db, string orderId, TransactionStatus? statusFilter = null) { var coinTran = GetCoinTransaction(db, orderId, statusFilter); if (coinTran.HasData) { // TODO: Full up the list of packages IAP items // //Result< List<CreditTransaction> >.Make(coinTran.Data, coinTran.Error); } // Else, not succeeded // var freeCoinTran = GetFreeCoinTransaction(db, orderId, statusFilter); if (freeCoinTran.HasData) { // TODO: Full up the list of packages IAP items // // return Result< List<CreditTransaction> >.Make(freeCoinTran.Data, freeCoinTran.Error); } // TEST // return Result<List<CreditTransaction>>.Null(); }
public void Constructor_DataTable() { // Arrange var dt = new DataTable(); dt.Columns.Add(new DataColumn("ErrorCode")); dt.Columns.Add(new DataColumn("ErrorMessage")); dt.Columns.Add(new DataColumn("TransactionInfo")); var row = dt.NewRow(); row[0] = 0; row[1] = "Test Message"; row[2] = "Test info about the transaction"; dt.Rows.Add(row); // Act var actual = new TransactionStatus(dt); // Assert Assert.AreEqual(TransactionStatusCode.Successful, actual.StatusCode); Assert.AreEqual("Test Message", actual.ErrorMessage); Assert.AreEqual("Test info about the transaction", actual.TransactionInfo); }
/// <summary> /// Заканчивает текущую транзакцию /// </summary> /// <param name="answer">Ответ slave-устройства</param> public void Stop(Message.Message answer) { if (!IsRunning) { switch (Status) { case TransactionStatus.Aborted: { throw new InvalidOperationException( String.Format("Transaction ID: {0}; Попытка завершить прерванную транзакцию", Identifier)); } case TransactionStatus.Completed: { throw new InvalidOperationException( String.Format("Transaction ID: {0}; Попытка завершить завершённую транзакцию", Identifier)); } case TransactionStatus.NotInitialized: { throw new InvalidOperationException( String.Format("Transaction ID: {0}; Попытка завершить не начатую транзакцию", Identifier)); } default: { throw new NotImplementedException(); } } } else { switch (TransactionType) { case TransactionType.UnicastMode: { if (answer != null) { _Answer = answer; } else { throw new NullReferenceException( "Попытка установить в null ответное сообщение для завершения " + "транзакции адресованного запроса"); } break; } case TransactionType.BroadcastMode: { if (answer != null) { throw new InvalidOperationException( "Попытка установить ответное сообщение для завершения транзакции " + "широковещательного запроса"); } break; } case TransactionType.Undefined: { _Answer = answer; break; } } _TimeOfEnd = Environment.TickCount; _Status = TransactionStatus.Completed; // Генерируем событие окончания транзакции. OnTransactionWasEnded(); //Debug.WriteLine(String.Format( // "Transaction ID: {0} - Конец транзакции: {1}; Время транзакции: {2}", // Identifier, _TimeOfEnd, TimeOfTransaction)); } return; }
public void EnlistDuringPhase0(EnlistmentOptions enlistmentOption, EnlistmentOptions phase0EnlistmentOption, Phase1Vote phase1Vote, bool expectPhase0EnlistSuccess, bool commit, EnlistmentOutcome expectedOutcome, TransactionStatus expectedTxStatus) { Transaction tx = null; AutoResetEvent outcomeEvent = null; try { using (TransactionScope ts = new TransactionScope()) { tx = Transaction.Current.Clone(); outcomeEvent = new AutoResetEvent(false); TestEnlistment enlistment = new TestEnlistment(phase1Vote, expectedOutcome, true, expectPhase0EnlistSuccess, outcomeEvent); tx.EnlistVolatile(enlistment, enlistmentOption); if (commit) { ts.Complete(); } } } catch (TransactionInDoubtException) { Assert.Equal(TransactionStatus.InDoubt, expectedTxStatus); } catch (TransactionAbortedException) { Assert.Equal(TransactionStatus.Aborted, expectedTxStatus); } Assert.True(outcomeEvent.WaitOne(TimeSpan.FromSeconds(MaxTransactionCommitTimeoutInSeconds))); Assert.NotNull(tx); Assert.Equal(expectedTxStatus, tx.TransactionInformation.Status); }
//for Add Consumer public TransactionStatus AddConsumer(ConsumerBo consumerBo) { var transactionStatus = new TransactionStatus(); var consumer = BuiltConsumerDomain(consumerBo); CemexDb con = new CemexDb(); SqlParameter[] Params = { new SqlParameter("@Cons_First_Name", SqlDbType.NVarChar), //0 new SqlParameter("@Cons_Last_Name", SqlDbType.NVarChar), //1 new SqlParameter("@Cons_Gender", SqlDbType.NVarChar), //2 new SqlParameter("@Cons_Dob", SqlDbType.NVarChar), //3 new SqlParameter("@Cons_mailid", SqlDbType.NVarChar), //4 new SqlParameter("@Cons_Pswd", SqlDbType.NVarChar), //5 new SqlParameter("@Cons_Mobile", SqlDbType.NVarChar), //6 new SqlParameter("@Cons_Addr1", SqlDbType.NVarChar), //7 new SqlParameter("@Cons_Addr2", SqlDbType.NVarChar), //8 new SqlParameter("@Cons_City", SqlDbType.NVarChar), //9 new SqlParameter("@Cons_Area", SqlDbType.NVarChar), //10 new SqlParameter("@Cons_Pincode", SqlDbType.Int), //11 new SqlParameter("@Cons_Company", SqlDbType.NVarChar), //12 new SqlParameter("@Cons_Company_Id", SqlDbType.NVarChar), //13 new SqlParameter("@Cons_Reference", SqlDbType.NVarChar), //14 new SqlParameter("@Cons_Affiliates_Id", SqlDbType.Int), //15 new SqlParameter("@Cons_Loyalty_Id", SqlDbType.Int), //16 new SqlParameter("@Cons_Earned_Loyalpoints", SqlDbType.Int), //17 new SqlParameter("@Cons_Ipaddress", SqlDbType.NVarChar), //19 new SqlParameter("@Cons_regist_On", DateTime.Now), //20 new SqlParameter("@Cons_Active_flag", 1), //21 new SqlParameter("@opReturnValue", SqlDbType.Int) //22 }; if (!String.IsNullOrEmpty(consumer.Cons_First_Name)) { Params[0].Value = consumer.Cons_First_Name; } else { Params[0].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Last_Name)) { Params[1].Value = consumer.Cons_Last_Name; } else { Params[1].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Gender)) { Params[2].Value = consumer.Cons_Gender; } else { Params[2].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Dob)) { Params[3].Value = consumer.Cons_Dob; } else { Params[3].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_mailid)) { Params[4].Value = consumer.Cons_mailid; } else { Params[4].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Pswd)) { Params[5].Value = consumer.Cons_Pswd; } else { Params[5].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Mobile)) { Params[6].Value = consumer.Cons_Mobile; } else { Params[6].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Addr1)) { Params[7].Value = consumer.Cons_Addr1; } else { Params[7].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Addr2)) { Params[8].Value = consumer.Cons_Addr2; } else { Params[8].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_City)) { Params[9].Value = consumer.Cons_City; } else { Params[9].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Area)) { Params[10].Value = consumer.Cons_Area; } else { Params[10].Value = DBNull.Value; } if (consumer.Cons_Pincode != 0) { Params[11].Value = consumer.Cons_Pincode; } else { Params[11].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Company)) { Params[12].Value = consumer.Cons_Company; } else { Params[12].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Company_Id)) { Params[13].Value = consumer.Cons_Company_Id; } else { Params[13].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Reference)) { Params[14].Value = consumer.Cons_Reference; } else { Params[14].Value = DBNull.Value; } if (consumer.Cons_Affiliates_Id != 0) { Params[15].Value = consumer.Cons_Affiliates_Id; } else { Params[15].Value = DBNull.Value; } if (consumer.Cons_Loyalty_Id != 0) { Params[16].Value = consumer.Cons_Loyalty_Id; } else { Params[16].Value = DBNull.Value; } if (consumer.Cons_Earned_Loyalpoints != 0) { Params[17].Value = consumer.Cons_Earned_Loyalpoints; } else { Params[17].Value = DBNull.Value; } if (consumer.Cons_Redeemed_Loyalpoints1 != 0) { Params[18].Value = consumer.Cons_Redeemed_Loyalpoints1; } else { Params[18].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Ipaddress)) { Params[19].Value = consumer.Cons_Ipaddress; } else { Params[19].Value = DBNull.Value; } Params[22].Direction = ParameterDirection.Output; //string conStr = ConfigurationManager.ConnectionStrings["conCityOfLongBeach"].ToString(); DataSet ds = SqlHelper.ExecuteDataset(con.GetConnection(), CommandType.StoredProcedure, "proc_AddConsumer", Params); ds.Locale = CultureInfo.InvariantCulture; string test = Params[22].Value.ToString(); return(transactionStatus); }
public async Task AddHistory(TransactionStatus history) { await proxyMarketContext.AddHistory(history); }
public static int AddCustomerPayment(string contractId, int invoiceId, string transactionId, decimal amount, string currency, string methodName, TransactionStatus status) { return(EC.Services.Storehouse.AddCustomerPayment(contractId, invoiceId, transactionId, amount, currency, methodName, status)); }
public void Commit() { CheckOpenStatus("Commit"); DoCommit(); m_Status = TransactionStatus.Comitted; }
public void Refund(TransactionStatus RefundTransactionStatus, Int64 TransactionID, string ORNo, decimal ItemSold, decimal QuantitySold, decimal GrossSales, decimal SubTotal, decimal NetSales, decimal ItemsDiscount, decimal SNRItemsDiscount, decimal PWDItemsDiscount, decimal OtherItemsDiscount, decimal Discount, decimal SNRDiscount, decimal PWDDiscount, decimal OtherDiscount, decimal TransDiscount, DiscountTypes TransDiscountType, decimal VAT, decimal VATableAmount, decimal ZeroRatedSales, decimal NonVATableAmount, decimal VATExempt, decimal EVAT, decimal EVATableAmount, decimal NonEVATableAmount, decimal LocalTax, decimal AmountPaid, decimal CashPayment, decimal ChequePayment, decimal CreditCardPayment, decimal CreditPayment, decimal DebitPayment, decimal RewardPointsPayment, decimal RewardConvertedPayment, decimal BalanceAmount, decimal ChangeAmount, PaymentTypes PaymentType, string DiscountCode, string DiscountRemarks, decimal Charge, decimal ChargeAmount, string ChargeCode, string ChargeRemarks, Int64 CashierID, string CashierName) { try { MySqlCommand cmd = new MySqlCommand(); cmd.CommandType = System.Data.CommandType.Text; string SQL = "UPDATE tblTransactions SET " + "ORNo = @ORNo, " + "TransactionStatus = @TransactionStatus, " + "ItemSold = @ItemSold, " + "QuantitySold = @QuantitySold, " + "GrossSales = @GrossSales, " + "SubTotal = @SubTotal, " + "NetSales = @NetSales, " + "ItemsDiscount = @ItemsDiscount, " + "SNRItemsDiscount = @SNRItemsDiscount, " + "PWDItemsDiscount = @PWDItemsDiscount, " + "OtherItemsDiscount = @OtherItemsDiscount, " + "Discount = @Discount, " + "SNRDiscount = @SNRDiscount, " + "PWDDiscount = @PWDDiscount, " + "OtherDiscount = @OtherDiscount, " + "TransDiscount = @TransDiscount, " + "TransDiscountType = @TransDiscType, " + "VAT = @VAT, " + "VATableAmount = @VATableAmount, " + "ZeroRatedSales = @ZeroRatedSales, " + "NonVATableAmount = @NonVATableAmount, " + "VATExempt = @VATExempt, " + "EVAT = @EVAT, " + "EVATableAmount = @EVATableAmount, " + "NonEVATableAmount = @NonEVATableAmount, " + "LocalTax = @LocalTax, " + "AmountPaid = @AmountPaid, " + "CashPayment = @CashPayment, " + "ChequePayment = @ChequePayment, " + "CreditCardPayment = @CreditCardPayment, " + "CreditPayment = @CreditPayment, " + "DebitPayment = @DebitPayment, " + "RewardPointsPayment = @RewardPointsPayment, " + "RewardConvertedPayment = @RewardConvertedPayment, " + "BalanceAmount = @BalanceAmount, " + "ChangeAmount = @ChangeAmount, " + "DateClosed = NOW(), " + "PaymentType = @PaymentType, " + "DiscountCode = @DiscCode, " + "DiscountRemarks = @DiscRemarks, " + "Charge = @Charge, " + "ChargeAmount = @ChargeAmount, " + "ChargeCode = @ChargeCode, " + "ChargeRemarks = @ChargeRemarks, " + "CashierID = @CashierID, " + "CashierName = @CashierName, " + "LastModified = NOW() " + "WHERE TransactionID = @TransactionID;"; cmd.Parameters.AddWithValue("ORNo", ORNo); cmd.Parameters.AddWithValue("TransactionStatus", RefundTransactionStatus.ToString("d")); cmd.Parameters.AddWithValue("ItemSold", ItemSold); cmd.Parameters.AddWithValue("QuantitySold", QuantitySold); cmd.Parameters.AddWithValue("GrossSales", GrossSales); cmd.Parameters.AddWithValue("SubTotal", SubTotal); cmd.Parameters.AddWithValue("NetSales", NetSales); cmd.Parameters.AddWithValue("ItemsDiscount", ItemsDiscount); cmd.Parameters.AddWithValue("SNRItemsDiscount", SNRItemsDiscount); cmd.Parameters.AddWithValue("PWDItemsDiscount", PWDItemsDiscount); cmd.Parameters.AddWithValue("OtherItemsDiscount", OtherItemsDiscount); cmd.Parameters.AddWithValue("Discount", Discount); cmd.Parameters.AddWithValue("SNRDiscount", SNRDiscount); cmd.Parameters.AddWithValue("PWDDiscount", PWDDiscount); cmd.Parameters.AddWithValue("OtherDiscount", OtherDiscount); cmd.Parameters.AddWithValue("TransDiscount", TransDiscount); cmd.Parameters.AddWithValue("TransDiscType", TransDiscountType.ToString("d")); cmd.Parameters.AddWithValue("VAT", VAT); cmd.Parameters.AddWithValue("VATableAmount", VATableAmount); cmd.Parameters.AddWithValue("ZeroRatedSales", ZeroRatedSales); cmd.Parameters.AddWithValue("NonVATableAmount", NonVATableAmount); cmd.Parameters.AddWithValue("VATExempt", VATExempt); cmd.Parameters.AddWithValue("EVAT", EVAT); cmd.Parameters.AddWithValue("EVATableAmount", EVATableAmount); cmd.Parameters.AddWithValue("NonEVATableAmount", NonEVATableAmount); cmd.Parameters.AddWithValue("LocalTax", LocalTax); cmd.Parameters.AddWithValue("AmountPaid", AmountPaid); cmd.Parameters.AddWithValue("CashPayment", CashPayment); cmd.Parameters.AddWithValue("ChequePayment", ChequePayment); cmd.Parameters.AddWithValue("CreditCardPayment", CreditCardPayment); cmd.Parameters.AddWithValue("CreditPayment", CreditPayment); cmd.Parameters.AddWithValue("DebitPayment", DebitPayment); cmd.Parameters.AddWithValue("RewardPointsPayment", RewardPointsPayment); cmd.Parameters.AddWithValue("RewardConvertedPayment", RewardConvertedPayment); cmd.Parameters.AddWithValue("BalanceAmount", BalanceAmount); cmd.Parameters.AddWithValue("ChangeAmount", ChangeAmount); cmd.Parameters.AddWithValue("PaymentType", PaymentType.ToString("d")); cmd.Parameters.AddWithValue("DiscCode", string.IsNullOrEmpty(DiscountCode) ? "" : DiscountCode); cmd.Parameters.AddWithValue("DiscRemarks", DiscountRemarks); cmd.Parameters.AddWithValue("Charge", Charge); cmd.Parameters.AddWithValue("ChargeAmount", ChargeAmount); cmd.Parameters.AddWithValue("ChargeCode", ChargeCode); cmd.Parameters.AddWithValue("ChargeRemarks", string.IsNullOrEmpty(ChargeRemarks) ? "" : ChargeRemarks); cmd.Parameters.AddWithValue("CashierID", CashierID); cmd.Parameters.AddWithValue("CashierName", CashierName); cmd.Parameters.AddWithValue("TransactionID", TransactionID); cmd.CommandText = SQL; base.ExecuteNonQuery(cmd); SalesTransactionItems clsSalesTransactionItems = new SalesTransactionItems(base.Connection, base.Transaction); clsSalesTransactionItems.RefundByTransaction(TransactionID); } catch (Exception ex) { throw base.ThrowException(ex); } }
/// <summary> /// Initializes a new instance of the <see cref="Transaction"/> class. /// </summary> /// <param name="id">Transaction id</param> /// <param name="revision">Revision of transaction id</param> /// <param name="created">When the transaction was created</param> /// <param name="expires">When the transaction expires and the script should be executed</param> /// <param name="expired">When the transaction actually expired</param> /// <param name="payload">Dynamic payload object</param> /// <param name="script">Script used to execute when transaction expires</param> /// <param name="status">Transaction status</param> /// <param name="parent">Parent transaction and revision. This can be null</param> /// <param name="error">Error associated with the transaction (if any)</param> /// <param name="storage">Storage engine that produced the transaction</param> public Transaction(Guid id, int revision, DateTime created, DateTime?expires, DateTime?expired, object payload, string script, TransactionStatus status, TransactionRevision?parent, object error, ITransactionStorage storage) : this(new TransactionData { Id = id, Revision = revision, Created = created, Expires = expires, Expired = expired, Parent = parent, Payload = payload, Script = script, Status = status, Error = error }, storage) { }
public void TwoPhaseDurable(int volatileCount, EnlistmentOptions volatileEnlistmentOption, EnlistmentOptions durableEnlistmentOption, Phase1Vote volatilePhase1Vote, Phase1Vote durablePhase1Vote, bool commit, EnlistmentOutcome expectedVolatileOutcome, EnlistmentOutcome expectedDurableOutcome, TransactionStatus expectedTxStatus) { Transaction tx = null; try { using (TransactionScope ts = new TransactionScope()) { tx = Transaction.Current.Clone(); if (volatileCount > 0) { TestEnlistment[] volatiles = new TestEnlistment[volatileCount]; for (int i = 0; i < volatileCount; i++) { // It doesn't matter what we specify for SinglePhaseVote. volatiles[i] = new TestEnlistment(volatilePhase1Vote, expectedVolatileOutcome); tx.EnlistVolatile(volatiles[i], volatileEnlistmentOption); } } TestEnlistment durable = new TestEnlistment(Phase1Vote.Prepared, expectedDurableOutcome); // TODO: Issue #10353 - This needs to change once we have promotion support. Assert.Throws <PlatformNotSupportedException>(() => // Creation of two phase durable enlistment attempts to promote to MSDTC { tx.EnlistDurable(Guid.NewGuid(), durable, durableEnlistmentOption); }); if (commit) { ts.Complete(); } } } catch (TransactionInDoubtException) { Assert.Equal(TransactionStatus.InDoubt, expectedTxStatus); } catch (TransactionAbortedException) { Assert.Equal(TransactionStatus.Aborted, expectedTxStatus); } Assert.NotNull(tx); Assert.Equal(expectedTxStatus, tx.TransactionInformation.Status); }
public void SinglePhaseDurable(int volatileCount, EnlistmentOptions volatileEnlistmentOption, Phase1Vote volatilePhase1Vote, SinglePhaseVote singlePhaseVote, bool commit, EnlistmentOutcome expectedVolatileOutcome, TransactionStatus expectedTxStatus) { Transaction tx = null; try { using (TransactionScope ts = new TransactionScope()) { tx = Transaction.Current.Clone(); if (volatileCount > 0) { TestSinglePhaseEnlistment[] volatiles = new TestSinglePhaseEnlistment[volatileCount]; for (int i = 0; i < volatileCount; i++) { // It doesn't matter what we specify for SinglePhaseVote. volatiles[i] = new TestSinglePhaseEnlistment(volatilePhase1Vote, SinglePhaseVote.InDoubt, expectedVolatileOutcome); tx.EnlistVolatile(volatiles[i], volatileEnlistmentOption); } } // Doesn't really matter what we specify for EnlistmentOutcome here. This is an SPC, so Phase2 won't happen for this enlistment. TestSinglePhaseEnlistment durable = new TestSinglePhaseEnlistment(Phase1Vote.Prepared, singlePhaseVote, EnlistmentOutcome.Committed); tx.EnlistDurable(Guid.NewGuid(), durable, EnlistmentOptions.None); if (commit) { ts.Complete(); } } } catch (TransactionInDoubtException) { Assert.Equal(TransactionStatus.InDoubt, expectedTxStatus); } catch (TransactionAbortedException) { Assert.Equal(TransactionStatus.Aborted, expectedTxStatus); } Assert.NotNull(tx); Assert.Equal(expectedTxStatus, tx.TransactionInformation.Status); }
public void GetByTransactionStatus_ThrowsException_WhenEmpty() { TransactionStatus status = TransactionStatus.Aborted; Assert.Throws <InvalidOperationException>(() => testChainblock.GetByTransactionStatus(status)); }
public virtual void Interrupt() { this.Status = TransactionStatus.Exhausted; }
public virtual void Execute() { this.Status = TransactionStatus.Started; }
/// <summary> /// Check if the transaction is complete /// </summary> /// <param name="transaction">the transaction object</param> protected override bool CheckTransactionDone(TransactionStatus transaction) { return(transaction.Status != "pending"); }
internal void ClearTransaction() { if (_txStatus == TransactionStatus.Idle) { return; } _tx.Connection = null; _tx = null; _txStatus = TransactionStatus.Idle; }
/// <summary> /// Plug-in service processor method /// </summary> /// <param name="transactionId">Transaction ID reference</param> public void ProcessSubmit(string transactionId) { TransactionStatus status = new TransactionStatus(transactionId); try { LazyInit(); WriteOut("Runtime arguments:"); foreach (string param in Enum.GetNames(typeof(AqsEndpointProxyServiceParameterType))) { WriteOut("{0} = {1}; ", param, ConfigurationArguments[param]); } WriteOut("Getting documents:"); IList <Document> documents = _documentManager.GetDocuments(transactionId, true); List <string> documentPaths = new List <string>(); string tempDirPath = Path.Combine(_settingsProvider.TempFolderPath, Guid.NewGuid().ToString()); WriteOut("Creating temp. directory: " + tempDirPath); Directory.CreateDirectory(tempDirPath); foreach (Document doc in documents) { WriteOut("Doc: {0} ({1}); ", doc.DocumentName, doc.Type); string tempDocPath = Path.Combine(tempDirPath, doc.DocumentName); WriteOut("Saving content: " + tempDocPath); File.WriteAllBytes(tempDocPath, doc.Content); documentPaths.Add(tempDocPath); } WriteOut("Parsing argument values..."); _strSubmitEndpointUri = ConfigurationArguments[AqsEndpointProxyServiceParameterType.SUBMIT_ENDPOINT_URI.ToString()]; WriteOut("endpointUrl: {0}; ", _strSubmitEndpointUri); if (!string.IsNullOrEmpty(_strSubmitEndpointUri)) { _strEnsUserId = GetConfigParameter(AqsEndpointProxyServiceParameterType.ENS_USER_ID.ToString()); WriteOut(" submit user: {0}", _strEnsUserId); _strEnsPassword = GetConfigParameter(AqsEndpointProxyServiceParameterType.ENS_PASSWORD.ToString()); WriteOut(" submit password: *********", _strEnsPassword); WriteOut("Creating endpoint client..."); _strDataFlow = ConfigurationArguments[AqsEndpointProxyServiceParameterType.DATA_FLOW.ToString()]; if (String.IsNullOrEmpty(_strDataFlow)) { _strDataFlow = FLOW_NAME; } string resultTranId = null; if (!String.IsNullOrEmpty(_strEnsUserId) && !String.IsNullOrEmpty(_strEnsPassword)) { WriteOut("Using custom credentials"); using (INodeEndpointClient nodeClient = _nodeEndpointClientFactory.Make(_strSubmitEndpointUri, EndpointVersionType.EN20, new AuthenticationCredentials(_strEnsUserId, _strEnsPassword))) { WriteOut("Submitting documents..."); resultTranId = nodeClient.Submit(_strDataFlow, null, documentPaths); if (string.IsNullOrEmpty(resultTranId)) { throw new ApplicationException("Node client did not return any transaction!"); } _transactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Completed, WriteOut("Remote transaction Id: {1}", _strSubmitEndpointUri, resultTranId), true); _transactionManager.SetNetworkId(transactionId, resultTranId, EndpointVersionType.EN20, _strSubmitEndpointUri, _strDataFlow, null); WriteOut("Submission done..."); } } else { WriteOut("Using default credentials"); using (INodeEndpointClient nodeClient = _nodeEndpointClientFactory.Make(_strSubmitEndpointUri, EndpointVersionType.EN20)) { WriteOut("Submitting documents..."); resultTranId = nodeClient.Submit(_strDataFlow, null, documentPaths); if (string.IsNullOrEmpty(resultTranId)) { throw new ApplicationException("Node client did not return any transaction!"); } _transactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Completed, WriteOut("Remote transaction Id: {1}", _strSubmitEndpointUri, resultTranId), true); _transactionManager.SetNetworkId(transactionId, resultTranId, nodeClient.Version, _strSubmitEndpointUri, _strDataFlow, null); WriteOut("Submission done..."); } } status.Description = string.Format("The AQS document was successfully submitted at {0} with a returned transaction id of {1}.", DateTime.Now, resultTranId); status.Status = CommonTransactionStatusCode.Completed; } } catch (Exception ex) { status.Description = string.Format("An error occurred running the {0} service:{1}{2}{3}", SERVICE_NAME, Environment.NewLine, Environment.NewLine, ExceptionUtils.GetDeepExceptionMessage(ex)); status.Status = CommonTransactionStatusCode.Failed; throw; } finally { if (status.Description != null) { AppendAuditLogEvent(status.Description); } if ((_notificationManager != null) && !string.IsNullOrEmpty(_strNotificationEmails)) { string strMessage; if (status.Status == CommonTransactionStatusCode.Completed) { strMessage = "Submitted AQS Document"; } else { strMessage = "Failed to Submit AQS Document"; } _notificationManager.DoScheduleNotifications(status, _strNotificationEmails, strMessage, SERVICE_NAME, null, null, status.Description); } } }
public void EnlistVolatile(int volatileCount, EnlistmentOptions enlistmentOption, Phase1Vote volatilePhase1Vote, Phase1Vote lastPhase1Vote, bool commit, EnlistmentOutcome expectedEnlistmentOutcome, TransactionStatus expectedTxStatus) { AutoResetEvent[] outcomeEvents = null; Transaction tx = null; try { using (TransactionScope ts = new TransactionScope()) { tx = Transaction.Current.Clone(); if (volatileCount > 0) { TestEnlistment[] volatiles = new TestEnlistment[volatileCount]; outcomeEvents = new AutoResetEvent[volatileCount]; for (int i = 0; i < volatileCount - 1; i++) { outcomeEvents[i] = new AutoResetEvent(false); volatiles[i] = new TestEnlistment(volatilePhase1Vote, expectedEnlistmentOutcome, false, true, outcomeEvents[i]); tx.EnlistVolatile(volatiles[i], enlistmentOption); } outcomeEvents[volatileCount - 1] = new AutoResetEvent(false); volatiles[volatileCount - 1] = new TestEnlistment(lastPhase1Vote, expectedEnlistmentOutcome, false, true, outcomeEvents[volatileCount - 1]); tx.EnlistVolatile(volatiles[volatileCount - 1], enlistmentOption); } if (commit) { ts.Complete(); } } } catch (TransactionInDoubtException) { Assert.Equal(TransactionStatus.InDoubt, expectedTxStatus); } catch (TransactionAbortedException) { Assert.Equal(TransactionStatus.Aborted, expectedTxStatus); } Task.Run(() => // in case current thread is STA thread, where WaitHandle.WaitAll isn't supported { Assert.True(WaitHandle.WaitAll(outcomeEvents, TimeSpan.FromSeconds(MaxTransactionCommitTimeoutInSeconds))); }).GetAwaiter().GetResult(); Assert.NotNull(tx); Assert.Equal(expectedTxStatus, tx.TransactionInformation.Status); }
public static int ChangeCustomerPaymentStatus(int paymentId, TransactionStatus status) { return(EC.Services.Storehouse.ChangeCustomerPaymentStatus(paymentId, status)); }
protected virtual string GetZippedTransactionDocumentsAsTempFile(TransactionStatus transactionStatus) { string filePath = _transactionManager.GetZippedTransactionDocumentsAsTempFile(transactionStatus.Id); return(filePath); }
public DataSet AddConsumerMandet(ConsumerMandetBo consumerBo) { var transactionStatus = new TransactionStatus(); var consumer = BuiltConsumerMandetDomain(consumerBo); string compName = string.Empty; if (consumer.emailCheck) { var index = consumer.Cons_mailid.IndexOf('.'); var domain = consumer.Cons_mailid.Split('@')[1]; compName = domain.Split('.')[0]; consumer.Cons_Company = compName; } CemexDb con = new CemexDb(); SqlParameter[] Params = { new SqlParameter("@Cons_First_Name", SqlDbType.NVarChar), //0 new SqlParameter("@Cons_Last_Name", SqlDbType.NVarChar), //1 new SqlParameter("@Cons_mailid", SqlDbType.NVarChar), //2 new SqlParameter("@Cons_Pswd", SqlDbType.NVarChar), //3 new SqlParameter("@Cons_Mobile", SqlDbType.NVarChar), //4 new SqlParameter("@Cons_regist_On", DateTime.Now), //5 new SqlParameter("@Cons_Active_flag", 1), //6 new SqlParameter("@opReturnValue", SqlDbType.Int), //7 new SqlParameter("@cons_company", SqlDbType.NVarChar) }; if (!String.IsNullOrEmpty(consumer.Cons_First_Name)) { Params[0].Value = consumer.Cons_First_Name; } else { Params[0].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Last_Name)) { Params[1].Value = consumer.Cons_Last_Name; } else { Params[1].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Last_Name)) { Params[1].Value = consumer.Cons_Last_Name; } else { Params[1].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_mailid)) { Params[2].Value = consumer.Cons_mailid; } else { Params[2].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Pswd)) { Params[3].Value = consumer.Cons_Pswd; } else { Params[3].Value = DBNull.Value; } if (!String.IsNullOrEmpty(consumer.Cons_Mobile)) { Params[4].Value = consumer.Cons_Mobile; } else { Params[4].Value = DBNull.Value; } Params[7].Direction = ParameterDirection.Output; if (!String.IsNullOrEmpty(consumer.Cons_Company)) { Params[8].Value = consumer.Cons_Company; } else { Params[8].Value = DBNull.Value; } //string conStr = ConfigurationManager.ConnectionStrings["conCityOfLongBeach"].ToString(); DataSet ds = SqlHelper.ExecuteDataset(con.GetConnection(), CommandType.StoredProcedure, "proc_AddConsumerMandet", Params); return(ds); }
public Task <Response <TransactionModel> > ChangeTransactionStatusById(int id, TransactionStatus newStatus) { var command = new ChangeTransactionStatusCommand(id, newStatus); var result = _mediator.Send(command); return(result); }
public void Rollback() { CheckOpenStatus("Rollback"); DoRollback(); m_Status = TransactionStatus.RolledBack; }
/// <summary> /// Commits the changes to the database. /// </summary> /// <returns>IServiceResponse{Boolean}.</returns> /// <exception cref="System.InvalidOperationException"></exception> public IServiceResponse <Unit> Commit() { if (Status == TransactionStatus.Active) { throw new InvalidOperationException(String.Format(LocalizedPersistenceError.UnitOfWorkCommitting, Id)); } if (Status == TransactionStatus.Committed) { throw new InvalidOperationException(String.Format(LocalizedPersistenceError.UnitOfWorkCommitted, Id)); } if (!AmbientContextManager.CanCommitUnitOfWork(this)) { return(NContextPersistenceError.UnitOfWorkNonCommittable(Id).ToServiceResponse()); } if (ScopeTransaction == null) { return(NContextPersistenceError.ScopeTransactionIsNull().ToServiceResponse()); } TransactionScope transactionScope = null; if (Parent == null && ScopeThread == Thread.CurrentThread) { // Use the existing CurrentTransaction. _CurrentTransactionFactory = new Lazy <Transaction>(() => ScopeTransaction); transactionScope = new TransactionScope(CurrentTransaction, TransactionOptions.Timeout); } else if (ScopeThread != Thread.CurrentThread) { // UnitOfWork is being committed on a different thread. _CurrentTransactionFactory = new Lazy <Transaction>(() => ScopeTransaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete)); transactionScope = new TransactionScope(CurrentTransaction, TransactionOptions.Timeout); } _Status = TransactionStatus.Active; return(CommitTransaction(transactionScope) .Catch(_ => { _Status = TransactionStatus.Aborted; }) .Bind(_ => { _Status = TransactionStatus.Committed; if (CurrentTransaction is DependentTransaction) { if (transactionScope != null) { transactionScope.Complete(); transactionScope.Dispose(); } var dependentTransaction = CurrentTransaction as DependentTransaction; dependentTransaction.Complete(); dependentTransaction.Dispose(); } else if (CurrentTransaction is CommittableTransaction) { try { (CurrentTransaction as CommittableTransaction).Commit(); } catch (TransactionAbortedException abortedException) { return NContextPersistenceError.CommitFailed(Id, CurrentTransaction.TransactionInformation.LocalIdentifier, abortedException) .ToServiceResponse(); } } return new DataResponse <Unit>(default(Unit)); })); }
public void ChangeStatus(TransactionStatus status) { this.Status = status; this.LastUpdateUtcTime = DateTime.Now.ToUniversalTime(); }
//------------------------ public IEnumerable <string> GetAllReceiversWithTransactionStatus(TransactionStatus status) { //var result = transactions.Values.Where() return(null); }
public void GetByTransactionStatusAndMaximumAmount_ReturnsEmptyCollection_WhenThereAreNoMatches(TransactionStatus status, double amount) { Transaction tx = new Transaction(1, "Sracimir", "Dimitar", 100); tx.Status = TransactionStatus.Aborted; Transaction tx1 = new Transaction(2, "Mihail", "Murjo", 450.12); tx.Status = TransactionStatus.Failed; transactions.Add(tx.Id, tx); transactions.Add(tx1.Id, tx1); Assert.That(testChainblock.GetByTransactionStatusAndMaximumAmount(status, amount), Is.Empty); }
public void DtcTransactionCompleted(Guid connectionId, TransactionStatus status) { LoggerTransactions.DebugFormat("Connection {0}: {1}", connectionId, "Transaction completed: " + status); }
protected void AssertState(TransactionStatus status) { AssertState(status, null); }
public InventoryTransaction Build(TransactionStatus status) { return(new InventoryTransaction(status, items)); }
protected void AssertState(TransactionStatus status, string msg) { if (status != Status) { if (!string.IsNullOrEmpty(msg)) throw new TransactionException(msg); throw new TransactionException(string.Format("State failure; should have been {0} but was {1}", status, Status)); } }
public TransactionStatus transfer(int Source_AccountId, int Target_AccountId, int amount) { try { TransactionStatus transferstatus = new TransactionStatus(); if (Source_AccountId < 0 || Target_AccountId < 0 || amount < 0) { _log4net.Error("invalid parameters"); return(new TransactionStatus() { message = "Transfer Not Allowed" }); } Account account = getAccount(Source_AccountId); RuleStatus ruleStatus = rulesStatus(Source_AccountId, amount, account); if (ruleStatus.status == "allowed") { TransactionStatus status = withdraw(Source_AccountId, amount); if (status.message == null) { return(new TransactionStatus() { message = "Unable to withdraw from source id" + Source_AccountId }); } addToTransactionHistory(status, account); transferstatus.source_balance = status.destination_balance; Account targetAccount = getAccount(Target_AccountId); TransactionStatus targetStatus = deposit(Target_AccountId, amount); if (status.message == null) { return(new TransactionStatus() { message = "Unable to deposit into target account " + Target_AccountId }); } addToTransactionHistory(targetStatus, targetAccount); transferstatus.destination_balance = targetStatus.destination_balance; transferstatus.message = "Tranferred " + amount + " from account " + Source_AccountId + " to Account " + Target_AccountId; _log4net.Info("Transfer from Account Id: " + Source_AccountId + "to Account Id" + Target_AccountId + " Completed Successfully"); return(transferstatus); } return(new TransactionStatus() { message = "Unable to transfer into target account " + Target_AccountId }); } catch (ArgumentNullException e) { _log4net.Error(e.Message); throw e; } catch (Exception e) { _log4net.Error(e.Message); throw e; } }
public System.Data.DataTable ListAsDataTable(Int32 BranchID, string TerminalNo = "", Int64 TransactionID = 0, string TransactionNo = "", DateTime? TransactionDateFrom = null, DateTime? TransactionDateTo = null, TransactionStatus TransactionStatus = TransactionStatus.NotYetApplied, PaymentTypes PaymentType = PaymentTypes.NotYetAssigned, bool isConsignment = false, bool isPacked = false, string CustomerName = "", string CustomerGroupName = "", Int64 CashierID = 0, string CashierName = "", string AgentName = "", bool WithTF = false, bool ShowSuspendedOnly = false, string SortField = "", SortOption SortOption = SortOption.Ascending, Int32 limit = 0) { try { MySqlCommand cmd = new MySqlCommand(); cmd.CommandType = System.Data.CommandType.Text; string SQL = "CALL procTransactionsSelect(@BranchID, @TerminalNo, @TransactionID, @TransactionNo, @TransactionDateFrom, " + "@TransactionDateTo, @TransactionStatus, @PaymentType, @isConsignment, @isPacked, @CustomerName, " + "@CustomerGroupName, @CashierID, @CashierName, @AgentName, @WithTF, @ShowSuspended, " + "@SortField, @SortOption, @Limit);"; cmd.Parameters.AddWithValue("BranchID", BranchID); cmd.Parameters.AddWithValue("TerminalNo", TerminalNo); cmd.Parameters.AddWithValue("TransactionID", TransactionID); cmd.Parameters.AddWithValue("TransactionNo", TransactionNo); cmd.Parameters.AddWithValue("TransactionDateFrom", TransactionDateFrom.GetValueOrDefault() == DateTime.MinValue ? Constants.C_DATE_MIN_VALUE : TransactionDateFrom); cmd.Parameters.AddWithValue("TransactionDateTo", TransactionDateTo.GetValueOrDefault() == DateTime.MinValue ? Constants.C_DATE_MIN_VALUE : TransactionDateTo); cmd.Parameters.AddWithValue("TransactionStatus", TransactionStatus.ToString("d")); cmd.Parameters.AddWithValue("PaymentType", PaymentType.ToString("d")); cmd.Parameters.AddWithValue("isConsignment", isConsignment); cmd.Parameters.AddWithValue("isPacked", isPacked); cmd.Parameters.AddWithValue("CustomerName", CustomerName); cmd.Parameters.AddWithValue("CustomerGroupName", CustomerGroupName); cmd.Parameters.AddWithValue("CashierID", CashierID); cmd.Parameters.AddWithValue("CashierName", CashierName); cmd.Parameters.AddWithValue("AgentName", AgentName); cmd.Parameters.AddWithValue("WithTF", WithTF); cmd.Parameters.AddWithValue("ShowSuspended", ShowSuspendedOnly); cmd.Parameters.AddWithValue("SortField", SortField); cmd.Parameters.AddWithValue("SortOption", SortOption==SortOption.Ascending ? "ASC" : "DESC"); cmd.Parameters.AddWithValue("Limit", limit); cmd.CommandText = SQL; string strDataTableName = "tbl" + this.GetType().FullName.Split(new Char[] { '.' })[this.GetType().FullName.Split(new Char[] { '.' }).Length - 1]; System.Data.DataTable dt = new System.Data.DataTable(strDataTableName); base.MySqlDataAdapterFill(cmd, dt); return dt; } catch (Exception ex) { throw base.ThrowException(ex); } }
private void validateRequestResults(string i = Constants.Unspecified, decimal?a = 0, string e = Constants.Unspecified, string s = Constants.Unspecified, string r = Constants.Unspecified, DateTime?f = null, DateTime?t = null, TransactionStatus stat = TransactionStatus.Pending) { Assert.AreEqual(i, req.Data.ID); Assert.AreEqual(a, req.Data.Amount); Assert.AreEqual(e, req.Data.Explanation); Assert.AreEqual(s, req.Data.SenderAccountId); Assert.AreEqual(r, req.Data.ReceiverAccountId); Assert.AreEqual(f ?? DateTime.MinValue, req.Data.ValidFrom); Assert.AreEqual(t ?? DateTime.MaxValue, req.Data.ValidTo); Assert.AreEqual(stat, req.Data.Status); }
/// <summary> /// Constructor. /// </summary> /// <param name="connectionString">Connection string.</param> /// <param name="pooled">Pooled</param> public NpgsqlConnector(NpgsqlConnectionStringBuilder connectionString, bool pooled) { State = ConnectorState.Closed; _txStatus = TransactionStatus.Idle; _settings = connectionString; Pooled = pooled; BackendParams = new Dictionary<string, string>(); Mediator = new NpgsqlMediator(); _messagesToSend = new List<FrontendMessage>(); _preparedStatementIndex = 0; _portalIndex = 0; _deferredCommands = new List<string>(); }
public ScheduledItem ProcessScheduledItem(string scheduleId, bool forceRun, out Activity activity) { activity = null; using (INodeProcessorMutex mutex = GetMutex(scheduleId)) { if (!mutex.IsAcquired) { LOG.Debug("Exiting ProcessScheduleItem(), could not acquire mutex"); return(null); // Another thread is already working on this transaction, get out of here } bool isRunNow; ScheduledItem scheduledItem = ScheduleManager.GetScheduledItem(scheduleId, out isRunNow); /*************************************/ var isDebugging = DebugUtils.IsDebugging; var computerPrefix = "COMPUTER: "; var allowScheduleToRun = !isDebugging; var hasComputerPrefix = scheduledItem.Name.StartsWith(computerPrefix, StringComparison.OrdinalIgnoreCase); if (hasComputerPrefix) { var specialPrefix = computerPrefix + Environment.MachineName; var hasSpecialPrefix = scheduledItem.Name.StartsWith(specialPrefix, StringComparison.OrdinalIgnoreCase); allowScheduleToRun = hasSpecialPrefix; } if (!allowScheduleToRun) { return(null); } /*************************************/ DateTime startTime = DateTime.Now; // Make sure the transaction has not been processed yet if (!forceRun && ((scheduledItem.NextRunOn > startTime) && !isRunNow)) { LOG.Debug("Exiting ProcessScheduledItem(), schedule {0} has already run", scheduledItem); return(null); } string flowName = _flowManager.GetDataFlowNameById(scheduledItem.FlowId); activity = new Activity(NodeMethod.Schedule, flowName, scheduledItem.Name, ActivityType.Info, null, NetworkUtils.GetLocalIp(), "Start processing schedule: \"{0}\"", scheduledItem.Name); string transactionId = null; try { // Make sure the user that created the schedule is still active UserAccount userAccount = _accountManager.GetById(scheduledItem.ModifiedById); if ((userAccount == null) || !userAccount.IsActive) { activity.AppendFormat("The user account that created the scheduled item \"{0}\" is no longer active. Scheduled item cannot execute.", scheduledItem.Name); return(null); } activity.ModifiedById = userAccount.Id; scheduledItem.ExecuteStatus = ScheduleExecuteStatus.Running; ScheduleManager.UpdateScheduleStatus(scheduledItem.Id, scheduledItem.ExecuteStatus); transactionId = _transactionManager.CreateTransaction(NodeMethod.Schedule, EndpointVersionType.Undefined, scheduledItem.FlowId, scheduledItem.Name, userAccount.Id, CommonTransactionStatusCode.Processing, null, null, null, false); activity.TransactionId = transactionId; SchedulePostProcessingAction postProcessingAction = SchedulePostProcessingAction.ContinueNormally; switch (scheduledItem.SourceType) { case ScheduledItemSourceType.LocalService: postProcessingAction = ProcessLocalServiceSource(scheduledItem, activity, transactionId); break; case ScheduledItemSourceType.File: ProcessFileSource(scheduledItem, activity, transactionId); break; case ScheduledItemSourceType.WebServiceQuery: ProcessWebServiceQuerySource(scheduledItem, activity, transactionId); break; case ScheduledItemSourceType.WebServiceSolicit: ProcessWebServiceSolicitSource(scheduledItem, activity, transactionId); break; default: throw new ArgumentException(string.Format("Unrecognized scheduledItem.SourceType: {0}", scheduledItem.SourceType)); } TransactionStatus transactionStatus = null; if (postProcessingAction != SchedulePostProcessingAction.None) { if (scheduledItem.TargetType != ScheduledItemTargetType.None) { transactionStatus = _transactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Processed, null, false); switch (scheduledItem.TargetType) { case ScheduledItemTargetType.LocalService: ProcessLocalServiceTarget(transactionStatus, scheduledItem, activity); break; case ScheduledItemTargetType.Email: ProcessEmailTarget(transactionStatus, scheduledItem, activity); break; case ScheduledItemTargetType.File: ProcessFileTarget(transactionStatus, scheduledItem, activity); break; case ScheduledItemTargetType.Partner: ProcessPartnerTarget(transactionStatus, scheduledItem, activity); break; case ScheduledItemTargetType.Schematron: ProcessSchematronTarget(transactionStatus, scheduledItem, activity); break; default: throw new ArgumentException(string.Format("Unrecognized scheduledItem.TargetType: {0}", scheduledItem.TargetType)); } } } transactionStatus = _transactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Completed, null, true); activity.AppendFormat("End processing schedule: \"{0}\", processing duration: {1}", scheduledItem.Name, TimeSpan.FromTicks(DateTime.Now.Ticks - startTime.Ticks).ToString()); activity.AppendFormat("Transaction \"{0}\" status set to \"{1}\"", transactionStatus.Id.ToString(), transactionStatus.Status.ToString()); _notificationManager.DoScheduleNotifications(transactionStatus, scheduledItem.FlowId, scheduledItem.Name); scheduledItem.ExecuteStatus = ScheduleExecuteStatus.CompletedSuccess; } catch (Exception e) { activity.Type = ActivityType.Error; TransactionStatus transactionStatus = null; if (transactionId != null) { transactionStatus = _transactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Failed, e.Message, true); activity.AppendFormat("Transaction \"{0}\" status set to \"{1}\"", transactionStatus.Id.ToString(), transactionStatus.Status.ToString()); } LogActivityError(activity, ExceptionUtils.ToShortString(e)); LOG.Error("ProcessTransactionRequest() threw an exception.", e); if (transactionId != null) { _notificationManager.DoScheduleNotifications(transactionStatus, scheduledItem.FlowId, scheduledItem.Name, "Error: " + ExceptionUtils.GetDeepExceptionMessageOnly(e)); } scheduledItem.ExecuteStatus = ScheduleExecuteStatus.CompletedFailure; } finally { ActivityManager.Log(activity); UpdateScheduleRunInfo(scheduledItem, activity); } return(scheduledItem); } }
internal ReadyForQueryMessage Load(NpgsqlBuffer buf) { TransactionStatusIndicator = (TransactionStatus)buf.ReadByte(); return this; }
protected virtual void ProcessPartnerTarget(TransactionStatus transactionStatus, ScheduledItem scheduledItem, Activity activity) { PartnerIdentity partner = _partnerManager.GetById(scheduledItem.TargetId); if (partner == null) { throw new ArgumentException(string.Format("Invalid partner id \"{0}.\" Could not find partner for scheduled item \"{1}\".", scheduledItem.TargetId, scheduledItem.Name)); } string filePath = GetZippedTransactionDocumentsAsTempFile(transactionStatus); if (filePath != null) { string transactionId; EndpointVersionType endpointVersion; string endpointUrl; string networkFlowName = null, networkFlowOperation = null; using (INodeEndpointClient client = GetNodeClient(partner, activity, scheduledItem.TargetEndpointUser)) { try { if (client.Version == EndpointVersionType.EN11) { LogActivity(activity, "Attempting to submit target documents as \"{0}\" to partner \"{1}\" for flow \"{2}\"", Path.GetFileName(filePath), partner.Name, scheduledItem.TargetFlow); transactionId = client.Submit(scheduledItem.TargetFlow, string.Empty, new string[] { filePath }); networkFlowName = scheduledItem.TargetFlow; } else { LogActivity(activity, "Attempting to submit target documents as \"{0}\" to partner \"{1}\" for flow \"{2}\" and operation \"{3}\"", Path.GetFileName(filePath), partner.Name, scheduledItem.TargetFlow, scheduledItem.TargetRequest); transactionId = client.Submit(scheduledItem.TargetFlow, scheduledItem.TargetRequest, string.Empty, new string[] { filePath }); networkFlowName = scheduledItem.TargetFlow; networkFlowOperation = scheduledItem.TargetRequest; } } catch (Exception e) { LogActivityError(activity, "Error returned from node endpoint: \"{0}\"", ExceptionUtils.GetDeepExceptionMessage(e)); throw; } endpointVersion = client.Version; endpointUrl = client.Url; } LogActivity(activity, "Submitted target documents to partner \"{0}\" at url \"{1}\" for flow \"{2}\" with returned transaction id \"{3}\"", partner.Name, partner.Url, scheduledItem.TargetFlow, transactionId); _transactionManager.SetNetworkIdAndEndpointUserId(transactionStatus.Id, transactionId, endpointVersion, endpointUrl, networkFlowName, networkFlowOperation, null, scheduledItem.TargetEndpointUser); } else { LogActivity(activity, "No target documents found to submit to partner \"{0}\"", partner.Name); } }