public async Task Handle(CreateTransaction message, IMessageHandlerContext context) { _log.Info($"The transaction was recorded, starting the transfer process between {message.FromAccountId} and {message.ToAccountId} "); Transaction newTransaction = new Transaction() { TransactionId = message.TransactionId, ToAccountId = message.ToAccountId, FromAccountId = message.FromAccountId, Amount = message.Amount }; TransactionCreated transactionCreated = await _transferenceService.CreateTransaction(newTransaction); if (transactionCreated.IsSucceeded == true) { TransactionSucceeded transactionSucceeded = new TransactionSucceeded() { TransactionId = transactionCreated.TransactionId, FromAccountId = message.FromAccountId, ToAccountId = message.ToAccountId, Amount = message.Amount }; await context.SendLocal(transactionSucceeded).ConfigureAwait(false); } _log.Info("publish transactionCreated"); await context.Publish(transactionCreated).ConfigureAwait(false); }
public async Task Handle(TransactionCreated message, IMessageHandlerContext context) { _log.Info($"recived transaction created back to saga, succeeded? - {message.IsSucceeded}, reason: {message.FailureReason}"); await _transactionService.UpdateStatus(_mapper.Map <TransactionStatus>(message)); //return Task.CompletedTask; }
public ITransaction CreateTransaction(TransactionMode txMode, IsolationMode iMode, bool isAmbient) { txMode = ObtainDefaultTransactionMode(txMode); AssertModeSupported(txMode); if (CurrentTransaction == null && (txMode == TransactionMode.Supported || txMode == TransactionMode.NotSupported)) { return(null); } TransactionBase transaction = null; if (CurrentTransaction != null) { if (txMode == TransactionMode.Requires || txMode == TransactionMode.Supported) { transaction = ((TransactionBase)CurrentTransaction).CreateChildTransaction(); _Logger.DebugFormat("Child transaction \"{0}\" created", transaction.Name); } } if (transaction == null) { transaction = InstantiateTransaction(txMode, iMode, isAmbient); if (isAmbient) { #if MONO throw new NotSupportedException("Distributed transactions are not supported on Mono"); #else transaction.Enlist(new TransactionScopeResourceAdapter(txMode, iMode)); #endif } _Logger.DebugFormat("Transaction \"{0}\" created", transaction.Name); } _ActivityManager.CurrentActivity.Push(transaction); if (transaction.IsChildTransaction) { ChildTransactionCreated.Fire(this, new TransactionEventArgs(transaction)); } else { TransactionCreated.Fire(this, new TransactionEventArgs(transaction)); } return(transaction); }
private async Task ProcessTransactionCreatedEventForDestination(Transaction destinationTransaction, Account destinationAccount) { var transactionCreatedEvent = new TransactionCreated { TransactionId = destinationTransaction.Id, AccountId = destinationTransaction.AccountId, Amount = destinationTransaction.Amount, TransactionType = destinationTransaction.TransactionType, Remarks = destinationTransaction.Remarks, CurrentBalance = destinationAccount.Balance }; await _messagePublisher.PublishMessageAsync(transactionCreatedEvent.MessageType, transactionCreatedEvent, ""); }
private async Task ProcessTransactionCreatedEventForSourceAccount(Transaction sourceTransaction, Account sourceAccount) { var transactionCreatedEvent = new TransactionCreated { TransactionId = sourceTransaction.Id, AccountId = sourceTransaction.AccountId, Amount = sourceTransaction.Amount, TransactionType = sourceTransaction.TransactionType, Remarks = sourceTransaction.Remarks, CurrentBalance = sourceAccount.Balance }; await _messagePublisher.PublishMessageAsync(transactionCreatedEvent.MessageType, transactionCreatedEvent, ""); }
public async Task CreateAsync(Transaction transaction) { await context.Transactions.AddAsync(transaction); await context.SaveChangesAsync(); TransactionCreatedEventArgs args = new TransactionCreatedEventArgs { Transaction = transaction }; TransactionCreated?.Invoke(this, args); }
public void Handle(TransactionCreated message) { BookDto book = _repo.FindByAggregateId(message.Id); book.Journal.Add(message.JournalEntry); foreach (var ledgerAccount in message.LedgerEntry) { // Ledger List <LedgerEntry> ledgerList = new List <LedgerEntry>(); if (book.Ledger.ContainsKey(ledgerAccount.Key)) { ledgerList = book.Ledger[ledgerAccount.Key]; } ledgerList.Add(ledgerAccount.Value); book.Ledger[ledgerAccount.Key] = ledgerList; // Trial Balance List <TrialBalanceEntry> trialBalanceList = new List <TrialBalanceEntry>(); bool isNewEntry = true; if (book.TrialBalance.ContainsKey(ledgerAccount.Key)) { trialBalanceList = book.TrialBalance[ledgerAccount.Key]; foreach (TrialBalanceEntry trialBalanceEntry in trialBalanceList) { if (trialBalanceEntry.CurrencyId == ledgerAccount.Value.CurrencyId) { isNewEntry = false; } else { trialBalanceEntry.CurrencyId = ledgerAccount.Value.CurrencyId; } if (ledgerAccount.Value.Journal == JournalType.Debit) { trialBalanceEntry.TotalDebit += ledgerAccount.Value.TotalValue; } else { trialBalanceEntry.TotalCredit += ledgerAccount.Value.TotalValue; } if (isNewEntry) { trialBalanceList.Add(trialBalanceEntry); } } } book.TrialBalance[ledgerAccount.Key] = trialBalanceList; } _repo.Update(book.UniqueId, book); }
private async Task <bool> Handle(TransactionCreated transaction) { Log.Information($"Updating the balance >>> [{transaction.CurrentBalance}] of AccountId [{transaction.AccountId}]"); var accountToBeUpdated = _unitOfWork.Account.GetFirstOrDefault(a => a.Id == transaction.AccountId); accountToBeUpdated.CurrentBalance = transaction.CurrentBalance; if (await _dbContext.SaveChangesAsync() == 0) { throw new ApplicationException(); } return(true); }
public void CreateTransaction() { var transactionCommand = new TransactionCreated() { UserID = 1010, FirstName = "Damla", LastName = "Koksal", OrderID = 40, CardNumber = "1234123412341234", TotalPrice = 50 }; var response = transactionService.CreateTransaction(transactionCommand); Assert.AreEqual(response.Type, Common.ServiceResponseTypes.Success); }
private void When(TransactionCreated e) { if (_lastTransactionId < e.Id) { _lastTransactionId = e.Id; } var transaction = new Transaction() { Id = e.Id, Timestamp = e.Timestamp, Description = e.Description, Amount = e.Amount }; int index = _transactions.BinarySearch(transaction); _transactions.Insert(~index, transaction); Rebalance(~index); }
private async Task ProcessMessage(ConsumeResult <Ignore, TransactionRequest> cr) { var rq = cr.Message.Value; logger.LogInformation($"Consumed message '{rq}' (amount: {rq.AmountCents})'."); var replyGroupId = cr.Message.Headers.SingleOrDefault(p => p.Key == "reply-group-id"); // We are going to pretend that we do some processing here and then send out two events: // * Reply to the Request that it has been processesed // * Publish the fact that the transaction has been created onto the bus // This is obviously not a real world implementation. We're sending two messages independently, without transactions. // We're also not concerned about commits and idempotency upon reprocessing // Also, if we are doing other work, such as databases, things can get complex because you will have multiple transactions, each // of which can fail independently. // Do our 'processing' var reply = new TransactionReply { RequestId = rq.RequestId, Status = $"Transaction of value {rq.AmountCents} has been processed" }; var replyHeaders = new List <Tuple <string, byte[]> >(); if (replyGroupId != null) { replyHeaders.Add(new Tuple <string, byte[]>("reply-group-id", replyGroupId.GetValueBytes())); } var createdEvent = new TransactionCreated { AmountCents = rq.AmountCents, FromAccount = rq.FromAccount, ToAccount = rq.ToAccount, CreatedAt = DateTime.UtcNow, TransactionId = Guid.NewGuid().ToString("B") }; await createdSender.SendToBusWithoutRetries(createdEvent, "transactions"); await replySender.SendToBusWithoutRetries(reply, "transaction-replies", replyHeaders); }
public TransactionServiceResponse <Transaction> CreateTransaction(TransactionCreated ev, List <ServiceLogRecord> logRecords = null) { // Create the watch var sw = new Stopwatch(); sw.Start(); // Create a log record collection if necessary if (logRecords == null) { logRecords = new List <ServiceLogRecord>(); } // Add log logRecords.Add(new ServiceLogRecord() { Type = "DEBUG", TimeStamp = DateTime.Now, Body = "Create Transaction request received." }); var response = new TransactionServiceResponse <Transaction>(); #region [ Validate Request ] logRecords.Add(new ServiceLogRecord() { Type = "DEBUG", TimeStamp = DateTime.Now, Body = "User has the required permissions. Now validating the incoming event data." }); // Check required data List <string> dataErrors = new List <string>(); //if (ev.ResellerId == default(int) || String.IsNullOrEmpty(ev.ResellerName)) //{ // dataErrors.Add("No reseller!"); //} //if (ev.Items == null || ev.Items.Count == 0) //{ // dataErrors.Add("No Transaction item(s)!"); //} //if (String.IsNullOrEmpty(ev.Name)) //{ // dataErrors.Add("No product name!"); //} //if (ev.Items.Count == 0) //{ // dataErrors.Add("No Transaction item"); //} if (dataErrors.Count > 0) { // Add log logRecords.Add(new ServiceLogRecord() { Type = "DEBUG", TimeStamp = DateTime.Now, Body = dataErrors.Count + " error(s) found within the event data! Terminating the process. Errors:" + String.Join(";", dataErrors) }); // Stop the sw sw.Stop(); response.Type = ServiceResponseTypes.Error; response.Code = ((short)HeadstoneServiceResponseCodes.Invalid_Request).ToString(); response.PreProcessingTook = sw.ElapsedMilliseconds; response.Message = "There are some errors with the incoming event data!"; response.Errors.AddRange(dataErrors); response.LogRecords = logRecords; return(response); } #endregion #region [ Data manuplation ] // Stop the timer sw.Stop(); // Set the pre-processing time and start the time response.PreProcessingTook = sw.ElapsedMilliseconds; sw.Start(); #endregion #region [ Create Object ] logRecords.Add(new ServiceLogRecord() { Type = "DEBUG", TimeStamp = DateTime.Now, Body = "Creating Transaction." }); // Create the reseller application var command = new Transaction() { CardNumber = ev.CardNumber, FirstName = ev.FirstName, LastName = ev.LastName, OrderID = ev.OrderID, Status = Framework.Models.EntityStatus.Active, TotalPrice = ev.TotalPrice, UserID = ev.UserID, Created = DateTime.Now }; // Add log logRecords.Add(new ServiceLogRecord() { Type = "DEBUG", TimeStamp = DateTime.Now, Body = string.Format("Transaction created", ev.UserToken, ev.SessionId) }); #endregion #region [ Save Transaction ] var baseServiceResponse = _transactionServiceBase.Create(command); if (baseServiceResponse.Type != Headstone.Framework.Models.ServiceResponseTypes.Success) { // Add log logRecords.Add(new ServiceLogRecord() { Type = "ERROR", TimeStamp = DateTime.Now, Body = "There was an error while saving Transaction!" }); // Stop the sw sw.Stop(); response.Type = ServiceResponseTypes.Error; response.Code = ((short)HeadstoneServiceResponseCodes.General_Exception).ToString(); response.ServiceTook = sw.ElapsedMilliseconds; response.Message = "There was an error while saving the request!"; response.Errors.AddRange(baseServiceResponse.Errors); response.LogRecords = logRecords; return(response); } else { // Add log logRecords.Add(new ServiceLogRecord() { Type = "DEBUG", TimeStamp = DateTime.Now, Body = string.Format("Transaction successfuly created. TransactionId:{0}", command.TransactionID) }); // Add the new object to the result response.Result.Add(command); // Set the object id response.TransactionId = command.TransactionID; } // Stop the sw sw.Stop(); response.Type = ServiceResponseTypes.Success; response.Code = ((short)HeadstoneServiceResponseCodes.Request_Successfuly_Completed).ToString(); response.ServiceTook = sw.ElapsedMilliseconds; response.Message = string.Format("Transaction successfuly created. TransactionId:{0}", command.TransactionID); response.LogRecords = logRecords; #endregion return(response); }
internal virtual void OnTransactionCreated(RemoteDbTransaction connection) { TransactionCreated?.Invoke(connection); }