Querying a WebService using LINQ – LINQ to CountryInfo

Posted by: Suprotim Agarwal , on 5/7/2010, in Category LINQ
Views: 69510
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 http://ws.geonames.org/countryInfo?
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:
C#
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:
C#
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;
    }
}
 
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 "http://ws.geonames.org/countryInfo?" & "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
C#
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();
}
 
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
      Console.ReadLine()
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:
File_Path
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
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
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
hi,
My name is Hakan CILASUN , I am software developer , from Turkey ,
I am writing web site project with asp.net. 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 ,
bye.
Comment posted by Tony on Tuesday, February 4, 2014 1:29 AM
hi my name is tony denga from south Africa...how can I query webservice that returns xml in dataset format in vb.net using linq and then be able to bind it to gridview...Please help

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel