Exemple #1
0
        public async Task <decimal> GetCurrencyRate(CurrencyConversion currencyConversion)
        {
            var client      = _httpClientFactory.CreateClient();
            var requestBody = GetCurrencyRequestBody(currencyConversion);

            var action  = "urn:getInterestAndExchangeRates";
            var content = new StringContent(requestBody, Encoding.UTF8, "application/soap+xml");

            content.Headers.Add("SOAPAction", action);
            content.Headers.ContentType.Parameters.Add(
                new NameValueHeaderValue("action", $"\"{action}\""));

            try
            {
                var response = await client.PostAsync(_sweaUrl, content);

                //Unfortunately the model classed created from the WSDL can not be used in the serialization.
                //Maybe the WSDL is not aligned with the actual response from the api?
                var stringResponse = await response.Content.ReadAsStringAsync();

                var xmlResponse = new XmlDocument();
                xmlResponse.LoadXml(stringResponse);

                var namespaceManager = new XmlNamespaceManager(xmlResponse.NameTable);
                namespaceManager.AddNamespace("ns0", _sweaSchemeSource);

                var currencyRateAsExponentialValue = xmlResponse.SelectSingleNode("//resultrows/value", namespaceManager).InnerXml.Replace('.', ',');

                return(decimal.Parse(currencyRateAsExponentialValue, NumberStyles.Float));
            }
            catch (Exception e)
            {
                throw new SweaCurrencyConversionException("Could not fetch currency rates", e);
            }
        }
Exemple #2
0
        private string GetCurrencyRequestBody(CurrencyConversion currencyConversion)
        {
            var serieshelper = new SweaSeriesHelper();

            return($@"<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:xsd=""{_sweaSchemeSource}"">
                     <soap:Header/>
                     <soap:Body>
                      <xsd:getInterestAndExchangeRates>
                       <searchRequestParameters>
                        <aggregateMethod>D</aggregateMethod>
                        <datefrom>{currencyConversion.ExchangeRateDate.ToString(_dateFormat)}</datefrom>
                        <dateto>{currencyConversion.ExchangeRateDate.ToString(_dateFormat)}</dateto>
                        <languageid>en</languageid>
                        <min>false</min>
                        <avg>true</avg>
                        <max>false</max>
                        <ultimo>false</ultimo>			
                        <searchGroupSeries>		
                                        <groupid>130</groupid>			
                         <seriesid>{serieshelper.GetSeriesId(currencyConversion.InputCurrency, currencyConversion.OutputCurrency)}</seriesid>
                        </searchGroupSeries>
                       </searchRequestParameters>
                      </xsd:getInterestAndExchangeRates>
                     </soap:Body>
                    </soap:Envelope>");
        }
        public decimal Convert(decimal inputAmount, CurrencyType convertFrom, CurrencyType convertTo)
        {
            if (inputAmount == 0)
            {
                throw new ArgumentOutOfRangeException("input");
            }
            if (convertTo == convertFrom)
            {
                throw new ArgumentException("convertion from and to are the same");
            }

            var     convertionRates = GetCurrencyConversions();
            decimal convertedAmount = 0;

            CurrencyConversion currencyConvertion = new CurrencyConversion();

            if (convertionRates.Any(r => r.CurrencyTypeFrom == convertFrom && r.CurrencyTypeTo == r.CurrencyTypeTo))
            {
                currencyConvertion = convertionRates.FirstOrDefault((r => r.CurrencyTypeFrom == convertFrom && r.CurrencyTypeTo == convertTo));
            }

            if (currencyConvertion.Rate > 0)
            {
                convertedAmount = inputAmount * currencyConvertion.Rate;
            }

            return(convertedAmount);
        }
Exemple #4
0
        /// <summary>
        /// Adjusts value for currency
        /// </summary>
        /// <param name="originalValue">Original value</param>
        /// <param name="currencyString">Currency string</param>
        /// <returns>Return adjusted value for currency</returns>
        public double AdjustValueForCurrency(double originalValue, string currencyString)
        {
            CurrencyConversion currencyConversion = this.CurrencyConversion;

            if (currencyConversion == null)
            {
                return(originalValue);
            }

            int currencyCode     = currencyString.ToInt();
            int analysisCurrency = this.Settings.CurrencyCode;

            if (currencyCode == 0 || currencyCode == analysisCurrency || analysisCurrency == 0)
            {
                return(originalValue);
            }

            var conversionRate = currencyConversion.ExchangeRateFromCodeToCode(currencyCode, analysisCurrency);

            if (conversionRate == 0 || conversionRate == 1)
            {
                return(originalValue);
            }

            return(originalValue / conversionRate);
        }
Exemple #5
0
        public async Task <IActionResult> Edit(Currency id, [Bind("Currency,Buy,AmountInNativeCurrencyPerUnit")] CurrencyConversion currencyConversion)
        {
            if (id != currencyConversion.Currency)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(currencyConversion);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CurrencyConversionExists(currencyConversion.Currency))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(currencyConversion));
        }
 private CurrencyConversion CalculateConversionForAmount(CurrencyConversion singleMoneyUnitConversion, decimal amount)
 {
     return(new CurrencyConversion(
                singleMoneyUnitConversion.From,
                singleMoneyUnitConversion.ToCurrencies.Select(CurrencyRateFor(amount)),
                singleMoneyUnitConversion.OnDate));
 }
Exemple #7
0
        public void CurrencyConversion_From_USD_To_MXN_Fails()
        {
            var result = CurrencyConversion.Convert(
                42,
                CurrencyType.USD,
                CurrencyType.MXN);

            Assert.IsTrue(result.IsError);
        }
Exemple #8
0
        public void CurrencyConversion_From_USD_To_CAD_Succeeds()
        {
            var result = CurrencyConversion.Convert(
                42,
                CurrencyType.USD,
                CurrencyType.CAD)
                         .AssertOk();

            Assert.AreEqual(84, result.Amount);
        }
Exemple #9
0
        public void CurrencyConversion_From_CAD_To_MXN_Succeeds()
        {
            var result = CurrencyConversion.Convert(
                42,
                CurrencyType.CAD,
                CurrencyType.MXN)
                         .AssertOk();

            Assert.AreEqual(420, result.Amount);
        }
Exemple #10
0
        public async Task Convert(string amountInput, string fromInput, string ignoreThis, string toInput)
        {
            bool validFrom   = Enum.TryParse(fromInput.ToUpper(), out CoinType from);
            bool validTo     = Enum.TryParse(toInput.ToUpper(), out CoinType to);
            bool validAmount = double.TryParse(amountInput, out double amount);

            if (!validFrom)
            {
                await ReplyAsync(string.Format("'{0}' is not a valid currency", fromInput));
            }
            else if (!validTo)
            {
                await ReplyAsync(string.Format("'{0}' is not a valid currency", toInput));
            }
            else if (!validAmount || amount < 0)
            {
                await ReplyAsync("The amount you gave is invalid");
            }
            else if (amount % 1 != 0)
            {
                await ReplyAsync("Please use whole numbers, you can't have half a coin. Convert to smaller coin values if you need to");
            }
            else if (amount >= 1000000000000000)
            {
                await ReplyAsync("The amount you gave is too large");
            }
            else
            {
                ConversionResult result = CurrencyConversion.Convert(from, to, amount);

                string reply = string.Format("{0:n0} {1} is {2:n0} {3}", amount, from.ToTileString(), result.result, result.resultCurrency.ToTileString());

                List <string> remainders = new List <string>();

                for (int i = result.remainders.Length - 1; i >= 0; i--)
                {
                    if (result.remainders[i] != 0)
                    {
                        remainders.Add(string.Format("{0:n0} {1}", result.remainders[i], ((CoinType)i).ToTileString()));
                    }
                }

                if (remainders.Count > 0)
                {
                    for (int i = 0; i < remainders.Count - 1; i++)
                    {
                        reply += ", " + remainders[i];
                    }

                    reply += " and " + remainders[remainders.Count - 1];
                }

                await ReplyAsync(reply);
            }
        }
 public CurrencyConversionForm()
 {
     InitializeComponent();
     currencyConversion = new CurrencyConversion();
     currencyRates      = currencyConversion.GetCurrencyRates();
     for (int i = 0; i < currencyRates.Length; i++)
     {
         SourceCurrencyBox.Items.Add(currencyRates[i].currencyName);
         DestinationCurrencyBox.Items.Add(currencyRates[i].currencyName);
     }
 }
Exemple #12
0
 private void AddRates(CurrencyDto dto, CurrencyConversion from, IEnumerable<CurrencyConversion> toCurrencies)
 {
     var rates = dto.CurrencyRate;
     foreach (var to in toCurrencies)
     {
         var rate = (double)(from.Factor / to.Factor);
         var fromRow = GetCurrency(dto, from.Currency);
         var toRow = GetCurrency(dto, to.Currency);
         rates.AddCurrencyRateRow(rate, rate, DateTime.Now, fromRow, toRow, DateTime.Now);
     }
 }
Exemple #13
0
 public CurrencyToolViewModel()
 {
     InputAmount      = 1000;
     CurrencyTypeFrom = CurrencyType.GBP;
     CurrencyTypeTo   = CurrencyType.USD;
     CurrentRate      = new CurrencyConversion()
     {
         CurrencyTypeFrom = CurrencyType.GBP,
         CurrencyTypeTo   = CurrencyType.USD,
         Rate             = 1.7277m
     };
 }
Exemple #14
0
        private void AddRates(CurrencyDto dto, CurrencyConversion from, IEnumerable <CurrencyConversion> toCurrencies)
        {
            var rates = dto.CurrencyRate;

            foreach (var to in toCurrencies)
            {
                var rate    = (double)(from.Factor / to.Factor);
                var fromRow = GetCurrency(dto, from.Currency);
                var toRow   = GetCurrency(dto, to.Currency);
                rates.AddCurrencyRateRow(rate, rate, DateTime.Now, fromRow, toRow, DateTime.Now);
            }
        }
Exemple #15
0
        public void Creation()
        {
            // arrange

            // act
            var rate = new CurrencyConversion("USD", "EUR", 0.85M);

            // assert
            Assert.NotNull(rate);
            Assert.Equal("USD", rate.ConvertFrom);
            Assert.Equal("EUR", rate.ConvertTo);
            Assert.Equal(0.85M, rate.Rate);
        }
        public async Task <decimal> GetConvertedAmountAsync(CurrencyConversion conversion)
        {
            decimal exchangeRate = Convert.ToDecimal(await GetExchangeRateAsync(
                                                         conversion.CurrencyTypeFrom, conversion.CurrencyTypeTo));

            decimal convertedAmount = conversion.CurrencyTypeTo switch
            {
                Currency.BulgarianLev => decimal.Round(conversion.AmountToConvert / exchangeRate, 2),
                _ => decimal.Round(conversion.AmountToConvert * exchangeRate, 2),
            };

            return(convertedAmount);
        }
        public CurrencyConversionViewModel(CurrencyConversion currencyConversion, decimal amount)
        {
            FromCurrency = new CurrencyViewModel
            {
                Symbol = currencyConversion.From.ToString(),
                Amount = amount
            };

            Date = currencyConversion.OnDate;

            Rates = currencyConversion
                    .ToCurrencies
                    .Select(ToCurrencyViewModel);
        }
Exemple #18
0
        public Money Convert(Money money, string destinationCurrencyISOName)
        {
            Argument.NotEmpty(destinationCurrencyISOName, "destinationCurrencyISOName");

            if (money.Currency.ISOName == destinationCurrencyISOName)
            {
                return new Money(money.Currency, money.Amount);
            }
            var conversion = new CurrencyConversion(money.Currency.ISOName, destinationCurrencyISOName);
            var converter = _converterFactory.Create(conversion);
            Currency resultingCurrency;
            var convertedAmount = converter.Convert(conversion, money.Amount, out resultingCurrency);
            return new Money(resultingCurrency, convertedAmount);
        }
Exemple #19
0
        public async Task <CurrencyConversion> Convert(CurrencyConversion currencyConversion)
        {
            var currencyRate = await _currencyService.GetCurrencyRate(currencyConversion);

            if (currencyConversion.InputCurrency == Currency.SEK)
            {
                currencyConversion.ConvertedAmount = currencyConversion.Amount / currencyRate;
            }
            else
            {
                currencyConversion.ConvertedAmount = currencyConversion.Amount * currencyRate;
            }

            return(currencyConversion);
        }
 public CurrencyConverter Create(CurrencyConversion conversion)
 {
     var rates = _exchangeRateRepository.GetActualForExchange(conversion.ExchangeRateKey);
     if (rates.Count == 0)
     {
         var message = string.Format("Conversion {0} is not supported.", conversion);
         throw new NotSupportedException(message);
     }
     if (rates.Count == 1)
     {
         return rates[0].Converter;
     }
     var rate = rates.OrderBy(x => _settings.GetPriority(x.Base.ISOName)).First();
     return rate.Converter;
 }
Exemple #21
0
 internal decimal Convert(CurrencyConversion conversion, decimal amount, out Currency resultingCurrency)
 {
     if (_exchangeRate.Key != conversion.ExchangeRateKey)
     {
         var message = string.Format("Conversion {0} is not supported.", conversion);
         throw new NotSupportedException(message);
     }
     var convertedAmount = _exchangeRate.Base.ISOName == conversion.From
         ? ConvertFromBase(amount)
         : ConvertFromForeign(amount);
     resultingCurrency = _exchangeRate.Base.ISOName == conversion.From
         ? _exchangeRate.Foreign
         : _exchangeRate.Base;
     return convertedAmount;
 }
        public async Task <IActionResult> Convert([FromBody] CurrencyConversion conversion)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    string baseURL = "https://openexchangerates.org/api/latest.json";
                    string appId   = "803b49d404bb4dc9baf6091b9b97de8a";

                    HttpResponseMessage response = client.GetAsync(
                        baseURL + $"?app_id={appId}&symbols={conversion.InputCurrency},{conversion.OutputCurrency}").Result;

                    response.EnsureSuccessStatusCode();
                    string content = response.Content.ReadAsStringAsync().Result;

                    var resultado = JsonConvert.DeserializeObject <OpenExchangeRatesResponse>(content);

                    decimal inCurrencyValue  = 0;
                    decimal outCurrencyValue = 0;

                    resultado.Rates.TryGetValue(conversion.InputCurrency, out inCurrencyValue);
                    resultado.Rates.TryGetValue(conversion.OutputCurrency, out outCurrencyValue);

                    var outputValue = decimal.Round((conversion.InputValue / inCurrencyValue * outCurrencyValue), 2);

                    await CreateRecord(new CurrencyConversion
                    {
                        Id             = Guid.NewGuid(),
                        InputValue     = decimal.Round(conversion.InputValue, 2),
                        InputCurrency  = conversion.InputCurrency,
                        OutputCurrency = conversion.OutputCurrency,
                        OutputValue    = outputValue,
                        ConvertedAt    = DateTime.Now
                    });

                    return(Ok(outputValue));
                }
            }
            catch (System.Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Failure converting."));
            }
        }
Exemple #23
0
        public CurrencyConverter Create(CurrencyConversion conversion)
        {
            var rates = _exchangeRateRepository.GetActualForExchange(conversion.ExchangeRateKey);

            if (rates.Count == 0)
            {
                var message = string.Format("Conversion {0} is not supported.", conversion);
                throw new NotSupportedException(message);
            }
            if (rates.Count == 1)
            {
                return(rates[0].Converter);
            }
            var rate = rates.OrderBy(x => _settings.GetPriority(x.Base.ISOName)).First();

            return(rate.Converter);
        }
    public static void Main()
    {
        CurrencyConversion calculator = new CurrencyConversion();

        Dictionary <string, decimal> exchangeRates = calculator.getExchangeRates();


        Console.WriteLine("What is the currency you are exchanging from? (? -> USD). Enter 'list' to display list of currencies.");
        string currencyEntry = Console.ReadLine();

        while (!exchangeRates.ContainsKey(currencyEntry))
        {
            if (currencyEntry == "list")
            {
                Console.WriteLine("Available currencies: ");
                foreach (KeyValuePair <string, decimal> item in exchangeRates)
                {
                    Console.Write(item.Key + " ");
                }
            }
            else
            {
                Console.WriteLine("Please enter a valid currency.");
            }
            Console.WriteLine("What is the currency you are exchanging from? (? -> USD). Enter 'list' to display list of currencies.");
            currencyEntry = Console.ReadLine();
        }

        Console.WriteLine("How much " + currencyEntry + " are you exchanging?");
        string  moneyEntry = Console.ReadLine();
        decimal money;

        while (!decimal.TryParse(moneyEntry, out money) || money <= 0 || (Decimal.Round(money, 2) != money))
        {
            Console.WriteLine("Must be a valid amount of money greater than 0. Enter amount to exchange: ");
            moneyEntry = Console.ReadLine();
        }

        decimal rate = exchangeRates[currencyEntry];

        decimal exchangedMoney = calculator.exchange(money, rate);

        Console.WriteLine(money + " " + currencyEntry + " at an exchange rate of " + rate + " is " + exchangedMoney + " USD.");
    }
        public void TestCurrencyConversionControllerUpdateModelIdLessThanZeroOrZeroReturnsBadResultObjectFail()
        {
            CurrencyConversion currencyConversion = new CurrencyConversion
            {
                SourceCurrencyId = 1,
                TargetCurrencyId = 2,
                BuyingRate       = 12.22,
                SellingRate      = 13,
                IsActive         = true,
                IsDeleted        = false
            };

            currencyConversionMock.Setup(x => x.UpdateEntity(currencyConversion)).Returns(Task.FromResult(new BaseResult <bool>()
            {
                Result = true, IsError = false
            }));

            var result = mockCurrencyConversionController.Update(currencyConversion).Result;

            Assert.That(result is BadRequestObjectResult);
        }
        private async Task <IActionResult> CreateRecord(CurrencyConversion conversion)
        {
            try
            {
                using (var db = new SQLiteDBContext())
                {
                    await db.CurrencyConversions.AddAsync(conversion);

                    if (await db.SaveChangesAsync() > 0)
                    {
                        return(Ok());
                    }
                    ;
                }

                return(BadRequest());
            }
            catch (System.Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Failure creating record."));
            }
        }
Exemple #27
0
        public async Task Given_CurrencyRate_When_ConvertingFromEurToSek_Then_ConvertedAmountIsCorrect()
        {
            //Arrange
            var currencyService = new Mock <ICurrencyService>();
            var currencyRate    = 10.3183M;

            currencyService.Setup(p => p.GetCurrencyRate(It.IsAny <CurrencyConversion>())).ReturnsAsync(currencyRate);

            var currencyConversionService = new CurrencyConversionService(currencyService.Object);
            var currencyConversion        = new CurrencyConversion()
            {
                OutputCurrency   = Currency.SEK,
                InputCurrency    = Currency.EUR,
                Amount           = 100,
                ExchangeRateDate = new DateTime(2020, 08, 19)
            };

            //Act
            currencyConversion = await currencyConversionService.Convert(currencyConversion);

            //Assert
            Assert.AreEqual(1031.83M, decimal.Round(currencyConversion.ConvertedAmount, 2));
        }
Exemple #28
0
 public void init()
 {
     currencyConversion = new CurrencyConversion();
     AddActionClassesToList(currencyConversion);
 }
Exemple #29
0
 /// <summary>
 /// Currencies the conversion did fail with error.
 /// </summary>
 /// <param name="currencyConversion">The currency conversion.</param>
 /// <param name="error">The error.</param>
 public void CurrencyConversionDidFailWithError(CurrencyConversion currencyConversion, Exception error)
 {
     this.TheDelegate.PricingDidFailWithError(this, error);
 }
Exemple #30
0
        private static ConversionRate Parse(DataRow row)
        {
            var conversion = new CurrencyConversion("BYR", (string)row[Columns.ISOName]);

            return(new ConversionRate(conversion, (decimal)row[Columns.Rate]));
        }
Exemple #31
0
 /// <summary>
 /// Currencies the conversion did finish with result.
 /// </summary>
 /// <param name="currencyConversion">The currency conversion.</param>
 /// <param name="result">The result.</param>
 public void CurrencyConversionDidFinishWithResult(CurrencyConversion currencyConversion, object result)
 {
     this.HandleCurrencyResult();
 }
 public IActionResult Convert(CurrencyConversion model)
 {
     model.ConvertedAmount = currencyConverter.convert(model.ConvertTo, model.Amount);
     return(View("Index", model));
 }
        public IActionResult Index()
        {
            CurrencyConversion converter = new CurrencyConversion();

            return(View(converter));
        }