Exemplo n.º 1
0
        public IActionResult Index(double FromAmount, string FromCurrency, string ToCurrency)
        {
            if (FromCurrency == ToCurrency)
            {
                ViewBag.Result     = 0;
                ViewBag.Rate       = "";
                ViewBag.FromAmount = FromAmount;
                ViewBag.Error      = "The currency you want to exchange is the same as the currency you want to receive.";
            }
            else
            {
                ViewBag.FromAmount = FromAmount;
                double rate = HttpClientHandler.GetExchangeRateAsync(FromCurrency, ToCurrency);
                ViewBag.Result = FromAmount * rate;
                ViewBag.Rate   = $"•1 {FromCurrency} = {rate} {ToCurrency}";

                ExchangeHistory exchangeHistory = new ExchangeHistory();
                exchangeHistory.Date         = DateTime.UtcNow;
                exchangeHistory.FromAmount   = FromAmount;
                exchangeHistory.FromCurrency = FromCurrency;
                exchangeHistory.ToAmount     = ViewBag.Result;
                exchangeHistory.ToCurrency   = ToCurrency;

                dataManager.ExchangeHistory.SaveExchangeHistory(exchangeHistory);
            }
            return(View());
        }
        public JsonResult NewExchangeHistory(string score, string money, string cache, string appId)
        {
            int             userId;
            string          token;
            ExchangeHistory eHistory = null;
            string          message  = string.Empty;
            bool            success  = false;

            if (GetToken(out userId, out token))
            {
                try
                {
                    eHistory = AddEntity <ExchangeHistory>(new ExchangeHistory
                    {
                        User_Id        = userId,
                        ApplyTime      = DateTime.Now,
                        Application_Id = int.Parse(appId),
                        Score          = int.Parse(score),
                        Money          = int.Parse(money),
                        SettlementTime = DateTime.Now.AddDays(10),
                        Cache          = int.Parse(cache),
                        OptUser_Id     = BuiltIns.Administrator.Id,
                        Status         = (int)RequestStatus.Submitted
                    });
                    success = true;
                }
                catch (DatabaseException excpetion)
                {
                    message = excpetion.Message;
                }
            }
            return(Json(new { Success = success, Model = new ExchangeHistoryModel(eHistory), Message = message }, JsonRequestBehavior.AllowGet));
        }
        public void FetchFossilRateAsync_Does_Not_Throw_For_Current_League()
        {
            var exchangeHistoryService = new ExchangeHistoryService();

            var exchangeHistory = new ExchangeHistory();

            exchangeHistoryService.Run(exchangeHistory);
        }
Exemplo n.º 4
0
        public async Task <MoneyExchangeViewModel> Handle(AddEntryToHistoryCommand request, CancellationToken cancellationToken)
        {
            var    ratesDictionary = _moneyExchangeService.CreateRatesDictionary(await _moneyExchangeRepository.GetRates());
            double fromAmount      = request.FromAmount;
            double toAmount        = request.ToAmount;
            double ratio           = 0;

            var entry = new ExchangeHistory
            {
                FromCurrency = request.FromCurrency,
                FromAmount   = fromAmount,
                ToCurrency   = request.ToCurrency,
                ToAmount     = toAmount,
                Date         = DateTime.Now
            };

            var moneyExchange = new MoneyExchangeViewModel
            {
                ToAmount        = toAmount,
                RatesDictionary = ratesDictionary,
                FromAmount      = fromAmount
            };

            if (request.FromAmount != 0 | request.ToAmount != 0)
            {
                if (request.FromAmount == 0)
                {
                    fromAmount = _moneyExchangeService.CalculateTheRate(entry);
                    ratio      = _moneyExchangeService.CalculatTheRatio(entry);

                    entry.FromAmount = fromAmount;

                    moneyExchange.FromAmount   = fromAmount;
                    moneyExchange.Ratio        = ratio;
                    moneyExchange.FromCurrency = ratesDictionary.FirstOrDefault(x => x.Key.ToString() == request.ToCurrency).Value;
                    moneyExchange.ToCurrency   = ratesDictionary.FirstOrDefault(x => x.Key.ToString() == request.FromCurrency).Value;
                }
                else
                {
                    toAmount = _moneyExchangeService.CalculateTheRate(entry);
                    ratio    = _moneyExchangeService.CalculatTheRatio(entry);

                    entry.ToAmount = toAmount;

                    moneyExchange.ToAmount     = toAmount;
                    moneyExchange.Ratio        = ratio;
                    moneyExchange.FromCurrency = ratesDictionary.FirstOrDefault(x => x.Key.ToString() == request.FromCurrency).Value;
                    moneyExchange.ToCurrency   = ratesDictionary.FirstOrDefault(x => x.Key.ToString() == request.ToCurrency).Value;
                }
                entry.FromCurrency = ratesDictionary.FirstOrDefault(x => x.Key.ToString() == request.FromCurrency).Value;
                entry.ToCurrency   = ratesDictionary.FirstOrDefault(x => x.Key.ToString() == request.ToCurrency).Value;
            }


            await _moneyExchangeRepository.AddEntryToHistory(entry);

            return(moneyExchange);
        }
Exemplo n.º 5
0
        public async Task <ExchangeHistory> RunAsync(ExchangeHistory exchangeHistory)
        {
            if (IsRunning())
            {
                throw new InvalidOperationException();
            }

            Stopwatch.Restart();

            DocumentSession.Advanced.MaxNumberOfRequestsPerSession = int.MaxValue;

            if (!string.IsNullOrEmpty(exchangeHistory.Id))
            {
                exchangeHistory = DocumentSession.Load <ExchangeHistory>(exchangeHistory.Id);
            }

            exchangeHistory.CompletedOnDateTimeUtc = null;

            if (PoeNinjaDataService == null)
            {
                PoeNinjaDataService = new PoeNinjaDataService();
            }

            FetchCurrencyQueue        = new ConcurrentQueue <PoeNinjaDataService.CurrencyType>();
            FetchItemQueue            = new ConcurrentQueue <PoeNinjaDataService.ItemType>();
            FetchCurrencyHistoryQueue = new ConcurrentQueue <IdCurrencyTypePair>();
            FetchItemHistoryQueue     = new ConcurrentQueue <IdItemTypePair>();

            FetchCurrencyQueue.Enqueue(PoeNinjaDataService.CurrencyType.Currency);

            foreach (var itemType in (PoeNinjaDataService.ItemType[])Enum.GetValues(typeof(PoeNinjaDataService.ItemType)))
            {
                FetchItemQueue.Enqueue(itemType);
            }

            var tasks = new Task [NumberOfThreads];

            for (var i = 0; i < NumberOfThreads; i++)
            {
                tasks[i] = FillAndEmptyFetchQueuesAsync(exchangeHistory);
            }

            await Task.WhenAll(tasks);

            exchangeHistory.CompletedOnDateTimeUtc = DateTime.UtcNow;

            if (!string.IsNullOrEmpty(exchangeHistory.Id))
            {
                DocumentSession.SaveChanges();
            }

            return(exchangeHistory);
        }
Exemplo n.º 6
0
 public ExchangeHistoryModel(ExchangeHistory history)
     : base(history)
 {
     if (history != null)
     {
         OptUser_Id     = history.OptUser_Id;
         User_Id        = history.User_Id;
         Application_Id = history.Application_Id;
         ApplyTime      = history.ApplyTime;
         SettlementTime = history.SettlementTime;
         Score          = history.Score;
         Money          = history.Money;
         Cache          = history.Cache;
         Status         = history.Status;
     }
 }
        public double CalculatTheRatio(ExchangeHistory exchangeHistory)
        {
            try
            {
                if (exchangeHistory.FromAmount == 0)
                {
                    return(exchangeHistory.ToAmount / Convert.ToDouble(exchangeHistory.ToCurrency) * Convert.ToDouble(exchangeHistory.FromCurrency) / exchangeHistory.ToAmount);
                }
                else
                {
                    return(exchangeHistory.FromAmount / Convert.ToDouble(exchangeHistory.FromCurrency) * Convert.ToDouble(exchangeHistory.ToCurrency) / exchangeHistory.FromAmount);
                }
            }

            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }
Exemplo n.º 8
0
        private void AddAndSaveExchangeHistory(ExchangeHistory exchangeHistory, ExchangeHistory.ItemData itemData)
        {
            lock (LockObject)
            {
                exchangeHistory.Items.Add(itemData);

                exchangeHistory.LastFetchDateTimeUtc = DateTime.UtcNow;

                if (string.IsNullOrEmpty(exchangeHistory.Id))
                {
                    return;
                }

                if (Stopwatch.ElapsedMilliseconds >= SaveEveryMilliSeconds)
                {
                    Debug.WriteLine("Saved at " + DateTime.UtcNow + " UTC");

                    DocumentSession.SaveChanges();

                    Stopwatch.Restart();
                }
            }
        }
Exemplo n.º 9
0
        public override void Execute()
        {
            ExchangeHistory exchangeHistory = null;

            lock (LockObject)
            {
                exchangeHistory = DocumentSession.Load <ExchangeHistory>(ExchangeHistory.DbId(Date));

                if (exchangeHistory != null)
                {
                    return;
                }

                exchangeHistory = new ExchangeHistory {
                    Date = Date
                };

                DocumentSession.Store(exchangeHistory);

                DocumentSession.SaveChanges();
            }

            new ExchangeHistoryService().Run(exchangeHistory);
        }
        public async Task AddEntryToHistory(ExchangeHistory entry)
        {
            await _moneyExchangeContext.ExchangeHistory.AddAsync(entry);

            await _moneyExchangeContext.SaveChangesAsync();
        }
Exemplo n.º 11
0
        private static void SetupDocumentStore()
        {
            if (DocumentStore != null)
            {
                return;
            }

            DocumentStore = new DocumentStore
            {
                Urls        = new string[] { "http://localhost:8080" /*ConfigurationManager.AppSettings["DatabaseUrl"]*/ },
                Database    = "poe-analyzer" /*ConfigurationManager.AppSettings["DatabaseName"]*/,
                Conventions = new DocumentStoreConventionSetup().Setup(),
            };

            DocumentStore.Conventions.RegisterAsyncIdConvention <ExchangeHistory>((db, item) => Task.FromResult(ExchangeHistory.DbId(item.Date)));

            DocumentStore.Initialize();

            SetupIndexes();
        }
Exemplo n.º 12
0
 public ExchangeHistory AddExchangeHistory(int userId, string token, ExchangeHistory history)
 {
     return(client.AddExchangeHistory(application_Id, userId, token, history));
 }
Exemplo n.º 13
0
        public IActionResult Index()
        {
            var date = DateTime.Today;

            var exchangeHistory = DocumentSession.Load <ExchangeHistory>(ExchangeHistory.DbId(date));

            if (exchangeHistory == null)
            {
                exchangeHistory = new ExchangeHistory
                {
                    Date = date,
                };

                TaskService.ExecuteLater(new FetchAndStoreExchangeHistoryTask(date));
            }

            var model = new ExchangeHistoryViewModel
            {
                Date = exchangeHistory.Date,
                LastFetchDateTimeUtc   = exchangeHistory.LastFetchDateTimeUtc,
                CompletedOnDateTimeUtc = exchangeHistory.CompletedOnDateTimeUtc,
            };

            foreach (var item in exchangeHistory.Items)
            {
                if (item.Type == "Skill Gem")
                {
                    continue;
                }

                var averageValueFirstTwoDays = item.AverageValue(2);

                if (averageValueFirstTwoDays == 0)
                {
                    averageValueFirstTwoDays = 1m;
                }

                //if(averageValueFirstTwoDays > 30)
                //{
                //    continue;
                //}

                var averageValueLastTwoDays = item.AverageValue(exchangeHistory.Items.Count - 3, 2);

                //if(averageValueLastTwoDays < 50)
                //{
                //    continue;
                //}

                var averageValueFirstWeek = item.AverageValue(7);

                if (averageValueFirstWeek == 0)
                {
                    averageValueFirstWeek = 1m;
                }

                var averageValueLastWeek = item.AverageValue(exchangeHistory.Items.Count - 8, 7);

                var i = new ExchangeHistoryViewModel.ItemData
                {
                    Type = item.Type,
                    Name = item.Name,
                    AverageValueFirstTwoDaysString = averageValueFirstTwoDays.ToString("##.##"),
                    AverageValueLastTwoDaysString  = averageValueLastTwoDays.ToString("##.##"),
                    IncreaseFromFirstTwoDays       = (averageValueLastTwoDays / averageValueFirstTwoDays * 100),
                    AverageValueFirstWeekString    = averageValueFirstWeek.ToString("##.##"),
                    AverageValueLastWeekString     = averageValueLastWeek.ToString("##.##"),
                    IncreaseFromFirstWeek          = (averageValueLastWeek / averageValueFirstWeek * 100),
                };

                i.IncreaseFromFirstTwoDaysString = i.IncreaseFromFirstTwoDays.ToString("##.##");
                i.IncreaseFromFirstWeekString    = i.IncreaseFromFirstWeek.ToString("##.##");

                model.Items.Add(i);
            }

            return(View(model));
        }
Exemplo n.º 14
0
        private async Task FillAndEmptyFetchQueuesAsync(ExchangeHistory exchangeHistory)
        {
            PoeNinjaDataService.CurrencyType currencyType;
            PoeNinjaDataService.ItemType     itemType;
            IdCurrencyTypePair idCurrencyTypePair;
            IdItemTypePair     idItemTypePair;

            while (FetchCurrencyQueue.TryDequeue(out currencyType))
            {
                Debug.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId + " fetched currency type: " + currencyType);

                var currencyJsonResponse = await PoeNinjaDataService.FetchCurrencyJsonResponseAsync(currencyType);

                foreach (var details in currencyJsonResponse.CurrencyDetails)
                {
                    FetchCurrencyHistoryQueue.Enqueue(new IdCurrencyTypePair {
                        Id = details.Id, Name = details.Name, CurrencyType = currencyType
                    });
                }

                Thread.Sleep(10);
            }

            while (FetchItemQueue.TryDequeue(out itemType))
            {
                Debug.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId + " fetched item type: " + itemType);

                var itemJsonResponse = await PoeNinjaDataService.FetchItemJsonResponseAsync(itemType);

                foreach (var line in itemJsonResponse.Lines)
                {
                    FetchItemHistoryQueue.Enqueue(new IdItemTypePair {
                        Id = line.Id, Name = line.Name, ItemType = itemType
                    });
                }

                Thread.Sleep(10);
            }

            while (FetchCurrencyHistoryQueue.TryDequeue(out idCurrencyTypePair))
            {
                Debug.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId + " fetched currency id: " + idCurrencyTypePair.Id);

                var currencyHistoryJsonResponse = await PoeNinjaDataService.FetchCurrencyHistoryJsonResponseAsync(idCurrencyTypePair.CurrencyType, idCurrencyTypePair.Id);

                // can be null for certain currency items like Chaos Orb
                if (currencyHistoryJsonResponse != null)
                {
                    var item = new ExchangeHistory.ItemData
                    {
                        Type       = idCurrencyTypePair.CurrencyType.Name(),
                        Name       = idCurrencyTypePair.Name,
                        PoeNinjaId = idCurrencyTypePair.Id,
                    };

                    item.ChaosValuePerDay.AddRange(currencyHistoryJsonResponse.ReceiveCurrencyGraphData.Select(o => o.Value));

                    AddAndSaveExchangeHistory(exchangeHistory, item);
                }

                Thread.Sleep(10);
            }

            while (FetchItemHistoryQueue.TryDequeue(out idItemTypePair))
            {
                Debug.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId + " fetched item id: " + idItemTypePair.Id);

                var itemHistoryJsonResponse = await PoeNinjaDataService.FetchItemHistoryJsonResponseAsync(idItemTypePair.ItemType, idItemTypePair.Id);

                // can be null for certain currency items like Chaos Orb
                if (itemHistoryJsonResponse != null)
                {
                    var item = new ExchangeHistory.ItemData
                    {
                        Type       = idItemTypePair.ItemType.Name(),
                        Name       = idItemTypePair.Name,
                        PoeNinjaId = idItemTypePair.Id,
                    };

                    item.ChaosValuePerDay.AddRange(itemHistoryJsonResponse.Select(o => o.Value));

                    AddAndSaveExchangeHistory(exchangeHistory, item);
                }

                Thread.Sleep(10);
            }
        }
Exemplo n.º 15
0
 public void SaveExchangeHistory(ExchangeHistory exchangeHistory)
 {
     context.ExchangeHistory.Add(exchangeHistory);
     context.SaveChanges();
 }
Exemplo n.º 16
0
 public void SettlementExchange(int userId, string token, ExchangeHistory history)
 {
     client.SettlementExchange(application_Id, userId, token, history);
 }
Exemplo n.º 17
0
 public ExchangeHistory Run(ExchangeHistory exchangeHistory)
 {
     return(RunAsync(exchangeHistory).Result);
 }