コード例 #1
0
        public static ExchangeRateOutputModel GetExchangeRateStatistics(string startDate, string endDate, string baseCurrency, string targetCurrency)
        {
            int retryCounter = 0;

retry:
            try
            {
                ExchangeRateHistoryServiceResponseModel exchangeRateHistory = ExchangeRateService.GetExchangeRateHistory(startDate, endDate, baseCurrency,
                                                                                                                         targetCurrency).Result;

                List <ExchangeRateDateModel> exchangeRateDateModelList = exchangeRateHistory.rates.Select(x => new ExchangeRateDateModel
                {
                    Date = x.Key,
                    Rate = x.Value.ContainsKey(targetCurrency.ToUpper()) ?
                           x.Value.Where(y => y.Key.Equals(targetCurrency, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().Value : 0
                }).OrderBy(z => z.Rate).ToList();

                return(GetCurrencyStatisticsDataLogic(exchangeRateDateModelList));
            }
            catch (Exception exService)
            {
                retryCounter++;
                if (retryCounter <= 2)
                {
                    goto retry;
                }
                else
                {
                    throw exService;
                }
            }
        }
コード例 #2
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);
        }
コード例 #3
0
        public async Task GetForeignCurrencyConversionWhenResponseIsNotNullTest()
        {
            var request = new ForeignCurrencyConversionRequest
            {
                Amount          = 10,
                Currency        = Currency.USD,
                CustomerSegment = CustomerSegment.RETAIL
            };

            _foreignExchangeRatesServiceMock.Setup(
                setup => setup.GetLatestExchangeRateAsync(request.Currency)
                ).ReturnsAsync(ForeignExchangeRatesResponseBuilder.ForeignExchangeRatesResponse(request.Currency));

            _exchangeRatePerSegmentMock.Setup(setup => setup.Value)
            .Returns(ExchangeRatePerSegmentBuilder.ExchangeRatePerSegment);

            var service = new ExchangeRateService(
                _foreignExchangeRatesServiceMock.Object,
                _domainNotificationMock.Object,
                _exchangeRatePerSegmentMock.Object
                );
            var method = await service.GetForeignCurrencyConversionAsync(request);

            Assert.IsType <ExchangeRateResponse>(method);
        }
コード例 #4
0
        protected async override Task OnInitializedAsync()
        {
            if (Id != null)
            {
                Guid invoiceNumber = new Guid(Id);
                ViewTitle = "Edit Invoice";
                Invoice   = await InvoiceService.GetInvoice(invoiceNumber);
            }
            else
            {
                ViewTitle = "New Invoice";
                Invoice   = new Invoice
                {
                    DeliveryDate = DateTime.Now,
                    SettleDate   = DateTime.Now,
                    InvoiceDate  = DateTime.Now,
                    InvoiceVat   = "",
                    Client       = "",
                    Currency     = "",
                    ExchangeRate = ""
                };
            }

            Vats          = (await VatService.GetVats()).ToList();
            Currencies    = (await CurrencyService.GetCurrencies()).ToList();
            ExchangeRates = (await ExchangeRateService.GetExchangeRates()).ToList();
            Clients       = (await ClientService.GetClients()).ToList();
            Mapper.Map(Invoice, InvoiceViewModel);
        }
コード例 #5
0
        public static IExchangeRateService GetExchangeRateService()
        {
            ApplicationContext   context = GetContext();
            IExchangeRateService service = new ExchangeRateService(context, GetAccountService());

            return(service);
        }
コード例 #6
0
        public async Task ShouldReturnARateAndIndicateThatItShouldDivideTheAmountWhenConvertingToAccountCurrency()
        {
            //Arrange
            var wrapperExchangeRateAPI       = NSubstitute.Substitute.For <IWrapperExchangeRateAPI>();
            var cachedExchangeRateRepository = NSubstitute.Substitute.For <ICachedExchangeRateRepository>();

            cachedExchangeRateRepository.GetRate(Arg.Any <DateTime>(), "USD", "EUR").Returns(new System.Collections.Generic.List <CachedExchangeRate>
            {
                new CachedExchangeRate
                {
                    CurrencyCodeFrom = "EUR",
                    CurrencyCodeTo   = "USD",
                    Rate             = 1.18M,
                    RateDate         = DateTime.Today
                }
            });

            var exchangeRateService = new ExchangeRateService(wrapperExchangeRateAPI, cachedExchangeRateRepository);

            //Act
            var result = await exchangeRateService.GetExchangeRate(DateTime.Today, "USD", "EUR");

            //Assert
            result.Should().NotBeNull();
            result.Rate.Should().Be(1.18M);
            result.IsBaseCurrencySameAsTo.Should().BeTrue();
        }
コード例 #7
0
        public async Task <ActionResult <ExchangeRate> > GetExchangeRates()
        {
            IExchangeRateService exchangeRateService = new ExchangeRateService(_settings);
            var result = await exchangeRateService.GetExchangeRates();

            return(Ok(result));
        }
コード例 #8
0
        public async Task ShouldNotCallTheVendorAPIWhenThereIsDataInTheDatabase()
        {
            //Arrange
            var wrapperExchangeRateAPI       = NSubstitute.Substitute.For <IWrapperExchangeRateAPI>();
            var cachedExchangeRateRepository = NSubstitute.Substitute.For <ICachedExchangeRateRepository>();

            cachedExchangeRateRepository.GetRate(Arg.Any <DateTime>(), "USD", "EUR").Returns(new System.Collections.Generic.List <CachedExchangeRate>
            {
                new CachedExchangeRate
                {
                    CurrencyCodeFrom = "EUR",
                    CurrencyCodeTo   = "USD",
                    Rate             = 1.18M,
                    RateDate         = DateTime.Today
                }
            });

            var exchangeRateService = new ExchangeRateService(wrapperExchangeRateAPI, cachedExchangeRateRepository);

            //Act
            await exchangeRateService.GetExchangeRate(DateTime.Today, "USD", "EUR");

            //Assert
            await wrapperExchangeRateAPI.DidNotReceive().GetLatestRates();
        }
コード例 #9
0
        public void Invalid_ExchangeRateService()
        {
            ExchangeRateService.Api = "badconnection.dk";
            var res = ExchangeRateService.GetRates();

            Assert.IsTrue(res == null);
        }
コード例 #10
0
        public void GetExchangeRate_DoesNotThrowException()
        {
            // arrange
            ExchangeRateService svc = new ExchangeRateService();

            // act assert
            Assert.DoesNotThrow(() => svc.GetExchangeRate("EUR", "RUB"));
        }
コード例 #11
0
        public async Task Should_greater_than_zero_When_from_and_to_are_different_base_currency()
        {
            var exchangeRateService = new ExchangeRateService();

            var result = await exchangeRateService.GetRateAsync(Currency.TRY, Currency.GBP);

            Assert.IsTrue(result > 0);
        }
コード例 #12
0
        public async Task Should_greater_than_zero_When_to_is_same_base_currency()
        {
            var exchangeRateService = new ExchangeRateService();

            var result = await exchangeRateService.GetRateAsync(Currency.USD, Currency.EUR);

            Assert.IsTrue(result > 0);
        }
コード例 #13
0
        public void TestGetPreviousExchangeData()
        {
            var date         = new DateTime(2018, 1, 1);
            var fromCurrency = "USD";
            var toCurrency   = "VND";
            var result       = ExchangeRateService.GetPreviousExchangeData(date, fromCurrency, toCurrency);

            Assert.AreEqual(result.Length, 12);
        }
コード例 #14
0
        public ExchangeRateServiceTest()
        {
            this.service = new ExchangeRateService();

            this.listOptions = new ExchangeRateListOptions()
            {
                Limit = 1,
            };
        }
コード例 #15
0
        public async void Refresh()
        {
            Exchange exchangeRates = await ExchangeRateService.GetExchangeRates(BaseCurrency);

            if (exchangeRates != null)
            {
                ExchangeRates = exchangeRates;
            }
        }
コード例 #16
0
        // GET: Profit
        public ActionResult Index()
        {
            List <PL> pls = new List <PL>();

            // get realised profit
            var profits = db.Profits.Include(p => p.Stock);

            foreach (Profit p in profits)
            {
                PL pl = new PL();
                pl.Stock          = p.Stock;
                pl.RealisedAmount = p.Amount * ExchangeRateService.GetRate(p.Stock.Currency);
                pls.Add(pl);
            }

            // get unrealised profit
            var portfolios = db.Portfolios.Include(p => p.Stock);

            foreach (Portfolio p in portfolios)
            {
                PL pl = pls.Where(item => item.Stock.ID == p.StockID).FirstOrDefault();
                if (pl == null)
                {
                    pl       = new PL();
                    pl.Stock = p.Stock;
                    pls.Add(pl);
                }
                pl.UnrealisedAmount = p.PL;
            }

            // add divident
            var dividents = db.Dividents.Include(p => p.Stock);

            foreach (Divident d in dividents)
            {
                PL pl = pls.Where(item => item.Stock.ID == d.StockID).FirstOrDefault();
                if (pl == null)
                {
                    pl       = new PL();
                    pl.Stock = d.Stock;
                    pls.Add(pl);
                }
                pl.RealisedAmount += d.AmountSGD;
            }

            // update total profit/loss
            foreach (PL pl in pls)
            {
                pl.Amount = pl.RealisedAmount + pl.UnrealisedAmount;
            }

            decimal totalAmountSGD = (from od in pls select od.Amount).Sum();

            ViewBag.TotalAmountSGD = totalAmountSGD;

            return(View(pls));
        }
コード例 #17
0
        public void TestGetExchangeDataOfDay()
        {
            var date         = new DateTime(2018, 1, 1);
            var fromCurrency = "USD";
            var toCurrency   = "VND";
            var result       = ExchangeRateService.GetExchangeDataOfDay(date, fromCurrency, toCurrency);

            Assert.AreEqual(result, 22700.883864);
        }
コード例 #18
0
        public async Task <ActionResult> GetExchangeRateHistory(DateTime startDate, DateTime endDate, string baseCurrency, string targetCurrency)

        {
            var _service = new ExchangeRateService();

            var res = await _service.GetExchangeRateHistory(startDate, endDate, baseCurrency, targetCurrency);

            return(Ok(res));
        }
コード例 #19
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ExchangeRateService exchangeRateService =
                       (ExchangeRateService)user.GetService(DfpService.v201802.ExchangeRateService))
            {
                // Set the ID of the exchange rate.
                long exchangeRateId = long.Parse(_T("INSERT_EXCHANGE_RATE_ID_HERE"));

                // Create a statement to get the exchange rate.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :exchangeRateId and refreshRate = :refreshRate").OrderBy("id ASC")
                                                    .Limit(1).AddValue("exchangeRateId", exchangeRateId)
                                                    .AddValue("refreshRate", ExchangeRateRefreshRate.FIXED.ToString());

                try
                {
                    // Get exchange rates by statement.
                    ExchangeRatePage page =
                        exchangeRateService.getExchangeRatesByStatement(
                            statementBuilder.ToStatement());

                    ExchangeRate exchangeRate = page.results[0];

                    // Update the exchange rate value to 1.5.
                    exchangeRate.exchangeRate = 15000000000L;

                    // Update the exchange rate on the server.
                    ExchangeRate[] exchangeRates = exchangeRateService.updateExchangeRates(
                        new ExchangeRate[]
                    {
                        exchangeRate
                    });

                    if (exchangeRates != null)
                    {
                        foreach (ExchangeRate updatedExchangeRate in exchangeRates)
                        {
                            Console.WriteLine(
                                "An exchange rate with ID '{0}', currency code '{1}', " +
                                "direction '{2}' and exchange rate '{3}' was updated.",
                                exchangeRate.id, exchangeRate.currencyCode, exchangeRate.direction,
                                (exchangeRate.exchangeRate / 10000000000f));
                        }
                    }
                    else
                    {
                        Console.WriteLine("No exchange rates updated.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to update exchange rates. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
コード例 #20
0
        public void Should_Return_ArgumentNullException_When_ExchangeModel_is_Null()
        {
            var effortContext = new BankSystemContext(Effort.DbConnectionFactory.CreateTransient());


            var sut = new ExchangeRateService(effortContext);


            Assert.ThrowsException <ArgumentNullException>(() => sut.GetExchangeRate(null));
        }
コード例 #21
0
        public ExchangeRateServiceTest(MockHttpClientFixture mockHttpClientFixture)
            : base(mockHttpClientFixture)
        {
            this.service = new ExchangeRateService();

            this.listOptions = new ExchangeRateListOptions
            {
                Limit = 1,
            };
        }
コード例 #22
0
        public void GetExchangeRate_EURToRUB_ReturnsGreaterThanZero()
        {
            // arrange
            ExchangeRateService svc = new ExchangeRateService();

            // act
            var exchangeRate = svc.GetExchangeRate("EUR", "RUB");

            // assert
            Assert.Greater(exchangeRate, 0);
        }
コード例 #23
0
        private static void Main(string[] args)
        {
            var service = new ExchangeRateService(new FixerApiService(), new CurrencyExchangeRateRepository());

            service.DownloadExchangeRateDataAsync().GetAwaiter().GetResult();
            var result = service.GetExchangeRateAsync(Currency.EUR, new DateRange {
                StartTime = new DateTime(2018, 7, 11)
            }).GetAwaiter().GetResult();

            Console.WriteLine(JsonConvert.SerializeObject(result));
            Console.ReadLine();
        }
コード例 #24
0
        public ExchangeRateServiceTest(
            StripeMockFixture stripeMockFixture,
            MockHttpClientFixture mockHttpClientFixture)
            : base(stripeMockFixture, mockHttpClientFixture)
        {
            this.service = new ExchangeRateService(this.StripeClient);

            this.listOptions = new ExchangeRateListOptions
            {
                Limit = 1,
            };
        }
コード例 #25
0
 public DetailsModel(IOrderService context)
 {
     rates      = ExchangeRateService.GetRates();
     Currencies = new List <SelectListItem>()
     {
         new SelectListItem("USD", "USD"),
         new SelectListItem("DKK", "DKK"),
         new SelectListItem("EUR", "EUR"),
         new SelectListItem("GBP", "GBP"),
         new SelectListItem("CAD", "CAD")
     };
     _context = context;
 }
コード例 #26
0
        public MainPage()
        {
            InitializeComponent();
            currentCurrency     = new Currency();
            exchangeRateService = new ExchangeRateService();
            imageService        = new ImageService();

            MessagingCenter.Subscribe <string, Currency>("MainPage", "FavoriteCurrencySelected", async(sender, arg) => {
                currentCurrency = arg;
                var datePicker  = Main_DatePicker.Date;
                await GetRateForDate(datePicker.Date);
            });
        }
コード例 #27
0
        public void LoadBySystemName_ReturnExpectedValue()
        {
            var provider = new Mock <IExchangeRateProvider>();

            provider.Setup(c => c.SystemName).Returns("sysname");
            var exchangeRateService = new ExchangeRateService(new List <IExchangeRateProvider>()
            {
                provider.Object
            }, _settings);
            var result = exchangeRateService.LoadExchangeRateProviderBySystemName("sysname");

            Assert.IsNotNull(result);
            Assert.AreEqual(result.SystemName, "sysname");
        }
コード例 #28
0
        public async Task GetCurrencyLiveRates_InvokeExpectedMethod()
        {
            var provider = new Mock <IExchangeRateProvider>();

            provider.Setup(c => c.SystemName).Returns("sysname");
            _settings.ActiveExchangeRateProviderSystemName = "sysname";
            var exchangeRateService = new ExchangeRateService(new List <IExchangeRateProvider>()
            {
                provider.Object
            }, _settings);
            await exchangeRateService.GetCurrencyLiveRates("rate");

            provider.Verify(c => c.GetCurrencyLiveRates(It.IsAny <string>()), Times.Once);
        }
コード例 #29
0
        public void ExchangeShouldCalculateCorrectly()
        {
            // Arrange
            var repository = new Mock <IExchangeRateRepository>();

            repository.Setup(x => x.GetExchangeRate(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(0.8m);
            var sut = new ExchangeRateService(repository.Object);

            // Act
            var result = sut.Exchange("AUD", "USD", 100);

            // Assert
            Assert.AreEqual(result, 80m);
        }
コード例 #30
0
        public async Task GetExchangeRateAsync_WhenCurrencySymbolIsPln_ShouldReturnOne()
        {
            // Arrange
            const string plnCurrencySymbol = "PLN";
            var          httpClientMock    = new HttpClientMock();

            var service = new ExchangeRateService(httpClientMock.GetHttpClient(),
                                                  new Mock <ILogger <ExchangeRateService> >().Object);

            // Act
            decimal result = await service.GetExchangeRateAsync(plnCurrencySymbol, _today);

            // Assert
            result.ShouldBe(1m);
        }