Created
November 6, 2018 22:23
-
-
Save hotdang-ca/e7e1f34b60cb0c7d2ac8ea40bd906de9 to your computer and use it in GitHub Desktop.
C# Service Wrapper around FreeCurrencyConverterApi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Net; | |
using System.Web.Script.Serialization; | |
namespace App.Service.Services | |
{ | |
public class FreeCurrencyConverterService : IFreeCurrencyConverterService | |
{ | |
private readonly String BASE_URI = "http://free.currencyconverterapi.com"; | |
private readonly String API_VERSION = "v5"; | |
public FreeCurrencyConverterService() {} | |
public Decimal GetCurrencyExchange(String localCurrency, String foreignCurrency) | |
{ | |
var code = $"{localCurrency}_{foreignCurrency}"; | |
var newRate = FetchSerializedData(code); | |
return newRate; | |
} | |
private Decimal FetchSerializedData(String code) | |
{ | |
var url = $"{BASE_URI}/api/{API_VERSION}/convert?q={code}&compact=y"; | |
var webClient = new WebClient(); | |
var jsonData = String.Empty; | |
var conversionRate = 1.0m; | |
try | |
{ | |
jsonData = webClient.DownloadString(url); | |
var jsonObject = new JavaScriptSerializer().Deserialize<Dictionary<string, Dictionary<string, decimal>>>(jsonData); | |
var result = jsonObject[code]; | |
conversionRate = result["val"]; | |
} | |
catch (Exception) { } | |
return conversionRate; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment