Example #1
0
        /// <summary>
        /// Creation of a transaction instance with all information needed to provide cancellation and management operation.
        /// </summary>
        /// <param name="transactionEntry">Transaction entry used in the authorization process.</param>
        /// <param name="cardInfo">Card information obtained from the authorization process.</param>
        /// <param name="rawApprovedTransaction">Transaction information returned from STONE authorization service.</param>
        /// <returns>A transaction model.</returns>
        public static TransactionModel Create(ITransactionEntry transactionEntry, ICard cardInfo, AuthorizationResponse rawApprovedTransaction)
        {
            TransactionModel transaction = new TransactionModel();

            // Mapeando informações da transação:
            transaction.Amount   = transactionEntry.Amount;
            transaction.DateTime = DateTime.Now;
            transaction.InitiatorTransactionKey = transactionEntry.InitiatorTransactionKey;
            if (transactionEntry.Installment != null)
            {
                transaction.InstallmentCount = transactionEntry.Installment.Number;
            }
            else
            {
                transaction.InstallmentCount = 0;
            }

            // Mapeando informações direto do retorno do autorizador da Stone.
            transaction.AuthorizationTransactionKey = rawApprovedTransaction.AcquirerTransactionKey;
            transaction.ResponseCode    = (int)(rawApprovedTransaction.OriginalResponse as AcceptorAuthorisationResponse).Data.AuthorisationResponse.TransactionResponse.AuthorisationResult.ResponseToAuthorisation.Response;
            transaction.ResponseReason  = (rawApprovedTransaction.OriginalResponse as AcceptorAuthorisationResponse).Data.AuthorisationResponse.TransactionResponse.AuthorisationResult.ResponseToAuthorisation.ResponseReason;
            transaction.TransactionType = transactionEntry.Type;

            // Mapeando informações do cartão:
            transaction.Aid            = cardInfo.ApplicationId;
            transaction.BrandName      = cardInfo.BrandName;
            transaction.CardholderName = cardInfo.CardholderName;
            transaction.BrandId        = cardInfo.BrandId;
            transaction.Arqc           = cardInfo.ApplicationCryptogram;
            transaction.MaskedPan      = cardInfo.MaskedPrimaryAccountNumber;

            return(transaction);
        }
        public override ITransactionEntry FormatTransaction(ITransactionEntry transactionEntry)
        {
            var configurations = GetConfiguration();

            var request  = transactionEntry.Request;
            var response = transactionEntry.Response;

            if (configurations.Count > 0)
            {
                var requestChanged  = false;
                var responseChanged = false;

                foreach (var configuration in configurations
                         .Where(x => !string.IsNullOrWhiteSpace(x.RegEx) &&
                                !string.IsNullOrWhiteSpace(x.Replacement)))
                {
                    if (configuration.EventPredicate != null &&
                        configuration.EventPredicate.Invoke(transactionEntry))
                    {
                        if (!string.IsNullOrEmpty(request))
                        {
                            request        = MaskCreditCardInfo(request, configuration);
                            requestChanged = true;
                        }
                        if (!string.IsNullOrEmpty(response))
                        {
                            response        = MaskCreditCardInfo(response, configuration);
                            responseChanged = true;
                        }
                    }
                }
                if (requestChanged)
                {
                    transactionEntry.SetRequestString(request);
                }

                if (responseChanged)
                {
                    transactionEntry.SetResponseString(response);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(request))
                {
                    request = MaskCreditCardInfo(request, null);

                    transactionEntry.SetRequestString(request);
                }

                if (!string.IsNullOrEmpty(response))
                {
                    response = MaskCreditCardInfo(response, null);

                    transactionEntry.SetResponseString(response);
                }
            }

            return(base.FormatTransaction(transactionEntry));
        }
        public static void DoWork()
        {
            ITransactionEntry entry = null;

            try
            {
                entry = Utility.GetTransactionLogEntry();


                entry.ServiceUrl = "www.testurl.com";

                entry.MethodName = "testbooking";


                //do stuff

                entry.TimeTaken = 10; //entered a time taken
            }
            catch (Exception ex)
            {
                Utility.GetLogger().Write(ex.ToContextualEntry(), null); //null category causes the framework to pick up the default logger.
            }
            finally
            {
                Utility.GetLogger().WriteAsync(entry, KeyStore.Categories.ServiceLevel); //specify a category
                //var stop = false;
                //Utility.GetLogger().WriteAsync(entry, KeyStore.Categories.ServiceLevel, task => stop = true); //specify a category

                //while (!stop)
                //{
                //    System.Threading.Thread.Sleep(1);
                //}
            }
        }
        /// <summary>
        /// Waits for a card to be inserted or swiped.
        /// </summary>
        /// <param name="transaction">Transaction information.</param>
        /// <param name="cardRead">Information about the card read.</param>
        public void WaitForCard(ITransactionEntry transaction, out ICard cardRead)
        {
            ResponseStatus readingStatus;

            // Waits for the card:
            do
            {
                try
                {
                    readingStatus = this.Authorizer.ReadCard(out cardRead, transaction);

                    if (readingStatus == ResponseStatus.Ok && transaction.Type == AccountType.Undefined)
                    {
                        transaction.Type = this.GetManualTransactionType();
                    }

                    if (readingStatus == ResponseStatus.OperationCancelled)
                    {
                        cardRead = null;
                        return;
                    }
                }
                catch (Exception)
                {
                    //this.ShowSomething(string.Empty, "cartao expirado", DisplayPaddingType.Center, true);
                    cardRead = null;
                    return;
                }
            } while (readingStatus != ResponseStatus.Ok);
        }
        /// <summary>
        /// Send Asset Method
        /// </summary>
        /// <param name="client"></param>
        /// <returns>tx.Id</returns>
        public async Task <Tuple <string, string> > Send(Address myaddress, Address opponetaddress, decimal amount)
        {
            var client     = SetClient();
            var generalApi = new GeneralApi(client);
            var from       = myaddress;
            var to         = opponetaddress;

            System.Diagnostics.Debug.WriteLine(myaddress);
            System.Diagnostics.Debug.WriteLine(opponetaddress);
            System.Diagnostics.Debug.WriteLine(amount);
            var privatekey = new[] { PrivateKey.Parse("263b6a4606168f64aca7c5ac1640ecb52a36142b0d96b07cb520de2eb4d237e5") };

            System.Diagnostics.Debug.WriteLine(PrivateKey.Parse("263b6a4606168f64aca7c5ac1640ecb52a36142b0d96b07cb520de2eb4d237e5"));
            // enter the send amount
            var moveCoin = new AssetMove(TableName, amount, from, to);

            System.Diagnostics.Debug.WriteLine(moveCoin);
            var move = new ITransactionEntry[] { moveCoin };

            System.Diagnostics.Debug.WriteLine(move);
            Transaction tx = TransactionCreator.SimpleSignedTransaction(moveCoin, privatekey);

            await this.SendTransaction(tx);

            var result = await Utils.WaitTx(generalApi, tx.Id);

            return(new Tuple <string, string>(tx.Id.ToString(), result));
        }
Example #6
0
        protected override void WriteTransaction(ITransactionEntry transactionEntry)
        {
            var translator = GetTranslator();

            var data = translator.TranslateTransaction(transactionEntry);

            WriteToFile(data);
        }
Example #7
0
        protected override void WriteTransaction(ITransactionEntry transactionEntry)
        {
            var translator = GetTranslator();

            var data = translator.TranslateTransaction(transactionEntry);

            WriteToEventViewer(GetSource(), data, EventLogEntryType.Information);
        }
Example #8
0
        // Methods
        /// <summary>
        /// Initiates the main transaction flow.
        /// When reads a card, initiates a transaction flow.
        /// </summary>
        public void TurnOn()
        {
            do
            {
                ITransactionEntry transaction = null;
                ICard             card        = null;

                // Asks for a card to be inserted or swiped:
                Task readCard = new Task(() => this.PizzaAuthorizer.WaitForCard(out transaction, out card));
                readCard.Start();
                readCard.Wait();

                // Gets pizza price
                // Enable pizza buttons throgh dispatcher
                this.View.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    this.View.ChangePizzaButtonState(true);
                }).AsTask();

                this.PizzaAuthorizer.ShowSomething("pick the pizza!", ":-)", DisplayPaddingType.Center, false);

                // Waits user select the pizza
                Task waitPizza = new Task(() => { do
                                                  {
                                                      ;
                                                  } while (string.IsNullOrEmpty(this.View.PizzaPickedId) == true); });
                waitPizza.Start();
                waitPizza.Wait();

                transaction.Amount = this.GetPizzaPrice(this.View.PizzaPickedId);

                // Disable buttons
                this.View.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    this.View.ChangePizzaButtonState(false);
                }).AsTask();

                string authorizationMessage;
                bool   status = this.PizzaAuthorizer.BuyThePizza(card, transaction, out authorizationMessage);

                // Verify response
                if (status == true)
                {
                    this.PizzaAuthorizer.ShowSomething("approved!", ":-D", DisplayPaddingType.Center, true);
                }
                else
                {
                    this.PizzaAuthorizer.ShowSomething("not approved", ":-(", DisplayPaddingType.Center, true);
                }

                // Clear transaction info
                this.View.PizzaPickedId = null;
            }while (true);
        }
Example #9
0
 protected override void WriteTransaction(ITransactionEntry transactionEntry)
 {
     if (transactionEntry != null)
     {
         if (transactionEntry.Id == Guid.Empty)
         {
             transactionEntry.Id = Guid.NewGuid();
         }
         var str = Newtonsoft.Json.JsonConvert.SerializeObject(transactionEntry);
         PushData(str);
     }
 }
Example #10
0
        /// <summary>
        /// Envia a transação para a SDK da Stone.
        /// </summary>
        /// <param name="transaction">Transação a ser capturada.</param>
        /// <returns>Report da transação.</returns>
        private IAuthorizationReport SendRequest(ITransactionEntry transaction)
        {
            ICardPaymentAuthorizer currentAuthorizer = this.GetCurrentPinpad();

            if (currentAuthorizer == null)
            {
                this.Log("Selecione um pinpad.");
            }

            IAuthorizationReport response = null;

            try
            {
                ResponseStatus authorizationStatus;
                response = currentAuthorizer.Authorize(transaction, out authorizationStatus);
            }
            catch (ExpiredCardException)
            {
                this.Log("Cartão expirado.");
                currentAuthorizer.PromptForCardRemoval("CARTAO EXPIRADO");
                return(null);
            }
            catch (CardHasChipException)
            {
                this.Log("Cartão possui chip. Insira o cartão.");
                currentAuthorizer.PromptForCardRemoval("CARTAO POSSUI CHIP");
                return(null);
            }
            catch (InvalidConnectionException)
            {
                this.Log("Computador não está conectado a internet!");
                currentAuthorizer.PromptForCardRemoval("SEM CONEXAO");
                return(null);
            }

            if (response == null)
            {
                this.Log("Um erro ocorreu durante a transação.");
                return(null);
            }

            // Handle poi response:
            this.VerifyPoiResponse(response);

            // Loga as mensagens de request e response enviadas e recebidas do autorizador da Stone:
            this.LogTransaction(response);

            currentAuthorizer.PinpadFacade.Display.ShowMessage(this.PinpadMessages.MainLabel, null, DisplayPaddingType.Center);

            return(response);
        }
Example #11
0
        /// <summary>
        /// Reads the card password.
        /// Perfoms an authorization operation.
        /// </summary>
        /// <param name="card">Information about the card.</param>
        /// <param name="transaction">Information about the transaction.</param>
        /// <param name="authorizationMessage">Authorization message returned.</param>
        /// <returns></returns>
        public bool BuyThePizza(ICard card, ITransactionEntry transaction, out string authorizationMessage)
        {
            Pin pin;

            authorizationMessage = string.Empty;

            // Tries to read the card password:
            if (this.authorizer.ReadPassword(out pin, card, transaction.Amount) != ResponseStatus.Ok)
            {
                return(false);
            }

            // Tries to authorize the transaction:
            PoiResponseBase response = this.authorizer.Authorize(card, transaction, pin);

            // Verifies if there were any return:
            if (response == null)
            {
                return(false);
            }

            // Verifies authorization response:
            if (response.Rejected == false && (response as AuthorizationResponse).Approved == true)
            {
                // The transaction was approved:
                this.BoughtPizzas.Add(TransactionModel.Create(transaction, card, response as AuthorizationResponse));
                authorizationMessage = "Transação aprovada";
                return(true);
            }
            else
            {
                // The transaction was rejected or declined:
                if (response.Rejected == true && response is Rejection)
                {
                    // Transaction was rejected:
                    authorizationMessage = "Transação rejeitada";
                }
                else if (this.WasDeclined(response.OriginalResponse as AcceptorAuthorisationResponse) == true)
                {
                    // Transaction was declined:
                    authorizationMessage = this.GetDeclinedMessage(response.OriginalResponse as AcceptorAuthorisationResponse);
                }

                return(false);
            }
        }
        /// <summary>
        /// Reads the card password.
        /// Perfoms an authorization operation.
        /// </summary>
        /// <param name="card">Information about the card.</param>
        /// <param name="transaction">Information about the transaction.</param>
        /// <param name="authorizationMessage">Authorization message returned.</param>
        /// <returns></returns>
        public bool BuyGas(ICard card, ITransactionEntry transaction, out string authorizationMessage)
        {
            Pin pin;

            authorizationMessage = string.Empty;

            // Tries to read the card password:
            try
            {
                if (this.Authorizer.ReadPassword(out pin, card, transaction.Amount) != ResponseStatus.Ok)
                {
                    return(false);
                }
            }
            catch (Exception) { return(false); }

            // Tries to authorize the transaction:
            IAuthorizationReport report = this.Authorizer.SendAuthorizationAndGetReport(card, transaction, pin);

            // Verifies if there were any return:
            if (report == null)
            {
                return(false);
            }

            // Verifies authorization response:
            if (report.WasSuccessful == true)
            {
                // The transaction was approved:
                authorizationMessage = "Transação aprovada";

                Task.Run(() =>
                {
                    this.Authorizer.Cancel(report.AcquirerTransactionKey, report.Amount);
                });

                return(true);
            }
            else
            {
                // The transaction was rejected or declined:
                authorizationMessage = string.Format("({0}) {1}", report.ResponseCode, report.ResponseReason);
                return(false);
            }
        }
        /// <summary>
        /// Reads the card password.
        /// Perfoms an authorization operation.
        /// </summary>
        /// <param name="card">Information about the card.</param>
        /// <param name="transaction">Information about the transaction.</param>
        /// <param name="authorizationMessage">Authorization message returned.</param>
        /// <returns></returns>
        public bool BuyThePizza(ICard card, ITransactionEntry transaction, out string authorizationMessage)
        {
            Pin pin;

            authorizationMessage = string.Empty;

            // Tries to read the card password:
            try
            {
                if (this.authorizer.ReadPassword(out pin, card, transaction.Amount) != ResponseStatus.Ok)
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                pin = null;
                Debug.WriteLine(e.Message);
                return(false);
            }
            // Tries to authorize the transaction:
            IAuthorizationReport report = this.authorizer.SendAuthorizationAndGetReport(card, transaction, pin);

            // Verifies if there were any return:
            if (report == null)
            {
                return(false);
            }

            // Verifies authorization response:
            if (report.WasSuccessful == true)
            {
                // The transaction was approved:
                this.BoughtPizzas.Add(report);
                authorizationMessage = "Transação aprovada";
                return(true);
            }
            else
            {
                // Transaction was declined:
                authorizationMessage = string.Format("({0}) {1}", report.ResponseCode, report.ResponseReason);
                return(false);
            }
        }
Example #14
0
        public TransactionTableEntry(ITransactionEntry entry, bool isCancelled)
        {
            this.Amount = entry.Amount;

            if (entry.Type == AccountType.Credit)
            {
                this.Type = AccountType.Credit;
            }
            else if (entry.Type == AccountType.Debit)
            {
                this.Type = AccountType.Debit;
            }
            else
            {
                this.Type = AccountType.Undefined;
            }

            this.IsCaptured = !isCancelled;
        }
Example #15
0
        /// <summary>
        /// Default implementation, returns the object with the request and response compressed,
        /// this method should be overridden in case of any customizations
        /// required e.g. masking capability addition. To keep compression, the base method should be called
        /// at the end.
        /// Also think of overriding <seealso cref="FormatException(Tavisca.Frameworks.Logging.IExceptionEntry)"/>
        /// </summary>
        /// <param name="transactionEntry">The event entry to be formatted.</param>
        /// <returns>Formatted event.</returns>
        public virtual ITransactionEntry FormatTransaction(ITransactionEntry transactionEntry)
        {
            var request = transactionEntry.Request;

            if (!string.IsNullOrWhiteSpace(request))
            {
                request = request.Compress();

                transactionEntry.SetRequestString(request);
            }

            var response = transactionEntry.Response;

            if (!string.IsNullOrWhiteSpace(response))
            {
                response = response.Compress();

                transactionEntry.SetResponseString(response);
            }

            return(transactionEntry);
        }
Example #16
0
        public async Task Post_Calculate_Should_Succeed_With_3_Transactions()
        {
            List <ITransactionEntry> mockedTransactions = new List <ITransactionEntry>();
            var line1 = new ITransactionEntry {
                Account = "Acc1", AccountTerm = "short", MonthlyPayment = null, Type = "asset", Value = 7000
            };
            var line2 = new ITransactionEntry {
                Account = "Acc2", AccountTerm = "short", MonthlyPayment = null, Type = "liability", Value = 3000
            };
            var line3 = new ITransactionEntry {
                Account = "Acc3", AccountTerm = "long", MonthlyPayment = null, Type = "liability", Value = 3000
            };

            mockedTransactions.Add(line1);
            mockedTransactions.Add(line2);
            mockedTransactions.Add(line3);

            var stringContent = new StringContent(JsonConvert.SerializeObject(mockedTransactions), Encoding.UTF8, "application/json");
            var response      = await Client.PostAsync("/calculator/calculate?conversionType=CAD_CAD", stringContent);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
            (await response.Content.ReadAsStringAsync()).Should().Contain("\"totalAssets\":7000,\"totalLiabilities\":6000,\"netWorth\":1000");
        }
        // Methods
        /// <summary>
        /// Waits for a card to be inserted or swiped.
        /// </summary>
        /// <param name="transaction">Transaction information.</param>
        /// <param name="cardRead">Information about the card read.</param>
        public void WaitForCard(out ITransactionEntry transaction, out ICard cardRead)
        {
            ResponseStatus readingStatus;

            transaction = new TransactionEntry();

            // We know very little about the transaction:
            transaction.CaptureTransaction = true;
            transaction.Type = AccountType.Undefined;

            // Update tables: this is mandatory for the pinpad to recognize the card inserted.
            this.authorizer.UpdateTables(3, false);

            // Waits for the card:
            do
            {
                readingStatus = this.authorizer.ReadCard(out cardRead, transaction);
                if (readingStatus == ResponseStatus.Ok && transaction.Type == AccountType.Undefined)
                {
                    transaction.Type = this.GetManualTransactionType();
                }
            } while (readingStatus != ResponseStatus.Ok);
        }
Example #18
0
        // Methods
        /// <summary>
        /// Waits for a card to be inserted or swiped.
        /// </summary>
        /// <param name="transaction">Transaction information.</param>
        /// <param name="cardRead">Information about the card read.</param>
        public void WaitForCard(out ITransactionEntry transaction, out ICard cardRead)
        {
            ResponseStatus readingStatus;

            transaction = new TransactionEntry();

            // We know very little about the transaction:
            transaction.CaptureTransaction = true;
            transaction.Type = TransactionType.Undefined;

            // Update tables: this is mandatory for the pinpad to recognize the card inserted.
            this.authorizer.UpdateTables(1, true);

            // Waits for the card:
            do
            {
                readingStatus = this.authorizer.ReadCard(out cardRead, transaction);
            }while (readingStatus != ResponseStatus.Ok);

            if (cardRead.Type == CardType.MagneticStripe)
            {
                transaction.Type = GetTransactionTypeFromMagneticStripe(cardRead);
            }
        }
Example #19
0
        public override ITransactionEntry FormatTransaction(ITransactionEntry transactionEntry)
        {
            transactionEntry.AddMessage("This extensibility point is really useful!");

            return(base.FormatTransaction(transactionEntry));
        }
 public string TranslateTransaction(ITransactionEntry entry)
 {
     return(DumpObject(entry));
 }
Example #21
0
        private void InitiateFlow(GasStationAuthorizer authorizer)
        {
            do
            {
                ITransactionEntry transaction = null;
                ICard             card        = null;

                Nullable <short> pump = 0;

                Task readPump = new Task(() =>
                {
                    do
                    {
                        try
                        {
                            pump = authorizer.Authorizer.PinpadFacade.Keyboard.DataPicker.GetNumericValue("Escolha a bomba", true, 1, 4);
                        }
                        catch (Exception) { break; }
                    } while (pump == null);
                });
                readPump.Start();
                readPump.Wait();

                // We know very little about the transaction:
                transaction = new TransactionEntry();
                transaction.CaptureTransaction = true;
                transaction.Type = AccountType.Undefined;

                // Get transaction amount:
                decimal amount = 0;
                amount = this.View.Dispatcher.Invoke <decimal>(() =>
                {
                    return(GetPumpuAmount(pump.Value));
                });

                if (amount == 0)
                {
                    continue;
                }

                transaction.Amount = amount;

                // Asks for a card to be inserted or swiped:
                Task readCard = new Task(() => authorizer.WaitForCard(transaction, out card));
                readCard.Start();
                readCard.Wait();

                string authorizationMessage;
                bool   status = authorizer.BuyGas(card, transaction, out authorizationMessage);

                // Verify response
                if (status == true)
                {
                    authorizer.ShowSomething("approved!", ":-D", DisplayPaddingType.Center, true);
                }
                else
                {
                    authorizer.ShowSomething("not approved", ":-(", DisplayPaddingType.Center, true);
                }
            }while (true);
        }
Example #22
0
 protected override void WriteTransaction(ITransactionEntry transactionEntry)
 {
     System.Threading.Thread.Sleep(500);
 }
 protected override void WriteTransaction(ITransactionEntry transactionEntry)
 {
     throw new Exception("I have failed event log.", new Exception("This is a test.", new Exception("inner most exception message")));
 }
Example #24
0
 protected abstract void WriteTransaction(ITransactionEntry transactionEntry);