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.
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:
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
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
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
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn