Skip to content

Instantly share code, notes, and snippets.

@hotdang-ca
Created November 6, 2018 22:23
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hotdang-ca/e7e1f34b60cb0c7d2ac8ea40bd906de9 to your computer and use it in GitHub Desktop.
C# Service Wrapper around FreeCurrencyConverterApi
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