Nej - koden skal bare justeres lidt.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
namespace E
{
public class Program
{
private static IDictionary<string, XmlDocument> cache = new Dictionary<string, XmlDocument>();
public static decimal GetRate(DateTime date, string currency)
{
if(currency == "DKK") return 100.00m;
string datestr = date.ToString("yyyy-MM-dd");
XmlDocument doc;
if(cache.ContainsKey(datestr))
{
doc = cache[datestr];
}
else
{
doc = new XmlDocument();
doc.Load("
http://www.nationalbanken.dk/_vti_bin/DN/DataService.svc/CurrencyRatesHistoryXML?lang=da");
cache[datestr] = doc;
}
XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
xnm.AddNamespace("gesmes", "
http://www.gesmes.org/xml/2002-08-01");
xnm.AddNamespace("default", "
http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
XmlNode rateinfo = doc.SelectSingleNode("/gesmes:Envelope/default:Cube/default:Cube[@time='" + datestr + "']/default:Cube[@currency='" + currency + "']/@rate", xnm);
if(rateinfo != null)
{
// current file has info for this date => we use that info
string ratestr = rateinfo.Value;
return decimal.Parse(ratestr, new CultureInfo("da-DK", false));
}
else
{
// current file has info for this date => we try previous day
cache.Remove(datestr);
Console.WriteLine("recurse");
return GetRate(date.AddDays(-1), currency);
}
}
public static decimal Convert(DateTime date, decimal amount, string fromcurrency, string tocurrency)
{
decimal fromrate = GetRate(date, fromcurrency);
decimal torate = GetRate(date, tocurrency);
return amount * fromrate / torate;
}
public static decimal Convert(decimal amount, string fromcurrency, string tocurrency) {
return Convert(DateTime.Now, amount, fromcurrency, tocurrency);
}
public static void Main(string[] args)
{
Console.WriteLine(Convert(10.00m, "DKK", "EUR"));
Console.WriteLine(Convert(10.00m, "DKK", "USD"));
Console.ReadKey();
}
}
}