// PUT api/awbuildversion/5
        public void Put(CurrencyRate value)
        {
            var GetActionType = Request.Headers.Where(x => x.Key.Equals("ActionType")).FirstOrDefault();

            if (GetActionType.Key != null)
            {
                if (GetActionType.Value.ToList()[0].Equals("DELETE"))
                    adventureWorks_BC.CurrencyRateDelete(value);
                if (GetActionType.Value.ToList()[0].Equals("UPDATE"))
                    adventureWorks_BC.CurrencyRateUpdate(value);
            }
        }
Beispiel #2
0
        public void GetLatestRates()
        {
            try
            {
                // Create a request for the URL.
                WebRequest request = WebRequest.Create("https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5");

                // Get the response.
                WebResponse response = request.GetResponse();

                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);

                // Read the content.
                string json = reader.ReadToEnd();

                var data = JsonConvert.DeserializeObject<List<CurrencyJson>>(json);
                // Clean up the streams and the response.
                reader.Close();
                response.Close();

                foreach (var item in data.Where(x => x.ccy == "EUR" || x.ccy == "USD"))
                {
                    var last = _currencyRepository.Get().ToList().LastOrDefault(x => x.Currency.Name == item.ccy);
                    if (last == null || last.BuyRate != item.buy || last.SaleRate != item.sale)
                    {
                        //add new row to db
                        CurrencyRate rate = new CurrencyRate()
                        {
                            CurrencyId = item.ccy == "USD" ? 1 : 2,
                            BuyRate = item.buy,
                            SaleRate = item.sale,
                            Date = DateTime.Now
                        };

                        _currencyRepository.AddAsync(rate);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
        public int SaveOrUpdate(CurrencyRate currencyRate)
        {
            using (var db = GetDb())
            {
                if (String.IsNullOrEmpty(currencyRate.FromCurrency) || String.IsNullOrEmpty(currencyRate.ToCurrency) || currencyRate.Rate < 0)
                    throw new ArgumentException();

                if (currencyRate.ID > 0 && currencyRate.Rate == 0)
                    return Delete(currencyRate.ID);

                if (db.ExecuteScalar<int>(Query("crm_currency_rate").SelectCount().Where(Exp.Eq("id", currencyRate.ID))) == 0)
                {
                    var query = Insert("crm_currency_rate")
                        .InColumnValue("id", 0)
                        .InColumnValue("from_currency", currencyRate.FromCurrency.ToUpper())
                        .InColumnValue("to_currency", currencyRate.ToCurrency.ToUpper())
                        .InColumnValue("rate", currencyRate.Rate)
                        .InColumnValue("create_by", SecurityContext.CurrentAccount.ID)
                        .InColumnValue("create_on", DateTime.UtcNow)
                        .InColumnValue("last_modifed_by", SecurityContext.CurrentAccount.ID)
                        .InColumnValue("last_modifed_on", DateTime.UtcNow)
                        .Identity(1, 0, true);

                    currencyRate.ID = db.ExecuteScalar<int>(query);
                }
                else
                {
                    db.ExecuteNonQuery(
                        Update("crm_currency_rate")
                            .Set("from_currency", currencyRate.FromCurrency.ToUpper())
                            .Set("to_currency", currencyRate.ToCurrency.ToUpper())
                            .Set("rate", currencyRate.Rate)
                            .Set("last_modifed_on", DateTime.UtcNow)
                            .Set("last_modifed_by", SecurityContext.CurrentAccount.ID)
                            .Where(Exp.Eq("id", currencyRate.ID)));
                }

                return currencyRate.ID;
            }
        }
        public async Task Seed()
        {
            //if schema already exists - no seeds
            if (!context.Database.EnsureCreated())
            {
                return;
            }

            var currencies = new Currency[] {
                new Currency()
                {
                    Name = "Bitcoin", Symbol = "Btc"
                },
                new Currency()
                {
                    Name = "Etherium", Symbol = "Eth"
                }
            };

            context.Currencies.AddRange(currencies);
            await context.SaveChangesAsync();

            var markets = new Market[] {
                new Market()
                {
                    Name = "Coin Market Cap",
                    AggregationDriver = Aggregators.AggregationDriverType.CoinMarketCapDriver
                }
            };

            context.Markets.AddRange(markets);
            await context.SaveChangesAsync();

            var marketCurrencies = new CurrencyMarket[] {
                new CurrencyMarket()
                {
                    Currency = currencies[0], Market = markets[0], MarketCurrencyId = 1
                },
                new CurrencyMarket()
                {
                    Currency = currencies[1], Market = markets[0], MarketCurrencyId = 1027
                }
            };

            context.CurrencyMarkets.AddRange(marketCurrencies);
            await context.SaveChangesAsync();

            var currencyRates = new CurrencyRate[] {
                new CurrencyRate()
                {
                    Currency = marketCurrencies[0], Date = DateTime.Now, Rate = 1.0M
                },
                new CurrencyRate()
                {
                    Currency = marketCurrencies[1], Date = DateTime.Now, Rate = 1.0M
                }
            };

            context.CurrencyRates.AddRange(currencyRates);
            await context.SaveChangesAsync();
        }
        private static AvitoAd GetAdFromSneaker(Model.AllStock.AllStockSneaker sneaker, FullCatalogRecord fcSneaker, DateTime startTime, int position, int count)
        {
            AvitoAd Ad = new AvitoAd();

            if (fcSneaker.images == null)
            {
                return(null);
            }
            if (fcSneaker.images.Count == 0)
            {
                return(null);
            }
            if (String.IsNullOrWhiteSpace(sneaker.category))
            {
                return(null);
            }
            if (sneaker.sizes == null)
            {
                return(null);
            }
            if (sneaker.sizes.Count == 0)
            {
                return(null);
            }

            Ad.Id = sneaker.sku;

            //DateBegin

            /* нужно все объявления размазать на месяц (ну пусть будет на 30 дней).
             * допустим если у меня есть 3000 объявлений то это значит что нужно постить по 100 в день
             * Постить будем допустим с 7.00 утра 23.59. Получается 17 часов. это 61200 секунд.
             * Получается объявление нужно постить каждые 612 секунд, начиная с 7 утра
             *
             * В сутках 24 часа, это 86400 секунд.
             * В 30 днях 2 592 000 секунд
             * То есть если у нас есть 3000 объявлений, значит начиная с текущего момента нужно постить объявление каждые 864 секунды
             */
            double delay    = 2592000 / count * position;
            var    intDelay = (int)delay;

            //Ad.DateBegin = startTime.AddSeconds(intDelay);
            Ad.DateBegin    = startTime;
            Ad.ManagerName  = "Евгений";
            Ad.ContactPhone = "88002001121";
            Ad.AllowEmail   = "Да";
            Ad.Region       = "Москва";


            //goods type
            if (sneaker.category == "men")
            {
                Ad.Category  = "Одежда, обувь, аксессуары";
                Ad.GoodsType = "Мужская одежда";
            }
            else if (sneaker.category == "women")
            {
                Ad.Category  = "Одежда, обувь, аксессуары";
                Ad.GoodsType = "Женская одежда";
            }
            else if (sneaker.category == "kids")
            {
                Ad.Category = "Детская одежда и обувь";
                var rnd = new Random().NextDouble();
                if (rnd > 0.5)
                {
                    Ad.GoodsType = "Для девочек";
                }
                else
                {
                    Ad.GoodsType = "Для мальчиков";
                }
            }

            Ad.Apparel = "Обувь";

            //size
            //буду брать случайный русский размер из списка размеров, нужно будет округлить до целого
            var rnd2              = new Random().Next(sneaker.sizes.Count - 1);
            var sizeUsAllStock    = sneaker.sizes[rnd2];
            var sizeAllStock      = new Size(sneaker.brand, sneaker.category, sizeUsAllStock.us, null, null, null, null);
            var sizeFromSizeChart = SizeChart.GetSizeStatic(sizeAllStock);

            if (sizeFromSizeChart == null)
            {
                Ad.Size = "Без размера";
            }
            else
            {
                var    ruSize       = sizeFromSizeChart.ru.Replace(".", ",");
                double doubleRuSize = 0;
                if (Double.TryParse(ruSize, out doubleRuSize))
                {
                    Ad.Size = Math.Round(doubleRuSize, 0).ToString();
                }
                else
                {
                    Ad.Size = "Без размера";
                }
            }
            if (Ad.Size == "Без размера")
            {
                if (sneaker.category == "men")
                {
                    Ad.Size = "42";
                }
                else if (sneaker.category == "women")
                {
                    Ad.Size = "37";
                }
                else if (sneaker.category == "kids")
                {
                    Ad.Size = "35";
                }
            }

            //title
            Ad.Title = "Новые оригинальные " + sneaker.title.ToUpper() + " " + sneaker.sku;
            if (Ad.Title.Length > 50)
            {
                Ad.Title = Ad.Title.Substring(0, 50);
            }
            //Ad.Title = Ad.Title.ToLower();

            //description
            var br   = "\n";
            var desc = "<![CDATA[" + br;

            if (fcSneaker.type == null)
            {
                fcSneaker.type = String.Empty;
            }
            desc += "<p>Новые оригинальные " + fcSneaker.type.ToLower() + " " + sneaker.title.ToUpper() + "</p>" + br;
            desc += "<p>Артикул: " + sneaker.sku + "</p>" + br;
            desc += "<p>В оригинальной упаковке Nike.</p>" + br;
            desc += "<p>БЕСПЛАТНАЯ доставка по Москве</p>" + br;
            desc += "<p>Доставка по России 3-5 дней компанией СДЭК.</p>" + br;
            desc += "<p>Стоимость доставки по РФ - 300 рублей.</p>" + br;
            desc += "<p>Доставка в регионы только по 100% предоплате, наложенным платежом не отправляем</p>" + br;
            desc += "<p>Работаем с 2012 года, более 4000 моделей в ассортименте. Можете перейти в магазин авито (страница Контакты), потом на сайт и в группу Вконтакте, чтобы убедиться в том, что мы продаем только оригинальную обувь. Никаких подделок и реплик!</p>" + br;
            desc += "<p>В нашей группе Вконтакте более 70 реальных отзывов от клиентов!</p>" + br;
            desc += "<p>Размеры в наличии:</p>" + br;
            desc += "<ul>" + br;
            foreach (var size in sneaker.sizes)
            {
                var scSize       = SizeChart.GetSizeStatic(new Size(sneaker.brand, sneaker.category, size.us, null, null, null, null));
                var priceSize    = size.offers[0].price_usd_with_delivery_to_usa_and_minus_vat;
                var priceSizeRub = (int)CurrencyRate.ConvertCurrency("USD", "RUB", priceSize) + MARGIN;
                if (scSize != null)
                {
                    desc += "<li>" + scSize.GetAllSizeString() + ". Цена:" + priceSizeRub + "</li>" + br;
                }
            }
            desc          += "</ul>" + br;
            desc          += "<p>Уточняйте наличие размеров.</p>" + br;
            desc          += "<p>Если размера нет в наличии, можем его привезти под заказ. Срок поставки товара под заказ: 7-10 дней. </p>" + br;
            desc          += "<p>Sneaker Icon - это большой выбор оригинальной брендовой обуви Nike и Jordan. Кроссовки, кеды, бутсы, футзалки, шиповки, сланцы, ботинки и другие типы обуви</p>" + br;
            desc          += "<p>Звоните или пишите в сообщения Авито по всем вопросам</p>" + br;
            desc          += "]]>";
            Ad.Description = desc;

            //price
            var priceUsd  = sneaker.GetMinPrice();
            var priceRub  = CurrencyRate.ConvertCurrency("USD", "RUB", priceUsd);
            var pricetest = (int)priceRub + MARGIN;

            Ad.Price = (int)Math.Round(priceRub, 0) + MARGIN;

            Ad.Images = fcSneaker.images;

            return(Ad);
        }
Beispiel #6
0
        internal static decimal CalculateCommission(FeeFormula commissionFormula, TradePLFormula tradePLFormula, decimal unitCommission, decimal lot, decimal contractSize, Price price, CurrencyRate currencyRate, decimal tradePL = 0)
        {
            if (unitCommission > 1)
            {
                unitCommission = Math.Round(unitCommission, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero);
            }

            decimal commission = 0;

            switch (commissionFormula)
            {
            case FeeFormula.FixedAmount:
                commission = unitCommission * lot;
                commission = Math.Round(commission, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero);
                break;

            case FeeFormula.CS:
                commission = unitCommission * lot * contractSize;
                commission = -currencyRate.Exchange(-commission);
                break;

            case FeeFormula.CSDividePrice:
                commission = unitCommission * lot * contractSize / (decimal)price;
                commission = -currencyRate.Exchange(-commission);
                break;

            case FeeFormula.CSMultiplyPrice:
                commission = unitCommission * lot * contractSize * (decimal)price;
                commission = -currencyRate.Exchange(-commission);
                break;

            case FeeFormula.Pips:
                Price buyPrice, sellPrice;
                if ((int)tradePLFormula != 2)
                {
                    buyPrice  = price;
                    sellPrice = price + (int)unitCommission;
                }
                else
                {
                    buyPrice  = price + (int)unitCommission;
                    sellPrice = price;
                }
                Price closePrice = price;

                commission = TradePLCalculator.Calculate(tradePLFormula, lot, contractSize, (decimal)buyPrice, (decimal)sellPrice, (decimal)closePrice, currencyRate.SourceCurrency.Decimals);
                commission = -currencyRate.Exchange(-commission);
                break;

            case FeeFormula.PricePips:
                commission = 0;
                break;

            case FeeFormula.RealizedProfit:
                commission = tradePL > 0 ? unitCommission * tradePL : 0;
                break;

            case FeeFormula.RealizedLoss:
                commission = tradePL < 0 ? unitCommission * tradePL : 0;
                break;

            case FeeFormula.RealizedPL:
                commission = unitCommission * Math.Abs(tradePL);
                break;

            case FeeFormula.SharedPL:
                commission = unitCommission * tradePL;
                break;
            }

            return(commission);
        }
Beispiel #7
0
        internal static decimal CalculateCGSELevy(decimal lot, bool isOpen, SpecialTradePolicyDetail policy, CurrencyRate currencyRate)
        {
            int     roundValue = (int)Math.Round(lot, MidpointRounding.AwayFromZero);
            decimal levy       = roundValue * (isOpen ? policy.CGSENewLevyMultipler : policy.CGSECloseLevyMultipler);

            if (lot > roundValue)
            {
                levy += (isOpen ? policy.CGSENewLevyRemainder : policy.CGSECloseLevyRemainder);
            }
            return(-currencyRate.Exchange(-levy));
        }
Beispiel #8
0
        internal static decimal CalculateLevy(FeeFormula levyFormula, TradePLFormula tradePLFormula, decimal unitLevy, decimal lot, decimal contractSize, Price price, CurrencyRate currencyRate, decimal tradePL = 0)
        {
            if (unitLevy > 1)
            {
                unitLevy = Math.Round(unitLevy, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero);
            }

            decimal levy = 0;

            switch (levyFormula)
            {
            case FeeFormula.FixedAmount:
                levy = unitLevy * lot;
                levy = Math.Round(levy, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero);
                break;

            case FeeFormula.CS:
                levy = unitLevy * lot * contractSize;
                levy = -currencyRate.Exchange(-levy);
                break;

            case FeeFormula.CSDividePrice:
                levy = unitLevy * lot * contractSize / (decimal)price;
                levy = -currencyRate.Exchange(-levy);
                break;

            case FeeFormula.CSMultiplyPrice:
                levy = unitLevy * lot * contractSize * (decimal)price;
                levy = -currencyRate.Exchange(-levy);
                break;

            case FeeFormula.Pips:
                Price buyPrice, sellPrice;
                if ((int)tradePLFormula != 2)
                {
                    buyPrice  = price;
                    sellPrice = price + (int)unitLevy;
                }
                else
                {
                    buyPrice  = price + (int)unitLevy;
                    sellPrice = price;
                }
                Price closePrice = price;

                levy = TradePLCalculator.Calculate(tradePLFormula, lot, contractSize, (decimal)buyPrice, (decimal)sellPrice, (decimal)closePrice, currencyRate.SourceCurrency.Decimals);
                levy = -currencyRate.Exchange(-levy);
                break;

            case FeeFormula.PricePips:
                levy = 0;
                break;

            case FeeFormula.RealizedProfit:
                levy = tradePL > 0 ? unitLevy * tradePL : 0;
                break;

            case FeeFormula.RealizedLoss:
                levy = tradePL < 0 ? unitLevy * tradePL : 0;
                break;

            case FeeFormula.RealizedPL:
                levy = unitLevy * Math.Abs(tradePL);
                break;

            case FeeFormula.SharedPL:
                levy = unitLevy * tradePL;
                break;
            }

            return(levy);
        }
Beispiel #9
0
 public CurrencyToIsBaseCurrencyCase(CurrencyRate currencyFrom, CurrencyRate currencyTo)
 {
     _currencyFrom = currencyFrom;
     _currencyTo   = currencyTo;
 }
Beispiel #10
0
        private ActionResult Sell(ExchangeViewModel exchangeViewModel)
        {
            CurrencyRate changeRate = new CurrencyRate();
            int          transactionType;

            if (Enum.TryParse(exchangeViewModel.toCurrency, out Currency currentCurrency))
            {
                if (ModelState.IsValid)
                {
                    using (CryptowalletDbContext ctx = new CryptowalletDbContext())
                    {
                        User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name);

                        ExchangeService exchangeService = new ExchangeService();
                        var             sellingAccount  = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == currentCurrency.ToString() && a.UserId == currentUser.UserId);

                        if (sellingAccount == null)
                        {
                            ModelState.AddModelError("", "Inexistent account");

                            switch (TempData["TransactionType"])
                            {
                            case "Buy":
                                transactionType = 1;
                                break;

                            case "Sell":
                                transactionType = 0;
                                break;

                            default:
                                transactionType = 0;
                                break;
                            }

                            return(MakeTransactions(transactionType, currentCurrency));
                        }

                        List <CurrencyRate> rates = exchangeService.GetConversionRate(currentCurrency, new Currency[] { Currency.EUR });

                        changeRate = rates.FirstOrDefault(a => a.Currency == Currency.EUR);

                        if (exchangeViewModel.Amount > sellingAccount.Amount)
                        {
                            ModelState.AddModelError("", "Insuficient funds");


                            //return RedirectToAction("MakeTransactions", new { transactionType = 1 });
                            switch (TempData["TransactionType"])
                            {
                            case "Buy":
                                transactionType = 1;
                                break;

                            case "Sell":
                                transactionType = 0;
                                break;

                            default:
                                transactionType = 0;
                                break;
                            }

                            return(MakeTransactions(transactionType, currentCurrency));
                        }

                        UserBankAccount euroBankAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == Currency.EUR.ToString() && a.UserId == currentUser.UserId);

                        euroBankAccount.Amount += exchangeViewModel.Amount * changeRate.Rate;
                        sellingAccount.Amount  -= exchangeViewModel.Amount;

                        ctx.SaveChanges();


                        UserTransaction userTransaction = new UserTransaction
                        {
                            Amount          = exchangeViewModel.Amount,
                            FromAccountId   = sellingAccount.AccountId,
                            ToAccountId     = euroBankAccount.AccountId,
                            CurrencyRate    = changeRate.Rate,
                            TransactionDate = DateTime.Now
                        };

                        ctx.UserTransactions.Add(userTransaction);
                        ctx.SaveChanges();
                    }
                    return(View(exchangeViewModel));
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid Currency");
                switch (TempData["TransactionType"])
                {
                case "Buy":
                    transactionType = 1;
                    break;

                case "Sell":
                    transactionType = 0;
                    break;

                default:
                    transactionType = 0;
                    break;
                }
                return(MakeTransactions(transactionType, currentCurrency));
            }
            return(RedirectToAction("Wallet"));
        }
Beispiel #11
0
        public ActionResult Exchange(ExchangeViewModel viewModel)
        {
            SetupExchangeViewModel(viewModel);
            CurrencyRate changeRate = new CurrencyRate();

            if (ModelState.IsValid)
            {
                using (CryptowalletDbContext ctx = new CryptowalletDbContext())
                {
                    User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name);

                    ExchangeService exchangeService = new ExchangeService();
                    Enum.TryParse(viewModel.fromCurrency, out Currency fromCurrency);
                    List <CurrencyRate> rates = exchangeService.GetConversionRate(fromCurrency, new Currency[] { Currency.EUR, Currency.ETH, Currency.LTC, Currency.BTC, Currency.EOS });
                    //  List<CurrencyRate> rate =e.GetConversionRate(Currency.BTC, new Currency[] { Currency.EUR, Currency.USD, Currency.GBP });

                    changeRate = rates.FirstOrDefault(a => a.Currency.ToString() == viewModel.toCurrency);

                    UserBankAccount bankAccount     = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == viewModel.toCurrency && a.UserId == currentUser.UserId);
                    UserBankAccount fromBankAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == viewModel.fromCurrency && a.UserId == currentUser.UserId);
                    if (fromBankAccount.Amount < viewModel.Amount)
                    {
                        ModelState.AddModelError("", "Insuficient funds");
                        return(View(viewModel));
                    }
                    if (bankAccount == null)
                    {
                        bankAccount = new UserBankAccount
                        {
                            Currency = viewModel.toCurrency,
                            UserId   = currentUser.UserId,
                            Amount   = 0,
                        };

                        ctx.UserBankAccounts.Add(bankAccount);
                    }



                    bankAccount.Amount     += viewModel.Amount * changeRate.Rate;
                    fromBankAccount.Amount -= viewModel.Amount;
                    ctx.SaveChanges();


                    UserTransaction userTransaction = new UserTransaction
                    {
                        Amount          = viewModel.Amount,
                        FromAccountId   = fromBankAccount.AccountId,
                        ToAccountId     = bankAccount.AccountId,
                        CurrencyRate    = changeRate.Rate,
                        TransactionDate = DateTime.Now
                    };

                    ctx.UserTransactions.Add(userTransaction);
                    ctx.SaveChanges();
                    ViewBag.successMessage = "Transaction successful";
                }
                return(View(viewModel));
            }
            return(View(viewModel));
        }
        public void UpdateCard(BalanceModel balance, CurrencyRate currencyRate, int i)
        {
            _login.Text = $"@{balance.UserInfo.Login}";
            double usdBalance = 0;

            switch (balance.CurrencyType)
            {
            case CurrencyType.Steem:
            case CurrencyType.Golos:
            {
                _secondTokenLabel.Text = $"{balance.CurrencyType.ToString()} Power".ToUpper();
                usdBalance             = (balance.Value + balance.EffectiveSp) * (currencyRate?.UsdRate ?? 1);
                break;
            }

            case CurrencyType.Sbd:
            case CurrencyType.Gbg:
            {
                _secondTokenLabel.Hidden = true;
                _secondTokenValue.Hidden = true;
                usdBalance = balance.Value * (currencyRate?.UsdRate ?? 1);
                break;
            }
            }

            _balanceLabel.Text      = $"{balance.CurrencyType.ToString()} balance";
            _equivalentBalance.Text = $"$ {usdBalance.ToBalanceValueString()}".ToUpper();
            _firstTokenLabel.Text   = balance.CurrencyType.ToString().ToUpper();
            _firstTokenValue.Text   = balance.Value.ToBalanceValueString();
            _secondTokenValue.Text  = balance.EffectiveSp.ToBalanceValueString();

            switch (i)
            {
            case 0:
            {
                _image.Image = UIImage.FromBundle("ic_red_card");
                Constants.CreateShadowFromZeplin(_shadowHelper, UIColor.FromRGB(232, 56, 31), 0.3f, 0, 20, 30, 0);
                break;
            }

            case 1:
            {
                _image.Image = UIImage.FromBundle("ic_blue_card");
                Constants.CreateShadowFromZeplin(_shadowHelper, Constants.R74G144B226, 0.3f, 0, 20, 30, 0);
                break;
            }

            case 2:
            {
                _image.Image = UIImage.FromBundle("ic_green_card");
                Constants.CreateShadowFromZeplin(_shadowHelper, UIColor.FromRGB(103, 184, 47), 0.3f, 0, 20, 30, 0);
                break;
            }

            case 3:
            {
                _image.Image = UIImage.FromBundle("ic_orange_card");
                Constants.CreateShadowFromZeplin(_shadowHelper, UIColor.FromRGB(218, 146, 44), 0.3f, 0, 20, 30, 0);
                break;
            }

            case 4:
            {
                _image.Image = UIImage.FromBundle("ic_pink_card");
                Constants.CreateShadowFromZeplin(_shadowHelper, UIColor.FromRGB(189, 16, 224), 0.3f, 0, 20, 30, 0);
                break;
            }

            case 5:
            {
                _image.Image = UIImage.FromBundle("ic_purple_card");
                Constants.CreateShadowFromZeplin(_shadowHelper, UIColor.FromRGB(144, 19, 254), 0.3f, 0, 20, 30, 0);
                break;
            }

            case 6:
            {
                _image.Image = UIImage.FromBundle("ic_grey_card");
                Constants.CreateShadowFromZeplin(_shadowHelper, UIColor.FromRGB(155, 155, 155), 0.3f, 0, 20, 30, 0);
                break;
            }

            case 7:
            {
                _image.Image = UIImage.FromBundle("ic_light_red_card");
                Constants.CreateShadowFromZeplin(_shadowHelper, UIColor.FromRGB(208, 2, 166), 0.3f, 0, 20, 30, 0);
                break;
            }

            default:
                break;
            }
        }
Beispiel #13
0
        public ActionResult CurrencyRateEdit(CurrencyRate model)
        {
            DAL.CurrencyRateSaveAdd(model);

            return(RedirectToAction("CurrencyRates", new { id = model.CurrencyId }));
        }
        private static async void PostPrivateToTelegram(HotOffer offer)
        {
            var message = "Горячее предложение\n"
                          + "Название: " + offer.title + " \n"
                          + "Артикул: " + offer.sku + "\n";
            var regPriceRub = CurrencyRate.ConvertCurrency("USD", "RUB", offer.regular_price);

            message += "Цена в розницу: " + offer.regular_price + " USD = " + regPriceRub + " RUB\n";
            var ourPriceRub = CurrencyRate.ConvertCurrency("USD", "RUB", offer.our_price);

            message += "Наша цена со скидкой: " + offer.our_price + " USD = " + ourPriceRub + "RUB\n";
            var rusCategory = Helper.ConvertEngToRusCategory(offer.sizes[0].size.category);

            message += "Категория: " + rusCategory + "\n";
            //sizes
            message += "\nДоступные размеры:\n";
            var sizeChart = SizeChart.ReadSizeChartJson();
            var shops     = new List <string>();
            var sizesUS   = new List <string>();
            var ourPrices = new List <double>();

            foreach (var offerSize in offer.sizes)
            {
                var size = sizeChart.GetSize(offerSize.size);
                if (size != null)
                {
                    message += size.us + " US / " + size.eu + " EU / " + size.uk + " UK / " + size.cm + " CM \n";
                    ourPrices.Add(offerSize.price);
                    //message += offerSize.price + "USD (with ship and return vat) \n";
                    if (!shops.Contains(offerSize.url))
                    {
                        shops.Add(offerSize.url);
                    }
                    //message += offerSize.url + "\n";
                }
                else
                {
                    Program.Logger.Warn("Ошибка в размере " + offer.title + " " + offer.sku);
                }
            }

            //our prices
            message += "\nНаша цена (с доставкой до РФ и вычетом VAT если есть)\n";
            foreach (var offerSize in offer.sizes)
            {
                var rubPrice = CurrencyRate.ConvertCurrency("USD", "RUB", offerSize.price);
                message += offerSize.size.us + " US: " + offerSize.price + "USD = " + rubPrice + "RUB\n";
            }

            //shops
            message += "\nОткуда брать:\n";
            foreach (var url in shops)
            {
                message += url + "\n";
            }

            //images
            message += "\nИзображения:\n";
            foreach (var image in offer.images)
            {
                message += image + "\n";
            }

            var chatId = "-1001101919442";
            await Helper.TelegramPost(message, chatId);
        }
 public CurrencyBasketWrapper(decimal rate, CurrencyRate currencyRate)
 {
     Rate = rate;
     CurrencyRate = currencyRate;
 }
Beispiel #16
0
        public decimal ConvertRate(CurrencyRate currencyRate)
        {
            CentralBankService centralBankService = new CentralBankService();

            return(centralBankService.ConvertRate(currencyRate));
        }
 // POST api/awbuildversion
 public void Post(CurrencyRate value)
 {
     adventureWorks_BC.CurrencyRateAdd(value);
 }
 /// <summary>
 /// There are no comments for CurrencyRate in the schema.
 /// </summary>
 public void AddToCurrencyRate(CurrencyRate currencyRate)
 {
     base.AddObject("CurrencyRate", currencyRate);
 }
Beispiel #19
0
 public void AddCurrencyRate(CurrencyRate currencyRate)
 {
     _dbContext.Add(currencyRate);
 }
Beispiel #20
0
 public CurrencyRate CurrencyRateSaveAdd(CurrencyRate model)
 {
     return(CurrencyRateSaveAdd(model.Id, model.CurrencyId, model.DateTime, model.Value, 0));
 }
Beispiel #21
0
 public void DeleteCurrency(CurrencyRate currencyRate)
 {
     _dbContext.Remove(currencyRate);
 }
Beispiel #22
0
        internal static CurrencyRate GetCGSELevyCurrencyRate(Settings.Account account, Settings.Instrument instrument, SpecialTradePolicyDetail specialTradePolicyDetail, CurrencyRate defaultCurrencyRate, ExecuteContext context)
        {
            if (specialTradePolicyDetail.CGSELevyCurrecyType == CGSELevyCurrecyType.UseInstrumentCurrencyType)
            {
                return(defaultCurrencyRate);
            }
            else
            {
                Guid sourceCurrencyId = account.CurrencyId;
                Guid targetCurrencyId = account.IsMultiCurrency ? instrument.CurrencyId : account.CurrencyId;

                return(context != null && context.ShouldUseHistorySettings ? Settings.Setting.Default.GetCurrencyRate(sourceCurrencyId, targetCurrencyId, context.TradeDay)
                                                                            : Settings.Setting.Default.GetCurrencyRate(sourceCurrencyId, targetCurrencyId));
            }
        }
Beispiel #23
0
        public object GetAll()
        {
            var queryValues = Request.RequestUri.ParseQueryString();

            int page  = Convert.ToInt32(queryValues["page"]);
            int start = Convert.ToInt32(queryValues["start"]);
            int limit = Convert.ToInt32(queryValues["limit"]);
            int id    = Convert.ToInt32(queryValues["id"] ?? "0");
            int orden = Convert.ToInt32(queryValues["orden"]);


            #region Configuramos el orden de la consulta si se obtuvo como parametro
            string strOrder = !string.IsNullOrWhiteSpace(queryValues["sort"]) ? queryValues["sort"] : "";
            strOrder = strOrder.Replace('[', ' ');
            strOrder = strOrder.Replace(']', ' ');

            Sort sort;

            if (!string.IsNullOrWhiteSpace(strOrder))
            {
                sort = JsonConvert.DeserializeObject <Sort>(strOrder);
            }
            else
            {
                sort = new Sort();
            }
            #endregion

            string query = !string.IsNullOrWhiteSpace(queryValues["query"]) ? queryValues["query"] : "";

            int totalRecords = 0;

            try
            {
                if (id == 0)
                {
                    object json;
                    string msgError = "";
                    IList <CurrencyRate> lista;

                    lista = repository.GetList(query, sort, page, start, limit, ref totalRecords, ref msgError);

                    json = new
                    {
                        total   = totalRecords,
                        data    = lista,
                        success = true
                    };

                    return(json);
                }
                else
                {
                    string       msgError = "";
                    CurrencyRate estatus  = repository.Get(id, ref msgError);

                    object json = new
                    {
                        data    = estatus,
                        success = true,
                        message = msgError
                    };

                    return(json);
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("ERROR:" + Environment.NewLine + "\tMETHOD = " + this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name + Environment.NewLine + "\tMESSAGE = " + ex.Message);

                object error = new { message = ex.Message };

                object json = new
                {
                    message = ex.Message,
                    success = false
                };

                return(json);
            }
        }
Beispiel #24
0
        internal static decimal CaculateInstalmentAdministrationFee(decimal value, decimal lot, InstalmentPolicyDetail instalmentPolicyDetail, CurrencyRate currencyRate)
        {
            decimal result = 0;

            switch (instalmentPolicyDetail.InstalmentFeeType)
            {
            case InstalmentFeeType.FixedAmountPerLot:
                result = lot * instalmentPolicyDetail.InstalmentFeeRate;
                result = Math.Round(result, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero);
                break;

            case InstalmentFeeType.ValueProportion:
                result = value * instalmentPolicyDetail.InstalmentFeeRate;
                result = -currencyRate.Exchange(-result);
                break;

            case InstalmentFeeType.FixedAmount:
                result = instalmentPolicyDetail.InstalmentFeeRate;
                result = Math.Round(result, currencyRate.TargetCurrency.Decimals, MidpointRounding.AwayFromZero);
                break;

            default:
                result = 0;
                break;
            }
            return(result);
        }
Beispiel #25
0
        protected override void OnBeginImport()
        {
            this._tablePrefix = string.Format("{0}_{1}_{2}_{3}", this.TablePrefixType, this.CurrentDelivery.Account.ID, DateTime.Now.ToString("yyyMMdd_HHmmss"), this.CurrentDelivery.DeliveryID.ToString("N").ToLower());
            this.CurrentDelivery.Parameters[Consts.DeliveryOutputParameters.TablePerfix] = this._tablePrefix;

            int bufferSize = int.Parse(AppSettings.Get(this, Consts.AppSettings.BufferSize));

            // Connect to database
            _sqlConnection = NewDeliveryDbConnection();
            _sqlConnection.Open();

            // Create bulk objects
            _bulks = new Dictionary <Type, BulkObjects>();
            Type tableList = this.GetType().GetNestedType("Tables", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);

            foreach (Type table in tableList.GetNestedTypes())
            {
                _bulks[table] = new BulkObjects(this._tablePrefix, table, _sqlConnection, bufferSize);
            }

            // Get measures
            using (SqlConnection oltpConnection = new SqlConnection(this.Options.StagingConnectionString))
            {
                oltpConnection.Open();

                this.Measures = Measure.GetMeasures(
                    this.CurrentDelivery.Account,
                    this.CurrentDelivery.Channel,
                    oltpConnection,
                    this.Options.MeasureOptions,
                    this.Options.MeasureOptionsOperator
                    );

                this.SegmentTypes = Segment.GetSegments(
                    this.CurrentDelivery.Account,
                    this.CurrentDelivery.Channel,
                    oltpConnection,
                    this.Options.SegmentOptions,
                    this.Options.SegmentOptionsOperator
                    );

                this.CurrencyRates = CurrencyRate.GetCurrencyRates(
                    this.CurrentDelivery.TimePeriodDefinition.Start.ToDateTime()
                    );
            }

            // Add measure columns to metrics
            StringBuilder measuresFieldNamesSQL = new StringBuilder(",");
            StringBuilder measuresNamesSQL      = new StringBuilder(",");
            StringBuilder measuresValidationSQL = new StringBuilder();
            int           count       = 0;
            BulkObjects   bulkMetrics = _bulks[this.MetricsTableDefinition];

            foreach (Measure measure in this.Measures.Values)
            {
                bulkMetrics.AddColumn(new ColumnDef(
                                          name: measure.Name,
                                          type: SqlDbType.Float,
                                          nullable: true
                                          ));

                measuresFieldNamesSQL.AppendFormat("[{0}]{1}", measure.OltpName, count < this.Measures.Values.Count - 1 ? "," : null);
                measuresNamesSQL.AppendFormat("[{0}]{1}", measure.Name, count < this.Measures.Values.Count - 1 ? "," : null);

                if (measure.Options.HasFlag(MeasureOptions.ValidationRequired))
                {
                    measuresValidationSQL.AppendFormat("{1}SUM([{0}]) as [{0}]", measure.Name, measuresValidationSQL.Length > 0 ? ", " : null);
                }

                count++;
            }

            this.CurrentDelivery.Parameters.Add(Consts.DeliveryOutputParameters.MeasureFieldsSql, measuresFieldNamesSQL.ToString());
            this.CurrentDelivery.Parameters.Add(Consts.DeliveryOutputParameters.MeasureNamesSql, measuresNamesSQL.ToString());
            if (string.IsNullOrEmpty(measuresValidationSQL.ToString()))
            {
                Log.Write("No measures marked for checksum validation; there will be no validation before the final commit.", LogMessageType.Warning);
            }
            else
            {
                this.CurrentDelivery.Parameters.Add(Consts.DeliveryOutputParameters.MeasureValidateSql, measuresValidationSQL.ToString());
            }

            // Create the tables
            StringBuilder createTableCmdText = new StringBuilder();

            foreach (BulkObjects bulk in _bulks.Values)
            {
                createTableCmdText.Append(bulk.GetCreateTableSql());
            }
            SqlCommand cmd = new SqlCommand(createTableCmdText.ToString(), _sqlConnection);

            cmd.CommandTimeout = 80;             //DEFAULT IS 30 AND SOMTIME NOT ENOUGH WHEN RUNING CUBE
            cmd.ExecuteNonQuery();
        }
        public virtual async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            activity.Recipient.Name = "Contoso Bank Bot";

            userMessage = activity.Text;
            string endOutput = $"Welcome To Contoso Bank Bot Service";

            StateClient stateClient = activity.GetStateClient();

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

            User user = (userData.GetProperty <User>("user") != null) ? userData.GetProperty <User>("user") : null;

            if (activity.Type == ActivityTypes.Message)
            {
                if (userData.GetProperty <bool>("isLoginSuccessful"))
                {
                    activity.From.Name = userData.GetProperty <string>("username");

                    // Add new account
                    if (userData.GetProperty <bool>("isAddAccount"))
                    {
                        int count = userData.GetProperty <int>("count");
                        if (count == 1)
                        {
                            string[] pairs = Regex.Split(userMessage, "\\s+");
                            if (pairs.Length > 1)
                            {
                                userMessage = "";
                                foreach (string str in pairs)
                                {
                                    userMessage += str;
                                }
                            }

                            userData.SetProperty <string>("accName", userMessage);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            endOutput = "Enter Deposit Value";

                            userData.SetProperty <int>("count", 2);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            Activity quickreply = activity.CreateReply($"{endOutput}");
                            await connector.Conversations.ReplyToActivityAsync(quickreply);

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                        else if (count == 2)
                        {
                            bool           flag     = false;
                            string         accValue = userMessage;
                            string         accName  = userData.GetProperty <string>("accName");
                            List <Account> accounts = await AzureManager.AzureManagerInstance.GetAccounts(user.ID);

                            foreach (Account account in accounts)
                            {
                                if (account.Name.Equals(accName))
                                {
                                    flag = true;
                                }
                            }

                            if (!flag)
                            {
                                if (userData.GetProperty <bool>("process"))
                                {
                                    Account account = new Account()
                                    {
                                        Name   = accName,
                                        Type   = "Saving",
                                        Value  = Convert.ToDecimal(accValue),
                                        UserID = user.ID
                                    };

                                    userData.SetProperty <Account>("account", account);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("process", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }

                                if (userData.GetProperty <bool>("confirm"))
                                {
                                    await Conversation.SendAsync(activity, () => new EchoDialog());
                                }

                                string result = userMessage;

                                if (result.ToLower().Equals("yes") || result.ToLower().Equals("1"))
                                {
                                    userData.SetProperty <int>("count", 0);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    await AzureManager.AzureManagerInstance.AddCount(userData.GetProperty <Account>("account"));

                                    List <Account> list = await AzureManager.AzureManagerInstance.GetAccounts(user.ID);

                                    await connector.Conversations.SendToConversationAsync(DisplayAccount(list, activity));

                                    userData.SetProperty <bool>("confirm", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("isAddAccount", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    return(Request.CreateResponse(HttpStatusCode.OK));
                                }
                                else if (result.ToLower().Equals("no") || result.ToLower().Equals("2"))
                                {
                                    userData.SetProperty <bool>("isAddAccount", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("confirm", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    endOutput = $"Process is cancelled";
                                    Activity rep = activity.CreateReply($"{endOutput}");
                                    await connector.Conversations.ReplyToActivityAsync(rep);

                                    return(Request.CreateResponse(HttpStatusCode.OK));
                                }
                            }
                            else
                            {
                                userData.SetProperty <int>("count", 0);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                List <Account> list = await AzureManager.AzureManagerInstance.GetAccounts(user.ID);

                                await connector.Conversations.SendToConversationAsync(DisplayAccount(list, activity));

                                userData.SetProperty <bool>("isAddAccount", false);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                userData.SetProperty <bool>("confirm", false);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                endOutput = $"{accName} Is Existed!";
                                Activity rep = activity.CreateReply($"{endOutput}");
                                await connector.Conversations.ReplyToActivityAsync(rep);

                                return(Request.CreateResponse(HttpStatusCode.OK));
                            }
                        }
                    }

                    // Update an account
                    if (userData.GetProperty <bool>("isUpdateAccount"))
                    {
                        int count = userData.GetProperty <int>("count");
                        if (count == 1)
                        {
                            try
                            {
                                if (userData.GetProperty <bool>("process"))
                                {
                                    string[] pairs = Regex.Split(userMessage, "\\s+");

                                    userData.SetProperty <string>("accName", pairs[1]);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <string>("accValue", pairs[2]);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("process", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }

                                string         name     = userData.GetProperty <string>("accName");
                                List <Account> accounts = await AzureManager.AzureManagerInstance.GetAccounts(user.ID);

                                Account acc = (accounts.Where(a => a.Name == name).Count() > 0) ? accounts.Where(a => a.Name == name).First() : null;

                                if (acc != null)
                                {
                                    if (userData.GetProperty <bool>("confirm"))
                                    {
                                        await Conversation.SendAsync(activity, () => new EchoDialog());
                                    }

                                    string result = userMessage;

                                    if (result.ToLower().Equals("yes") || result.ToLower().Equals("1"))
                                    {
                                        userData.SetProperty <int>("count", 0);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        acc.Value = Convert.ToDecimal(userData.GetProperty <string>("accValue"));
                                        await AzureManager.AzureManagerInstance.UpdateCount(acc);

                                        await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                                        userData.SetProperty <bool>("isUpdateAccount", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        userData.SetProperty <bool>("confirm", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        return(Request.CreateResponse(HttpStatusCode.OK));
                                    }
                                    else if (result.ToLower().Equals("no") || result.ToLower().Equals("2"))
                                    {
                                        userData.SetProperty <int>("count", 0);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                                        userData.SetProperty <bool>("isUpdateAccount", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        userData.SetProperty <bool>("confirm", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        endOutput = $"Process is cancelled";
                                        Activity rep = activity.CreateReply($"{endOutput}");
                                        await connector.Conversations.ReplyToActivityAsync(rep);

                                        return(Request.CreateResponse(HttpStatusCode.OK));
                                    }
                                }
                                else
                                {
                                    userData.SetProperty <int>("count", 0);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                                    userData.SetProperty <bool>("isUpdateAccount", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("confirm", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("process", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    endOutput = $"Account {name} is not existed!";
                                    Activity rep = activity.CreateReply($"{endOutput}");
                                    await connector.Conversations.ReplyToActivityAsync(rep);

                                    return(Request.CreateResponse(HttpStatusCode.OK));
                                }
                            }
                            catch (Exception e)
                            {
                                userData.SetProperty <int>("count", 0);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                userData.SetProperty <bool>("confirm", false);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                userData.SetProperty <bool>("process", false);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                endOutput = $"{userMessage} - Syntax is not correct";
                                Activity rep = activity.CreateReply($"{endOutput}");
                                await connector.Conversations.ReplyToActivityAsync(rep);

                                return(Request.CreateResponse(HttpStatusCode.OK));
                            }
                        }
                    }

                    // Delete an account
                    if (userData.GetProperty <bool>("isDeleteAccount"))
                    {
                        int count = userData.GetProperty <int>("count");
                        if (count == 1)
                        {
                            try
                            {
                                if (userData.GetProperty <bool>("process"))
                                {
                                    string[] pairs = Regex.Split(userMessage, "\\s+");

                                    userData.SetProperty <string>("accName", pairs[1]);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("process", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }

                                string         name     = userData.GetProperty <string>("accName");
                                List <Account> accounts = await AzureManager.AzureManagerInstance.GetAccounts(user.ID);

                                Account acc = (accounts.Where(a => a.Name == name).Count() > 0) ? accounts.Where(a => a.Name == name).First() : null;

                                if (acc != null)
                                {
                                    if (userData.GetProperty <bool>("confirm"))
                                    {
                                        await Conversation.SendAsync(activity, () => new EchoDialog());
                                    }

                                    string result = userMessage;

                                    if (result.ToLower().Equals("yes") || result.ToLower().Equals("1"))
                                    {
                                        userData.SetProperty <int>("count", 0);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        await AzureManager.AzureManagerInstance.DeleteCount(acc);

                                        accounts.Remove(acc);
                                        await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                                        userData.SetProperty <bool>("isDeleteAccount", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        userData.SetProperty <bool>("confirm", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        return(Request.CreateResponse(HttpStatusCode.OK));
                                    }
                                    else if (result.ToLower().Equals("no") || result.ToLower().Equals("2"))
                                    {
                                        userData.SetProperty <int>("count", 0);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                                        userData.SetProperty <bool>("isDeleteAccount", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        userData.SetProperty <bool>("confirm", false);
                                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                        endOutput = $"Process is cancelled";
                                        Activity rep = activity.CreateReply($"{endOutput}");
                                        await connector.Conversations.ReplyToActivityAsync(rep);

                                        return(Request.CreateResponse(HttpStatusCode.OK));
                                    }
                                }
                                else
                                {
                                    userData.SetProperty <int>("count", 0);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                                    userData.SetProperty <bool>("isDeleteAccount", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("confirm", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    userData.SetProperty <bool>("process", false);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                    endOutput = $"Account {name} Is Not Existing!";
                                    Activity rep = activity.CreateReply($"{endOutput}");
                                    await connector.Conversations.ReplyToActivityAsync(rep);

                                    return(Request.CreateResponse(HttpStatusCode.OK));
                                }
                            }
                            catch (Exception e)
                            {
                                userData.SetProperty <int>("count", 0);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                userData.SetProperty <bool>("confirm", false);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                userData.SetProperty <bool>("process", false);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                endOutput = $"{userMessage} - Syntax is not correct";
                                Activity rep = activity.CreateReply($"{endOutput}");
                                await connector.Conversations.ReplyToActivityAsync(rep);

                                return(Request.CreateResponse(HttpStatusCode.OK));
                            }
                        }
                    }

                    // Logout
                    if (userMessage.ToLower().Equals("logout") || userMessage.ToLower().Equals("6"))
                    {
                        userData.SetProperty <bool>("logoutProcess", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    else if (userMessage.ToLower().Equals("menu"))
                    {
                        await connector.Conversations.SendToConversationAsync(DisplayMenu(activity));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (userMessage.ToLower().Equals("view account") || userMessage.ToLower().Equals("1"))
                    {
                        if (user != null)
                        {
                            List <Account> accounts = await AzureManager.AzureManagerInstance.GetAccounts(user.ID);

                            await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                    }
                    else if (userMessage.ToLower().Equals("add account") || userMessage.ToLower().Equals("2"))
                    {
                        userData.SetProperty <bool>("isAddAccount", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        endOutput = "Enter Account Name";

                        userData.SetProperty <int>("count", 1);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <bool>("confirm", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <bool>("process", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        Activity rep = activity.CreateReply($"{endOutput}");
                        await connector.Conversations.ReplyToActivityAsync(rep);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (userMessage.ToLower().Equals("update account") || userMessage.ToLower().Equals("3"))
                    {
                        userData.SetProperty <bool>("isUpdateAccount", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        List <Account> accounts = await AzureManager.AzureManagerInstance.GetAccounts(user.ID);

                        await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                        endOutput = "Update <AccountName> <Value>";

                        userData.SetProperty <int>("count", 1);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <bool>("confirm", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <bool>("process", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        Activity rep = activity.CreateReply($"{endOutput}");
                        await connector.Conversations.ReplyToActivityAsync(rep);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (userMessage.ToLower().Equals("delete account") || userMessage.ToLower().Equals("4"))
                    {
                        userData.SetProperty <bool>("isDeleteAccount", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        List <Account> accounts = await AzureManager.AzureManagerInstance.GetAccounts(user.ID);

                        await connector.Conversations.SendToConversationAsync(DisplayAccount(accounts, activity));

                        userData.SetProperty <bool>("confirm", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <bool>("process", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <int>("count", 1);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        endOutput = "Delete <AccountName>";
                        Activity rep = activity.CreateReply($"{endOutput}");
                        await connector.Conversations.ReplyToActivityAsync(rep);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (userMessage.ToLower().Equals("currency rate") || userMessage.ToLower().Equals("5"))
                    {
                        HttpClient client = new HttpClient();
                        string     result = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=NZD"));

                        CurrencyRate currencyRate = JsonConvert.DeserializeObject <CurrencyRate>(result);
                        await connector.Conversations.SendToConversationAsync(DisplayCurrencyRate(currencyRate, activity));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }

                    // Logout process
                    if (userData.GetProperty <bool>("logoutProcess"))
                    {
                        string username = "";
                        string password = "";
                        userData.SetProperty <string>("username", username);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <string>("password", password);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <bool>("isLoginSuccessful", false);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        endOutput = $"Logout successful! See You Again";
                        Activity rep = activity.CreateReply($"{endOutput}");
                        await connector.Conversations.ReplyToActivityAsync(rep);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                }
                else
                {
                    if (userMessage.ToLower().Equals("login"))
                    {
                        endOutput = "Enter Your Username";
                        userData.SetProperty <bool>("isEnterUser", true); // set property isEnterUser is true
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        Activity rep = activity.CreateReply($"{endOutput}");
                        await connector.Conversations.ReplyToActivityAsync(rep);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }

                    if (userData.GetProperty <bool>("isEnterPass"))
                    {
                        userData.SetProperty <string>("password", userMessage);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <bool>("isEnterPass", false);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }

                    if (userData.GetProperty <bool>("isEnterUser"))
                    {
                        userData.SetProperty <string>("username", userMessage);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        endOutput = "Enter Your Password";

                        userData.SetProperty <bool>("isEnterUser", false);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                        userData.SetProperty <bool>("isEnterPass", true);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }

                    string username = userData.GetProperty <string>("username");
                    string password = userData.GetProperty <string>("password");
                    if (username != null && password != null && userMessage != "" && password != "")
                    {
                        List <User> users = await AzureManager.AzureManagerInstance.GetUsers(username, password);

                        if (users.Count > 0)
                        {
                            userData.SetProperty <User>("user", users.First());
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            endOutput = $"Login Successfull! Welcome {username} To Contoso Bank Bot Service";
                            userData.SetProperty <string>("username", username);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            activity.From.Name = userData.GetProperty <string>("username");
                            userData.SetProperty <string>("password", password);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            userData.SetProperty <bool>("isLoginSuccessful", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                        else
                        {
                            endOutput = "Login Fail!";
                            username  = "";
                            password  = "";
                            userData.SetProperty <string>("username", username);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            activity.From.Name = userData.GetProperty <string>("username");
                            userData.SetProperty <string>("password", password);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }

                        activity.Recipient.Name = "Contoso Bank Bot";
                    }
                }

                if (!userData.GetProperty <bool>("confirm"))
                {
                    Activity reply = activity.CreateReply($"{endOutput}");
                    await connector.Conversations.ReplyToActivityAsync(reply);

                    if (userData.GetProperty <bool>("isLoginSuccessful"))
                    {
                        await connector.Conversations.SendToConversationAsync(DisplayMenu(activity));
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public int CreateNewBusinessTrip(BusinessTripDTO businessTrip, string userName)
        {
            User user = repo.Users.UsersQueryable.FirstOrDefault(u => u.UserName == userName);

            BusinessTrip trip = repo.BusinessTrips.Create(new BusinessTrip()
            {
                Title           = businessTrip.Title,
                Date            = businessTrip.Date.ParseAppString(),
                BusinessReason  = businessTrip.BusinessReason,
                BusinessPurpose = businessTrip.BusinessPurpose,
                Notes           = businessTrip.Notes,
                User            = user
            });

            if (businessTrip.Subsistence != null)
            {
                CreateBusinessTripSubsistence(trip, businessTrip);
            }

            List <Expense> expenses = new List <Expense>();

            if (businessTrip.Expenses != null)
            {
                foreach (ExpenseDTO expDto in businessTrip.Expenses)
                {
                    Expense expense = new Expense();
                    expense.Trip         = trip;
                    expense.Type         = repo.Dictionaries.GetExpenseType(expDto.ExpenseTypeId);
                    expense.Date         = expDto.Date.ParseAppString();
                    expense.City         = expDto.City;
                    expense.Amount       = expDto.Amount;
                    expense.AmountPLN    = expDto.AmountPLN;
                    expense.Country      = repo.Dictionaries.GetCountry(expDto.CountryId);
                    expense.CurrencyCode = expDto.CurrencyCode;
                    expense.ExchangeRate = expDto.ExchangeRate;
                    CurrencyRate systemRate = currenciesTasks.GetCurrencyRateForDay(expense.CurrencyCode, expense.Date.Date);
                    if (Math.Abs(systemRate.ExchangeRate - expense.ExchangeRate) > 0.0001)
                    {
                        expense.ExchangeRateModifiedByUser = true;
                    }
                    else
                    {
                        expense.ExchangeRateModifiedByUser = false;
                    }

                    expense.VATRate      = expDto.VATRate;
                    expense.Notes        = expDto.Notes;
                    expense.DoNotReturn  = expDto.DoNotReturn;
                    expense.DocumentType = repo.Dictionaries.GetExpenseDocumentType(expDto.ExpenseDocumentTypeId);
                    expenses.Add(expense);
                }

                repo.Expenses.CreateSet(expenses);
            }



            if (businessTrip.MileageAllowances != null)
            {
                List <MileageAllowance> mileageAllowances = new List <MileageAllowance>();
                foreach (MileageAllowanceDTO maDto in businessTrip.MileageAllowances)
                {
                    MileageAllowance ma = new MileageAllowance();
                    ma.Trip     = trip;
                    ma.Date     = maDto.Date.ParseAppString();
                    ma.Distance = maDto.Distance;
                    ma.Amount   = maDto.Amount;
                    ma.Notes    = maDto.Notes;
                    ma.Type     = repo.Dictionaries.GetVehicleType(maDto.VehicleTypeId);

                    mileageAllowances.Add(ma);
                }

                repo.MileageAllowances.CreateSet(mileageAllowances);
            }

            this.repo.SaveChanges();
            return(trip.Id);
        }
Beispiel #28
0
 public void AddCurrencyRate(CurrencyRate currencyRate)
 {
     this._currencyRateRepository.AddCurrencyRate(currencyRate);
 }
Beispiel #29
0
 public string Dump(CurrencyRate rate)
 {
     return(Convert.ToString(rate.BankDay, new CultureInfo("ru-RU")) + " ; " +
            rate.Currency + " ; " + rate.Rate.ToString(new CultureInfo("en-US")));
 }
 private CurrencyRateWrapper ToCurrencyRateWrapper(CurrencyRate currencyRate)
 {
     return(new CurrencyRateWrapper(currencyRate));
 }
Beispiel #31
0
 /// <summary>
 /// This method deletes a record in the table.
 /// Change this method to alter how records are deleted.
 /// </summary>
 /// <param name=entity>entity</param>
 public void Delete(CurrencyRate entity)
 {
     DbContext.CurrencyRates.DeleteOnSubmit(entity);
     DbContext.SubmitChanges();
 }
 public void TestGetCurrencyRateEmptyValabiility()
 {
     String       currencyVal   = "";
     Currency     validCurrency = currencyService.GetCurrencyByName("Euro");
     CurrencyRate currencyRate  = currencyRateService.GetCurrencyRateByMonth(currencyVal, validCurrency);
 }
Beispiel #33
0
 /// <summary>
 /// This method inserts a new record in the table.
 /// Change this method to alter how records are inserted.
 /// </summary>
 /// <param name=entity>entity</param>
 public void Insert(CurrencyRate entity)
 {
     DbContext.CurrencyRates.InsertOnSubmit(entity);
     DbContext.SubmitChanges();
 }
Beispiel #34
0
 public decimal ConvertRate(CurrencyRate currencyRate)
 {
     return(currencyRate.Price / (decimal)5.28);
 }
Beispiel #35
0
        private static string GetRatingString(CurrencyRate rate)
        {
            var postfix = rate.RateDirection == CurrencyRateDirection.Down ? "Снижение!" : "";

            return($"{CurrencySymbols.GetSymbol(rate.Target)} {rate.Rate:N3} {postfix}");
        }
Beispiel #36
0
 /// <summary>
 /// Make any alterations necessary (i.e. for DB check constraints, special test cases, etc.)
 /// </summary>
 /// <param name="mock">Object to be modified</param>
 static private void SetSpecialTestData(CurrencyRate mock)
 {
     //Code your changes to the data object here.
 }
 /// <summary>
 /// Create a new CurrencyRate object.
 /// </summary>
 /// <param name="currencyRateID">Initial value of CurrencyRateID.</param>
 /// <param name="currencyRateDate">Initial value of CurrencyRateDate.</param>
 /// <param name="averageRate">Initial value of AverageRate.</param>
 /// <param name="endOfDayRate">Initial value of EndOfDayRate.</param>
 /// <param name="modifiedDate">Initial value of ModifiedDate.</param>
 public static CurrencyRate CreateCurrencyRate(int currencyRateID, global::System.DateTime currencyRateDate, decimal averageRate, decimal endOfDayRate, global::System.DateTime modifiedDate)
 {
     CurrencyRate currencyRate = new CurrencyRate();
     currencyRate.CurrencyRateID = currencyRateID;
     currencyRate.CurrencyRateDate = currencyRateDate;
     currencyRate.AverageRate = averageRate;
     currencyRate.EndOfDayRate = endOfDayRate;
     currencyRate.ModifiedDate = modifiedDate;
     return currencyRate;
 }