Realtime Currency Converter in C# ASP.NET using Yahoo API


In this article, Let’s see how to convert worldwide currencies in realtime using Yahoo API.

Steps:

1. Create a ASP.NET empty project, call it as “RealtimeCurrencyConverterUsingYahooAPI”.

2. Add a webpage called “Default.aspx” to the project.

3. Since we are using jQuery, include the jQuery latest library in the project. Add a reference to it on “Default.aspx” page.


<script src="jquery-1.10.2.js"></script>

4. Add the following webmethod in code behind.


using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Services;

[WebMethod]
public static Decimal ConvertCurrency(decimal amount, string fromCurrency, string toCurrency)
{
WebClient client = new WebClient();
Stream response = client.OpenRead(string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", fromCurrency.ToUpper(), toCurrency.ToUpper()));
StreamReader reader = new StreamReader(response);
string yahooResponse = reader.ReadLine();
response.Close();
if (!string.IsNullOrWhiteSpace(yahooResponse))
{
string[] values = Regex.Split(yahooResponse, ",");
if (values.Length > 0)
{
decimal rate = System.Convert.ToDecimal(values[1]);
return rate * amount;
}
}
return 0;
}

The webmethod simple get response from yahoo URL. Parses it and returns the calculated result back on the screen.

5. To call this webmethod from “Default.aspx”, just add the following jQuery Code.


<script type="text/javascript">

$(document).ready(function () {
$('#submit').click(function () {
var errormsg = "";
var amount = $('#txtAmount').val();
var fromCurrency = $('#drpFromCurrency').val();
var toCurrency = $('#drpToCurrency').val();
$.ajax({
type: "POST",
url: "Default.aspx/ConvertCurrency",
data: "{amount:" + amount + ",fromCurrency:'" + fromCurrency + "',toCurrency:'" + toCurrency + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#results').html(amount + ' ' + fromCurrency + ' equals ' + data.d.toFixed(2) + ' ' + toCurrency);
},
error: function (jqXHR, exception) {
$('#results').html(jqXHR.responseText);
}
});
});
});

</script>

If you don’t know how to call a webmethod in jQuery, Please refer this.

6. To style the table, I have just added a stylesheet and referred it in the “Default.aspx” page. You can generate such styles very easily from here.

7. Now run the project and you will find the output like e.g

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

One thought on “Realtime Currency Converter in C# ASP.NET using Yahoo API

Leave a comment