Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting exchange rates from the internet

What I wanna do is, to get exchange rates from internet. I found this function after long research.

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
        string xmlResult = null;
        string url;
        url = "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=" + TextBox1.Text + "&ToCurrency=" + TextBox2.Text + "";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader resStream = new StreamReader(response.GetResponseStream());
        XmlDocument doc = new XmlDocument();
        xmlResult = resStream.ReadToEnd();
        doc.LoadXml(xmlResult);
        Label1.Text = "Current Exchange Rate for " + TextBox1.Text.ToUpper() + " ---> " + TextBox2.Text.ToUpper() + " value " + doc.GetElementsByTagName("double").Item(0).InnerText;
        }
        catch(Exception ex)
        {
            Label1.Text="Not a valid Currency or Try again later";
        }
    } 

But http://www.webservicex.net/ doesn't support AZN (Azerbaijani Manat) to usd and vice versa conversion. What I wanna do is, if it's possible connect to the internet and get rates. Else use written function for conversion (I'VE already written).

What do you advice, how can I get current rates for USD and AZN (or just get result by sending USD or AZN) ? Is there anyway to get it from inside Windows forms application?

like image 420
heron Avatar asked Oct 07 '22 07:10

heron


1 Answers

This simple algorythm will give you all that you need in a key value pair list.

public static List<KeyValuePair<string, decimal>> GetCurrencyListFromWeb(out DateTime   currencyDate)
    {
        List<KeyValuePair<string, decimal>> returnList = new List<KeyValuePair<string, decimal>>();
        string date = string.Empty;
        using (XmlReader xmlr = XmlReader.Create(@"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"))
        {
            xmlr.ReadToFollowing("Cube");
            while (xmlr.Read())
            {
                if (xmlr.NodeType != XmlNodeType.Element) continue;
                if (xmlr.GetAttribute("time") != null)
                {
                    date = xmlr.GetAttribute("time");
                }
                else returnList.Add(new KeyValuePair<string, decimal>(xmlr.GetAttribute("currency"), decimal.Parse(xmlr.GetAttribute("rate"), CultureInfo.InvariantCulture)));
            }
            currencyDate = DateTime.Parse(date);
        }
        returnList.Add(new KeyValuePair<string, decimal>("EUR", 1));
        return returnList;
    }
like image 100
Freeman Avatar answered Oct 13 '22 10:10

Freeman