Exemple #1
0
        public void Should_Return_the_expected_exchange()
        {
            var effortContext = new BankSystemContext(Effort.DbConnectionFactory.CreateTransient());



            var exchangeCheck = new ExchangeRateModel()
            {
                FromCurrency = (Currency)840,
                ToCurrency   = (Currency)975,
            };

            var exchangeAdd = new ExchangeRate()
            {
                FromCurrency = (Currency)840,
                ToCurrency   = (Currency)975,
                Rate         = 0.5m,
                IsDeleted    = false
            };


            effortContext.ExchangeRates.Add(exchangeAdd);
            effortContext.SaveChanges();

            var sut = new ExchangeRateService(effortContext);

            //Act & Assert
            Assert.IsTrue(sut.GetExchangeRate(exchangeCheck) == 0.5m);
        }
        public ActionResult Create()
        {
            ExchangeRateModel ExchangeRate = new ExchangeRateModel();

            CreateViewBag();
            return(View(ExchangeRate));
        }
        public async Task <List <BalancePrimaryCurrencyModel> > GetUserPrimaryCurrencyBalancesAsync(Guid userId)
        {
            UserCurrency userCurrency = await _userCurrencyRepository.GetPrimaryCurrencyAsync(userId);

            IEnumerable <Balance> balances = await _balanceRepository.GetLatestBalancesAsync(userId);

            List <BalancePrimaryCurrencyModel> result = new List <BalancePrimaryCurrencyModel>();

            if (balances.Count() == 0)
            {
                return(result);
            }

            DateTime effectiveDate = balances.First().EffectiveDate;
            List <ExchangeRateModel> exchangeRates = await _exchangeRateService.GetExchangeRatesAsync(userId, effectiveDate);

            foreach (Balance balance in balances)
            {
                ExchangeRateModel rate = exchangeRates.First(r =>
                                                             r.BaseCurrency.Equals(balance.Asset.Balance.Currency, StringComparison.OrdinalIgnoreCase) &&
                                                             r.CounterCurrency.Equals(userCurrency.Currency, StringComparison.OrdinalIgnoreCase));

                result.Add(new BalancePrimaryCurrencyModel(userCurrency.Currency, balance, rate));
            }

            return(result);
        }
        public ExchangeRateFixture()
        {
            Date       = new DateTime(2018, 08, 06);
            DateString = "06.08.2018";

            ExchangeRateModel = new ExchangeRateModel
            {
                ExchangeRate = new List <ExchangeRate>()
            };

            NotFilteredExchangeRates = new List <ExchangeRate>
            {
                new ExchangeRate {
                    Currency = "CAD"
                },
                new ExchangeRate {
                    Currency = "XAU"
                },
                new ExchangeRate {
                    Currency = "EUR"
                },
                new ExchangeRate {
                    Currency = "SEK"
                }
            };
        }
        public async Task <ExchangeRateModel> InsertOrMergeExchangeRateAsync(ExchangeRateModel entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("ExchangeRates");
            }
            try
            {
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

                var table = GetTable("ExchangeRates");

                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);

                var insertedCustomer = result.Result as ExchangeRateModel;


                return(insertedCustomer);
            }
            catch (StorageException ex)
            {
                _logger.LogError(ex.Message);
                throw ex;
            }
        }
        public static CrossRatesModel ToCrossRates(this ExchangeRateModel @this, string baseCurrency, string targetCurrency)
        {
            if ([email protected](Symbols.EUR, out var baseEURRate))
            {
                return(new CrossRatesModel {
                    Success = false,
                    Error = "Unable to retrieve Base Rate."
                });
            }
            if ([email protected](baseCurrency, out var requestedBaseCurrencyRates))
            {
                return(new CrossRatesModel {
                    Success = false,
                    Error = "Unable to retrieve rates for requested base currency."
                });
            }
            if ([email protected](targetCurrency, out var targetCurrencyRates))
            {
                return(new CrossRatesModel {
                    Success = false,
                    Error = "Unable to retrieve rates for target currency."
                });
            }

            var calculatedRates = targetCurrencyRates / requestedBaseCurrencyRates;

            return(new CrossRatesModel {
                Success = @this.Success,
                BaseCurrency = baseCurrency,
                TargetCurrency = targetCurrency,
                ExchangeRate = calculatedRates,
                Timestamp = DateTimeOffset.FromUnixTimeSeconds(@this.Timestamp),
                Error = [email protected] ? @this.Error.Info : null,
            });
        }
        public async Task <IActionResult> ExchangeStatistics([FromQuery] string baseCurrency, [FromQuery] string targetCurrency, [FromQuery] string[] referenceDates)
        {
            var model = new ExchangeRateModel {
                BaseCurrency = baseCurrency, TargetCurrency = targetCurrency, ReferenceDates = referenceDates
            };

            return(await ExchangeStatistics(model));
        }
Exemple #8
0
        public ExchangeRateProvider()
        {
            using var client = new WebClient();
            var json =
                client.DownloadString("https://v6.exchangerate-api.com/v6/f32774e0581819e2bbf8ced6/latest/USD");

            _exchangeRate = JsonConvert.DeserializeObject <ExchangeRateModel>(json);
        }
 public BalancePrimaryCurrencyModel(string primaryCurrency, Balance balance, ExchangeRateModel exchangeRate)
 {
     AssetName       = balance.Asset.Name;
     PrimaryCurrency = primaryCurrency;
     EffectiveDate   = balance.EffectiveDate;
     Value           = balance.Value;
     Rate            = exchangeRate.Sell;
 }
        public ActionResult Details(int id = 0)
        {
            ExchangeRateModel ExchangeRate = _context.ExchangeRateModel.Find(id);

            if (ExchangeRate == null)
            {
                return(HttpNotFound());
            }
            return(View(ExchangeRate));
        }
Exemple #11
0
        public ActionResult Edit(Guid?id)
        {
            var ExchangeRate = new ExchangeRateModel();

            if (id != null)
            {
                ExchangeRate = Mapper.Map <ExchangeRateDTO, ExchangeRateModel>(_exchangeRateReportService.GetById((Guid)id));
            }
            return(View("Edit", ExchangeRate));
        }
 public YesCommand(ICommandDispatcher commandDispatcher, ExchangeRateModel model, string targetCurrencyUniqueCode)
     : base(commandDispatcher)
 {
     Ensure.NotNull(commandDispatcher, "commandDispatcher");
     Ensure.NotNull(model, "model");
     Ensure.NotNullOrEmpty(targetCurrencyUniqueCode, "targetCurrencyUniqueCode");
     this.commandDispatcher        = commandDispatcher;
     this.model                    = model;
     this.targetCurrencyUniqueCode = targetCurrencyUniqueCode;
 }
        private Task <RateModel>[] GenerateRateFatchers(ExchangeRateModel model)
        {
            var rateFatchers = model.ReferenceDates.Select(m =>
            {
                var exchangeRateReferenceDate = DateTime.ParseExact(m, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
                return(_exchangeRateFetcher.FetchExchangeRate(model.BaseCurrency, model.TargetCurrency, exchangeRateReferenceDate));
            });

            return(rateFatchers.ToArray());
        }
 public ActionResult Create(ExchangeRateModel model)
 {
     if (ModelState.IsValid)
     {
         _context.ExchangeRateModel.Add(model);
         _context.SaveChanges();
         return(RedirectToAction("Index"));
     }
     CreateViewBag(model.CurrencyId);
     return(View(model));
 }
        public ActionResult Edit(int id = 0)
        {
            ExchangeRateModel ExchangeRate = _context.ExchangeRateModel.Find(id);

            if (ExchangeRate == null)
            {
                return(HttpNotFound());
            }
            CreateViewBag(ExchangeRate.CurrencyId);
            return(View(ExchangeRate));
        }
        private decimal SellPrimaryCurrency(
            List <ExchangeRateModel> rates,
            string currency,
            string primaryCurrency,
            decimal value)
        {
            ExchangeRateModel rate = rates
                                     .FirstOrDefault(r => string.Equals(r.BaseCurrency, currency, StringComparison.OrdinalIgnoreCase) &&
                                                     string.Equals(r.CounterCurrency, primaryCurrency, StringComparison.OrdinalIgnoreCase));

            return(value / rate.Sell);
        }
Exemple #17
0
 private void Save(ExchangeRateModel model)
 {
     if (model.ExchangeRateId == Guid.Empty)
     {
         var createCommand = new AddExchangeRateCommand(model.Name, model.Price);
         model.ExchangeRateId = _exchangeRateCommandService.AddExchangeRate(createCommand);
     }
     else
     {
         var updateCommand = new EditExchangeRateCommand(model.ExchangeRateId, model.Name, model.Price);
         _exchangeRateCommandService.EditExchangeRate(updateCommand);
     }
 }
Exemple #18
0
        Task IEventHandler <CurrencyExchangeRateRemoved> .HandleAsync(CurrencyExchangeRateRemoved payload)
        {
            List <ExchangeRateModel> exchangeRates = currencies[payload.TargetUniqueCode];
            ExchangeRateModel        exchangeRate  = exchangeRates.FirstOrDefault(r => r.SourceCurrency == payload.SourceUniqueCode && r.Rate == payload.Rate && r.ValidFrom == payload.ValidFrom);

            if (exchangeRate != null)
            {
                exchangeRates.Remove(exchangeRate);
                exchangeRates.Sort(exchangeRateComparer);
            }

            return(Task.CompletedTask);
        }
Exemple #19
0
        public async Task <ActionResult <bool> > UpdateExchangeRate([FromBody] ExchangeRateModel model)
        {
            UserViewModel user = await GetCurrentUserAsync();

            if (user == null)
            {
                return(HandleUserNotFoundResult());
            }

            await _exchangeRateService.UpdateExchangeRateAsync(model);

            return(true);
        }
Exemple #20
0
        async Task IEventHandler <CurrencyExchangeRateRemoved> .HandleAsync(CurrencyExchangeRateRemoved payload)
        {
            await EnsureUserStorageAsync(payload.UserKey);

            List <ExchangeRateModel> exchangeRates = storage[payload.UserKey].Currencies[payload.TargetUniqueCode];
            ExchangeRateModel        exchangeRate  = exchangeRates.FirstOrDefault(r => r.SourceCurrency == payload.SourceUniqueCode && r.Rate == payload.Rate && r.ValidFrom == payload.ValidFrom);

            if (exchangeRate != null)
            {
                exchangeRates.Remove(exchangeRate);
                exchangeRates.Sort(exchangeRateComparer);
            }
        }
Exemple #21
0
        /// <summary>
        /// Saves this instance.
        /// </summary>
        /// <returns></returns>
        public int Save()
        {
            var exchangeRate = new ExchangeRateModel
            {
                ExchangeRateId   = View.ExchangeRateId,
                Description      = View.Description,
                FromDate         = View.FromDate,
                ToDate           = View.ToDate,
                ExchangeRate     = View.ExchangeRate,
                BudgetSourceCode = View.BudgetSourceCode,
                Inactive         = View.Inactive
            };

            return(View.ExchangeRateId == 0 ? Model.AddExchangeRate(exchangeRate) : Model.UpdateExchangeRate(exchangeRate));
        }
Exemple #22
0
        public string GetExchangeRate()
        {
            //指定來源網頁
            WebClient url = new WebClient();
            //將網頁來源資料暫存到記憶體內
            MemoryStream ms = new MemoryStream(url.DownloadData("http://rate.bot.com.tw/Pages/Static/UIP003.zh-TW.htm"));
            //以台灣銀行為範例

            // 使用預設編碼讀入 HTML
            HtmlDocument doc = new HtmlDocument();

            try
            {
                doc.Load(ms, Encoding.UTF8);
                if (doc.DocumentNode != null)
                {
                    ExchangeRateList = new List <ExchangeRateModel>();
                    ExchangeRateModel Data;
                    // 取得匯率
                    for (int x = 1; x <= 21; x++)
                    {
                        Data = new ExchangeRateModel();
                        Data.CurrencyTypeName     = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/div[1]/main[1]/div[4]/table[1]/tbody[1]/tr[" + x + "]/td[1]/div[1]/div[2]").InnerText.ToString().Replace("\r\n", "").Replace(" ", "");
                        Data.CashBuyExchangeRate  = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/div[1]/main[1]/div[4]/table[1]/tbody[1]/tr[" + x + "]/td[2]").InnerText.ToString().Replace("\r\n", "").Replace(" ", "");
                        Data.CashSellExchangeRate = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/div[1]/main[1]/div[4]/table[1]/tbody[1]/tr[" + x + "]/td[3]").InnerText.ToString().Replace("\r\n", "").Replace(" ", "");
                        Data.SpotBuyExchangeRate  = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/div[1]/main[1]/div[4]/table[1]/tbody[1]/tr[" + x + "]/td[4]").InnerText.ToString().Replace("\r\n", "").Replace(" ", "");
                        Data.SpotSellExchangeRate = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/div[1]/main[1]/div[4]/table[1]/tbody[1]/tr[" + x + "]/td[5]").InnerText.ToString().Replace("\r\n", "").Replace(" ", "");
                        ExchangeRateList.Add(Data);
                    }
                }
                if (ExchangeRateList == null || ExchangeRateList.Count <= 0)
                {
                    return("查無資料");
                }
                return(null);
            }
            catch (Exception ex)
            {
                return("取得匯率錯誤!");
            }
            finally
            {
                //清除資料
                doc = null;
                url = null;
                ms.Close();
            }
        }
Exemple #23
0
        async Task IEventHandler <CurrencyExchangeRateRemoved> .HandleAsync(CurrencyExchangeRateRemoved payload)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                CurrencyEditViewModel viewModel = ViewModel.Items.FirstOrDefault(c => c.UniqueCode == payload.TargetUniqueCode);
                if (viewModel != null)
                {
                    ExchangeRateModel model = viewModel.ExchangeRates
                                              .FirstOrDefault(r => r.SourceCurrency == payload.SourceUniqueCode && r.Rate == payload.Rate && r.ValidFrom == payload.ValidFrom);

                    if (model != null)
                    {
                        viewModel.ExchangeRates.Remove(model);
                        viewModel.ExchangeRates.SortDescending(r => r.ValidFrom);
                    }
                }
            });
        }
Exemple #24
0
        public ActionResult Edit(ExchangeRateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(ModelState.JsonValidation());
            }

            try
            {
                Save(model);
                return(ModelState.JsonValidation(new { Success = true, model.ExchangeRateId }));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Edit_exchangeRate", ex.Message);
            }
            return(ModelState.JsonValidation());
        }
        public JsonResult GetAllExchangeRate(string page, string pageSize, bool latest = false, int appId = -1)
        {
            int total = 0;
            List <ExchangeRateModel> models = new List <ExchangeRateModel>();

            try
            {
                var exchangeRateModels = GetEntities <ExchangeRate>(page, pageSize, out total, GetQueryCondition());
                if (latest)
                {
                    ExchangeRateModel eModel = null;
                    foreach (var eRate in exchangeRateModels)
                    {
                        eModel = new ExchangeRateModel(eRate as ExchangeRate);
                        if (DateTime.Compare(Convert.ToDateTime(eModel.ValidTime), DateTime.Now) > 0)
                        {
                            if (appId == -1 || appId == eModel.Application_Id)
                            {
                                return(Json(new { Success = true, Model = eModel, Total = 1, Message = "" }, JsonRequestBehavior.AllowGet));
                            }
                        }
                    }
                }

                else
                {
                    foreach (var eRate in exchangeRateModels)
                    {
                        ExchangeRateModel eModel = new ExchangeRateModel(eRate as ExchangeRate);
                        if (appId == -1 || appId == eModel.Application_Id)
                        {
                            models.Add(new ExchangeRateModel(eRate as ExchangeRate));
                        }
                    }
                }

                return(Json(new { Success = true, Rows = models.ToArray(), Total = total, Message = "" }, JsonRequestBehavior.AllowGet));
            }
            catch (DatabaseException exception)
            {
                return(Json(new { Success = false, Rows = models.ToArray(), Total = total, Message = exception.Message }, JsonRequestBehavior.AllowGet));
            }
        }
        public async Task <ExchangeRateModel> RetrieveExchangeRateUsingPointQueryAsync(string partitionKey, string rowKey)
        {
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <ExchangeRateModel>(partitionKey, rowKey);

                var table = GetTable("ExchangeRates");

                TableResult result = await table.ExecuteAsync(retrieveOperation);

                ExchangeRateModel exchange = result.Result as ExchangeRateModel;

                return(exchange);
            }
            catch (StorageException ex)
            {
                throw ex;
            }
        }
Exemple #27
0
        public void Should_Return_ArgumentNullException_When_Exchange_is_Null()
        {
            var effortContext = new BankSystemContext(Effort.DbConnectionFactory.CreateTransient());


            var sut = new ExchangeRateService(effortContext);


            var exchange = new ExchangeRateModel()
            {
                FromCurrency = (Currency)840,
                ToCurrency   = (Currency)986
            };



            //Act & Assert
            Assert.ThrowsException <ArgumentException>(() => sut.GetExchangeRate(exchange));
        }
Exemple #28
0
        public void Should_Return_1_When_The_Same_Currency_is_used()
        {
            var effortContext = new BankSystemContext(Effort.DbConnectionFactory.CreateTransient());


            var sut = new ExchangeRateService(effortContext);


            var exchange = new ExchangeRateModel()
            {
                FromCurrency = (Currency)840,
                ToCurrency   = (Currency)840
            };



            //Act & Assert
            Assert.IsTrue(sut.GetExchangeRate(exchange) == 1);
        }
Exemple #29
0
        // TODO: Single user mode for now.
        public Price ToDefault(IKey userKey, IPriceFixed price)
        {
            Ensure.NotNull(price, "price");

            if (price.Amount.Currency == defaultCurrencyUniqueCode)
            {
                return(price.Amount);
            }

            if (currencies.TryGetValue(defaultCurrencyUniqueCode, out List <ExchangeRateModel> rates))
            {
                ExchangeRateModel rate = rates.FirstOrDefault(e => e.SourceCurrency == price.Amount.Currency && e.ValidFrom <= price.When);
                if (rate != null)
                {
                    return(new Price(price.Amount.Value * (decimal)rate.Rate, defaultCurrencyUniqueCode));
                }
            }

            return(new Price(price.Amount.Value, defaultCurrencyUniqueCode));
        }
        Task IEventHandler <CurrencyExchangeRateRemoved> .HandleAsync(CurrencyExchangeRateRemoved payload)
        {
            Log.Debug($"Got '{nameof(CurrencyExchangeRateRemoved)}' with TargetCurrency: '{payload.TargetUniqueCode}'.");
            if (payload.TargetUniqueCode == TargetCurrency)
            {
                ExchangeRateModel model = Models.FirstOrDefault(m => m.SourceCurrency == payload.SourceUniqueCode && m.Rate == payload.Rate && m.ValidFrom == payload.ValidFrom);
                if (model != null)
                {
                    Log.Debug($"Found model.");
                    Models.Remove(model);
                    StateHasChanged();
                }
                else
                {
                    Log.Debug($"Model not found, SourceCurreny: '{payload.SourceUniqueCode}', Rate: '{payload.Rate}', ValidFrom: '{payload.ValidFrom}'.");
                }
            }

            return(Task.CompletedTask);
        }
        /// <summary>
        /// Saves the exchange rates.
        /// </summary>
        /// <param name="exchangeRateList">The exchange rate list.</param>
        /// <returns></returns>
        public ExchangeRateControllerViewModel SaveExchangeRates(IList<ExchangeRateViewModel> exchangeRateList)
        {
            // Load all ExchangeRateModels for the periods in the exchangeRateList (should only be one period, but just in case...)
            var periodList = exchangeRateList.Select(e => (int)e.Period).Distinct().ToList();
            var exchangeRateModels = this._exchangeRatesDao.FindExchangeRatesForPeriods(periodList);

            // Update models with Rate data from the exchangeRateList for each combination of Period and CurrencyCode
            foreach (ExchangeRateViewModel viewModel in exchangeRateList)
            {
                var exchangeRateModel = exchangeRateModels.FirstOrDefault(e => e.Period == viewModel.Period && e.CurrencyCode == viewModel.CurrencyCode);

                if (exchangeRateModel == null)
                {
                    // Create a new ExchangeRateModel to be saved
                    exchangeRateModel = new ExchangeRateModel(viewModel.Period, viewModel.CurrencyCode);

                    exchangeRateModels.Add(exchangeRateModel);
                }

                exchangeRateModel.Rate = viewModel.Rate;
            }

            // Get the return ViewModel
            var returnViewModel = ExchangeRatesControllerPresenter.ValidateExchangeRateModels(exchangeRateModels);

            // If we have no errors, then pass the exchangeRateModels to the DAO for saving
            if (returnViewModel.Errors.Count == 0)
            {
                var errors = this._exchangeRatesDao.UpdateExchangeRates(exchangeRateModels);

                if (errors.Count != 0)
                {
                    // We should pass each error into our error list, but we are instead just re-writting the error
                    returnViewModel.Errors.Add("Could not persist the changes to the datastore.");
                }
            }

            return returnViewModel;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ExchangeRateViewModel"/> class.
 /// </summary>
 /// <param name="exchangeRateModel">The exchange rate model.</param>
 public ExchangeRateViewModel(ExchangeRateModel exchangeRateModel)
 {
     this.Period = exchangeRateModel.Period;
     this.CurrencyCode = exchangeRateModel.CurrencyCode;
     this.Rate = exchangeRateModel.Rate;
 }