Home > Software design >  How to Set Salary Currency Exchange for one currency to another using API?
How to Set Salary Currency Exchange for one currency to another using API?

Time:12-12

I'm really confused right now. I'm not sure how to implement correctly Currency Exchange from one Currency to another using asp.net core, using this API: Currency Exchange-API What I'm trying to do is when user input Salary it should exchange that value from foreign currency in EUR and USD currency.

This provided API is very weird, I mean I don't have much experience with API's. With SDK's yes but with API's unfortunately not much. So here is my Code so hopefully someone will know what I need to do to Implement this API right.

using System.ComponentModel.DataAnnotations;
using System.Security.AccessControl;

namespace Test_Project_Web.Models
{
    public class EmployeeCategory
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public double GrossSalary_ForeignCurrency { get; set; }
        [Required]
        public double NetSalary_EUR { get; set; }
        public double NetSalary_USD { get; set; }
using Newtonsoft.Json;
namespace Test_Project_Web.Models
{
    public class ExchangeRate_API
    {
        class Rates
        {
            public static bool Import()
            {
                try
                {
                    String URLString = "https://v6.exchangerate-api.com/v6/YOUR-API-KEY/latest/USD";
                    using (var webClient = new System.Net.WebClient())
                    {
                        var json = webClient.DownloadString(URLString);
                        API_Obj Test = JsonConvert.DeserializeObject<API_Obj>(json);
                        return true;
                    }
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        public class API_Obj
        {
            public string ? result { get; set; }
            public string ? documentation { get; set; }
            public string ? terms_of_use { get; set; }
            public string ? time_last_update_unix { get; set; }
            public string ? time_last_update_utc { get; set; }
            public string ? time_next_update_unix { get; set; }
            public string ? time_next_update_utc { get; set; }
            public string ? base_code { get; set; }
            public ConversionRate ? conversion_rates { get; set; }
        }

        public class ConversionRate
        {
            public double EUR { get; set; }
            public double USD { get; set; }
        }

 
    }
}
using Microsoft.AspNetCore.Mvc;
using Test_Project_Web.Data;
using Test_Project_Web.Models;

namespace Test_Project_Web.Controllers
{
    public class EmployeeCategoryController : Controller
    {
        private readonly ApplicationDbContext _db;

        
        public EmployeeCategoryController(ApplicationDbContext db)
        {
            _db = db;
        }

        public IActionResult Index()
        {
            IEnumerable<EmployeeCategory> objEmployeeCategoryList = _db.EmployeeCategories;

            return View(objEmployeeCategoryList);
        }

        //GET
        public IActionResult Create()
        {
            return View();
        }

        //POST
        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public IActionResult Create(EmployeeCategory obj)
        {
            if (ModelState.IsValid)
            {   
            _db.EmployeeCategories.Add(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");
            }
            return View(obj);
        }
    }
}

CodePudding user response:

To use the data from the Currency Exchange API, you could wrap the API call in a service provider:

public class ExchangeRateProvider
{
    public ConversionRate? Rate { get; private set; }

    private const string ApiUrl = "https://v6.exchangerate-api.com/v6/<API-KEY>/latest/{0}";

    public ExchangeRateProvider()
    {
    }

    public async Task UpdateRatesAsync(string foreignCurrency = "USD")
    {
      try
      {
        using var httpClient = new HttpClient();
        API_Obj? jsonResponse = await httpClient.GetFromJsonAsync<API_Obj>(string.Format(ApiUrl, foreignCurrency));
        Rate = jsonResponse?.conversion_rates;
      }
      catch(Exception ex)
      {
         throw new Exception("Unable to download Exchange API data.", ex);
      }
    }

    public class API_Obj
    {
        public string? result { get; set; }
        public string? documentation { get; set; }
        public string? terms_of_use { get; set; }
        public long? time_last_update_unix { get; set; }
        public string? time_last_update_utc { get; set; }
        public long? time_next_update_unix { get; set; }
        public string? time_next_update_utc { get; set; }
        public string? base_code { get; set; }
        public ConversionRate? conversion_rates { get; set; }
    }

    public class ConversionRate
    {
       public double EUR { get; set; }
       public double USD { get; set; }
    }
}

To use this provider, you first set up the dependency injection in the Program.cs or Startup.cs,

builder.Services.AddRazorPages();
builder.Services.AddSingleton<ExchangeRateProvider>();

Now, inject this service into your controller or other controllers where you want to use it,

public EmployeeCategoryController(ApplicationDbContext db, ExchangeRateProvider exchangeRateProvider)
{
      _db = db;
      _exchangeRateProvider = exchangeRateProvider;
}

The provider can be called like this,

public async Task<IActionResult> Create(EmployeeCategory obj)
{
   //your other code

   var foreignCurrency = "GBP";
   await _exchangeProvider.UpdateRatesAsync(foreignCurrency);
   var rates = _exchangeProvider.Rate;

   var grossSalary = 100; //salary in GBP
   var usdSalary = rates.USD * grossSalary;
   var eurSalary = rates.EUR * grossSalary;

   //check for null or do some calculation with this.
}

I hope this gives you some ideas. There are many other ways to do this depending on your project requirements, e.g. do you want to cache the rate or do you need it always to be the latest? my code is just a POC.

CodePudding user response:

Refactored POC Code:

To use the data from the Currency Exchange API, you could wrap the API call in a service provider:

public class ExchangeRateProvider
{
    public ConversionRate? Rate { get; private set; }

    private const string ApiUrl = "https://v6.exchangerate-api.com/v6/<API-KEY>/latest/GBP"; //Currency you want to exchange salary in this example GBP. Otherwise Will return 404 error if you put ".../latest/{0}"

    public ExchangeRateProvider()
    {
    }

    public async Task UpdateRatesAsync(string foreignCurrency = "USD", string foreignCurrency_02 = "EUR") //Update Rates for USD & EUR
    {
      try
      {
        using var httpClient = new HttpClient();
        API_Obj? jsonResponse = await httpClient.GetFromJsonAsync<API_Obj>(string.Format(ApiUrl, foreignCurrency, foreignCurrency_02));
        Rate = jsonResponse?.conversion_rates;
      }
      catch(Exception ex)
      {
         throw new Exception("Unable to download Exchange API data.", ex);
      }
    }

    public class API_Obj
    {
        public string? result { get; set; }
        public string? documentation { get; set; }
        public string? terms_of_use { get; set; }
        public long? time_last_update_unix { get; set; }
        public string? time_last_update_utc { get; set; }
        public long? time_next_update_unix { get; set; }
        public string? time_next_update_utc { get; set; }
        public string? base_code { get; set; }
        public ConversionRate? conversion_rates { get; set; }
    }

    public class ConversionRate
    {
       public double EUR { get; set; }
       public double USD { get; set; }
    }
}

The provider can be called like this,

public async Task<IActionResult> Create(EmployeeCategory obj)
{
   if(ModelState.IsValid)
   {

   //your other code

   var foreignCurrency = "EUR";
   var foreignCurrency_02 = "USD";
   await _exchangeRateProvider.UpdateRatesAsync(foreignCurrency);                
   await _exchangeRateProvider.UpdateRatesAsync(foreignCurrency_02);
   var rates = _exchangeRateProvider.Rate;

   var grossSalary = GrossSalary_GBP; //salary in GBP
   var usdSalary = rates.USD * grossSalary;
   var eurSalary = rates.EUR * grossSalary;

   obj.NetSalary_USD = eurSalary;
   obj.NetSalary_EUR = usdSalary;
   obj.NetSalary_GBP = GrossSalary_GBP;

   _db.EmployeeCategories.Add(obj);
   _db.SaveChanges();
   return RedirectToAction("Index");
   }
   return View(obj);
}

  • Related