quinta-feira, 26 de março de 2015

Consuming a web service

In this post we will be talking about on how to consume a web service with a desktop application developed with C#.

A web service is an API that is available through the internet and it can be used within the rules established. Some services are free and don't require identification others have to be payed or have some limitations on the number of calls or data produced.

To demonstrate this concept we will be using a free service that the European Central Bank maintains in the following url http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml.
This service returns the Euro currency rate over other countries currencies. This information is encapsulated in XML.

Since we are making a desktop app we have to keep in mind the responsiveness of the user interface (GUI). So the request of the data must not occur in the main thread of the application which could block the GUI during the wait that is associated with exchange of information through the internet.

The main code is this:

async void downloadXML()
        {
            string url = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
            WebRequest pedido = WebRequest.Create(url);
            WebResponse resposta = await pedido.GetResponseAsync();
            XDocument documento = XDocument.Load(resposta.GetResponseStream());
            textBox1.Text = documento.ToString();

            //preencher a listview
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(documento.ToString());
            XmlNodeList lista = xml.GetElementsByTagName("Cube");
            foreach (XmlNode no in lista)
            {
                if (no.Attributes.Count > 1)
                {
                    ListViewItem novo = new ListViewItem(no.Attributes[0].InnerXml);
                    novo.SubItems.Add(no.Attributes[1].InnerXml);
                    listView1.Items.Add(novo);
                }
            }
        }

This function is asynchronous. The execution starts normally and goes until the line where the reserved word AWAIT define a process that can promote a delay so the control is return to the line that call this asynchronous function. When this request terminates the function concludes the processing and updates the UI with the data returned (learn more).

The code that lays ahead is simply to manipulate the XML recived.

The project

Sem comentários:

Enviar um comentário