Click here to Skip to main content
15,886,067 members
Articles / Silverlight

Consuming External WebService from Silverlight Application

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
12 Apr 2011CPOL4 min read 11.8K  
How to consume external webservice from Silverlight application

While exploring Map API integration with SOI application, I felt that a separate post on consuming external web services from SL application is worth a write. As we know, services can be SOAP based (WCF bases) or can be REST (Simple HTTP) based on the implementation technology. As you Google, you will find a lot of services from different providers, here (webservice directory). May be, some are useful saving lots of time, some may look fancy.

Silverlight can access some services directly for e.g., HTTP/REST type and some using proxy for SOAP. Well, before describing the process, let's have a look at the web service in Silverlight. Services hosted by various hosts come with various security policies. For example, Yahoo allows access to the services to authenticated request only and authentication can be achieved using OpenID, Oauth and Hybrid (Yahoo API Auth.), similarly Google services. These external service administrators create policy files to restrict the request from other domain without proper authentication.

Basics of Webservice

The article expects readers will have a basic idea about webservices. I will suggest you refer to the tutorials from W3C to refresh the concept (W3C Webservices concept).

Cross Domain Policy for Services

What is Cross Domain Access

Suppose Domain A is hosting a webservice. A request made from Domain B to the service at A is said to be Cross Domain access.

By default, Silverlight allows access to the services hosted at the same domain without any restriction but if it's external, then that service should allow your domain specifically. Generally, the service providers use crossDomain policy files to grant/restrict the request. On the same lines, if you are going to build your own service and want to be accessed from other domain, then you have to add clientaccesspolicy.xml, where either you can allow all external requests or else to particular domains.

The typical structure of a clientaccesspolicy.xml can be as below, here it allows access to all:

XML
<;?xml version="1.0" encoding="utf-8"?>
<;access-policy>
  <;cross-domain-access>
    <;policy>
      <;allow-from http-request-headers="*">
        <;domain uri="*"/>
      <;/allow-from>
      <;grant-to>
        <;resource path="*" include-subpaths="true"/>
      <;/grant-to>
    <;/policy>
  <;/cross-domain-access>
<;/access-policy>

As mentioned above, some of the services such as for images, news feed are open for all, such as from Geonames. You can find more details about these APIs here.

External RESTful Service from Silverlight

As we know, Silverlight client sitting inside a browser has restricted access to server. For accessing database too, it depends on proxy service calls through WCF. All the service calls from Silverlight are asynchronous by their behaviour, as contrary to synchronous call of ASP.NET. Well, choosing Rest services here for this article can be seen as to maintain the simplicity and as most of the providers support it. Rest services expose themselves through HTTP, using their URL. On request made to the service, it can return results in various format, for example, XML, JSON, etc.

An external service from Silverlight can be called in 2 ways:

  • Either ask the service provider/administrator to allow your domain to access the service, by adding your domain to their policy files
  • Using proxy service call from your domain to that external webservice and your Silverlight app request to your domain proxy

Now, for the sake of an example, I have chosen a service from GeoName which allows me to get a place geographic detail as result. As mentioned on the web, this is a free service and allows all domain access. Their service URL says:

Url » api.geonames.org/postalCodeSearch?&username=***

Result » returns a list of postal codes and places for the placename/postalcode query as xml document

With your username and the search argument the url will be –:http://api.geonames.org/search?q=orissa&username=********

Now from your Silverlight code, we can call the service using WebClient or HTTPWebRequest. The code for accessing a webservice can be:

C#
string path = @"http://api.geonames.org/search?q=orissa&username=********"; 
public MainPage() 
{ 
InitializeComponent(); 
} 
private void btnCallService_Click(object sender, RoutedEventArgs e) 
{ 
WebClient client = new WebClient(); 
client.DownloadStringCompleted += (s, ev) => 
{ 
MessageBox.Show(ev.Result); 
}; 
client.DownloadStringAsync(new Uri(path)); 
}
  • Create a Webclient for sending an HTTP request to server.
    C#
    WebClient client = new WebClient();
  • Assign the callback with the async operation completed event handler.
    C#
    client.DownloadStringCompleted += (s, ev) =>
  • Call DownloadStringAsync with service URL
    C#
    client.DownloadStringAsync(new Uri(path));

    Here in the above example, we are showing the result in a message box after calling service, instead of which we can parse the XML and get meaningful data source for our app.

SNAGHTMLd026e5

The XML data can be parsed either using XmlReader, Linq To XML or using XmlSerializer which converts the XML data to plain CLR objects.The parsing of XML will not be using XMLReader. I will cover the conversion of XML data to CLR object with an example in my next post.

Conclusion

Not most of the services allow as simple access as mentioned above. A Yahoo API invites some extra steps and some more code stuff. You may refer to this article for accessing Yahoo web service from ASP.NET. Use of 3rd party proxy service also provides another way, for e.g., Yahoo Pipes. But it's always a nice feeling to use programs available free without writing anything :). Ok. I will try to extend the article with accessing services other than REST. Till then, keep learning.

Link and Source Code

Soon, I will post source code and live URL for reference, after finishing the article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Microsoft
India India
Nothing special .. I like challenges and love my critics.

Microsoft | Bangalore | India

Blog : http://manaspatnaik.com/blog

Twitter@manas_patnaik

Comments and Discussions

 
-- There are no messages in this forum --