public static ArrayList GetAllTrns_ByCustId(int CustId)
    {
        ArrayList TransList = new ArrayList();

        Connection con = new Connection();
        string strConnString = con.GetConnString();
        using (SqlConnection SqlCon = new SqlConnection(strConnString))
        {
            SqlCommand SqlComm = new SqlCommand("", SqlCon);
            SqlCon.Open();

            string query = string.Format("SELECT * FROM transactions WHERE t_cid='" + CustId + "' ORDER BY t_id DESC");
            SqlComm.CommandText = query;
            SqlDataReader reader = SqlComm.ExecuteReader();
            Transactions trns = null;

            while (reader.Read())
            {
                int Tr_Id = reader.GetInt32(0);
                int Tr_CustId = reader.GetInt32(1);
                string Tr_Nartn = reader.GetString(2);
                string Tr_ChqRefNo = reader.GetString(3);
                string Tr_WithdAmt = reader.IsDBNull(4) ? null : reader.GetString(4);
                string Tr_DpoAmt = reader.IsDBNull(5) ? null : reader.GetString(5);
                decimal Tr_Blnc = reader.GetDecimal(6);
                DateTime Tr_Data = reader.GetDateTime(7);

                trns = new Transactions(Tr_Id, Tr_CustId, Tr_Nartn, Tr_ChqRefNo, Tr_WithdAmt, Tr_DpoAmt, Tr_Blnc, Tr_Data);
                TransList.Add(trns);
            }
            return TransList;
        }
    }
Ejemplo n.º 2
0
 protected void AttachSubscriber(Transactions.Processes.Base process, Engine.AuthorizationDelegate onAuthorizationDenied)
 {
     process.OnAuthorizationDenied += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task)
     {
         try
         {
             if (onAuthorizationDenied != null &&
                 !_isEventSubscriptionSuppressed)
                 onAuthorizationDenied(_request);
         }
         catch (System.Exception e)
         {
             Logger.Storage.Error("An exception occurred while calling the method specified in the onAuthorizationDenied argument.", e);
             throw;
         }
     };
 }
Ejemplo n.º 3
0
		// Protected Methods (6) 

        protected void AttachSubscriber(Transactions.Processes.Base process, Engine.ActionDelegate onAction)
        {
            process.OnActionChanged += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task, EngineActionType actionType, bool willSendProgress)
            {
                try
                {
                    if (onAction != null &&
                        !_isEventSubscriptionSuppressed)
                        onAction(_request, actionType, willSendProgress);
                }
                catch (System.Exception e)
                {
                    Logger.Storage.Error("An exception occurred while calling the method specified in the onAction argument.", e);
                    throw;
                }
            };
        }
Ejemplo n.º 4
0
 protected void AttachSubscriber(Transactions.Processes.Base process, Engine.CompletionDelegate onComplete)
 {
     process.OnComplete += delegate(Transactions.Processes.Base sender, ICommandReply reply, object result)
     {
         try
         {
             if (onComplete != null &&
                 !_isEventSubscriptionSuppressed)
                 onComplete(_request, reply, result);
         }
         catch (System.Exception e)
         {
             Logger.Storage.Error("An exception occurred while calling the method specified in the onComplete argument.", e);
             throw;
         }
     };
 }
 private void MonthTotal(Transactions LT, bool IsIn)
 {
     if (IsIn)
     {
         if (LT.Deadline.Month == DateTime.Today.Month)
         {
             InMonthly.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (LT.Deadline.Month < DateTime.Today.Month)
         {
             InMonthly.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
     else
     {
         if (LT.Deadline.Month == DateTime.Today.Month)
         {
             OutMonthly.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
             switch (LT.Category)
             {
                 case "Food":
                     Food += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
                     break;
                 case "Accomodation":
                     Accomodation += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
                     break;
                 default:
                     break;
             }
         }
         else if (LT.Deadline.Month < DateTime.Today.Month)
         {
             OutMonthly.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
 }
        private void BtnAddIn_Click(object sender, EventArgs e)
        {
            Transactions temp = new Transactions(
            TBInName.Text,
            CBInCompany.Text,
            CBInCategory.Text,
            Type.In.ToString(),
            NuInAmountPre.Value,

            (DTInDeadline.Checked == true? NuInAmountReal.Value : 0),

            CBInCompleted.Checked,
            TBInComment.Lines,
            DTInDeadline.Value,
            DTInReal.Value,
            CBInRepeat.Checked,
            DTRepeatStartIn.Value,
            DTRepeatEndIn.Value,
            CBRepeatFreqIn.Text);
            Income.Add(temp);

            if (sender.ToString().Contains("Update"))
            {
                Income.RemoveAt(LBIn.SelectedIndex);
                BtnAddIn.Text = "BtnAddIn";
            }
            ResetTabIn(sender, e);
            PopulateTransLists();
            Total();
            WriteToFile(sender, e);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (!data.Bars.ContainsKey(symbol))
            {
                return;
            }

            // each month make an action
            if (Time.Month != LastMonth)
            {
                // we'll submit the next type of order from the queue
                var orderType = _orderTypesQueue.Dequeue();
                //Log("");
                Log($"\r\n--------------MONTH: {Time.ToStringInvariant("MMMM")}:: {orderType}\r\n");
                //Log("");
                LastMonth = Time.Month;
                Log("ORDER TYPE:: " + orderType);
                var isLong     = Quantity > 0;
                var stopPrice  = isLong ? (1 + StopPercentage) * data.Bars[symbol].High : (1 - StopPercentage) * data.Bars[symbol].Low;
                var limitPrice = isLong ? (1 - LimitPercentage) * stopPrice : (1 + LimitPercentage) * stopPrice;
                if (orderType == OrderType.Limit)
                {
                    limitPrice = !isLong ? (1 + LimitPercentage) * data.Bars[symbol].High : (1 - LimitPercentage) * data.Bars[symbol].Low;
                }
                var request = new SubmitOrderRequest(orderType, SecType, symbol, Quantity, stopPrice, limitPrice, UtcTime, ((int)orderType).ToString(CultureInfo.InvariantCulture));
                var ticket  = Transactions.AddOrder(request);
                _tickets.Add(ticket);
            }
            else if (_tickets.Count > 0)
            {
                var ticket = _tickets.Last();
                if (Time.Day > 8 && Time.Day < 14)
                {
                    if (ticket.UpdateRequests.Count == 0 && ticket.Status.IsOpen())
                    {
                        Log("TICKET:: " + ticket);
                        ticket.Update(new UpdateOrderFields
                        {
                            Quantity = ticket.Quantity + Math.Sign(Quantity) * DeltaQuantity,
                            Tag      = "Change quantity: " + Time.Day
                        });
                        Log("UPDATE1:: " + ticket.UpdateRequests.Last());
                    }
                }
                else if (Time.Day > 13 && Time.Day < 20)
                {
                    if (ticket.UpdateRequests.Count == 1 && ticket.Status.IsOpen())
                    {
                        Log("TICKET:: " + ticket);
                        ticket.Update(new UpdateOrderFields
                        {
                            LimitPrice = Security.Price * (1 - Math.Sign(ticket.Quantity) * LimitPercentageDelta),
                            StopPrice  = Security.Price * (1 + Math.Sign(ticket.Quantity) * StopPercentageDelta),
                            Tag        = "Change prices: " + Time.Day
                        });
                        Log("UPDATE2:: " + ticket.UpdateRequests.Last());
                    }
                }
                else
                {
                    if (ticket.UpdateRequests.Count == 2 && ticket.Status.IsOpen())
                    {
                        Log("TICKET:: " + ticket);
                        ticket.Cancel(Time.Day + " and is still open!");
                        Log("CANCELLED:: " + ticket.CancelRequest);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void transactionsMenu(UserContext userContext)
        {
            Transactions transactions = new Transactions();

            transactions.doMenu(userContext);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tran"></param>
        /// <param name="tableName"></param>
        public TextSearchTable(Transactions.Transaction tran, string tableName)
        {
            if (tran == null || String.IsNullOrEmpty(tableName))
                throw new Exception("DBreeze.TextSearch.TextSearchTable constructor: transaction or tableName is not supplied");

            this._tran = tran;
            this._tableName = tableName;
        }
        // will
        public void LoadFromExisting(Transactions.TransactionSubmission Sub)
        {
            //	Priority = Sub.Priority;

            //			AddForm.SubEditPanel.Expenses,
            //			AddForm.SubEditPanel.Earned,
            //			AddForm.SubEditPanel.DateReplied,
            //			AddForm.SubEditPanel.Note,
            //			AddForm.SubEditPanel.Rights,
            //			AddForm.SubEditPanel.Draft,
            //			AddForm.SubEditPanel.ReplyType,
            //			AddForm.SubEditPanel.ReplyFeedback,
            //			AddForm.SubEditPanel.SubmissionTypeType
            //	NewMessage.Show ("Load defaults");
            dateSubmission.Value = Sub.SubmissionDate;//(DateTime)row[Data.SubmissionIndexFields.SUBMISSIONDATE];
            SubmissionType.Text = Sub.SubmissionType;//row[Data.SubmissionIndexFields.SUBMISSIONTYPE].ToString();
            postage.Value = Sub.Expenses;
            earned.Value = Sub.Earned;

            replytype.Text = Sub.ReplyType;
                            if (!SubmissionMaster.IsValidReply(Sub.ReplyType))
                            {
                                dateReply.Value = DateTime.Today;
                            }
                            else
                                dateReply.Value =Sub.ReplyDate;

                            feedback.Text = Sub.Replyfeedback;
                            rights.Text = Sub.Rights;

            textBoxDraft.Text = Sub.Draft;

            ePriority.Text = Sub.Priority; //row[Data.SubmissionIndexFields.DESTINATION_PRIORITY].ToString();
            try
                                    {
                                        notes.Rtf = Sub.Notes;
                                    }
                                    catch (Exception)
                                    {
                                        notes.Text = Sub.Notes;
                                    }
        }
Ejemplo n.º 11
0
 public void AddTransaction(ITransaction transaction)
 {
     Transactions.Add(transaction);
 }
Ejemplo n.º 12
0
 public void AddTransaction(Transaction item) =>
 Transactions.Add(item);
Ejemplo n.º 13
0
 internal async Task<TransactionResponse> SignAndSubmitWithRetryAsync(ISignatory signatory, GossipContextStack context)
 {
     var request = await SignAsync(signatory, context.SignaturePrefixTrimLimit);
     return await Transactions.ExecuteSignedRequestWithRetryImplementationAsync(context, request, InstantiateNetworkRequestMethod, getResponseCode);
Ejemplo n.º 14
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            var userMessage = activity.Text;

            StateClient stateClient = activity.GetStateClient();
            BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

            string endOutput = "...";
            bool   isRequest = false;

            if (activity.Type == ActivityTypes.Message)
            {
                HttpClient client = new HttpClient();

                // using luis
                string luis = await client.GetStringAsync(new Uri("https://api.projectoxford.ai/luis/v2.0/apps/cb5cbd34-0b3a-482a-b6c8-2529d6e1cabf?subscription-key=eea0e6ea98c24b00908f85f120e09d44&q=" + userMessage + "&verbose=true"));

                Luis.RootObject luisRootObject;
                luisRootObject = JsonConvert.DeserializeObject <Luis.RootObject>(luis);

                string luisMessage = "...";
                double luisScore   = luisRootObject.topScoringIntent.score;

                // only use luis's reply if certainty is above 0.7
                if (luisScore > 0.7)
                {
                    luisMessage = luisRootObject.topScoringIntent.intent;
                }

                // responding to "Hello"
                if (userMessage.ToLower().Equals("hello"))
                {
                    if (userData.GetProperty <bool>("SentGreeting"))
                    {
                        endOutput = "Hello again";
                        if (userData.GetProperty <bool>("LoggedIn"))
                        {
                            endOutput += ", " + userData.GetProperty <string>("CurrentUsername");
                        }
                    }
                    else
                    {
                        userData.SetProperty <bool>("SentGreeting", true);
                        endOutput = "Hello";
                        if (userData.GetProperty <bool>("LoggedIn"))
                        {
                            endOutput += " " + userData.GetProperty <string>("CurrentUsername");
                        }
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                }

                // responding to "clear"
                if (userMessage.ToLower().Equals("clear"))
                {
                    endOutput = "User data cleared";
                    await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);
                }

                // responding to "log out"
                if (userMessage.ToLower().Equals("log out"))
                {
                    if (userData.GetProperty <bool>("LoggedIn"))
                    {
                        endOutput = "You have logged out";
                        userData.SetProperty <bool>("LoggedIn", false);
                        userData.SetProperty <bool>("SentGreeting", false);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    else
                    {
                        endOutput = "You are not logged in";
                    }
                }

                // replying to exchange rate messages
                if (userMessage.ToLower().Contains("to"))
                {
                    if (userMessage.Length >= 10)
                    {
                        string source = activity.Text.Substring(0, 3).ToUpper();
                        string symbol = activity.Text.Substring(7, 3).ToUpper();
                        string latest = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=" + source));

                        LatestObject.RootObject rootObject;
                        rootObject = JsonConvert.DeserializeObject <LatestObject.RootObject>(latest);

                        string @base = rootObject.@base;
                        string date  = rootObject.date;
                        double rates = 0.0;

                        if (symbol.ToUpper().Equals("AUD"))
                        {
                            rates = rootObject.rates.AUD;
                        }
                        if (symbol.ToUpper().Equals("BGN"))
                        {
                            rates = rootObject.rates.BGN;
                        }
                        if (symbol.ToUpper().Equals("BRL"))
                        {
                            rates = rootObject.rates.BRL;
                        }
                        if (symbol.ToUpper().Equals("CAD"))
                        {
                            rates = rootObject.rates.CAD;
                        }
                        if (symbol.ToUpper().Equals("CHF"))
                        {
                            rates = rootObject.rates.CHF;
                        }
                        if (symbol.ToUpper().Equals("CNY"))
                        {
                            rates = rootObject.rates.CNY;
                        }
                        if (symbol.ToUpper().Equals("CZK"))
                        {
                            rates = rootObject.rates.CZK;
                        }
                        if (symbol.ToUpper().Equals("DKK"))
                        {
                            rates = rootObject.rates.DKK;
                        }
                        if (symbol.ToUpper().Equals("GBP"))
                        {
                            rates = rootObject.rates.GBP;
                        }
                        if (symbol.ToUpper().Equals("HKD"))
                        {
                            rates = rootObject.rates.HKD;
                        }
                        if (symbol.ToUpper().Equals("HRK"))
                        {
                            rates = rootObject.rates.HRK;
                        }
                        if (symbol.ToUpper().Equals("HUF"))
                        {
                            rates = rootObject.rates.HUF;
                        }
                        if (symbol.ToUpper().Equals("IDR"))
                        {
                            rates = rootObject.rates.IDR;
                        }
                        if (symbol.ToUpper().Equals("ILS"))
                        {
                            rates = rootObject.rates.ILS;
                        }
                        if (symbol.ToUpper().Equals("INR"))
                        {
                            rates = rootObject.rates.INR;
                        }
                        if (symbol.ToUpper().Equals("JPY"))
                        {
                            rates = rootObject.rates.JPY;
                        }
                        if (symbol.ToUpper().Equals("KRW"))
                        {
                            rates = rootObject.rates.KRW;
                        }
                        if (symbol.ToUpper().Equals("MXN"))
                        {
                            rates = rootObject.rates.MXN;
                        }
                        if (symbol.ToUpper().Equals("MYR"))
                        {
                            rates = rootObject.rates.MYR;
                        }
                        if (symbol.ToUpper().Equals("NOK"))
                        {
                            rates = rootObject.rates.NOK;
                        }
                        if (symbol.ToUpper().Equals("NZD"))
                        {
                            rates = rootObject.rates.NZD;
                        }
                        if (symbol.ToUpper().Equals("PHP"))
                        {
                            rates = rootObject.rates.PHP;
                        }
                        if (symbol.ToUpper().Equals("PLN"))
                        {
                            rates = rootObject.rates.PLN;
                        }
                        if (symbol.ToUpper().Equals("RON"))
                        {
                            rates = rootObject.rates.RON;
                        }
                        if (symbol.ToUpper().Equals("RUB"))
                        {
                            rates = rootObject.rates.RUB;
                        }
                        if (symbol.ToUpper().Equals("SEK"))
                        {
                            rates = rootObject.rates.SEK;
                        }
                        if (symbol.ToUpper().Equals("SGD"))
                        {
                            rates = rootObject.rates.SGD;
                        }
                        if (symbol.ToUpper().Equals("THB"))
                        {
                            rates = rootObject.rates.THB;
                        }
                        if (symbol.ToUpper().Equals("TRY"))
                        {
                            rates = rootObject.rates.TRY;
                        }
                        if (symbol.ToUpper().Equals("USD"))
                        {
                            rates = rootObject.rates.USD;
                        }
                        if (symbol.ToUpper().Equals("ZAR"))
                        {
                            rates = rootObject.rates.ZAR;
                        }
                        if (symbol.ToUpper().Equals("EUR"))
                        {
                            rates = rootObject.rates.EUR;
                        }

                        if (rates == 0.0)
                        {
                            Activity ratesReply = activity.CreateReply($"Please enter a valid 3-letter country code.");
                            await connector.Conversations.ReplyToActivityAsync(ratesReply);
                        }
                        else
                        {
                            Activity ratesReply = activity.CreateReply($"The exchange rate from {@base} to {symbol} is {rates}.");

                            if (userMessage.Length > 10)
                            {
                                string amountStr = Regex.Match(userMessage, @"\d+").Value;
                                double amount    = Double.Parse(amountStr);

                                double convertedAmount = amount * rates;

                                ratesReply.Recipient   = activity.From;
                                ratesReply.Type        = "message";
                                ratesReply.Attachments = new List <Attachment>();
                                List <CardImage> cardImages = new List <CardImage>();
                                cardImages.Add(new CardImage(url: "http://icons.iconarchive.com/icons/designcontest/ecommerce-business/128/dollar-icon.png"));
                                List <CardAction> cardButtons = new List <CardAction>();
                                CardAction        ratesButton = new CardAction()
                                {
                                    Value = "https://www.msn.com/en-us/money/tools/currencyconverter",
                                    Type  = "openUrl",
                                    Title = "Click here for more conversions"
                                };
                                cardButtons.Add(ratesButton);
                                ThumbnailCard ratesCard = new ThumbnailCard()
                                {
                                    Title    = @base + " to " + symbol,
                                    Subtitle = amount + " " + @base + " = " + convertedAmount + " " + symbol,
                                    Images   = cardImages,
                                    Buttons  = cardButtons
                                };
                                Attachment plAttachment = ratesCard.ToAttachment();
                                ratesReply.Attachments.Add(plAttachment);
                                await connector.Conversations.SendToConversationAsync(ratesReply);
                            }
                            else
                            {
                                await connector.Conversations.ReplyToActivityAsync(ratesReply);
                            }
                        }
                    }

                    isRequest = true;
                }

                // reply to "login"

                if (userMessage.ToLower().Equals("log in") || userData.GetProperty <bool>("LoggingIn"))
                {
                    // check if logged in
                    if (userData.GetProperty <bool>("LoggedIn"))
                    {
                        endOutput = "You are already logged in as " + userData.GetProperty <string>("CurrentUsername");
                    }
                    else
                    {
                        if (userData.GetProperty <bool>("LoggingIn"))
                        {
                            if (userData.GetProperty <bool>("Password"))
                            {
                                if (userMessage == userData.GetProperty <string>("CorrectPassword"))
                                {
                                    userData.SetProperty <bool>("LoggedIn", true);
                                    userData.SetProperty <bool>("LoggingIn", false);
                                    userData.SetProperty <bool>("Password", false);
                                    userData.SetProperty <bool>("SentGreeting", false);
                                    userData.SetProperty <string>("CurrentPassword", userMessage);
                                    endOutput = "Logged in as " + userData.GetProperty <string>("CurrentUsername");
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }
                                else
                                {
                                    endOutput = "Invalid password, please try again";
                                }
                            }
                            else
                            {
                                List <Transactions> transactions = await AzureManager.AzureManagerInstance.GetTransactions();

                                // loop through all transactions for inputted username
                                foreach (Transactions t in transactions)
                                {
                                    string username = t.username;

                                    if (userMessage.Equals(username))
                                    {
                                        // found username, ask for password
                                        endOutput = "Please enter your password";

                                        // set property to false
                                        userData.SetProperty <bool>("Password", true);
                                        userData.SetProperty <string>("CurrentUsername", username);
                                        userData.SetProperty <string>("CorrectPassword", t.password);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        break;
                                    }
                                    else
                                    {
                                        endOutput = "Cannot find username: "******"\n\n Please try again";
                                    }
                                }
                            }
                        }
                        else
                        {
                            endOutput = "Please enter your username";
                            userData.SetProperty <bool>("LoggingIn", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                    }
                }

                // reply to "show transactions"
                if (luisMessage.Equals("showTransaction"))
                {
                    if (userData.GetProperty <bool>("LoggedIn"))
                    {
                        List <Transactions> transactions = await AzureManager.AzureManagerInstance.GetTransactions();

                        endOutput = "";
                        foreach (Transactions t in transactions)
                        {
                            string transactionUsername = userData.GetProperty <string>("CurrentUsername");

                            if (t.username == transactionUsername)
                            {
                                endOutput += t.id + "\n\n [" + t.createdAt + "] \n\n Withdraw: " + t.withdraw + ", Deposit: " + t.deposit + "\n\n" + "-" + "\n\n";
                            }
                        }
                        if (endOutput == "")
                        {
                            endOutput = "No transactions";
                        }
                    }
                    else
                    {
                        endOutput = "You must be logged in to do this";
                    }
                }

                // reply to "new transaction"
                if (luisMessage.Equals("newTransaction") || userData.GetProperty <bool>("NewTransaction"))
                {
                    if (userData.GetProperty <bool>("LoggedIn"))
                    {
                        if (userData.GetProperty <bool>("NewTransaction"))
                        {
                            // reply to "withdraw"
                            if (userData.GetProperty <bool>("Withdrawal"))
                            {
                                // reply to invalid withdraw input
                                double withdraw;
                                if (!double.TryParse(userMessage, out withdraw))
                                {
                                    endOutput = "Please enter a valid amount";
                                }
                                else
                                {
                                    // add new transaction to database
                                    Transactions transaction = new Transactions()
                                    {
                                        withdraw = Convert.ToDouble(userMessage),
                                        username = userData.GetProperty <string>("CurrentUsername"),
                                        password = userData.GetProperty <string>("CurrentPassword")
                                    };

                                    await AzureManager.AzureManagerInstance.AddTransaction(transaction);

                                    endOutput = "New transaction added [" + transaction.createdAt + "]";

                                    // set properties to false
                                    userData.SetProperty <bool>("Withdrawal", false);
                                    userData.SetProperty <bool>("NewTransaction", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }
                            }
                            else
                            {
                                if (luisMessage.Equals("withdraw"))
                                {
                                    userData.SetProperty <bool>("Withdrawal", true);
                                    endOutput = "Please enter the amount you would like to withdraw";
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }
                            }

                            // reply to "deposit"
                            if (userData.GetProperty <bool>("Deposit"))
                            {
                                // reply to invalid deposit input
                                double deposit;
                                if (!double.TryParse(userMessage, out deposit))
                                {
                                    endOutput = "Please enter a valid amount";
                                }
                                else
                                {
                                    // add new transaction to database
                                    Transactions transaction = new Transactions()
                                    {
                                        deposit  = Convert.ToDouble(userMessage),
                                        username = userData.GetProperty <string>("CurrentUsername"),
                                        password = userData.GetProperty <string>("CurrentPassword")
                                    };

                                    await AzureManager.AzureManagerInstance.AddTransaction(transaction);

                                    endOutput = "New transaction added [" + transaction.createdAt + "]";

                                    // set properties to false
                                    userData.SetProperty <bool>("Deposit", false);
                                    userData.SetProperty <bool>("NewTransaction", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }
                            }
                            else
                            {
                                if (luisMessage.Equals("deposit"))
                                {
                                    endOutput = "Please enter the amount you would like to deposit";
                                    userData.SetProperty <bool>("Deposit", true);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }
                            }
                        }
                        else
                        {
                            endOutput = "Withdraw or Deposit?";
                            userData.SetProperty <bool>("NewTransaction", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                    }
                    else
                    {
                        endOutput = "You must be logged in to do this";
                    }
                }

                // reply to "delete transaction"
                if (luisMessage.Equals("deleteTransaction") || userData.GetProperty <bool>("DeleteTransaction"))
                {
                    // check if logged in
                    if (userData.GetProperty <bool>("LoggedIn"))
                    {
                        if (userData.GetProperty <bool>("DeleteTransaction"))
                        {
                            // reply to transaction ID to be deleted
                            if (userMessage.Length.Equals(36))
                            {
                                List <Transactions> transactions = await AzureManager.AzureManagerInstance.GetTransactions();

                                // loop through all transactions for inputed transaction
                                foreach (Transactions t in transactions)
                                {
                                    string transactionId = t.id;

                                    if (userMessage.Equals(transactionId))
                                    {
                                        // delete transaction
                                        await AzureManager.AzureManagerInstance.DeleteTransaction(t);

                                        endOutput = "Transaction deleted \n\n [" + transactionId + "]";

                                        // set property to false
                                        userData.SetProperty <bool>("DeleteTransaction", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        break;
                                    }
                                    else
                                    {
                                        endOutput = "Cannot find ID : " + userMessage;
                                    }
                                }
                            }
                            else
                            {
                                endOutput = "Please enter a valid ID";
                            }
                        }
                        else
                        {
                            endOutput = "Please enter the ID of the transaction you would like to delete";
                            userData.SetProperty <bool>("DeleteTransaction", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                    }
                    else
                    {
                        endOutput = "You must be logged in to do this";
                    }
                }

                if (userMessage.ToLower().Equals("sign up") || userData.GetProperty <bool>("SigningUp"))
                {
                    if (userData.GetProperty <bool>("SigningUp"))
                    {
                        if (userData.GetProperty <bool>("NewPassword"))
                        {
                            if (userData.GetProperty <bool>("ConfirmPassword"))
                            {
                                if (userMessage == userData.GetProperty <string>("NewPasswords"))
                                {
                                    string username = userData.GetProperty <string>("CurrentUsername");
                                    userData.SetProperty <string>("CurrentPassword", userMessage);
                                    endOutput = "New account created. \n\n Now logged in as: " + username;
                                    userData.SetProperty <bool>("ConfirmPassword", false);
                                    userData.SetProperty <bool>("NewPassword", false);
                                    userData.SetProperty <bool>("SigningUp", false);
                                    userData.SetProperty <bool>("LoggedIn", true);
                                    userData.SetProperty <bool>("SentGreeting", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }
                                else
                                {
                                    endOutput = "Incorrect password, please confirm again";
                                }
                            }
                            else
                            {
                                if (userMessage.Length >= 5)
                                {
                                    userData.SetProperty <string>("NewPasswords", userMessage);
                                    endOutput = "Please confirm the new password";
                                    userData.SetProperty <bool>("ConfirmPassword", true);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }
                                else
                                {
                                    endOutput = "Please enter a new password with at least 5 characters";
                                }
                            }
                        }
                        else
                        {
                            List <Transactions> transactions = await AzureManager.AzureManagerInstance.GetTransactions();

                            bool taken = false;
                            foreach (Transactions t in transactions)
                            {
                                string newUsername = userMessage;

                                if (t.username == newUsername)
                                {
                                    taken = true;
                                }
                            }
                            if (taken)
                            {
                                endOutput = "This username has already been taken. Please try another";
                            }
                            else
                            {
                                userData.SetProperty <string>("CurrentUsername", userMessage);
                                endOutput = "Please enter a new password with at least 5 characters";
                                userData.SetProperty <bool>("NewPassword", true);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                            }
                        }
                    }
                    else
                    {
                        endOutput = "Please enter a new username";
                        userData.SetProperty <bool>("SigningUp", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                }

                if (!isRequest)
                {
                    Activity infoReply = activity.CreateReply(endOutput);
                    await connector.Conversations.ReplyToActivityAsync(infoReply);
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Ejemplo n.º 15
0
 // By keeping this in a separate method we avoid jitting system.enterpriseservices.dll in cases
 // where transactions are not used.
 void InvokeTransacted()
 {
     Transactions.InvokeTransacted(new TransactedCallback(this.Invoke), protocol.MethodAttribute.TransactionOption);
 }
Ejemplo n.º 16
0
 public GameServer(Transactions transactions, ICouchbaseCollection gameSim, ILogger logger)
 {
     _transactions = transactions;
     _gameSim      = gameSim;
     _logger       = logger;
 }
 private void TermTotal(Transactions LT, bool IsIn)
 {
     if (IsIn)
     {
         if (GetTerm() == GetTerm(LT.Deadline))
         {
             InTermly.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (GetTerm() > GetTerm(LT.Deadline))
         {
             InTermly.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
     else
     {
         if (GetTerm() == GetTerm(LT.Deadline))
         {
             OutTermly.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (GetTerm() > GetTerm(LT.Deadline))
         {
             OutTermly.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
 }
 private void YearTotal(Transactions LT, bool IsIn)
 {
     if (IsIn)
     {
         if (GetYear() == GetYear(LT.Deadline))
         {
             InAnualy.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (GetYear() > GetYear(LT.Deadline))
         {
             InAnualy.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
     else
     {
         if (GetYear() == GetYear(LT.Deadline))
         {
             OutAnualy.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (GetYear() > GetYear(LT.Deadline))
         {
             OutAnualy.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
 }
        public void TestTxAttributes()
        {
            ITransaction tx = Transactions.TxStart(TransactionConcurrency.Optimistic,
                                                   TransactionIsolation.RepeatableRead, TimeSpan.FromMilliseconds(2500), 100);

            Assert.IsFalse(tx.IsRollbackOnly);
            Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
            Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
            Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
            Assert.AreEqual(TransactionState.Active, tx.State);
            Assert.IsTrue(tx.StartTime.Ticks > 0);
            Assert.AreEqual(tx.NodeId, GetIgnite(0).GetCluster().GetLocalNode().Id);

            DateTime startTime1 = tx.StartTime;

            tx.Commit();

            Assert.IsFalse(tx.IsRollbackOnly);
            Assert.AreEqual(TransactionState.Committed, tx.State);
            Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
            Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
            Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
            Assert.AreEqual(startTime1, tx.StartTime);

            Thread.Sleep(100);

            tx = Transactions.TxStart(TransactionConcurrency.Pessimistic, TransactionIsolation.ReadCommitted,
                                      TimeSpan.FromMilliseconds(3500), 200);

            Assert.IsFalse(tx.IsRollbackOnly);
            Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency);
            Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation);
            Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds);
            Assert.AreEqual(TransactionState.Active, tx.State);
            Assert.IsTrue(tx.StartTime.Ticks > 0);
            Assert.IsTrue(tx.StartTime > startTime1);

            DateTime startTime2 = tx.StartTime;

            tx.Rollback();

            Assert.AreEqual(TransactionState.RolledBack, tx.State);
            Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency);
            Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation);
            Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds);
            Assert.AreEqual(startTime2, tx.StartTime);

            Thread.Sleep(100);

            tx = Transactions.TxStart(TransactionConcurrency.Optimistic, TransactionIsolation.RepeatableRead,
                                      TimeSpan.FromMilliseconds(2500), 100);

            Assert.IsFalse(tx.IsRollbackOnly);
            Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
            Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
            Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
            Assert.AreEqual(TransactionState.Active, tx.State);
            Assert.IsTrue(tx.StartTime > startTime2);

            DateTime startTime3 = tx.StartTime;

            tx.Commit();

            Assert.IsFalse(tx.IsRollbackOnly);
            Assert.AreEqual(TransactionState.Committed, tx.State);
            Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
            Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
            Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
            Assert.AreEqual(startTime3, tx.StartTime);

            // Check defaults.
            tx = Transactions.TxStart();

            Assert.AreEqual(Transactions.DefaultTransactionConcurrency, tx.Concurrency);
            Assert.AreEqual(Transactions.DefaultTransactionIsolation, tx.Isolation);
            Assert.AreEqual(Transactions.DefaultTimeout, tx.Timeout);

            tx.Commit();
        }
Ejemplo n.º 20
0
 private void RemoveTransactionExecute(Transaction transaction)
 {
     Transactions.Remove(transaction);
 }
Ejemplo n.º 21
0
 public virtual void AddTransaction(Transaction transaction)
 {
     Transactions.Add(transaction);
 }
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (Portfolio.CashBook["EUR"].ConversionRate == 0 ||
                Portfolio.CashBook["BTC"].ConversionRate == 0 ||
                Portfolio.CashBook["ETH"].ConversionRate == 0 ||
                Portfolio.CashBook["LTC"].ConversionRate == 0)
            {
                Log($"EUR conversion rate: {Portfolio.CashBook["EUR"].ConversionRate}");
                Log($"BTC conversion rate: {Portfolio.CashBook["BTC"].ConversionRate}");
                Log($"LTC conversion rate: {Portfolio.CashBook["LTC"].ConversionRate}");
                Log($"ETH conversion rate: {Portfolio.CashBook["ETH"].ConversionRate}");

                throw new Exception("Conversion rate is 0");
            }
            if (Time.Hour == 1 && Time.Minute == 0)
            {
                // Sell all ETH holdings with a limit order at 1% above the current price
                var limitPrice = Math.Round(Securities["ETHUSD"].Price * 1.01m, 2);
                var quantity   = Portfolio.CashBook["ETH"].Amount;
                LimitOrder("ETHUSD", -quantity, limitPrice);
            }
            else if (Time.Hour == 2 && Time.Minute == 0)
            {
                // Submit a buy limit order for BTC at 5% below the current price
                var usdTotal   = Portfolio.CashBook["USD"].Amount;
                var limitPrice = Math.Round(Securities["BTCUSD"].Price * 0.95m, 2);
                // use only half of our total USD
                var quantity = usdTotal * 0.5m / limitPrice;
                LimitOrder("BTCUSD", quantity, limitPrice);
            }
            else if (Time.Hour == 2 && Time.Minute == 1)
            {
                // Get current USD available, subtracting amount reserved for buy open orders
                var usdTotal    = Portfolio.CashBook["USD"].Amount;
                var usdReserved = Transactions.GetOpenOrders(x => x.Direction == OrderDirection.Buy && x.Type == OrderType.Limit)
                                  .Where(x => x.Symbol == "BTCUSD" || x.Symbol == "ETHUSD")
                                  .Sum(x => x.Quantity * ((LimitOrder)x).LimitPrice);
                var usdAvailable = usdTotal - usdReserved;

                // Submit a marketable buy limit order for ETH at 1% above the current price
                var limitPrice = Math.Round(Securities["ETHUSD"].Price * 1.01m, 2);

                // use all of our available USD
                var quantity = usdAvailable / limitPrice;

                // this order will be rejected for insufficient funds
                LimitOrder("ETHUSD", quantity, limitPrice);

                // use only half of our available USD
                quantity = usdAvailable * 0.5m / limitPrice;
                LimitOrder("ETHUSD", quantity, limitPrice);
            }
            else if (Time.Hour == 11 && Time.Minute == 0)
            {
                // Liquidate our BTC holdings (including the initial holding)
                SetHoldings("BTCUSD", 0m);
            }
            else if (Time.Hour == 12 && Time.Minute == 0)
            {
                // Submit a market buy order for 1 BTC using EUR
                Buy("BTCEUR", 1m);

                // Submit a sell limit order at 10% above market price
                var limitPrice = Math.Round(Securities["BTCEUR"].Price * 1.1m, 2);
                LimitOrder("BTCEUR", -1, limitPrice);
            }
            else if (Time.Hour == 13 && Time.Minute == 0)
            {
                // Cancel the limit order if not filled
                Transactions.CancelOpenOrders("BTCEUR");
            }
            else if (Time.Hour > 13)
            {
                // To include any initial holdings, we read the LTC amount from the cashbook
                // instead of using Portfolio["LTCUSD"].Quantity

                if (_fast > _slow)
                {
                    if (Portfolio.CashBook["LTC"].Amount == 0)
                    {
                        Buy("LTCUSD", 10);
                    }
                }
                else
                {
                    if (Portfolio.CashBook["LTC"].Amount > 0)
                    {
                        // The following two statements currently behave differently if we have initial holdings:
                        // https://github.com/QuantConnect/Lean/issues/1860

                        Liquidate("LTCUSD");
                        // SetHoldings("LTCUSD", 0);
                    }
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates a <see cref="Block{T}"/> instance by manually filling all field values.
        /// For a more automated way, see also <see cref="Mine"/> method.
        /// </summary>
        /// <param name="index">The height of the block to create.  Goes to the <see cref="Index"/>.
        /// </param>
        /// <param name="difficulty">The mining difficulty that <paramref name="nonce"/> has to
        /// satisfy.  Goes to the <see cref="Difficulty"/>.</param>
        /// <param name="nonce">The nonce which satisfy the given <paramref name="difficulty"/> with
        /// any other field values.  Goes to the <see cref="Nonce"/>.</param>
        /// <param name="miner">An optional address refers to who mines this block.
        /// Goes to the <see cref="Miner"/>.</param>
        /// <param name="previousHash">The previous block's <see cref="Hash"/>.  If it's a genesis
        /// block (i.e., <paramref name="index"/> is 0) this should be <c>null</c>.
        /// Goes to the <see cref="PreviousHash"/>.</param>
        /// <param name="timestamp">The time this block is created.  Goes to
        /// the <see cref="Timestamp"/>.</param>
        /// <param name="transactions">The transactions to be mined together with this block.
        /// Transactions become sorted in an unpredicted-before-mined order and then go to
        /// the <see cref="Transactions"/> property.
        /// </param>
        /// <seealso cref="Mine"/>
        public Block(
            long index,
            long difficulty,
            Nonce nonce,
            Address?miner,
            HashDigest <SHA256>?previousHash,
            DateTimeOffset timestamp,
            IEnumerable <Transaction <T> > transactions)
        {
            Index        = index;
            Difficulty   = difficulty;
            Nonce        = nonce;
            Miner        = miner;
            PreviousHash = previousHash;
            Timestamp    = timestamp;
            Transactions = transactions.OrderBy(tx => tx.Id).ToArray();
            Hash         = Hashcash.Hash(Serialize(false, false));

            // As the order of transactions should be unpredictable until a block is mined,
            // the sorter key should be derived from both a block hash and a txid.
            var hashInteger = new BigInteger(Hash.ToByteArray());

            // If there are multiple transactions for the same signer these should be ordered by
            // their tx nonces.  So transactions of the same signer should have the same sort key.
            // The following logic "flattens" multiple tx ids having the same signer into a single
            // txid by applying XOR between them.
            IImmutableDictionary <Address, IImmutableSet <Transaction <T> > > signerTxs = Transactions
                                                                                          .GroupBy(tx => tx.Signer)
                                                                                          .ToImmutableDictionary(
                g => g.Key,
                g => (IImmutableSet <Transaction <T> >)g.ToImmutableHashSet()
                );
            IImmutableDictionary <Address, BigInteger> signerTxIds = signerTxs
                                                                     .ToImmutableDictionary(
                pair => pair.Key,
                pair => pair.Value
                .Select(tx => new BigInteger(tx.Id.ToByteArray()))
                .OrderBy(txid => txid)
                .Aggregate((a, b) => a ^ b)
                );

            // Order signers by values derivied from both block hash and their "flatten" txid:
            IImmutableList <Address> signers = signerTxIds
                                               .OrderBy(pair => pair.Value ^ hashInteger)
                                               .Select(pair => pair.Key)
                                               .ToImmutableArray();

            // Order transactions for each signer by their tx nonces:
            Transactions = signers
                           .SelectMany(signer => signerTxs[signer].OrderBy(tx => tx.Nonce))
                           .ToImmutableArray();
        }
Ejemplo n.º 24
0
 public int SellCount(IEnumerable <Candle> candles) => Transactions.Count(t => t.Candles.Equals(candles) && t.Type == TransactionType.Sell);
Ejemplo n.º 25
0
        public decimal YTDinterestEarned()
        {
            decimal dailyInterest   = (decimal)InterestRate / (decimal)365;
            decimal principleAmount = 0;
            Dictionary <DateTime, decimal> DailyTransaction = new Dictionary <DateTime, decimal>();

            if (Transactions == null || Transactions.Count() == 0)
            {
                return(0);
            }
            for (int i = 0; i < Transactions.Count(); i++)
            {
                if (Transactions[i].transactionDate < DateTime.Today)
                {
                    if (DailyTransaction != null && DailyTransaction.Keys.Contains(Transactions[i].transactionDate))
                    {
                        DailyTransaction[Transactions[i].transactionDate] = DailyTransaction[Transactions[i].transactionDate] + Transactions[i].transactionAmount;
                    }
                    else
                    {
                        DailyTransaction[Transactions[i].transactionDate] = Transactions[i].transactionAmount;
                    }
                }
            }
            decimal interestAccrued = DailyTransaction.Values.Sum();

            DailyTransaction.Add(DateTime.Today.Date, 0);
            var myList = DailyTransaction.ToList();

            myList.Sort((pair1, pair2) => pair1.Key.CompareTo(pair2.Key));

            // DailyTransaction.Values.ToList().Sort();
            int     numberofDays        = 0;
            decimal accumulatedInterest = 0;

            int month = myList[0].Key.Month;

            for (int i = 0; i < myList.Count(); i++)
            {
                if (i > 0)
                {
                    if (month == myList[i].Key.Month)
                    {
                        numberofDays = myList[i].Key.DayOfYear - myList[i - 1].Key.DayOfYear;
                    }
                    else
                    {
                        numberofDays = (DateTime.DaysInMonth(myList[i - 1].Key.Year, myList[i - 1].Key.Month) - myList[i - 1].Key.Date.Day) + 1;
                    }
                }

                if (month != myList[i].Key.Month)
                {
                    accumulatedInterest = accumulatedInterest + principleAmount * (dailyInterest / 100) * (numberofDays);
                }
                if (month != myList[i].Key.Month && i != myList.Count() - 1)
                {
                    principleAmount     = principleAmount + accumulatedInterest;
                    accumulatedInterest = (principleAmount * ((dailyInterest) / 100) * (myList[i].Key.Day - 1));
                }

                principleAmount = principleAmount + myList[i].Value;
                month           = myList[i].Key.Month;
            }
            decimal total = principleAmount + accumulatedInterest;

            return(decimal.Round(total - interestAccrued, 2));
        }
Ejemplo n.º 26
0
        private static void ProcessTransaction(WebAPIQueries queries)
        {
            var id = queries["txn_id"];

            if (String.IsNullOrWhiteSpace(id))
            {
                return;
            }

            var status = queries["payment_status"];

            if (String.IsNullOrWhiteSpace(status))
            {
                return;
            }

            TransactionState state;

            status = status.Trim();

            switch (status.ToUpper())
            {
            case "PENDING":
            case "IN-PROGRESS":
                state = TransactionState.Pending;
                break;

            case "COMPLETED":
                state = TransactionState.Processed;
                break;

            default:
                state = TransactionState.Voided;
                break;
            }

            long   credit;
            double value;

            ExtractCart(queries, out credit, out value);

            var custom = queries["custom"] ?? String.Empty;

            var trans = Transactions.GetValue(id);

            var create = trans == null;

            if (create)
            {
                var email = queries["payer_email"] ?? String.Empty;
                var notes = queries["payer_note"] ?? String.Empty;
                var extra = queries["extra_info"] ?? String.Empty;

                var a = Accounts.GetAccount(custom) ?? CMOptions.FallbackAccount;

                Transactions[id] = trans = new DonationTransaction(id, a, email, value, credit, notes, extra);

                var profile = EnsureProfile(a);

                if (profile == null)
                {
                    state        = TransactionState.Voided;
                    trans.Extra += "{VOID: NO PROFILE}";
                }
                else
                {
                    profile.Add(trans);
                }
            }

            if (!VerifyValue(queries, "business", CMOptions.Business) && !VerifyValue(queries, "receiver_email", CMOptions.Business) &&
                !VerifyValue(queries, "receiver_id", CMOptions.Business))
            {
                state        = TransactionState.Voided;
                trans.Extra += "{VOID: UNEXPECTED BUSINESS}";
            }

            if (trans.Total != value)
            {
                state        = TransactionState.Voided;
                trans.Extra += "{VOID: TOTAL CHANGED}";
            }

            if (queries["test"] != null || queries["test_ipn"] != null)
            {
                state        = TransactionState.Voided;
                trans.Extra += "{VOID: TESTING}";
            }

            switch (state)
            {
            case TransactionState.Processed:
                trans.Process();
                break;

            case TransactionState.Voided:
                trans.Void();
                break;
            }

            if (create && trans.State == TransactionState.Pending)
            {
                DonationEvents.InvokeTransPending(trans);
            }

            SpotCheck(trans.Account);
        }
 public DepositWithdrawalViewModel()
 {
     Account     = new Accounts();
     Transaction = new Transactions();
 }
 private bool DoesCommitmentAmountExceedMinimumCommitmentAmount(JointPayee jointPayee)
 {
     return(Transactions.All(tran =>
                             DoesCommitmentAmountExceedMinimumCommitmentAmount(jointPayee.JointPayeeInternalId, tran)));
 }
        public async Task <PredictionEntity> GetPredictionsAsync(int monthsBack, DateTime predictDate)
        {
            PredictionEntity predictionEntity = null;

            await Task.Run(() =>
            {
                predictionEntity = new PredictionEntity()
                {
                    WarningMessage = IsAvailableEnoughtData(monthsBack) ? "" : _warningMessage,
                    TodayBalanace  = CurrentUser.CurrentBalance
                };
                IList <DailyBreakDownPredictionEntity> dailyBreakDownPredictions = new List <DailyBreakDownPredictionEntity>();

                predictDate             = predictDate.Date;
                DateTime todayDate      = DateTime.Now;
                todayDate               = todayDate.Date;// Remove time
                DateTime monthsBackDate = todayDate.AddMonths(-1 * monthsBack);

                IEnumerable <TransactionEntity> orderedTransactions = Transactions.Where(t => t.TransactionDateTime >= monthsBackDate && t.IsActive).OrderBy(t => t.TransactionDateTime);

                if (orderedTransactions.Count() > 0)
                {
                    predictionEntity.IsPredicted = true;
                    int daysFromBackMonth        = (int)todayDate.Subtract(monthsBackDate.Date).TotalDays;

                    double totalInCome     = orderedTransactions.Where(ot => ot.IsIncome).Select(ot => ot.Amount).Sum();
                    double totalInExpenses = orderedTransactions.Where(ot => !ot.IsIncome).Select(ot => ot.Amount).Sum();

                    predictionEntity.AverageIncome  = totalInCome / daysFromBackMonth;
                    predictionEntity.AverageExpense = totalInExpenses / daysFromBackMonth;

                    int daysToPredictDate            = (int)predictDate.Subtract(todayDate).TotalDays;
                    predictionEntity.PredictBalanace = CurrentUser.CurrentBalance + ((totalInCome - totalInExpenses) / daysFromBackMonth) * daysToPredictDate;

                    // Day by day predictions
                    IEnumerable <DayOfWeek> daysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast <DayOfWeek>();

                    foreach (DayOfWeek dayOfWeek in daysOfWeek)
                    {
                        DailyBreakDownPredictionEntity dailyBreakDown = new DailyBreakDownPredictionEntity()
                        {
                            DayOfWeek = dayOfWeek
                        };

                        IEnumerable <DateTime> dates = TimeConverterMethods.DatesDayOfWeekForDuration(monthsBackDate, todayDate, dayOfWeek);

                        if (dates.Count() > 0)
                        {
                            IEnumerable <TransactionEntity> dayOfWeekIncomeTransactions = orderedTransactions.Where(t => t.IsIncome && dates.Any(d => d.Date == t.TransactionDateTime.Date));
                            dailyBreakDown.AverageIncome = dayOfWeekIncomeTransactions.Select(x => x.Amount).Sum() / dates.Count();

                            IEnumerable <TransactionEntity> dayOfWeekExpensesTransactions = orderedTransactions.Where(t => !t.IsIncome && dates.Any(d => d.Date == t.TransactionDateTime.Date));
                            dailyBreakDown.AverageExpense = dayOfWeekExpensesTransactions.Select(x => x.Amount).Sum() / dates.Count();
                        }
                        else
                        {
                            dailyBreakDown.AverageIncome  = 0;
                            dailyBreakDown.AverageExpense = 0;
                        }

                        dailyBreakDownPredictions.Add(dailyBreakDown);
                    }

                    predictionEntity.DailyBreakDownPredictions = dailyBreakDownPredictions;
                }
                else
                {
                    predictionEntity.IsPredicted    = false;
                    predictionEntity.WarningMessage = "Error: No data found to do the predictions";
                }
            });

            return(predictionEntity);
        }
        private void BtnAddOut_Click(object sender, EventArgs e)
        {
            Transactions temp = new Transactions(TBOutName.Text, CBOutCompany.Text, CBOutCategory.Text,
                Type.Out.ToString(), NuOutAmountPre.Value, (CBOutCompleted.Checked ? NuOutAmountReal.Value : 0),
                CBOutCompleted.Checked, TBOutComment.Lines, DTOutDeadline.Value, DTOutReal.Value,
                CBOutRepeat.Checked, DTRepeatStartOut.Value, DTRepeatEndOut.Value, CBRepeatFreqOut.Text);
            Outcome.Add(temp);

            if (sender.ToString().Contains("Update"))
            {
                Outcome.RemoveAt(LBOut.SelectedIndex);
                BtnAddOut.Text = "BtnAddOut";
            }
            ResetTabOut(sender, e);
            PopulateTransLists();
            Total();
            WriteToFile(sender, e);
        }
Ejemplo n.º 31
0
        public bool AddValidTransaction(Transactions transact)
        {
            bool result = userServices.AddTransaction(transact);

            return(result);
        }
 private void QuarterTotal(Transactions LT, bool IsIn)
 {
     if (IsIn)
     {
         if (GetQuarter() == GetQuarter(LT.Deadline))
         {
             InQuarterly.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (GetQuarter() > GetQuarter(LT.Deadline))
         {
             InQuarterly.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
     else
     {
         if (GetQuarter() == GetQuarter(LT.Deadline))
         {
             OutQuarterly.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (GetQuarter() > GetQuarter(LT.Deadline))
             OutQuarterly.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
     }
 }
Ejemplo n.º 33
0
 public void AddTransaction(Transaction transaction)
 {
     Transactions.Add(transaction);
     TotalSize += transaction.Size;
     TotalFee  += transaction.Fee;
 }
 private void WeekTotal(Transactions LT, bool IsIn)
 {
     DateTime Start = GetStartOfWeek();
     DateTime End = Start.AddDays(7);
     if (IsIn)
     {
         if (Start < LT.Deadline && LT.Deadline < End)
         {
             InWeekly.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (LT.Deadline < Start)
         {
             InWeekly.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
     else
     {
         if (Start < LT.Deadline && LT.Deadline < End)
         {
             OutWeekly.Current += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
         else if (LT.Deadline < Start)
         {
             OutWeekly.Previous += (LT.AmountReal == 0 ? LT.AmountPre : LT.AmountReal);
         }
     }
 }
Ejemplo n.º 35
0
        public bool Insert(Transactions transactionName, List<SqlParameter> parameters)
        {
            SqlConnection dbConnection = CreateConnection();

            try
            {
                SqlCommand command = new SqlCommand(transactionName.ToString(), dbConnection);
                command.CommandType = CommandType.StoredProcedure;

                parameters.ForEach(x => command.Parameters.Add(x));

                return command.ExecuteNonQuery() > 0;
            }
            catch (SqlException exception)
            {
                throw (exception);
            }
            finally
            {
                dbConnection.Close();
            }
        }
Ejemplo n.º 36
0
 public Transaction AddTransaction(Transaction tx)
 {
     Transactions.Add(tx);
     return(tx);
 }
Ejemplo n.º 37
0
        public DataTable RunQuery(Transactions transactionName, List<SqlParameter> parameters)
        {
            SqlConnection dbConnection = CreateConnection();

            SqlCommand command = new SqlCommand(transactionName.ToString(), dbConnection);
            command.CommandType = CommandType.StoredProcedure;

            parameters.ForEach(x => command.Parameters.Add(x));

            DataTable result = new DataTable();
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(command);
            sqlDataAdapter.Fill(result);

            dbConnection.Close();

            return result;
        }
Ejemplo n.º 38
0
 public Program(ICluster cluster, IBucket bucket, ICouchbaseCollection collection, Transactions transactions)
 {
     _cluster      = cluster;
     _bucket       = bucket;
     _collection   = collection;
     _transactions = transactions;
 }
Ejemplo n.º 39
0
        public async Task <String> MakePayment(PaymentDetails paymentDetails)
        {
            String response = String.Empty;

            try
            {
                //Using Custom Credit Card Validation Instead of CreditCardAttribute
                if (!String.IsNullOrEmpty(paymentDetails?.CreditCardNumber) && Validation.IsCardNumberValid(paymentDetails.CreditCardNumber))
                {
                    if (paymentDetails.Amount > 0 && Validation.IsExpirationDateValid(paymentDetails.ExpirationDate))
                    {
                        //String encryptedCardNumber = _Encryption.EncryptAndSave(paymentDetails.CreditCardNumber);
                        String encryptedCardNumber = paymentDetails.CreditCardNumber;

                        //Checking for existing user.
                        var existing_user = _PaymentContext.People.Include(x => x.CardInformation)
                                            .Where(x => x.FullName == paymentDetails.CardHolderName)
                                            .FirstOrDefault();
                        if (existing_user is null)
                        {
                            // if the user doesn't exist , insert into the database
                            existing_user = AddNewUser(paymentDetails, encryptedCardNumber);
                        }
                        else
                        {
                            // checking whether the card exists or not
                            var card = existing_user.CardInformation.Where(x => x.CreditCardNumber == encryptedCardNumber).FirstOrDefault();
                            if (card is null)
                            {
                                CardInformation cardInformation = new CardInformation()
                                {
                                    CreditCardNumber = encryptedCardNumber,
                                    SecurityCode     = paymentDetails.SecurityCode
                                };
                                existing_user.CardInformation.Add(cardInformation);
                                existing_user = _PeopleRepo.UpdateAndGet(existing_user);
                            }
                        }

                        //Creating a new transaction
                        Transactions NewTransaction = new Transactions();
                        _TransactionRepo.Insert(NewTransaction);
                        _TransactionRepo.Save();
                        existing_user.CardInformation.Where(x => x.CreditCardNumber == encryptedCardNumber).FirstOrDefault().Transactions.Add(NewTransaction);
                        existing_user = _PeopleRepo.UpdateAndGet(existing_user);

                        //Payment Gateway Call
                        _PaymentGateway = _PaymentGatewayFactory.GetPaymentGateway(paymentDetails.Amount);
                        response        = await _PaymentGateway.GetPaymentStatus(paymentDetails);

                        //Updating the response
                        NewTransaction.PaymentState = response;
                        _TransactionRepo.Update(NewTransaction);
                        _TransactionRepo.Save();
                    }
                }
                else
                {
                    response = "Invalid Card Number";
                }
            }
            catch (Exception ex)
            {
                response = ex.Message;
            }

            return(response);
        }
Ejemplo n.º 40
0
 public DataTable RunQuery(Transactions transactionName, SqlParameter parameter)
 {
     return RunQuery(transactionName, new List<SqlParameter>() { parameter });
 }
Ejemplo n.º 41
0
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (!Security.HasData)
            {
                Log("::::: NO DATA :::::");
                return;
            }

            // each month make an action
            if (Time.Minute != LastMinute && Time.Second == 0)
            {
                Log("");
                Log("--------------Minute: " + Time.Minute);
                Log("");
                LastMinute = Time.Minute;
                // we'll submit the next type of order from the queue
                var orderType = _orderTypesQueue.Dequeue();
                Log("ORDER TYPE:: " + orderType);
                var isLong     = Quantity > 0;
                var stopPrice  = isLong ? (1 + StopPercentage) * Security.High : (1 - StopPercentage) * Security.Low;
                var limitPrice = isLong ? (1 - LimitPercentage) * stopPrice : (1 + LimitPercentage) * stopPrice;
                if (orderType == OrderType.Limit)
                {
                    limitPrice = !isLong ? (1 + LimitPercentage) * Security.High : (1 - LimitPercentage) * Security.Low;
                }
                var request = new SubmitOrderRequest(orderType, SecType, Symbol, Quantity, stopPrice, limitPrice, Time, orderType.ToString());
                var ticket  = Transactions.AddOrder(request);
                _tickets.Add(ticket);
                if ((decimal)Random.NextDouble() < ImmediateCancelPercentage)
                {
                    Log("Immediate cancellation requested!");
                    _immediateCancellations.Add(ticket.OrderId);
                }
            }
            else if (_tickets.Count > 0)
            {
                var ticket = _tickets.Last();
                if (Time.Second > 15 && Time.Second < 30)
                {
                    if (ticket.UpdateRequests.Count == 0 && ticket.Status.IsOpen())
                    {
                        Log(ticket.ToString());
                        ticket.Update(new UpdateOrderFields
                        {
                            Quantity = ticket.Quantity + Math.Sign(Quantity) * DeltaQuantity,
                            Tag      = "Change quantity: " + Time
                        });
                        Log("UPDATE1:: " + ticket.UpdateRequests.Last());
                    }
                }
                else if (Time.Second > 29 && Time.Second < 45)
                {
                    if (ticket.UpdateRequests.Count == 1 && ticket.Status.IsOpen())
                    {
                        Log(ticket.ToString());
                        ticket.Update(new UpdateOrderFields
                        {
                            LimitPrice = Security.Price * (1 - Math.Sign(ticket.Quantity) * LimitPercentageDelta),
                            StopPrice  = Security.Price * (1 + Math.Sign(ticket.Quantity) * StopPercentageDelta),
                            Tag        = "Change prices: " + Time
                        });
                        Log("UPDATE2:: " + ticket.UpdateRequests.Last());
                    }
                }
                else
                {
                    if (ticket.UpdateRequests.Count == 2 && ticket.Status.IsOpen())
                    {
                        Log(ticket.ToString());
                        ticket.Cancel(Time + " and is still open!");
                        Log("CANCELLED:: " + ticket.CancelRequest);
                    }
                }
            }
        }
        public override Transactions GetTransactions(long userId)
        {
            Transactions transactions = new Transactions();
            using (MySqlConnection conn = new MySqlConnection(GetConnectionString()))
            {
                using (MySqlCommand cmd = new MySqlCommand(QRY_GET_TRANSACTIONS_BY_USERID, conn))
                {
                    cmd.Parameters.Add("@user_id", MySqlDbType.Int64).Value = userId;

                    try
                    {
                        conn.Open();
                        using (MySqlDataReader rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read())
                            {
                                transactions.Add(new Transaction
                                {
                                    TransactionId = rdr.GetInt64(0),
                                    UserId = userId,
                                    Amount = rdr.GetDecimal(2),
                                    Date = rdr.GetDateTime(3),
                                    Description = rdr.GetString(4),
                                    ProductId = rdr.GetInt64(5),
                                    Status = rdr.GetString(6),
                                    StatusCode = rdr.GetString(7),
                                    Merchant = rdr.GetString(8),
                                    PaymentId = rdr.GetString(9),
                                    TransactionReference = rdr.GetString(10),
                                    PaymentMethod = rdr.GetString(11)
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "GetTransactions<Exception>");
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            return transactions;
        }
Ejemplo n.º 43
0
        private void GetCancelFeeFirstLast(Cancelations can)
        {
            Transactions Trans = SelectedReservations.Transactions.FirstOrDefault();
            List <DetailTransactions> lstDtChambres = Trans.DetailTransactions.Where(c => c.Etat == "ACTIF" && c.Produits.Categories.Libelle == "CHAMBRES").ToList();
            List <DetailPaiements>    lstDtPaie     = Trans.DetailPaiements.Where(c => c.Etat == "ACTIF").ToList();

            //Annuler les details transactions concernant la chambre
            foreach (DetailTransactions item in lstDtChambres)
            {
                item.Etat = "ANNULER";
            }

            foreach (DetailPaiements item in lstDtPaie)
            {
                item.Etat = "ANNULER";
            }

            double NbreHr = SelectedReservations.DateArrive.Value.Subtract(DateTime.Now).TotalDays;

            if (NbreHr < can.TimeFrame)
            {
                DetailTransactions trans = new DetailTransactions();
                trans.Produits = GlobalData.modelRP.Produits.Where(c => c.Libelle == "FRAIS D'ANNULATION DE LA RESERVATION").FirstOrDefault();;
                trans.Date     = DateTime.Now;
                trans.Quantite = (float)1;

                if (can.Type == 0)
                {
                    DetailTransactions dt = lstDtChambres.FirstOrDefault();

                    trans.prix = Convert.ToDecimal((double)dt.prix * can.PourcentageAfter * 0.01) + can.HandlingFee;
                }
                else
                {
                    trans.prix = Convert.ToDecimal(can.MontantAfter) + can.HandlingFee;
                }

                trans.Descriptions = "FRAIS D'ANNULATION DE LA RESERVATION " + SelectedReservations.ID;
                trans.Montant      = Convert.ToDecimal(trans.Quantite * (double)trans.prix);
                trans.Etat         = "ACTIF";
                //trans.idHotel = GlobalData.HotId;

                Trans.DetailTransactions.Add(trans);

                Trans.TotalTTC = Convert.ToDecimal(trans.Quantite * (double)trans.prix) + can.HandlingFee;
                Trans.TotalHT  = Trans.TotalTTC;
                Trans.TVA      = 0;

                if ((Trans.TotalPaye - Trans.TotalTTC) < 0)
                {
                    Trans.TotalReste = 0;

                    DetailPaiements dtPaie = new DetailPaiements();
                    dtPaie.Montant          = (double)Trans.TotalPaye;
                    dtPaie.DatePaiement     = DateTime.Now;
                    dtPaie.MethodePaiements = GlobalData.modelRP.MethodePaiements.Where(c => c.Libelle == "ESPECE").FirstOrDefault();
                    dtPaie.Transactions     = Trans;
                    dtPaie.Etat             = "ACTIF";
                    //dtPaie.idHotel = GlobalData.HotId;
                }
                else
                {
                    Trans.TotalReste = 0;
                    Trans.TotalPaye  = Trans.TotalTTC;

                    DetailPaiements dtPaie = new DetailPaiements();
                    dtPaie.Montant          = (double)Trans.TotalPaye;
                    dtPaie.DatePaiement     = DateTime.Now;
                    dtPaie.MethodePaiements = GlobalData.modelRP.MethodePaiements.Where(c => c.Libelle == "ESPECE").FirstOrDefault();
                    dtPaie.Transactions     = Trans;
                    dtPaie.Etat             = "ACTIF";
                    //dtPaie.idHotel = GlobalData.HotId;
                }

                SelectedReservations.TotalPaye  = Trans.TotalPaye;
                SelectedReservations.TotalReste = Trans.TotalReste;
                SelectedReservations.TotalTTC   = Trans.TotalTTC;
                SelectedReservations.Reduction  = Trans.Reduction;

                Trans.Etat = "PAYE";
                SelectedReservations.CancelDate    = DateTime.Now;
                SelectedReservations.Etat          = "TERMINER";
                SelectedReservations.EtatOperation = "ANNULER";

                if (SelectedReservations.Chambres != null)
                {
                    SelectedReservations.Chambres.EtatOperation = "LIBRE";
                }

                GlobalData.modelRP.SaveChanges();

                Load();

                MessageBox.Show("Operation terminée", "Message", MessageBoxButton.OK, MessageBoxImage.None);
            }
            else if (NbreHr > can.TimeFrame)
            {
                DetailTransactions trans = new DetailTransactions();
                trans.Produits = GlobalData.modelRP.Produits.Where(c => c.Libelle == "FRAIS D'ANNULATION DE LA RESERVATION").First();;
                trans.Date     = DateTime.Now;
                trans.Quantite = (float)1;

                if (can.Type == 0)
                {
                    DetailTransactions dt = lstDtChambres.FirstOrDefault();

                    trans.prix = Convert.ToDecimal((double)dt.prix * can.PourcentageBefore * 0.01) + can.HandlingFee;
                }
                else
                {
                    trans.prix = Convert.ToDecimal(can.MonantBefore) + can.HandlingFee;
                }

                trans.Descriptions = "FRAIS D'ANNULATION DE LA RESERVATION " + SelectedReservations.ID;
                trans.Montant      = Convert.ToDecimal(trans.Quantite * (double)trans.prix);
                trans.Etat         = "ACTIF";
                //trans.idHotel = GlobalData.HotId;

                Trans.DetailTransactions.Add(trans);

                Trans.TotalTTC = Convert.ToDecimal(trans.Quantite * (double)trans.prix) + can.HandlingFee;
                Trans.TotalHT  = Trans.TotalTTC;
                Trans.TVA      = 0;

                if ((Trans.TotalPaye - Trans.TotalTTC) < 0)
                {
                    Trans.TotalReste = 0;

                    DetailPaiements dtPaie = new DetailPaiements();
                    dtPaie.Montant          = (double)Trans.TotalPaye;
                    dtPaie.DatePaiement     = DateTime.Now;
                    dtPaie.MethodePaiements = GlobalData.modelRP.MethodePaiements.Where(c => c.Libelle == "ESPECE").FirstOrDefault();
                    dtPaie.Transactions     = Trans;
                    dtPaie.Etat             = "ACTIF";
                    //dtPaie.idHotel = GlobalData.HotId;
                }
                else
                {
                    Trans.TotalReste = 0;
                    Trans.TotalPaye  = Trans.TotalTTC;

                    DetailPaiements dtPaie = new DetailPaiements();
                    dtPaie.Montant          = (double)Trans.TotalPaye;
                    dtPaie.DatePaiement     = DateTime.Now;
                    dtPaie.MethodePaiements = GlobalData.modelRP.MethodePaiements.Where(c => c.Libelle == "ESPECE").FirstOrDefault();
                    dtPaie.Transactions     = Trans;
                    dtPaie.Etat             = "ACTIF";
                    //dtPaie.idHotel = GlobalData.HotId;
                }

                SelectedReservations.TotalPaye  = Trans.TotalPaye;
                SelectedReservations.TotalReste = Trans.TotalReste;
                SelectedReservations.TotalTTC   = Trans.TotalTTC;
                SelectedReservations.Reduction  = Trans.Reduction;

                Trans.Etat = "PAYE";
                SelectedReservations.CancelDate             = DateTime.Now;
                SelectedReservations.Etat                   = "TERMINER";
                SelectedReservations.EtatOperation          = "ANNULER";
                SelectedReservations.Chambres.EtatOperation = "LIBRE";


                GlobalData.modelRP.SaveChanges();

                Load();

                MessageBox.Show("Operation terminée", "Message", MessageBoxButton.OK, MessageBoxImage.None);
            }
            else
            {
            }
        }
Ejemplo n.º 44
0
 protected void AttachSubscriber(Transactions.Processes.Base process, Engine.ProgressDelegate onProgress)
 {
     process.OnProgress += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task, OpenDMS.Networking.Protocols.Tcp.DirectionType direction, int packetSize, decimal sendPercentComplete, decimal receivePercentComplete)
     {
         try
         {
             if (onProgress != null &&
                 !_isEventSubscriptionSuppressed)
                 onProgress(_request, direction, packetSize, sendPercentComplete, receivePercentComplete);
         }
         catch (System.Exception e)
         {
             Logger.Storage.Error("An exception occurred while calling the method specified in the onProgress argument.", e);
             throw;
         }
     };
 }
Ejemplo n.º 45
0
        private IEnumerable <TransactionViewModel> SortTransactionsByDate()
        {
            var sorted = Transactions.OrderByDescending((arg) => arg.Date);

            return(sorted as IEnumerable <TransactionViewModel>);
        }
 public void MarryTran(DTP dtp, Transactions tran)
 {
     _db.ExecuteNonQuery(string.Format("INSERT INTO DTP_Trans VALUES ('{0}','{1}','{2}')", Guid.NewGuid(), dtp.Id, tran.Id));
 }
Ejemplo n.º 47
0
        public async Task <IActionResult> Create([Bind("Id,InvoiceId,Amount,Discount,Tax,Extra,Total,AccountId,PaymentTypeId,OperationId,FromBankId,ToBankId,AddDate,AddTime,RefNo,Notes")] Payments payments)
        {
            var isValidtaedAmount = new TransactionsService(_context).ValidateBankBalance(payments.FromBankId, payments.Amount, payments.OperationId);

            if (ModelState.IsValid && isValidtaedAmount)
            {
                _context.Add(payments);
                await _context.SaveChangesAsync();

                #region "Update (Account/Banks) Balances"
                decimal _credit = 0, _debit = 0, _toCredit = 0, _toDebit = 0;
                var     _trans = new TransactionsService(_context);

                // قبض
                if (payments.OperationId == (int)PaymentTypesEnum.Credit || payments.OperationId == (int)PaymentTypesEnum.CheckCredit)
                {
                    _credit = _toCredit = payments.Amount;
                    //_debit = _toDebit = 0;
                }
                // صرف
                else if (payments.OperationId == (int)PaymentTypesEnum.Debit || payments.OperationId == (int)PaymentTypesEnum.CehckDebit)
                {
                    _debit  = _toDebit = payments.Amount;
                    _credit = _toCredit = 0;
                }
                // تحويل بنكى من بنك إلى بنك
                else if (payments.OperationId == (int)PaymentTypesEnum.BankTransfer)
                {
                    _debit    = payments.Amount; // Debit from
                    _toCredit = payments.Amount; // Debit to.

                    _toDebit = _credit = 0;
                }

                // Update account balance
                if (payments.AccountId > 0)
                {
                    var at = new Transactions()
                    {
                        AccountId     = payments.AccountId,
                        AddDate       = DateTime.Now,
                        Credit        = _credit,
                        Debit         = _debit,
                        TransactionId = payments.Id.ToString()
                    };
                    await _trans.UpdateAccountBalanceAsync(at);
                }
                // Update FromBank balance.
                if (payments.FromBankId > 0)
                {
                    var bt = new Transactions()
                    {
                        BankId        = payments.FromBankId,
                        AddDate       = DateTime.Now,
                        Credit        = _credit,
                        Debit         = _debit,
                        TransactionId = payments.Id.ToString()
                    };
                    await _trans.UpdateBankBalanceAsync(bt);
                }

                // Update ToBank balance.
                if (payments.ToBankId > 0)
                {
                    var bt = new Transactions()
                    {
                        BankId        = payments.ToBankId,
                        AddDate       = DateTime.Now,
                        Credit        = _toCredit,
                        Debit         = _toDebit,
                        TransactionId = payments.Id.ToString()
                    };
                    await _trans.UpdateBankBalanceAsync(bt);
                }
                #endregion


                // Archive client transactions in case he paying to us (قبض - قبض بشيك).
                if (payments.AccountId > 0 && (payments.OperationId == (int)PaymentTypesEnum.Credit || payments.OperationId == (int)PaymentTypesEnum.CheckCredit))
                {
                    await _trans.ArchiveAccountInvoicesPaymanetsAsync(payments.AccountId);
                }


                return(RedirectToAction(nameof(Index)));
            }
            ViewData["AccountId"]     = new SelectList(_context.Accounts, "AccountId", "Title", payments.AccountId);
            ViewData["FromBankId"]    = new SelectList(_context.Banks, "Id", "Name", payments.FromBankId);
            ViewData["InvoiceId"]     = new SelectList(_context.Invoices, "Id", "InvoiceNo", payments.InvoiceId);
            ViewData["OperationId"]   = new SelectList(_context.Operations, "Id", "Name", payments.OperationId);
            ViewData["PaymentTypeId"] = new SelectList(_context.PaymentTypes, "Id", "Name", payments.PaymentTypeId);
            ViewData["ToBankId"]      = new SelectList(_context.Banks, "Id", "Name", payments.ToBankId);
            if (!isValidtaedAmount)
            {
                ViewData["BankAmountMessage"] = SysLanguages.Lang.ValidateBankBalanceMessage;
            }


            return(View(payments));
        }
Ejemplo n.º 48
0
 protected void AttachSubscriber(Transactions.Processes.Base process, Engine.ErrorDelegate onError)
 {
     process.OnError += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task, string message, Exception exception)
     {
         try
         {
             if (onError != null &&
                 !_isEventSubscriptionSuppressed)
                 onError(_request, message, exception);
         }
         catch (System.Exception e)
         {
             Logger.Storage.Error("An exception occurred while calling the method specified in the onError argument.", e);
             throw;
         }
     };
 }
Ejemplo n.º 49
0
 public Transaction GetTransaction(UInt256 hash)
 {
     return(Transactions.TryGet(hash)?.Transaction);
 }