Saturday, January 11, 2025

C#: Realtime Currency Exchange Class

Share

Soon, I’m facing a new project where the need for up-to-date currency exchanges is crucial.

This is not the first time I’ve done this, but I wanted to make a reusable, self-maintainable class so I don’t have to do it again.

The European Central Bank (ECB) provides the currency exchange rates on a daily basis in XML format, so all there needs to be done, is to wrap the XML file into a generic dictionary for easy use. With that in mind, here are the rules of the Currency class:

  • Use XML file from ECB
  • Update the currencies daily
  • Must still function if the ECB has downtime
  • Must be self maintained
  • Must be plug ‘n play. Only CLR classes can be used.

In order to make the class self maintained it uses a System.Timers.Timer to check the ECB website once an hour for updates. As soon as it finds an update, the XML file is being downloaded and parsed. This is the Download method which runs once an hour.

/// <summary>
/// Downloads the latest exchange rates from ECB.
/// </summary>
private static void Download()
{
  try
  {
   _Timer.Stop();
   HttpWebRequest request = WebRequest.Create(_Url) as HttpWebRequest;
   using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
   {
    if (response.StatusCode == HttpStatusCode.OK && response.LastModified != _LastModified)
    {
     using (StreamWriter writer = new StreamWriter(_Filename, false))
     {
      StreamReader reader = new StreamReader(response.GetResponseStream());
      writer.Write(reader.ReadToEnd());
      reader.Close();
     }
    _LastModified = response.LastModified;
    }
   }

   _Timer.Interval = _UpdateInterval;
  }
   catch (Exception)
  {
   // If an error occurs, try again in 10 minuttes.
   _Timer.Interval = 1000 * 60 * 10;
  }
  finally
  {
   _Timer.Start();
  }
}

Examples of use

double fromUSDtoEUR = Currency.Exchange("USD", "EUR", 12.75);
double rateFromUSDtoNOK = Currency.GetRate("NOK", "USD");

     if (Currency.LastUpdated

Implementation

Download the Currency.cs below and add it to the App_Code folder of your website. Then add the following to the section of the web.config.

<add key="Currency.Filename" value="~/currency.xml"/>

The filename value can either be a relative or absolute file path.

Download

Currency.zip (1,93 KB)

Comments

Tag:

Reddit | Furl

Bookmark Murdok:

Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.

Home


Table of contents

Read more

Local News

Seca funding company.