private async void UpdateRates(object obj) { IsInProgress = true; try { await Task.Run(() => { foreach (var rate in RatesList) { if (rate.Currency == EnumCurrency.USD) { continue; } rate.Rate = CurrencyConverter.ConvertCurrency(1, rate.Currency.CurrencyToAPIString(), EnumCurrency.USD.CurrencyToAPIString()); } }); } catch (Exception ex) { LogProvider.Log.Error(ex); } IsInProgress = false; }
public void InvalidCurrencyThrowsArgumentException() { //Arrange var transactionCurrency = "EUA"; var mainCurrency = "NGN"; var amount = 1; //Assert Assert.Throws <AggregateException>(() => CurrencyConverter.ConvertCurrency(transactionCurrency, mainCurrency, amount).Wait()); }
public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. Button.AccessibilityIdentifier = "myButton"; Button.TouchUpInside += delegate { var convert = new CurrencyConverter(amountTextField.Text); var result = convert.ConvertCurrency(); resultLabel.Text = result; }; }
private void BtnConvert_Click(object sender, RoutedEventArgs e) { string fromCurrency= lbFromCurrency.Content.ToString(); string toCurrency = lbToCurrency.Content.ToString(); string amount = TbFromCurrency.Text.ToString(); if (Validator.ControlInputConverter(amount)) { double amounten = Convert.ToDouble(amount); CurrencyConverter c = new CurrencyConverter(); string hej = c.ConvertCurrency(fromCurrency, toCurrency, amounten); TbToCurrency.Text = hej; } else { TbToCurrency.Text = "failed to convert"; } }
public async Task <IActionResult> Get(string product, [FromQuery] string targetCurrency) { var pricesresponse = await client.GetAsync("Prices.csv"); pricesresponse.EnsureSuccessStatusCode(); var eratesresponse = await client.GetAsync("ExchangeRates.csv"); eratesresponse.EnsureSuccessStatusCode(); string products = await pricesresponse.Content.ReadAsStringAsync(); string rates = await eratesresponse.Content.ReadAsStringAsync(); PriceDTO p = CurrencyConverter.ConvertCurrency(products, rates, product, targetCurrency); return(Ok(p)); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button>(Resource.Id.myButton); EditText amountEditText = FindViewById <EditText>(Resource.Id.editTextAmount); TextView resultTextView = FindViewById <TextView>(Resource.Id.textViewResult); button.Click += delegate { var convert = new CurrencyConverter(amountEditText.Text); var result = convert.ConvertCurrency(); resultTextView.Text = result; }; }
private decimal ReadStockPrice(Stock stock) { try { string priceString = String.Empty; priceString = WebReader.ReadFromWeb(stock.URL, stock.XPath, stock.CssSelector); priceString = Utility.CleanCurrencyString(priceString); decimal priceDecimal = Utility.GetDecimalFromString(priceString, stock.IsScrapedPriceInPence); if (stock.Currency != CurrencyType.GBP) { priceDecimal = currencyConverter.ConvertCurrency(priceDecimal, stock.Currency, CurrencyType.GBP); } return(priceDecimal); } catch (Exception e) { DailyPortfolioTotalFunction.Logger.Write(e.Message + "\n" + e.StackTrace); return(-1); } }
[TestCase(1000, 3, 4, 115962.1212)] // USD to JPY public void ConvertCurrencyTest(decimal amount, int initialCurrencyId, int targetCurrencyId, decimal expected) { var actual = CurrencyConverter.ConvertCurrency(amount, initialCurrencyId, targetCurrencyId); Assert.AreEqual(Math.Round(actual, 4), expected); }
public async Task <IActionResult> ChangeMainCurrency([FromBody] ChangeMainCurrencyDTO model, string Id) { if (!ModelState.IsValid) { return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = ModelState }))); } if (string.IsNullOrWhiteSpace(Id)) { return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Invalid Id" }))); } var user = await _userManager.FindByIdAsync(Id); if (user == null) { return(NotFound(ResponseMessage.Message("Not found", new { message = $"User with id {Id} was not found" }))); } var userRoles = await _userManager.GetRolesAsync(user); if (userRoles[0] == "Admin") { return(BadRequest(ResponseMessage.Message("Bad request", new { message = "User is an Admin and has no main currency" }))); } var isValid = CurrencyConverter.ValidateCurrencyInput(model.NewMainCurrency); if (!isValid) { return(BadRequest(ResponseMessage.Message("Error", errors: new { message = "Invalid currency input" }))); } UserMainCurrencyDetail mainCurrencyDetails; try { mainCurrencyDetails = await _userMainCurrencyRepository.GetMainCurrencyByUserId(user.Id); } catch (Exception e) { _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Data access error", errors: new { message = "Could not access record from data source" }))); } try { mainCurrencyDetails.MainCurrency = model.NewMainCurrency; await _userMainCurrencyRepository.UpdateMainCurrency(mainCurrencyDetails); } catch (Exception e) { _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to update main currency" }))); } if (userRoles[0] == "Noob") { var wallets = await _walletRepository.GetWalletsByUserId(user.Id); var wallet = wallets.ToList()[0]; var oldCurrency = wallet.WalletCurrency; try { wallet.WalletCurrency = model.NewMainCurrency; decimal amount; try { amount = await CurrencyConverter.ConvertCurrency(oldCurrency, model.NewMainCurrency, wallet.Balance); } catch (Exception e) { return(BadRequest(ResponseMessage.Message("Error", errors: new { message = e.Message }))); } wallet.Balance = amount; await _walletRepository.UpdateWallet(wallet); } catch (Exception e) { mainCurrencyDetails.MainCurrency = oldCurrency; await _userMainCurrencyRepository.UpdateMainCurrency(mainCurrencyDetails); _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to update wallet" }))); } } return(Ok(ResponseMessage.Message("Success", data: new { message = "Updated Successfully!" }))); }
void ConvertCurrency() { CurrencyGetter.GetRate(leftSpinner.SelectedItem.ToString(), rightSpinner.SelectedItem.ToString()); toCurrency.Text = (string.IsNullOrEmpty((fromCurrency.Text)) ? "" : CurrencyConverter.ConvertCurrency((fromCurrency.Text))); }
public async Task <IActionResult> FundWallet([FromBody] FundWalletDTO model, string Id) { if (!ModelState.IsValid) { return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = ModelState }))); } var isValid = CurrencyConverter.ValidateCurrencyInput(model.TransactionCurrency); if (!isValid) { return(BadRequest(ResponseMessage.Message("Error", errors: new { message = "Invalid currency input" }))); } var wallet = await _walletRepository.GetWalletByWalletId(Id); if (wallet == null) { return(NotFound(ResponseMessage.Message("Not found", new { message = $"Wallet with id {Id} was not found" }))); } Transaction transaction = new Transaction { TransactionId = Guid.NewGuid().ToString(), TransactionType = "Credit", WalletId = wallet.WalletId, Amount = model.Amount, TransactionCurrency = model.TransactionCurrency }; try { await _transactionRepository.AddTransaction(transaction); } catch (Exception e) { _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to add transaction" }))); } try { var walletOwner = await _userManager.FindByIdAsync(wallet.ApplicationUserId); if (walletOwner == null) { return(NotFound(ResponseMessage.Message("Not found", new { message = $"User with id {wallet.ApplicationUserId} was not found" }))); } UserMainCurrencyDetail mainCurrencyDetail; try { mainCurrencyDetail = await _userMainCurrencyRepository.GetMainCurrencyByUserId(walletOwner.Id); } catch (Exception e) { await _transactionRepository.DeleteTransaction(transaction); _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Data access error", errors: new { message = "Could not access record from data source" }))); } var mainCurrency = mainCurrencyDetail.MainCurrency; decimal convertedAmount; try { convertedAmount = await CurrencyConverter.ConvertCurrency(model.TransactionCurrency, mainCurrency, model.Amount); } catch (Exception e) { return(BadRequest(ResponseMessage.Message("Error", errors: new { message = e.Message }))); } wallet.Balance += convertedAmount; await _walletRepository.UpdateWallet(wallet); return(Ok(ResponseMessage.Message("Success! Wallet funded"))); } catch (Exception e) { await _transactionRepository.DeleteTransaction(transaction); _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to fund wallet" }))); } }
public async Task <IActionResult> Withdraw([FromBody] WithdrawDTO model) { if (!ModelState.IsValid) { return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = ModelState }))); } var isValid = CurrencyConverter.ValidateCurrencyInput(model.TransactionCurrency); if (!isValid) { return(BadRequest(ResponseMessage.Message("Error", errors: new { message = "Invalid currency input" }))); } var loggedInUser = await _userManager.GetUserAsync(User); if (loggedInUser == null) { return(NotFound(ResponseMessage.Message("Not found", errors: new { message = "Could not access user" }))); } var loggedInUserRoles = await _userManager.GetRolesAsync(loggedInUser); Transaction transaction; if (loggedInUserRoles[0] == "Noob") { var wallets = await _walletRepository.GetWalletsByUserId(loggedInUser.Id); var wallet = wallets.ToList()[0]; transaction = new Transaction { TransactionId = Guid.NewGuid().ToString(), TransactionType = "Debit", WalletId = wallet.WalletId, TransactionStatus = "pending", Amount = model.Amount, TransactionCurrency = model.TransactionCurrency }; try { await _transactionRepository.AddTransaction(transaction); return(Ok(ResponseMessage.Message($"Success! Transaction with id {transaction.TransactionId} created. Withdrawal approval pending"))); } catch (Exception e) { _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to add transaction" }))); } } else { var wallets = await _walletRepository.GetWalletsByUserId(loggedInUser.Id); var wallet = wallets.FirstOrDefault(x => x.WalletCurrency == model.TransactionCurrency); string transactionCurrency = model.TransactionCurrency; if (wallet == null) { try { var mainCurrencyDetail = await _userMainCurrencyRepository.GetMainCurrencyByUserId(loggedInUser.Id); var mainCurrency = mainCurrencyDetail.MainCurrency; wallet = await _walletRepository.GetWalletByWalletCurrency(mainCurrency); transactionCurrency = mainCurrency; } catch (Exception e) { _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Data access error", errors: new { message = "Could not access record from data source" }))); } } transaction = new Transaction { TransactionId = Guid.NewGuid().ToString(), TransactionType = "Debit", WalletId = wallet.WalletId, Amount = model.Amount, TransactionCurrency = model.TransactionCurrency }; try { await _transactionRepository.AddTransaction(transaction); } catch (Exception e) { _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to add transaction" }))); } try { decimal amount; try { amount = await CurrencyConverter.ConvertCurrency(model.TransactionCurrency, transactionCurrency, model.Amount); } catch (Exception e) { return(BadRequest(ResponseMessage.Message("Error", errors: new { message = e.Message }))); } if (wallet.Balance >= amount) { wallet.Balance -= amount; await _walletRepository.UpdateWallet(wallet); return(Ok(ResponseMessage.Message("Success! Withdrawal successful"))); } else { return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Insufficient funds" }))); } } catch (Exception e) { await _transactionRepository.DeleteTransaction(transaction); _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to fund wallet" }))); } } }
public async Task <IActionResult> ApproveTransaction(string Id) { if (string.IsNullOrWhiteSpace(Id)) { return(BadRequest(ResponseMessage.Message("Invalid input", errors: new { message = "Id should not be null or empty or whitespace" }))); } Transaction transaction; try { transaction = await _transactionRepository.GetTransactionByTransactionId(Id); } catch (Exception e) { _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Data access error", errors: new { message = "Could not access record from data source" }))); } if (transaction.TransactionStatus == "approved") { return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Transaction is already approved" }))); } var isValid = CurrencyConverter.ValidateCurrencyInput(transaction.TransactionCurrency); if (!isValid) { return(BadRequest(ResponseMessage.Message("Error", errors: new { message = "Invalid currency input" }))); } Wallet wallet; UserMainCurrencyDetail mainCurrencyDetail; try { wallet = await _walletRepository.GetWalletByWalletId(transaction.WalletId); mainCurrencyDetail = await _userMainCurrencyRepository.GetMainCurrencyByUserId(wallet.ApplicationUserId); } catch (Exception e) { _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Data access error", errors: new { message = "Could not access record from data source" }))); } try { var mainCurrency = mainCurrencyDetail.MainCurrency; decimal convertedAmount; try { convertedAmount = await CurrencyConverter.ConvertCurrency(transaction.TransactionCurrency, mainCurrency, transaction.Amount); } catch (Exception e) { return(BadRequest(ResponseMessage.Message("Error", errors: new { message = e.Message }))); } if (transaction.TransactionType == "Credit") { wallet.Balance += convertedAmount; } else { if (wallet.Balance >= convertedAmount) { wallet.Balance -= convertedAmount; } else { return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Insufficient funds" }))); } } await _walletRepository.UpdateWallet(wallet); try { transaction.TransactionStatus = "approved"; await _transactionRepository.UpdateTransaction(transaction); } catch (Exception) { if (transaction.TransactionType == "Credit") { wallet.Balance -= convertedAmount; } else { wallet.Balance += convertedAmount; } await _walletRepository.UpdateWallet(wallet); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to approve transaction" }))); } } catch (Exception e) { await _transactionRepository.DeleteTransaction(transaction); _logger.LogError(e.Message); return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Failed to fund wallet" }))); } return(Ok(ResponseMessage.Message("Success! Transaction approved"))); }