Programming

Consuming a WebService using LINQ

[dropcap]T[/dropcap]his article demonstrates how to query a Web Service’s public API using LINQ. For this article, I am using the Web Service located at GeoNames. Our code will query the CountryInfo webservice which accepts a Country Code and returns information like the country’s capital, population, currency and so on.
Check out the XML document returned from this service over here http://ws.geonames.org/countryInfo?
Let us get started:

 

Step 1: Create a Console Application. To this application, add a class named ‘Country’ and ‘CountryInfo’. The CountryInfo class has the following definition:
class CountryInfo
{
    public string CountryName { get; set; }
    public long Population { get; set; }
    public string Capital { get; set; }
    public string CurrencyCode { get; set; }
    public float AreaSqKm { get; set; }
}
Step 2: The Country class contains a SearchCountry method that returns an IEnumerable<CountryInfo> as shown below:

 

class Country
{
    public IEnumerable<CountryInfo> SearchCountry(string countryCode)
    {
        string uri = Uri.EscapeUriString(countryCode);
        string url = FormatUrl(uri);
        XDocument xdoc = XDocument.Load(url);
        IEnumerable<CountryInfo> results =
        from cntry in xdoc.Descendants(“country”)
        select new CountryInfo
        {
            CountryName = cntry.Element(“countryName”).Value,
            Capital = cntry.Element(“capital”).Value,
            AreaSqKm = Convert.ToSingle(cntry.Element(“areaInSqKm”).Value),
            Population = Convert.ToInt64(cntry.Element(“population”).Value),
            CurrencyCode = cntry.Element(“currencyCode”).Value
        };
        return results;
    }
    string FormatUrl(string cCode)
    {
        return “http://ws.geonames.org/countryInfo?” +
            “country=” + cCode +
            “&username=christlin”;
    }
}
The code is pretty straightforward. We first create the url with the search string using our FormatUrlmethod. We then use the XDocument.Load to create an XML document from the url. The last step is to loop through the XML document, populate the CountryInfo object and return the results.

 

Step 3: The final step is to code the Main() method to retrieve and display the results from the WebService. Here’s how the Main() method looks
static void Main(string[] args)
{
    Country country = new Country();
    string cntryCode = “IN”;
    IEnumerable<CountryInfo> cntryInfo = country.SearchCountry(cntryCode);
    foreach (var c in cntryInfo)
    {
        Console.WriteLine(“You searched for {0}. “ +
                        “The population of {0} is {1} and its capital is {2}. “ +
                        “The CurrencyCode for {0} is {3} and it’s area in Sq. Km is {4}”,
            c.CountryName, c.Population, c.Capital,
            c.CurrencyCode, c.AreaSqKm);
    }
    Console.ReadLine();
}

 

In the example above, we are passing in the country code ‘IN’ for India. We then loop through an object of IEnumberable<CountryInfo> and print the result on the console. The output looks similar to the following:

 

00130032015 Console Output

 

Well that was a simple example of how to query a webservice using LINQ. I hope you liked this article and I thank you for viewing it. The entire source code of this article can be downloaded here

[wpfilebase tag=file id=1 tpl=download-button /]

Previous ArticleNext Article