public bool Charge(UUID agentID, int amount, string text, int daysUntilNextCharge, TransactionType type, string identifer, bool chargeImmediately)
 {
     IMoneyModule moneyModule = m_registry.RequestModuleInterface<IMoneyModule>();
     if (moneyModule != null)
     {
         if (chargeImmediately)
         {
             bool success = moneyModule.Charge(agentID, amount, text, type);
             if (!success)
                 return false;
         }
         IScheduleService scheduler = m_registry.RequestModuleInterface<IScheduleService>();
         if (scheduler != null)
         {
             OSDMap itemInfo = new OSDMap();
             itemInfo.Add("AgentID", agentID);
             itemInfo.Add("Amount", amount);
             itemInfo.Add("Text", text);
             itemInfo.Add("Type", (int)type);
             SchedulerItem item = new SchedulerItem("ScheduledPayment " + identifer,
                                                    OSDParser.SerializeJsonString(itemInfo), false,
                                                    DateTime.UtcNow, daysUntilNextCharge, RepeatType.days, agentID);
             itemInfo.Add("SchedulerID", item.id);
             scheduler.Save(item);
         }
     }
     return true;
 }
예제 #2
0
 public DescriptionRule(IList<string> terms, TextLookup location, TransactionType suggestedType, Weighting weighting)
 {
     Terms = terms;
     Location = location;
     SuggestedType = suggestedType;
     Weighting = weighting;
 }
예제 #3
0
 private static bool CreateTransaction(DateTime transactionDate,string description, decimal amount, int accountnumber, TransactionType transactionType)
 {
     try
     {
         using (var db = new CarRentalModel())
         {
             var transaction = new RentalTransaction
             {
                 CustomerNumber = accountnumber,
                 TransactionDate = transactionDate,
                 Description = description,
                 Debit = (transactionType == TransactionType.Debit)
                 ? amount : 0.0M,
                 Credit = (transactionType == TransactionType.Credit)
                 ? amount : 0.0M
             };
             db.Transactions.Add(transaction);
             db.SaveChanges();
             return true;
         }
     }
     catch (Exception)
     {
         return false;
     }
 }
예제 #4
0
        static void AddPendingOrder(LiveOpenPositionsEditor openPositionData, Symbol symbol, string orderId, long size, DateTime submittedTime,
            OrderType orderType, TransactionType transactionType, double price, string customString)
        {
            if (openPositionData.PortfolioXml.PendingOrders.Any(o => o.OrderId == orderId))
            {
                //  Order already tracked
                return;
            }

            PositionType positionType = (transactionType == TransactionType.Buy || transactionType == TransactionType.Sell) ? PositionType.Long : PositionType.Short;

            //  This assumes there is just one position per symbol.  If this isn't the case then you will need to find a way of figuring out which
            //  position a pending order corresponds to.
            PositionDataXml position = openPositionData.PortfolioXml.Positions.FirstOrDefault(pos => pos.Symbol.Equals(symbol) && pos.PositionType == positionType);

            if (position == null)
            {
                //  No existing position, so create a new one
                position = openPositionData.AddPosition(symbol, positionType);
                position.CustomString = customString;
            }

            BrokerOrder brokerOrder = new BrokerOrder();
            if (orderType == OrderType.Limit || orderType == OrderType.LimitOnClose)
            {
                brokerOrder.LimitPrice = price;
            }
            else if (orderType == OrderType.Stop || orderType == OrderType.TrailingStop)
            {
                brokerOrder.StopPrice = price;
            }
            brokerOrder.CustomString = customString;

            TradeOrderXml tradeOrder = openPositionData.AddPendingOrder(position, brokerOrder, orderId, size, submittedTime, orderType, transactionType);
        }
예제 #5
0
 public void AddOrder()
 {
     Assert.IsNotNull(TestData.NewItem, "Failed because no item available -- requires successful AddItem test");
     // Make API call.
     ApiException gotException = null;
     try
     {
     AddOrderCall api = new AddOrderCall(this.apiContext);
     OrderType order = new OrderType();
     api.Order = order;
     TransactionType t1 = new TransactionType();
     t1.Item = TestData.NewItem;
     t1.TransactionID = "0";
     TransactionType t2 = new TransactionType();
     t2.Item = TestData.NewItem;
     t2.TransactionID = "0";
     TransactionTypeCollection tary = new TransactionTypeCollection();
         tary.Add(t1); tary.Add(t2);
     order.TransactionArray = tary;
     api.Order = order;
     // Make API call.
     /*AddOrderResponseType resp =*/ api.Execute();
     }
     catch(ApiException ex)
     {
         gotException = ex;
     }
     Assert.IsNotNull(gotException);
 }
예제 #6
0
 public CTransaction(Guid vID, double vdAmmount, DateTime vDate, TransactionType vType)
 {
     _mTransactionID = vID;
     _mdTransactionAmmount = vdAmmount;
     _mTransactionDate = vDate;
     _mTransactionType = vType;
 }
예제 #7
0
 public MapChange(long transactionId, Guid mapParameter, Relationship relationship, TransactionType operation)
 {
     TransactionId = transactionId;
     MapParameter = mapParameter;
     Relationship = relationship;
     Operation = operation;
 }
예제 #8
0
 public MapChange(long transactionId, Guid mapParameter, Node node, TransactionType operation)
 {
     TransactionId = transactionId;
     MapParameter = mapParameter;
     Node = node;
     Operation = operation;
 }
예제 #9
0
 public MapChange(long transactionId, Guid mapParameter, Descriptor descriptor, TransactionType operation)
 {
     TransactionId = transactionId;
     MapParameter = mapParameter;
     Descriptor = descriptor;
     Operation = operation;
 }
예제 #10
0
        public static Transaction CreateTransaction(int userId, int points, TransactionType transactionTypeId)
        {
            var parameters = new List<SqlParameter>
            {
                new SqlParameter
                {
                    ParameterName = "userId",
                    Value = userId
                },
                new SqlParameter
                {
                    ParameterName = "points",
                    Value = points
                },
                new SqlParameter
                {
                    ParameterName = "transactionTypeId",
                    Value = transactionTypeId
                }
            };

            var dataTable = DatabaseCommon.PerformAction("AddTransaction", parameters);

            return DatabaseCommon.ConvertRow(dataTable, PopulateTransaction);
        }
 public TransactionPreparation(Guid transactionId, TransactionType transactionType, PreparationType preparationType, decimal amount)
 {
     this.TransactionId = transactionId;
     this.TransactionType = transactionType;
     this.PreparationType = preparationType;
     this.Amount = amount;
 }
예제 #12
0
 // Methods
 public static List<TransactionType> Types()
 {
     List<TransactionType> list = new List<TransactionType>();
     string str = "SELECT TTID, ShortDescription FROM CodeTransactionType order by ShortDescription ";
     SqlConnection connection = new SqlConnection();
     SqlCommand command = new SqlCommand();
     connection.ConnectionString = ConfigurationManager.ConnectionStrings["ChargeProgramConnectionString"].ConnectionString;
     command.CommandText = str;
     command.Connection = connection;
     connection.Open();
     SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleResult);
     TransactionType item = new TransactionType();
     item.description = "ALL";
     item.ttid = "ALL";
     list.Add(item);
     while (reader.Read())
     {
         TransactionType type2 = new TransactionType();
         type2.Ttid = reader["TTID"].ToString();
         type2.Description = reader["ShortDescription"].ToString();
         list.Add(type2);
     }
     reader.Close();
     connection.Close();
     return list;
 }
예제 #13
0
 public Trasaction(decimal balance, decimal ammount, TransactionType transactionType, Currency currency)
 {
     this.balance = balance;
     this.ammount = ammount;
     this.transactionType = transactionType;
     this.currency = currency;
 }
 public TransactionResult(decimal paymentOut, decimal balance, bool sucess, TransactionType tt)
 {
     _paymentOut = paymentOut;
     _balance = balance;
     _sucess = sucess;
     _transType = tt;
 }
예제 #15
0
 public bool Transfer(UUID toID, UUID fromID, UUID toObjectID, UUID fromObjectID, int amount, string description,
                      TransactionType type)
 {
     if ((type == TransactionType.ObjectPay) && (OnObjectPaid != null))
         OnObjectPaid((fromObjectID == UUID.Zero) ? toObjectID : fromObjectID, fromID, amount);
     return true;
 }
예제 #16
0
 public Transaction(TransactionType transactionType, double amount, double final)
 {
     _transactionType = transactionType;
     _amount = amount;
     _final = final;
     _date = DateTime.Now;
 }
예제 #17
0
 public MapChange(long transactionId, Guid mapParameter, Metadata metadata, TransactionType operation)
 {
     TransactionId = transactionId;
     MapParameter = mapParameter;
     Metadata = metadata;
     Operation = operation;
 }
예제 #18
0
        static void LotSerialRegister(TransactionType source, int reference, Warehouse warehouse,
		                               Product product, decimal quantity)
        {
            var query = from x in LotSerialRequirement.Queryable
                        where x.Source == source &&
                            x.Reference == reference &&
                            x.Warehouse.Id == warehouse.Id &&
                            x.Product == product
                        select x;
            var rqmt = query.SingleOrDefault ();

            if (rqmt != null) {
                rqmt.Quantity += quantity;
                rqmt.Update ();
            } else {
                rqmt = new LotSerialRequirement {
                    Source = source,
                    Reference = reference,
                    Warehouse = warehouse,
                    Product = product,
                    Quantity = quantity
                };

                rqmt.Create ();
            }
        }
        public void Save_DifferentTransactionTypes_CorrectlySaved(TransactionType type)
        {
            var accountRepoSetup = new Mock<IDataAccess<Account>>();
            accountRepoSetup.Setup(x => x.LoadList(null)).Returns(new List<Account>());

            var transactionDataAccessMock = new TransactionDataAccessMock();
            var repository = new TransactionRepository(transactionDataAccessMock,
                new RecurringTransactionDataAccessMock());

            var account = new Account
            {
                Name = "TestAccount"
            };

            var transaction = new FinancialTransaction
            {
                ChargedAccount = account,
                TargetAccount = null,
                Amount = 20,
                Type = (int) type
            };

            repository.Save(transaction);

            transactionDataAccessMock.FinancialTransactionTestList[0].ShouldBeSameAs(transaction);
            transactionDataAccessMock.FinancialTransactionTestList[0].ChargedAccount.ShouldBeSameAs(account);
            transactionDataAccessMock.FinancialTransactionTestList[0].TargetAccount.ShouldBeNull();
            transactionDataAccessMock.FinancialTransactionTestList[0].Type.ShouldBe((int) type);
        }
        public void Edit_ShouldReturnRedirectToEditActionOnExpectedController(TransactionType transactionType, string expectedController)
        {
            var controller = GetController();
            var result = (RedirectToRouteResult)controller.Edit(Guid.NewGuid(), transactionType);

            Assert.That(result.RouteValues["action"], Is.EqualTo("Edit"));
            Assert.That(result.RouteValues["controller"], Is.EqualTo(expectedController));
        }
예제 #21
0
 public static string GetDomain(TransactionType type)
 {
     if(type == TransactionType.Debit)
         return "Dr";
     if(type == TransactionType.Credit)
         return "Cr";
     throw new InvalidOperationException(LocalizationHelper.GetResourceString("Warnings", "UnknownTransactionType"));
 }
예제 #22
0
        public void returns_correct_values_from_cif_records(string value, TransactionType expectedResult)
        {
            var parser = BuildParser();

            var result = parser.ParseProperty(value);

            Assert.AreEqual(expectedResult, result);
        }
예제 #23
0
 public AddTransactionPreparationCommand(string accountId, string transactionId, TransactionType transactionType, PreparationType preparationType, double amount)
     : base(accountId)
 {
     TransactionId = transactionId;
     TransactionType = transactionType;
     PreparationType = preparationType;
     Amount = amount;
 }
 public AccountTransaction(DateTime transactionDate, TransactionType transactionType, string sortCode, int accountNumber, decimal amount)
 {
     TransactionDate = transactionDate;
     TransactionType = transactionType;
     SortCode = sortCode;
     AccountNumber = accountNumber;
     Amount = amount;
 }
예제 #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LoanTransaction"/> class.
 /// </summary>
 /// <param name="date">The date.</param>
 /// <param name="type">The type.</param>
 /// <param name="credit">The credit.</param>
 /// <param name="debit">The debit.</param>
 /// <param name="balance">The balance.</param>
 public LoanTransaction(DateTime date, TransactionType type, double credit, double debit, double balance)
 {
     Date = date;
     Type = type;
     Credit = credit;
     Debit = debit;
     Balance = balance;
 }
 public SearchResult(String jsonString, String searchString, String searchUri, JsonResultType jsonResultType, TransactionType transactionType)
 {
     this.TransactionType = transactionType;
     this.JsonResultType = jsonResultType;
     this.SearchUri = searchUri;
     this.JsonString = jsonString;
     this.Text = searchString;
 }
예제 #27
0
        public virtual bool IsValidFor( TransactionType transactionType )
        {
            _errorMessages.Clear();

             Validate( transactionType );

             return _errorMessages.Count == 0;
        }
예제 #28
0
 public Transaction()
 {
     this._BatchSteps = new BatchStepCollection();
     this._TCode = "";
     this._Type = TransactionType.Multiple;
     this._Returns = new BatchReturnCollection();
     this._CustomFunctionName = "";
 }
예제 #29
0
 public InsufficientBalanceException(string accountId, string transactionId, TransactionType transactionType, double amount, double currentBalance, double currentAvailableBalance) : base()
 {
     AccountId = accountId;
     TransactionId = transactionId;
     TransactionType = transactionType;
     Amount = amount;
     CurrentBalance = currentBalance;
     CurrentAvailableBalance = currentAvailableBalance;
 }
예제 #30
0
 /// <summary>
 /// Create a TransactionSettings object with the specified settings.
 /// </summary>
 /// <remarks>
 /// Note that IsolationLevel and Timeout have no affect if TransactionType is None.
 /// </remarks>
 public TransactionSettings(IsolationLevel isolationLevel, TimeSpan timeout, TransactionType transactionType)
 {
     IsolationLevel  = isolationLevel;
     Timeout         = timeout;
     TransactionType = transactionType;
 }
예제 #31
0
 public void Add(TransactionType transactionType, Amount amount)
 {
     _transactions.Add(new Transaction(transactionType, amount));
 }
 public TransactionsListItemVM(TransactionType transactionType) : base(transactionType)
 {
 }
예제 #33
0
 public TransactionRequest(TransactionType transType)
 {
     TransType = transType;
 }
 public MismatchTransactionPreparationException(TransactionType transactionType, PreparationType preparationType)
     : base(string.Format("Mismatch transaction type [{0}] and preparation type [{1}].", transactionType, preparationType))
 {
 }
예제 #35
0
        public async Task <byte[]> SignTransactionAsync(BitcoinTransaction transaction)
        {
            var txDic      = new Dictionary <string, TransactionType>();
            var unsignedTx = new TransactionType
            {
                Version      = transaction.Version,
                InputsCnt    = (uint)transaction.Inputs.Count,  // must be exact number of Inputs count
                OutputsCnt   = (uint)transaction.Outputs.Count, // must be exact number of Outputs count
                LockTime     = transaction.LockTime,
                ExtraData    = transaction.ExtraData,
                ExtraDataLen = transaction.ExtraData == null ? 0 : (uint)transaction.ExtraData.Length
            };

            CopyInputs(transaction.Inputs, unsignedTx.Inputs, false);
            CopyOutputs(transaction.Outputs, unsignedTx.Outputs);

            txDic.Add("unsigned", unsignedTx);

            foreach (var txInput in transaction.Inputs)
            {
                BitcoinTransaction prevTran = txInput.PrevTransaction;
                var tx = new TransactionType
                {
                    Version    = prevTran.Version,
                    LockTime   = prevTran.LockTime,
                    InputsCnt  = (uint)prevTran.Inputs.Count,
                    OutputsCnt = (uint)prevTran.Outputs.Count,
                };
                CopyInputs(prevTran.Inputs, tx.Inputs, true);
                CopyBinOutputs(prevTran.Outputs, tx.BinOutputs);

                txDic.Add(txInput.PrevHash.ToHex(), tx);
            }

            var serializedTx = new List <byte>();

            var request = await SendMessageAsync <TxRequest, SignTx>(new SignTx
            {
                CoinName     = transaction.CoinName,
                InputsCount  = (uint)transaction.Inputs.Count,
                OutputsCount = (uint)transaction.Outputs.Count
            });

            TxAck txAck;

            // We do loop here since we need to send over and over the same transactions to trezor because his 64 kilobytes memory
            // and he will sign chunks and return part of signed chunk in serialized manner, until we receive finall type of Txrequest TxFinished
            while (request.RequestType != RequestType.Txfinished)
            {
                TransactionType currentTx;
                if ((request.Details != null) && (request.Details.TxHash != null))
                {
                    string hash = request.Details.TxHash.ToHex();
                    if (txDic.ContainsKey(hash))
                    {
                        currentTx = txDic[hash];
                    }
                    else
                    {
                        Log.Error($"Unknown hash {hash}");
                        currentTx = txDic["unsigned"];
                    }
                }
                else
                {
                    currentTx = txDic["unsigned"];
                }

                switch (request.RequestType)
                {
                case RequestType.Txinput:
                {
                    var msg = new TransactionType();
                    foreach (var input in currentTx.Inputs)
                    {
                        msg.Inputs.Add(input);
                    }
                    ;

                    txAck = new TxAck {
                        Tx = msg
                    };
                    //We send TxAck() with  TxInputs
                    request = await SendMessageAsync <TxRequest, TxAck>(txAck);

                    // Now we have to check every response is there any SerializedTx chunk
                    if (request.Serialized != null)
                    {
                        serializedTx.AddRange(request.Serialized.SerializedTx);
                    }

                    break;
                }

                case RequestType.Txoutput:
                {
                    var msg = new TransactionType();
                    if ((request.Details != null) && (request.Details.TxHash != null))
                    {
                        msg.BinOutputs.Add(currentTx.BinOutputs[(int)request.Details.RequestIndex]);
                    }
                    else
                    {
                        msg.Outputs.Add(currentTx.Outputs[(int)request.Details.RequestIndex]);
                    }

                    txAck = new TxAck {
                        Tx = msg
                    };
                    //We send TxAck()  with  TxOutputs
                    request = await SendMessageAsync <TxRequest, TxAck>(txAck);

                    // Now we have to check every response is there any SerializedTx chunk
                    if (request.Serialized != null)
                    {
                        serializedTx.AddRange(request.Serialized.SerializedTx);
                    }

                    break;
                }

                case RequestType.Txextradata:
                {
                    var offset = request.Details.ExtraDataOffset;
                    var length = request.Details.ExtraDataLen;
                    var msg    = new TransactionType
                    {
                        ExtraData = currentTx.ExtraData.Skip((int)offset).Take((int)length).ToArray()
                    };
                    txAck = new TxAck {
                        Tx = msg
                    };
                    //We send TxAck() with  TxInputs
                    request = await SendMessageAsync <TxRequest, TxAck>(txAck);

                    // Now we have to check every response is there any SerializedTx chunk
                    if (request.Serialized != null)
                    {
                        serializedTx.AddRange(request.Serialized.SerializedTx);
                    }
                    break;
                }

                case RequestType.Txmeta:
                {
                    var msg = new TransactionType
                    {
                        Version    = currentTx.Version,
                        LockTime   = currentTx.LockTime,
                        InputsCnt  = currentTx.InputsCnt,
                        OutputsCnt = (request.Details != null) && (request.Details.TxHash != null) ? (uint)currentTx.BinOutputs.Count : (uint)currentTx.Outputs.Count,
                        //ExtraDataLen = currentTx.ExtraData != null ? (uint)currentTx.ExtraData.Length : 0
                    };
                    txAck = new TxAck {
                        Tx = msg
                    };
                    //We send TxAck() with  TxInputs
                    request = await SendMessageAsync <TxRequest, TxAck>(txAck);

                    // Now we have to check every response is there any SerializedTx chunk
                    if (request.Serialized != null)
                    {
                        serializedTx.AddRange(request.Serialized.SerializedTx);
                    }

                    break;
                }
                }
            }
            return(serializedTx.ToArray());
        }
예제 #36
0
 ImportRequest IImportRequestable.ToImportRequest(TransactionType transactionType)
 => transactionType switch
 {
예제 #37
0
 public TransactionalAttribute(TransactionType transactionType)
 {
     this.transactionType = transactionType;
 }
예제 #38
0
 public PayFacBuilder(TransactionType type)
 {
     TransactionType     = type;
     TransactionModifier = TransactionModifier.None;
 }
예제 #39
0
 public void OnTransactionEventHandler(TransactionType type, TransactionResult result, int amount)
 {
     GeneratePopup(result, amount);
 }
예제 #40
0
 public OrderCancelTransaction(TransactionID id, DateTime time, int userID, AccountID accountID, TransactionID batchID, RequestID requestID, TransactionType type, OrderID orderID, OrderID clientOrderID, OrderCancelReason reason, OrderID replacedByOrderID)
 {
     this.Id                = id;
     this.Time              = time;
     this.UserID            = userID;
     this.AccountID         = accountID;
     this.BatchID           = batchID;
     this.RequestID         = requestID;
     this.Type              = type;
     this.OrderID           = orderID;
     this.ClientOrderID     = clientOrderID;
     this.Reason            = reason;
     this.ReplacedByOrderID = replacedByOrderID;
 }
예제 #41
0
        protected override void Setup()
        {
            base.Setup();

            var background = DaggerfallUI.GetTextureFromImg(IMGNAME);

            if (background == null)
            {
                Debug.LogError(string.Format("Failed to load background image {0} for Banking pop-up", IMGNAME));
                CloseWindow();
                return;
            }

            ParentPanel.BackgroundColor = ScreenDimColor;

            mainPanel = DaggerfallUI.AddPanel(NativePanel, AutoSizeModes.None);
            mainPanel.BackgroundTexture = background;
            mainPanel.Size = new Vector2(225, 181);
            mainPanel.HorizontalAlignment = HorizontalAlignment.Center;
            mainPanel.VerticalAlignment   = VerticalAlignment.Middle;

            accountAmount               = new TextLabel();
            accountAmount.Position      = new Vector2(150, 14);
            accountAmount.Size          = new Vector2(60, 13);
            accountAmount.Name          = "accnt_total_label";
            accountAmount.MaxCharacters = 13;
            mainPanel.Components.Add(accountAmount);

            inventoryAmount               = new TextLabel();
            inventoryAmount.Position      = new Vector2(156, 24);
            inventoryAmount.Size          = new Vector2(64, 13);
            inventoryAmount.Name          = "inv_total_label";
            inventoryAmount.MaxCharacters = 11;
            mainPanel.Components.Add(inventoryAmount);

            loanAmountDue               = new TextLabel();
            loanAmountDue.Position      = new Vector2(96, 34);
            loanAmountDue.Size          = new Vector2(60, 13);
            loanAmountDue.Name          = "amount_due_label";
            loanAmountDue.MaxCharacters = 24;
            mainPanel.Components.Add(loanAmountDue);

            loanDueBy               = new TextLabel();
            loanDueBy.Position      = new Vector2(71, 44);
            loanDueBy.Size          = new Vector2(60, 13);
            loanDueBy.Name          = "loan_by_label";
            loanDueBy.MaxCharacters = 33;
            mainPanel.Components.Add(loanDueBy);

            depoGoldButton               = new Button();
            depoGoldButton.Position      = new Vector2(120, 58);
            depoGoldButton.Size          = new Vector2(45, 8);
            depoGoldButton.Name          = "depo_gold_button";
            depoGoldButton.OnMouseClick += DepoGoldButton_OnMouseClick;
            mainPanel.Components.Add(depoGoldButton);

            drawGoldButton               = new Button();
            drawGoldButton.Position      = new Vector2(172, 58);
            drawGoldButton.Size          = new Vector2(45, 8);
            drawGoldButton.Name          = "draw_gold_button";
            drawGoldButton.OnMouseClick += DrawGoldButton_OnMouseClick;
            mainPanel.Components.Add(drawGoldButton);

            depoLOCButton               = new Button();
            depoLOCButton.Position      = new Vector2(120, 76);
            depoLOCButton.Size          = new Vector2(45, 8);
            depoLOCButton.Name          = "depo_loc_button";
            depoLOCButton.OnMouseClick += DepoLOCButton_OnMouseClick;
            mainPanel.Components.Add(depoLOCButton);

            drawLOCButton               = new Button();
            drawLOCButton.Position      = new Vector2(172, 76);
            drawLOCButton.Size          = new Vector2(45, 8);
            drawLOCButton.Name          = "draw_LOC_button";
            drawLOCButton.OnMouseClick += DrawLOCButton_OnMouseClick;
            mainPanel.Components.Add(drawLOCButton);

            loanRepayButton               = new Button();
            loanRepayButton.Position      = new Vector2(120, 94);
            loanRepayButton.Size          = new Vector2(45, 8);
            loanRepayButton.Name          = "loan_repay_button";
            loanRepayButton.OnMouseClick += LoanRepayButton_OnMouseClick;
            mainPanel.Components.Add(loanRepayButton);

            loanBorrowButton               = new Button();
            loanBorrowButton.Position      = new Vector2(172, 94);
            loanBorrowButton.Size          = new Vector2(45, 8);
            loanBorrowButton.Name          = "loan_borrow_button";
            loanBorrowButton.OnMouseClick += LoanBorrowButton_OnMouseClick;
            mainPanel.Components.Add(loanBorrowButton);

            buyHouseButton               = new Button();
            buyHouseButton.Position      = new Vector2(120, 112);
            buyHouseButton.Size          = new Vector2(45, 8);
            buyHouseButton.Name          = "buy_house_button";
            buyHouseButton.OnMouseClick += BuyHouseButton_OnMouseClick;
            mainPanel.Components.Add(buyHouseButton);

            sellHouseButton               = new Button();
            sellHouseButton.Position      = new Vector2(172, 112);
            sellHouseButton.Size          = new Vector2(45, 8);
            sellHouseButton.Name          = "sell_house_button";
            sellHouseButton.OnMouseClick += SellHouseButton_OnMouseClick;
            mainPanel.Components.Add(sellHouseButton);

            buyShipButton               = new Button();
            buyShipButton.Position      = new Vector2(120, 130);
            buyShipButton.Size          = new Vector2(45, 8);
            buyShipButton.Name          = "buy_ship_button";
            buyShipButton.OnMouseClick += BuyShipButton_OnMouseClick;
            mainPanel.Components.Add(buyShipButton);

            sellShipButton               = new Button();
            sellShipButton.Position      = new Vector2(172, 130);
            sellShipButton.Size          = new Vector2(45, 8);
            sellShipButton.Name          = "sell_ship_button";
            sellShipButton.OnMouseClick += SellShipButton_OnMouseClick;
            mainPanel.Components.Add(sellShipButton);

            exitButton               = new Button();
            exitButton.Position      = new Vector2(92, 159);
            exitButton.Size          = new Vector2(40, 19);
            exitButton.Name          = "exit_button";
            exitButton.OnMouseClick += ExitButton_OnMouseClick;
            mainPanel.Components.Add(exitButton);

            transactionInput               = new TextBox();
            transactionInput.Position      = new Vector2(113, 146);
            transactionInput.Size          = new Vector2(103, 12);
            transactionInput.Numeric       = true;
            transactionInput.Enabled       = false;
            transactionInput.MaxCharacters = 9;
            mainPanel.Components.Add(transactionInput);

            playerEntity    = GameManager.Instance.PlayerEntity;
            regionIndex     = GameManager.Instance.PlayerGPS.CurrentRegionIndex;
            transactionType = TransactionType.None;
            UpdateLabels();
        }
예제 #42
0
        public IActionResult GetTransactionsByType([FromBody] TransactionType transactionType)
        {
            var answer = _raportReporisotry.GetTransactionsByType(transactionType);

            return(Ok(answer));
        }
예제 #43
0
 public SQLiteHelper(String connectionString)
 {
     mConnection       = new SQLiteConnection(connectionString);
     mConnectionIsOpen = false;
     mTransactionState = TransactionType.None;
 }
예제 #44
0
        private double amount;          // amount concerned

        // constructor
        public AccountTransaction(TransactionType type, double amount)
        {
            this.type   = type;
            this.amount = amount;
        }
예제 #45
0
        public async Task <int> GetCount(int agencyid, TransactionType type)
        {
            var query = await _transactionRepository.GetQueryTransaction(EntityType.Agency, agencyid, type);

            return(query.Count());
        }
예제 #46
0
        public async Task <CardLimit> CreateLimitAsync(string cardNumber, decimal amount, TransactionType type)
        {
            var limit = new CardLimit {
                AggregateAmount = amount, LimitType = type, CardNumber = (await GetByNumberAsync(cardNumber)).Number
            };
            await _dbContext.AddAsync(limit);

            return(limit);
        }
예제 #47
0
 public Transaction(decimal amount, TransactionType transactionType)
 {
     Amount            = amount;
     TransactionType   = transactionType;
     DateOfTransaction = DateTime.Today;
 }
예제 #48
0
        public List <ITransaction> GetTransactionList(SearchFilterObject SearchFilter)
        {
            List <ITransaction> ReturnList = new List <ITransaction>();

            StockRepo   StockRepo   = new StockRepo();
            AddressRepo AddressRepo = new AddressRepo();

            TransactionType TranType = (TransactionType)SearchFilter.ExtraSearchObject1;

            if (TranType == TransactionType.All || TranType == TransactionType.Sale)
            {
                var SalesQuery = (from S in DB.dtSales
                                  join U in DB.dtUsers on S.SoldBy equals U.uID
                                  join UD in DB.dtUserDetails on U.uID equals UD.UserID
                                  join P in DB.dtPersons on S.PersonID equals P.pID

                                  where S.tID.ToString().Equals(SearchFilter.ObjectID == null ? S.tID.ToString() : SearchFilter.ObjectID) &&
                                  S.Title.IndexOf(SearchFilter.ObjectName == null ? S.Title : SearchFilter.ObjectName) >= 0 &&
                                  S.Description.IndexOf(SearchFilter.ObjectDescription == null ? S.Description : SearchFilter.ObjectDescription) >= 0 &&
                                  (S.Created >= SearchFilter.ObjectCreatedFrom && S.Created <= SearchFilter.ObjectCreatedTo)
                                  select new skSales
                {
                    ID = S.tID,
                    Title = S.Title,
                    Description = S.Description,
                    Postage = S.PandP,
                    Amount = S.SoldValue,
                    SaleDate = S.SoldDate,
                    PayPalFees = S.PaypayFees,
                    PayPalTransactionID = S.PayPalTransactionID,
                    Created = S.Created,
                    Updated = S.Updated,
                    TransactionTime = S.SoldDate,
                    SaleMethod = S.SaleMethod,
                    UserObj = new skUser
                    {
                        UserID = U.uID,
                        DOB = UD.DateOfBirth,
                        Email = UD.Email,
                        FistName = UD.FirstName,
                        LastName = UD.LastName,
                        HomePhone = UD.HomePhone,
                        Initials = UD.Initials,
                        UserName = U.UserName,
                        WorkPhone = UD.WorkPhone
                    },
                    PersonObj = new skPerson
                    {
                        pID = P.pID,
                        Created = P.Created,
                        EbayName = P.EbayName,
                        Email = P.Email,
                        FirstName = P.FirstName,
                        HomePhone = P.HomePhone,
                        LinkedAddresses = AddressRepo.GetPersonAddressList(P.pID).ToList(),
                        Mobile = P.WorkPhone,
                        WorkPhone = P.WorkPhone,
                        Surname = P.SureName,
                        Updated = P.Updated
                    }
                    ,
                    StockList = new List <skStock>(StockRepo.GetStockListBySaleID(S.tID))
                }).Take(SearchFilter.RecordsToReturn == 0 ? 10000 : SearchFilter.RecordsToReturn);

                foreach (var item in SalesQuery)
                {
                    ReturnList.Add(item);
                }
            }
            if (TranType == TransactionType.All || TranType == TransactionType.Purchase)
            {
                var VendorRepo = new VendorRepo();

                var PurchaseQuery = (from P in DB.dtPurcheses
                                     from U in DB.dtUsers
                                     .Where(x => P.AddedBy == x.uID)
                                     .DefaultIfEmpty()
                                     where P.pID.ToString().Equals(SearchFilter.ObjectID == null ? P.pID.ToString() : SearchFilter.ObjectID) &&
                                     P.ItemTitle.IndexOf(SearchFilter.ObjectName == null ? P.ItemTitle : SearchFilter.ObjectName) >= 0 &&
                                     P.ItemDescription.IndexOf(SearchFilter.ObjectDescription == null ? P.ItemDescription : SearchFilter.ObjectDescription) >= 0 &&
                                     (P.Created >= SearchFilter.ObjectCreatedFrom && P.Created <= SearchFilter.ObjectCreatedTo)
                                     select new skPurchase
                {
                    ID = P.pID,
                    Created = P.Created,
                    CreatedBy = U.UserName,
                    PapPalTransactionID = P.PayPalTransactionID,
                    Description = P.ItemDescription,
                    Title = P.ItemTitle,
                    Invoice = P.InvoiceID,
                    Amount = Convert.ToDecimal(P.PurchesedValue),
                    Postage = Convert.ToDecimal(P.ShippingCosts),
                    VendorObject = VendorRepo.GetVendorDetails(Convert.ToInt32(P.VendorID)),
                    PurchaseDate = P.Purchesed_Date,
                    TransactionTime = P.Purchesed_Date,
                    Updated = P.Updated,
                    LinkedStock = new List <skStock>(StockRepo.GetStockListByPrucahseID(P.pID))
                }).Take(SearchFilter.RecordsToReturn == 0 ? 10000 : SearchFilter.RecordsToReturn);

                foreach (var item in PurchaseQuery)
                {
                    ReturnList.Add(item);
                }
            }

            if (TranType == TransactionType.All || TranType == TransactionType.Refund)
            {
                var RefundQuery = (from R in DB.dtRefunds
                                   from U in DB.dtUsers
                                   .Where(x => R.RefundedBy == x.uID)
                                   .DefaultIfEmpty()
                                   join UD in DB.dtUserDetails on U.uID equals UD.UserID

                                   join S in DB.dtStocks on R.StockID equals S.sID
                                   join ST in DB.dtCategories on S.CategoryID equals ST.CatID
                                   from SD in DB.dtStockDetails
                                   .Where(o => o.StockID == S.sID)
                                   .DefaultIfEmpty()

                                   select new skRefund
                {
                    Amount = R.Amount,
                    Created = R.Created,
                    Description = R.Reason,
                    Title = S.ItemTitle,
                    ID = R.rID,
                    PayPalTransactionID = R.PayPalTransactionID,
                    SHippingCosts = R.Postage,
                    StockItem = new skStock
                    {
                        Stockid = S.sID,
                        Created = S.Created,
                        Description = S.ItemDesc,
                        Name = S.ItemTitle,
                        purchasedvalue = SD.PurchaseValue,
                        SaleValue = SD.SaleValue,
                        Sold = S.Sold,
                        Updated = S.Updated,
                        CategoryObject = new skCategory
                        {
                            Description = ST.Description,
                            Name = ST.Title,
                            StockTypeID = ST.CatID
                        }
                    },
                    TransactionTime = R.Refunded,
                    TransactionType = TransactionType.Refund,
                    Updated = R.Updated,
                    User = new skUser
                    {
                        UserID = U.uID,
                        DOB = UD.DateOfBirth,
                        Email = UD.Email,
                        FistName = UD.FirstName,
                        LastName = UD.LastName,
                        HomePhone = UD.HomePhone,
                        Initials = UD.Initials,
                        UserName = U.UserName,
                        WorkPhone = UD.WorkPhone
                    }
                }).Take(SearchFilter.RecordsToReturn == 0 ? 10000 : SearchFilter.RecordsToReturn);

                foreach (var item in RefundQuery)
                {
                    ReturnList.Add(item);
                }
            }

            ReturnList = ReturnList.OrderBy(x => x.TransactionTime).Take(SearchFilter.RecordsToReturn == 0? 10000 : SearchFilter.RecordsToReturn).ToList();
            ReturnList = ReturnList.OrderBy(x => x.TransactionTime).Take(SearchFilter.RecordsToReturn == 0 ? 10000 : SearchFilter.RecordsToReturn).ToList();
            return(ReturnList);
        }
예제 #49
0
        public async Task <Result <Transaction> > AuthorizeAsync(string cardNumber, decimal amount, TransactionType type, string details)
        {
            try
            {
                if (type == TransactionType.Undefined)
                {
                    return(new Result <Transaction> {
                        Code = ResultCode.Error, ErrorMessage = "Transaction type not provided"
                    });
                }

                var card = await GetByNumberAsync(cardNumber);

                if (card == null)
                {
                    return(new Result <Transaction> {
                        Code = ResultCode.NotFound, ErrorMessage = "Card not found"
                    });                                                                                             // we shouldn't actually return "notfound" as an outer message. that could be abused.
                }

                if (amount > card.Balance)
                {
                    return(new Result <Transaction> {
                        Code = ResultCode.Error, ErrorMessage = "Not available balance"
                    });
                }

                //check daily limits

                var limit = await GetCardLimitAsync(cardNumber, type);

                var today = DateTime.Today.ToString("yyyy-MM-dd"); //datetime format should be global. I use this to avoid any confussion with datetime formats. standard ISO date.

                //no null check, limits will be init on card creation
                //limit = new CardLimit { AggregateAmount = amount, Card = card, IsoDate = today, LimitType = type };


                if (today == limit.IsoDate && (limit.AggregateAmount + amount) > HardLimits.GetLimit(type))
                {
                    return(new Result <Transaction> {
                        Code = ResultCode.Error, ErrorMessage = "Limit reached"
                    });
                }


                if (today == limit.IsoDate)
                {
                    limit.AggregateAmount += amount;
                }
                else
                {
                    limit.IsoDate         = today;
                    limit.AggregateAmount = amount;
                }

                card.Balance -= amount;

                var transaction = new Transaction {
                    Card = card, Id = Guid.NewGuid(), Amount = amount, Type = type, Timestamp = DateTimeOffset.Now, Details = details
                };
                await _dbContext.AddAsync(transaction);

                // the following will persist transaction, limit and card details
                //
                //
                await _dbContext.SaveChangesAsync();

                return(new Result <Transaction> {
                    Data = transaction, Code = ResultCode.Success
                });
            }
            catch (Exception e)
            {
                return(new Result <Transaction> {
                    Code = ResultCode.Error, ErrorMessage = e.Message
                });
            }
        }
예제 #50
0
 public SQLiteHelper(SQLiteConnection connection)
 {
     mConnection       = connection;
     mConnectionIsOpen = false;
     mTransactionState = TransactionType.None;
 }
예제 #51
0
 public virtual ValidationResult Validate(TransactionType type)
 {
     return(new Validator(type).Validate(this));
 }
예제 #52
0
        public static ErrorCodes UpdateUsedComponents(IEnumerable <ProductionLiveComponent> usedComponents, Container container, Character character, TransactionType transactionType)
        {
            var ec = ErrorCodes.NoError;

            foreach (var component in usedComponents)
            {
                var componentItem = container.GetItem(component.eid, true);
                if (componentItem == null)
                {
                    ec = ErrorCodes.ItemNotFound;
                    return(ec);
                }

                var logQuantity = componentItem.Quantity;

                if (component.resultQuantity == 0)
                {
                    Entity.Repository.Delete(componentItem);
                }
                else
                {
                    logQuantity            = componentItem.Quantity - component.resultQuantity;
                    componentItem.Quantity = component.resultQuantity;
                }

                var b = TransactionLogEvent.Builder().SetTransactionType(transactionType).SetCharacter(character).SetItem(componentItem.Definition, logQuantity);
                character.LogTransaction(b);
            }

            return(ec);
        }
예제 #53
0
        public async Task <long> GetTotalAmount(int agencyid, TransactionType type)
        {
            var query = await _transactionRepository.GetQueryTransaction(EntityType.Agency, agencyid, type);

            return(query.Select(m => m.Amount).Sum());
        }
 public TransactionTed(decimal ammount, TransactionType transactionType) : base(ammount, transactionType)
 {
 }
예제 #55
0
 internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction) : this(innerConnection, type, outerTransaction, NullTransactionId)
 {
 }
예제 #56
0
 public override object GenerateTransactionID(PaySession callerSession, ITransactionContext context, TransactionType type)
 {
     return(0);
 }
예제 #57
0
        public async Task <ListTransactionHistoryViewModel> GetTransactionHistory(EntityType entityType, int entityid, TransactionType type,
                                                                                  string daterange, int page, int pagesize)
        {
            var date = Common.Helpers.DateRangeHelper.GetDateRangeByDate(daterange);

            var walletid = await _walletRepository.GetWalletId(entityType, entityid);

            var filter = new TransactionHistorySpecification(walletid, date, type);

            var total = await _transactionHistoryRepository.CountAsync(filter);

            var transactionHistory = await _transactionHistoryRepository.ListPagedAsync(filter, "Id_desc", page, pagesize);

            return(new ListTransactionHistoryViewModel()
            {
                TransactionHistories = TransactionHistoryViewModel.GetList(transactionHistory),
                Pager = new PagerViewModel(page, pagesize, total)
            });
        }
예제 #58
0
        private static async Task <IEnumerable <Transaction> > GetAllTransactionsByType(HttpClient client, TransactionType transactionType)
        {
            var transactions = new List <Transaction>();

            int page_number   = 1;
            var pageCountDown = page_number;

            while (pageCountDown > 0)
            {
                var response = await client.GetAsync($"/api/transactions/search?txnType={transactionType}&page={page_number}");

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    var responseContent = JsonConvert.DeserializeObject <ResponseTransactionsDto>(content);

                    transactions.AddRange(responseContent.Transactions);
                    pageCountDown = responseContent.TotalPages - page_number;
                    page_number++;
                }
                else
                {
                    break;
                }
            }

            return(transactions);
        }
        public Transaction ProcessSecure3d(Secure3dBuilder builder)
        {
            TransactionType transType     = builder.TransactionType;
            IPaymentMethod  paymentMethod = builder.PaymentMethod;
            ISecure3d       secure3d      = (ISecure3d)paymentMethod;
            string          timestamp     = DateTime.Now.ToString("yyyy-MM-dd'T'hh:mm:ss.ffffff");

            JsonDoc request = new JsonDoc();

            if (transType.Equals(TransactionType.VerifyEnrolled))
            {
                request.Set("request_timestamp", timestamp);
                request.Set("merchant_id", MerchantId);
                request.Set("account_id", AccountId);
                request.Set("method_notification_url", MethodNotificationUrl);

                string hashValue = string.Empty;
                if (paymentMethod is CreditCardData cardData)
                {
                    request.Set("number", cardData.Number);
                    request.Set("scheme", MapCardScheme(cardData.CardType.ToUpper()));
                    hashValue = cardData.Number;
                }
                else if (paymentMethod is RecurringPaymentMethod storedCard)
                {
                    request.Set("payer_reference", storedCard.CustomerKey);
                    request.Set("payment_reference", storedCard.Key);
                    hashValue = storedCard.CustomerKey;
                }

                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, hashValue);
                SetAuthHeader(hash);

                string rawResponse = DoTransaction(HttpMethod.Post, "protocol-versions", request.ToString());
                return(MapResponse(rawResponse));
            }
            else if (transType.Equals(TransactionType.VerifySignature))
            {
                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, builder.ServerTransactionId);
                SetAuthHeader(hash);

                var queryValues = new Dictionary <string, string>();
                queryValues.Add("merchant_id", MerchantId);
                queryValues.Add("request_timestamp", timestamp);

                string rawResponse = DoTransaction(HttpMethod.Get, string.Format("authentications/{0}", builder.ServerTransactionId), request.ToString(), queryValues);
                return(MapResponse(rawResponse));
            }
            else if (transType.Equals(TransactionType.InitiateAuthentication))
            {
                string orderId = builder.OrderId;
                if (string.IsNullOrEmpty(orderId))
                {
                    orderId = GenerationUtils.GenerateOrderId();
                }
                ThreeDSecure secureEcom = secure3d.ThreeDSecure;

                request.Set("request_timestamp", timestamp);
                request.Set("authentication_source", builder.AuthenticationSource.ToString());
                request.Set("authentication_request_type", builder.AuthenticationRequestType.ToString());
                request.Set("message_category", builder.MessageCategory.ToString());
                request.Set("message_version", "2.1.0");
                request.Set("server_trans_id", secureEcom.ServerTransactionId);
                request.Set("merchant_id", MerchantId);
                request.Set("account_id", AccountId);
                request.Set("challenge_notification_url", ChallengeNotificationUrl);
                request.Set("method_url_completion", builder.MethodUrlCompletion.ToString());
                request.Set("merchant_contact_url", MerchantContactUrl);

                // card details
                string  hashValue  = string.Empty;
                JsonDoc cardDetail = request.SubElement("card_detail");
                if (paymentMethod is CreditCardData cardData)
                {
                    hashValue = cardData.Number;
                    cardDetail.Set("number", cardData.Number);
                    cardDetail.Set("scheme", cardData.CardType.ToUpper());
                    cardDetail.Set("expiry_month", cardData.ExpMonth.ToString());
                    cardDetail.Set("expiry_year", cardData.ExpYear.ToString().Substring(2));
                    cardDetail.Set("full_name", cardData.CardHolderName);

                    if (!string.IsNullOrEmpty(cardData.CardHolderName))
                    {
                        string[] names = cardData.CardHolderName.Split(' ');
                        if (names.Length >= 1)
                        {
                            cardDetail.Set("first_name", names[0]);
                        }
                        if (names.Length >= 2)
                        {
                            cardDetail.Set("last_name", names[1]);
                        }
                    }
                }
                else if (paymentMethod is RecurringPaymentMethod storedCard)
                {
                    hashValue = storedCard.CustomerKey;
                    cardDetail.Set("payer_reference", storedCard.CustomerKey);
                    cardDetail.Set("payment_reference", storedCard.Key);
                }

                // order details
                JsonDoc order = request.SubElement("order");
                order.Set("amount", builder.Amount.ToNumericString());
                order.Set("currency", builder.Currency);
                order.Set("id", orderId);
                order.Set("address_match_indicator", builder.AddressMatchIndicator ? "true" : "false");
                order.Set("date_time_created", builder.OrderCreateDate?.ToString("yyyy-MM-dd'T'hh:mm'Z'"));
                order.Set("gift_card_count", builder.GiftCardCount);
                order.Set("gift_card_currency", builder.GiftCardCurrency);
                order.Set("gift_card_amount", builder.GiftCardAmount?.ToNumericString());
                order.Set("delivery_email", builder.DeliveryEmail);
                order.Set("delivery_timeframe", builder.DeliveryTimeframe?.ToString());
                order.Set("shipping_method", builder.ShippingMethod?.ToString());
                order.Set("shipping_name_matches_cardholder_name", builder.ShippingNameMatchesCardHolderName);
                order.Set("preorder_indicator", builder.PreOrderIndicator?.ToString());
                order.Set("reorder_indicator", builder.ReorderIndicator?.ToString());
                order.Set("transaction_type", builder.OrderTransactionType?.ToString());
                order.Set("preorder_availability_date", builder.PreOrderAvailabilityDate?.ToString("yyyy-MM-dd"));

                // shipping address
                Address shippingAddress = builder.ShippingAddress;
                if (shippingAddress != null)
                {
                    JsonDoc shippingAddressElement = order.SubElement("shipping_address");
                    shippingAddressElement.Set("line1", shippingAddress.StreetAddress1);
                    shippingAddressElement.Set("line2", shippingAddress.StreetAddress2);
                    shippingAddressElement.Set("line3", shippingAddress.StreetAddress3);
                    shippingAddressElement.Set("city", shippingAddress.City);
                    shippingAddressElement.Set("post_code", shippingAddress.PostalCode);
                    shippingAddressElement.Set("state", shippingAddress.State);
                    shippingAddressElement.Set("country", shippingAddress.CountryCode);
                }

                // payer
                JsonDoc payer = request.SubElement("payer");
                payer.Set("email", builder.CustomerEmail);
                payer.Set("id", builder.CustomerAccountId);
                payer.Set("account_age", builder.AccountAgeIndicator?.ToString());
                payer.Set("account_creation_date", builder.AccountCreateDate?.ToString("yyyy-MM-dd"));
                payer.Set("account_change_indicator", builder.AccountChangeIndicator?.ToString());
                payer.Set("account_change_date", builder.AccountChangeDate?.ToString("yyyy-MM-dd"));
                payer.Set("account_password_change_indicator", builder.PasswordChangeIndicator?.ToString());
                payer.Set("account_password_change_date", builder.PasswordChangeDate?.ToString("yyyy-MM-dd"));
                payer.Set("payment_account_age_indicator", builder.PaymentAgeIndicator?.ToString());
                payer.Set("payment_account_creation_date", builder.PaymentAccountCreateDate?.ToString("yyyy-MM-dd"));
                payer.Set("purchase_count_last_6months", builder.NumberOfPurchasesInLastSixMonths);
                payer.Set("transaction_count_last_24hours", builder.NumberOfTransactionsInLast24Hours);
                payer.Set("transaction_count_last_year", builder.NumberOfTransactionsInLastYear);
                payer.Set("provision_attempt_count_last_24hours", builder.NumberOfAddCardAttemptsInLast24Hours);
                payer.Set("shipping_address_creation_indicator", builder.ShippingAddressUsageIndicator?.ToString());
                payer.Set("shipping_address_creation_date", builder.ShippingAddressCreateDate?.ToString("yyyy-MM-dd"));

                // suspicious activity
                if (builder.PreviousSuspiciousActivity != null)
                {
                    payer.Set("suspicious_account_activity", builder.PreviousSuspiciousActivity.Value ? "SUSPICIOUS_ACTIVITY" : "NO_SUSPICIOUS_ACTIVITY");
                }

                // home phone
                if (!string.IsNullOrEmpty(builder.HomeNumber))
                {
                    payer.SubElement("home_phone")
                    .Set("country_code", builder.HomeCountryCode)
                    .Set("subscriber_number", builder.HomeNumber);
                }

                // work phone
                if (!string.IsNullOrEmpty(builder.WorkNumber))
                {
                    payer.SubElement("work_phone")
                    .Set("country_code", builder.WorkCountryCode)
                    .Set("subscriber_number", builder.WorkNumber);
                }

                // payer login data
                if (builder.HasPayerLoginData)
                {
                    request.SubElement("payer_login_data")
                    .Set("authentication_data", builder.CustomerAuthenticationData)
                    .Set("authentication_timestamp", builder.CustomerAuthenticationTimestamp?.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"))
                    .Set("authentication_type", builder.CustomerAuthenticationMethod?.ToString());
                }

                // prior authentication data
                if (builder.HasPriorAuthenticationData)
                {
                    request.SubElement("payer_prior_three_ds_authentication_data")
                    .Set("authentication_method", builder.PriorAuthenticationMethod?.ToString())
                    .Set("acs_transaction_id", builder.PriorAuthenticationTransactionId)
                    .Set("authentication_timestamp", builder.PriorAuthenticationTimestamp?.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"))
                    .Set("authentication_data", builder.PriorAuthenticationData);
                }

                // recurring authorization data
                if (builder.HasRecurringAuthData)
                {
                    request.SubElement("recurring_authorization_data")
                    .Set("max_number_of_instalments", builder.MaxNumberOfInstallments)
                    .Set("frequency", builder.RecurringAuthorizationFrequency)
                    .Set("expiry_date", builder.RecurringAuthorizationExpiryDate?.ToString("yyyy-MM-dd"));
                }

                // billing details
                Address billingAddress = builder.BillingAddress;
                if (billingAddress != null)
                {
                    JsonDoc billingAddressElement = payer.SubElement("billing_address");
                    billingAddressElement.Set("line1", billingAddress.StreetAddress1);
                    billingAddressElement.Set("line2", billingAddress.StreetAddress2);
                    billingAddressElement.Set("line3", billingAddress.StreetAddress3);
                    billingAddressElement.Set("city", billingAddress.City);
                    billingAddressElement.Set("post_code", billingAddress.PostalCode);
                    billingAddressElement.Set("state", billingAddress.State);
                    billingAddressElement.Set("country", billingAddress.CountryCode);
                }

                // mobile phone
                if (!string.IsNullOrEmpty(builder.MobileNumber))
                {
                    JsonDoc mobilePhone = payer.SubElement("mobile_phone");
                    mobilePhone.Set("country_code", builder.MobileCountryCode);
                    mobilePhone.Set("subscriber_number", builder.MobileNumber);
                }

                // browser_data
                BrowserData broswerData = builder.BrowserData;
                if (broswerData != null)
                {
                    JsonDoc browserDataElement = request.SubElement("browser_data");
                    browserDataElement.Set("accept_header", broswerData.AcceptHeader);
                    browserDataElement.Set("color_depth", broswerData.ColorDepth.ToString());
                    browserDataElement.Set("ip", broswerData.IpAddress);
                    browserDataElement.Set("java_enabled", broswerData.JavaEnabled);
                    browserDataElement.Set("javascript_enabled", broswerData.JavaScriptEnabled);
                    browserDataElement.Set("language", broswerData.Language);
                    browserDataElement.Set("screen_height", broswerData.ScreenHeight);
                    browserDataElement.Set("screen_width", broswerData.ScreenWidth);
                    browserDataElement.Set("challenge_window_size", broswerData.ChallengeWindowSize.ToString());
                    browserDataElement.Set("timezone", broswerData.Timezone);
                    browserDataElement.Set("user_agent", broswerData.UserAgent);
                }

                // mobile fields
                if (builder.HasMobileFields)
                {
                    JsonDoc sdkInformationElement = request.SubElement("sdk_information")
                                                    .Set("application_id", builder.ApplicationId)
                                                    .Set("ephemeral_public_key", builder.EphemeralPublicKey)
                                                    .Set("maximum_timeout", builder.MaximumTimeout)
                                                    .Set("reference_number", builder.ReferenceNumber)
                                                    .Set("sdk_trans_id", builder.SdkTransactionId)
                                                    .Set("encoded_data", builder.EncodedData)
                    ;

                    // device render options
                    if (builder.SdkInterface != null || builder.SdkUiTypes != null)
                    {
                        var dro = sdkInformationElement.SubElement("device_render_options");
                        dro.Set("sdk_interface", builder.SdkInterface?.ToString());
                        if (builder.SdkUiTypes != null)
                        {
                            var uiTypes = new List <string>();
                            foreach (var sdkuiType in builder.SdkUiTypes)
                            {
                                uiTypes.Add(sdkuiType.ToString());
                            }
                            dro.Set("sdk_ui_type", uiTypes.ToArray());
                        }
                    }
                }

                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, hashValue, secureEcom.ServerTransactionId);
                SetAuthHeader(hash);

                string rawResponse = DoTransaction(HttpMethod.Post, "authentications", request.ToString());
                return(MapResponse(rawResponse));
            }

            throw new ApiException(string.Format("Unknown transaction type {0}.", transType));
        }
예제 #60
-1
        //  Order ID
        //  Transaction type
        static void AddFilledOrder(LiveOpenPositionsEditor openPositionData, string orderID, Symbol symbol, PositionType direction, TransactionType transactionType, double fillPrice, long fillSize, DateTime fillTime, string customString)
        {
            if (openPositionData.PortfolioXml.Positions.SelectMany(pos => pos.Trades).Any(trade => trade.OrderID == orderID))
            {
                //  Trade already recorded
                return;
            }

            PositionDataXml position;

            BrokerOrder existingOrder = openPositionData.PortfolioXml.PendingOrders.FirstOrDefault(order => order.OrderId == orderID);
            if (existingOrder != null)
            {
                //  Order was pending, remove it
                PositionDataXml existingPosition = openPositionData.PortfolioXml.Positions.Single(p => p.PosID == existingOrder.PositionID);
                TradeOrderXml existingTradeOrder = existingPosition.PendingOrders.Single(to => to.OrderID == existingOrder.OrderId);
                existingPosition.PendingOrders.Remove(existingTradeOrder);
                openPositionData.PortfolioXml.PendingOrders.Remove(existingOrder);

                position = existingPosition;
            }
            else
            {
                position = openPositionData.AddPosition(symbol, direction);
                position.CustomString = customString;
            }

            openPositionData.AddCompletedTradeToPosition(position, fillTime, transactionType, new Price(fillPrice, fillPrice), fillSize, orderID);
        }