brianmwadime
2/19/2014 - 3:30 PM

CurrencyHelper.cs

public static class CurrencyHelper
{
    private static string _currencyRegex = "rhs: \\\"(\\d*.\\d*)";

    // slightly modified from: http://www.ashishblog.com/blog/currency-exchange-rate-in-webpage-using-c-asp-net/
    // Uses a google api which takes requests in this format: http://www.google.com/ig/calculator?hl=en&q=1AUD%3D%3FUSD
    public static decimal Convert(decimal amount, string fromCurrency, string toCurrency)
    {
        var web = new WebClient();

        var query = string.Format("{0}{1}%3D%3F{2}", amount, fromCurrency, toCurrency);
        string url = "http://www.google.com/ig/calculator?hl=en&q=" + query;

        string response = web.DownloadString(url);

        //todo check for error

        //find right hand side rate
        var match = Regex.Match(response, _currencyRegex);
        var rate = System.Convert.ToDecimal(match.Groups[1].Value);

        return rate;
    }

    public static decimal ExchangeRate(string fromCurrency, string toCurrency)
    {
        return Convert(1, fromCurrency, toCurrency);
    }

    public static string Format(decimal amount, string currencyCode)
    {
        var culture = (from c in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                        let r = new RegionInfo(c.LCID)
                        where r != null
                        && r.ISOCurrencySymbol.ToUpper() == currencyCode.ToUpper()
                        select c).FirstOrDefault();

        if (culture == null)
            return amount.ToString("0.00");

        return string.Format(culture, "{0:C}", amount);
    }
}