DotNetCurry Logo

Querying a WebService using LINQ – LINQ to CountryInfo

Posted by: Suprotim Agarwal , on 5/7/2010, in Category LINQ
Views: 79331
Abstract: This article demonstrates how to query a Web Service’s public API using LINQ
This 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
Note: I assume that you are familiar with LINQ to XML. If not, I would recommend you to get some hands-on on LINQ to XML to check out how to traverse nodes. These three articles will help you out:
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; }       
VB.NET 10.0
Class CountryInfo
      Public Property CountryName() As String
      Public Property Population() As Long
      Public Property Capital() As String
      Public Property CurrencyCode() As String
      Public Property AreaSqKm() As Single
End Class
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 "" +
            "country=" + cCode;
VB.NET 10.0
Friend Class Country
      Public Function SearchCountry(ByVal countryCode As String) As IEnumerable(Of CountryInfo)
            Dim uri As String = Uri.EscapeUriString(countryCode)
            Dim url As String = FormatUrl(uri)
            Dim xdoc As XDocument = XDocument.Load(url)
            Dim results As IEnumerable(Of CountryInfo) = From cntry In xdoc.Descendants("country")
                                                         Select New CountryInfo With {.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
      End Function
      Private Function FormatUrl(ByVal cCode As String) As String
            Return "" & "country=" & cCode
      End Function
End Class
The code is pretty straightforward. We first create the url with the search string using our FormatUrl method. 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);   
VB.NET 10.0
Sub Main(ByVal args() As String)
      Dim country As New Country()
      Dim cntryCode As String = "IN"
      Dim cntryInfo As IEnumerable(Of CountryInfo) = country.SearchCountry(cntryCode)
      For Each 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)
      Next c
End Sub
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:
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 over here
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Sanjay on Tuesday, April 5, 2011 7:29 AM
Nice Article
Comment posted by Hakan CILASUN on Saturday, November 23, 2013 1:48 PM
My name is Hakan CILASUN , I am software developer , from Turkey ,
I am writing web site project with I am writing my project with entity framework.
In the same in project or different project , I wrote asmx web service.
but,when I used this web service , the project gived error.
Error is ;
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: A circular reference was detected while serializing an object of type Business.ProductDetail.

Can you help to me , please ?
What is this error ?
How can I resolve ?
I am very please,
see you ,
Comment posted by Tony on Tuesday, February 4, 2014 1:29 AM
hi my name is tony denga from south can I query webservice that returns xml in dataset format in using linq and then be able to bind it to gridview...Please help