Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET

Simple Class to get Currency Exchange Rates

Rate me:
Please Sign up or sign in to vote.
4.74/5 (23 votes)
12 Mar 2007CPOL5 min read 207.3K   13.3K   81   32
Explains how to get the latest currency exchange rates from the Internet.

Introduction

Many years, especially during international trips, I have used the Yahoo! Finance portal to get fresh foreign exchange rates for my expense reports. I found this site quite useful, especially because the information is free, even though a little bit delayed, but good enough for such goals. Unfortunately, the Yahoo! site doesn't have a version formatted to fit the small screens of mobile devices. That's why I decided to create .NET components that are reusable in WinForms, ASP.NET, and the Compact Framework to cover all my needs. Parsing HTML code is not a trivial task because it doesn't have a strong formatting as XML does. Again, fortunately, Yahoo! duplicates results as a comma-delimited file which is more easy to parse. So, let's look at the code closely.

Walk through the classes

Class diagram:

Image 1

There are two classes - CurrencyConverter and CurrencyList, and a structure CurrencyData. All of them are packed into the Zayko.Finance namespace.

CurrencyData structure

This structure represents a pair of currency codes and data coming from the Web Service:

  • BaseCode (string): get/set three-characters of the base currency code, for example: USD for United States Dollar, EUR for Euro etc.
  • TargetCode (string): get/set the target currency code, by the same rules as BaseCode.
  • Rate (double): last trade price of Base Currency, specified in the BaseCode property, calculated in currency units, specified in the TargetCode property.
  • Max and Min (double): they look like Ask and Bid, but values are different between the HTML version on the site and the comma-delimited file I mentioned above; unfortunately, there is no detailed explanation, that's why I named them "Min" and "Max" to avoid confusion with the real "Bid" and "Ask" values.
  • TradeDate (System.DateTime): last trade Date/Time.

This structure has one constructor:

C#
public CurrencyData(string baseCode, string targetCode)

to create a new structure and set the currency codes.

CurrencyConverter class

This is the main class which accesses the Yahoo! service and gets the data through several overloads of the GetCurrencyData method:

C#
public CurrencyData GetCurrencyData(string source, string target)

This is the simplest method: just supply the currency codes and get the result in the returned CurrencyData structure. For example:

C#
using Zayko.Finance;
...
CurrencyData cd = myCurrencyConverter.GetCurrencyData("USD", "EUR");
// Convert US Dollars to Euros

This version gets the currency pair in the supplied CurrencyData and packs the results back into there:

C#
public void GetCurrencyData(ref CurrencyData data)

Gets the currency pair in the CurrencyData structure and sets the data properties (Rate, Min/Max, TradeDate) by the given results. Example:

C#
using Zayko.Finance;
...
CurrencyData cd = new CurrencyData("EUR", "RUB");
// Creates new structure and set Base currency
// to Euro and Target to Russian Ruble

try
{
    myCurrencyConverter.GetCurrencyData(ref cd);
    // cd.Rate contains last price of Euro in Russian Rubles
}
catch
{
    // Catch an exception
}

This method is useful to get data for more than one currency pair at the same time:

C#
public void GetCurrencyData(ref IList<CurrencyData> listData);

Example:

C#
using Zayko.Finance;
...
IList<CurrencyData> currencyList = new List<CurrencyData>();
currencyList.Add(new CurrencyData("USD", "EUR"));
currencyList.Add(new CurrencyData("EUR", "RUR"));
try
{
    myCurrencyConverter.GetCurrencyData(ref currencyList);
    foreach(CurrencyData cd in currencyList)
    {
        // listing the data
    }
}
catch
{
    // Catch an exception
}

But before calling these functions, don't forget to set some important properties:

  • System.Net.WebProxy Proxy: represents a proxy server, if any; just skip this step if there is no proxy in your network.
  • bool AdjustToLocalTime: basically, CurrencyData.TradeDate is US Eastern Time (GMT-05:00).
  • Set this property to true if you want to adjust this time to your local automatically.

  • int Timeout and ReadWriteTimeout: same meaning as HttpWebRequst: namely, the time-out value for the GetResponse and GetRequestStream methods for Timeout and the time-out when writing to or reading from a stream for ReadWriteTimeout in milliseconds. Both defaulted to 30 seconds (30000 milliseconds).

CurrencyList class

This class contains only static methods, so doesn't need to be created manually before using it. Use this class to get all the supported currencies: get the three-characters codes from the static read only property Codes: public static ReadOnlyCollection Codes and their names from public static ReadOnlyCollection Descriptions.

Also, it is possible to get the exact code and/or description by its position:

  • public static string GetCode(int index): return a currency code, for example "USD".
  • public static string GetDescription(int index): return a currency description (name), for example "U.S. Dollar".

and opposite functions:

  • public static int GetCodeIndex(string code)
  • public static int GetDescriptionIndex(string description)

Since both codes and descriptions are unique, it's possible to get a currency code by its description and vice versa:

  • public static string GetCode(string description)
  • public static string GetDescription(string code)

Using the code

Finally, a couple of words about using the source code.

Probably the best way to show all the supported currencies either in a WinForms app or an ASP.NET app is ListBox or ComboBox objects. As I said above, this list could be taken from the static CurrencyList class. This task could be done in two different ways:

C#
// 1. Simply fill Combo or ListBox Items property...
string[] currencyDescriptions = new string[CurrencyList.Count];
CurrencyList.Descriptions.CopyTo(currencyDescriptions, 0);
comboBoxCurrencyList.Items.AddRange(currencyDescriptions);

// 2. Assign currencies one-by-one and set Value properties
//    to corresponded codes at the same time (useful in ASP.NET):
for(int i = 0; i < CurrencyList.Count; i++)
{
    DropDownListCurrency.Items.Add(CurrencyList.Descriptions[i]);
    DropDownListCurrency.Items[i].Value = CurrencyList.Codes[i];
}

// then simply use them in CurrencyData GetCurrencyData method:
CurrencyConverter cc = new CurrencyConverter();
CurrencyData cd = cc.GetCurrencyData(DropDownListFrom.SelectedValue, 
                                     DropDownListTo.SelectedValue);

Don't forget to set the CurrencyData.AdjustToLocalTime property to true if you want to make adjustments automatically. If your network is behind a proxy, don't forget to create and assign a proxy object before you call CurrencyData.GetCurrencyData(...):

C#
if(useProxy)
    cc.Proxy = new System.Net.WebProxy(proxyAddress, proxyPort);

Because the CurrencyConverter class has several versions of the GetCurrencyData method, and GetCurrencyData(ref IList<CurrencyData>) is one of them, you can pass more than one CurrencyData structure and get data for several currency pairs at the same time. Although this method has no restrictions on the number of currencies you can pass, please remember that some old network routers have a limitation on URL length and can trim everything to below 256 characters.

Here is the demo app screenshot (source code is included with this article):

Image 2

Important notes

As a developer, I don't impose any restrictions on using this code, but please remember that Yahoo! services could be under different types of licensing and commercial use could be restricted. So please follow Yahoo! instructions.

Although I said at the beginning that I created these classes to fit to any .NET target, I didn't test this code on the Compact Framework at all, but I promise to return to this article in a couple of weeks and hope will get your opinions during this time to make this code more useful.

Enjoy!

Links

History

  • March 7, 2007 - Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Russian Federation Russian Federation
More than 15 years in the industry.
Delphi, C# (Win/WebForms), MS SQL

Comments and Discussions

 
GeneralMy vote of 5 Pin
atif_sh2-Jan-12 3:16
atif_sh2-Jan-12 3:16 
GeneralMy vote of 5 Pin
hakimsameh22-Dec-11 4:45
hakimsameh22-Dec-11 4:45 
QuestionUsing Zayko with CultureInfo class Pin
~Pete27-Nov-11 4:22
~Pete27-Nov-11 4:22 
Thank you for this very nice class.
Do you know how I could use this class and then display my converted values using the CultureInfo class?
The 3 letter CurrencyList.Codes don't match the Application Culture Windows Name.
Example Russian Ruble - The Zayko code is RUB and the Windows Name is RUS.

I would like to add to the static CurrencyList to include the Windows 3 letter name.
This way I can get the conversion rate and display my converted value in the correct format using the Culture Information class.

Is there another way to do this that I don't know of?

Regards,
Dave Peterson
AnswerAmazing Pin
WossiBock663-Nov-11 1:31
WossiBock663-Nov-11 1:31 
QuestionHow to read the .chm file Pin
Spokane-dude3-Oct-11 10:40
Spokane-dude3-Oct-11 10:40 
Questionpassword Pin
aaashivabalaji5-Aug-11 3:21
aaashivabalaji5-Aug-11 3:21 
Generalgrand merci) Pin
sherpc11-Feb-11 12:29
sherpc11-Feb-11 12:29 
GeneralPassword Pin
Amit Rajani24-Nov-10 20:09
Amit Rajani24-Nov-10 20:09 
Questionwhat is the password Pin
siren993315-Nov-10 21:45
siren993315-Nov-10 21:45 
GeneralPassword Pin
elaiz26-Oct-10 5:08
elaiz26-Oct-10 5:08 
GeneralThanks Pin
Danie de Kock7-Oct-10 22:03
Danie de Kock7-Oct-10 22:03 
Generalpassword Pin
asafbr10-May-10 23:24
asafbr10-May-10 23:24 
QuestionCan i have same example writing by delphi Pin
Rami Khoury9-Jan-10 12:37
Rami Khoury9-Jan-10 12:37 
Generalthank you Pin
Rami Khoury9-Jan-10 12:00
Rami Khoury9-Jan-10 12:00 
GeneralThank u Pin
essam_ag28-Dec-09 20:16
essam_ag28-Dec-09 20:16 
GeneralHistorical rates Pin
ElrondCT8-Sep-09 5:13
ElrondCT8-Sep-09 5:13 
Generalbase converter Pin
jayyaj7-Apr-08 11:35
jayyaj7-Apr-08 11:35 
Generalhi sir Pin
manoj.joshi28-Feb-08 23:12
manoj.joshi28-Feb-08 23:12 
GeneralCompatibility issue with 2003 Studio Pin
Barraq6-Sep-07 9:52
Barraq6-Sep-07 9:52 
Generalplease what is your pass key Pin
tokzhee10-Jul-07 23:53
tokzhee10-Jul-07 23:53 
GeneralRe: please what is your pass key Pin
Vitaly Zayko12-Jul-07 2:45
Vitaly Zayko12-Jul-07 2:45 
GeneralThank you Pin
Z.J.Liu21-Mar-07 4:49
Z.J.Liu21-Mar-07 4:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.