Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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