Using Google Calculator for Money Exchange

While working in one of the projects, one of the main requirements was to do money exchange from a specific currency to another. When I was looking into this functionality, I thought that is going to be a hard thing to be implemented as it is touching a critical area related to money. in fact, Thanks to Google calculator.. implementing such a functionality was a very easy job and it took from me like 1 hour to be done… Google Calculator has a very easy to be consumed APIs. below code explaining how could I consume Google Calculators to get the up to date exchange rate between 2 different currencies.

   /// <summary>
/// Currency Exchange Service that is responsible
/// </summary>
public class CurrencyExchangeService
{private static string GoogleCalculatorApiUrl
{
get
{
return “http://www.google.com/ig/calculator?hl=en&q={0} {1} to {2}”;
}
}

/// <summary>
/// Do currency Exchange between currencies.
/// </summary>
/// <param name=”fromCurrencyCode”>Source Currency Code</param>
/// <param name=”toCurrencyCode”></param>
/// <param name=”amountToConvert”></param>
/// <param name=”roundedDecimalPoints”></param>
/// <returns></returns>
public static decimal ConvertCurrency(string fromCurrencyCode, string toCurrencyCode, decimal amountToConvert = 1, int roundedDecimalPoints = 4)
{
if (fromCurrencyCode == null)
throw new ArgumentNullException(“fromCurrencyCode”);
else if (toCurrencyCode == null)
throw new ArgumentNullException(“toCurrencyCode”);
else if (amountToConvert < 0)
throw new ArgumentOutOfRangeException(“amountToConvert”);

if (string.Compare(fromCurrencyCode, toCurrencyCode, true) == 0)
return amountToConvert;
else if (amountToConvert == 0)
return 0;

var request = HttpWebRequest.Create(string.Format(GoogleCalculatorApiUrl, amountToConvert, fromCurrencyCode, toCurrencyCode));
request.Timeout = 5000;
using (var response = request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(“iso-8859-1”)))
{
Match match;
if ((match = Regex.Match(
stream.ReadLine(),
@”{lhs: “”(?<From>[0-9.\s]+)(.*?)””,rhs: “”(?<To>[0-9.\s]+)(.*?)””,error: “”(?<Error>(.*?))””,icc: (true|false)}”,
RegexOptions.Singleline | RegexOptions.IgnoreCase)
).Success)
{
//Parse response from Google Calculator.
var result = new
{
From = Regex.Replace(match.Groups[“From”].Value, “[^0-9.]”, string.Empty),
To = Regex.Replace(match.Groups[“To”].Value, “[^0-9.]”, string.Empty),
Error = match.Groups[“Error”].Value
};

if (string.IsNullOrEmpty(result.Error))
{
return Math.Round(Convert.ToDecimal(result.To, CultureInfo.InvariantCulture), roundedDecimalPoints);
}

throw new Exception(string.Format(“Converter error: {0}.”, result.Error));
}

throw new Exception(“Response format error.”);
}
}
}
}

Leave a Reply

Your email address will not be published.