20/03/2011 UPDATE: code samples after changes to WP7Contrib code base.
Simply I want to show how we do communication with web services when using WP7Contrib.
When using web services from WP7 devices you have several options on how you are going to communicate with the service. What follows are the steps required to achieve this using the WP7Contrib. We show how to use a third party web service and how this pattern is very advantageous in this scenario.
We aren't advocating this is a better approach than using WCF data services (or any of other implementation), we've just been burnt before by WCF and prefer to possibly go through the pain of hand crafting resources (DTOs) than deal with WCF configs and it's short comings in Silverlight.
In Silverlight as we all know communication with web services has to be asynchronous, this in it's self is not a problem, but it can make the code ugly at best and difficult to understand. This is where Reactive Extensions come to the rescue, they allow you to handle asynchronous calls in a synchronous programming manner - I can write the code in a synchronous manner and it will execute in an asynchronous manner.
In the example below I'm using one of the 'secret' services available via the Google API - there's a great post here giving more info. The example uses the Google Weather API, this is a read only service that gives weather information for any location around the world, you access the data via a HTTP GET request.
Below is the code to make a HTTP request and debug out when the response is returned:
As you can see the code is very simple and has abstracted away the complexity of using the HttpWebRequest class. The other thing to note is the use of 'ObserveOnDispatcher' and 'Subscribe', these are method provided by the Reactive Extensions framework, if you're not familiar I would recommend doing some research. The 'ObserveOnDispatcher' method makes sure the asynchronous method invocation is on the dispatcher thread so we don't get any surprises when binding data. The 'Subscribe' method allows you to register as an observer.
Below is the code to initialise the 'weatherResource':
We use a class called 'ResourceClient' which implements an interface IHandleResources. The methods POST & PUT have 2 generic types, one for the request resource and one for the response resource. The reason why we don't just a single generic type is because this pattern is not just for making RESTful calls to REST services but can be used to make calls to SOAP services. The 2 other methods of interested are used to defined how the resource is serialized (JSON or XML) - 'ForType' and the templated URL to use for a HTTP GET request. The parameters passed in the previous example to the 'Get' method are combined with the templated URL to create a valid url - http://www.google.com/ig/api?weather=london (make sure you 'view source' to see what is returned).
Below is the code defining the 'weatherResource':
As you can see we define the interface 'IHandleResources<TRequest, TResponse>' this defines the operations that are supported - GET, PUT, POST & DELETE, along with a set of methods for configuring the URLs (for the operations), authentication, namespaces etc. The interface definition is shown below:
As you can see the request & response resources used in the examples are of type 'xml_api_reply' - I generated this automatically from an example XML response using XML Schema Definition Tool (xsd.exe). This was then included in the demo project and I removed manually the attributes which aren't supported by Silverlight in WP7.
If I was using a RESTful service which returned JSON I would have handcrafted the request & response resources as required - we use JSON.NET to handle the serialisation of JSON, so any request or response resources have to support serialization\deserialization by JSON.NET when communication with JSON based services.
That pretty much covers the basics of what is required to make a HTTP request using this pattern. You can find the demo application 'CommunicationDemo' in the Spikes directory of the WP7Contrib code base. Shown below is a screenshot from the demo application.
For completeness I've included a more detailed class on how to use this pattern - this is in the demo application. It shows how we don't use the 'ResourceClient' or the resources directly in a view model - we map the resources into a model and encapsulate this and the 'ResourceClient' class inside a 'Service' class. The service class then uses it's own IObservable<T> via the Subject <T>class. If you're not come across the idea of 'services' before check out Eric Evans Domain Driven Design book.
So that pretty much covers it, keep your eyes open for a post on applying this principle to the MS Bing Maps API by Rich Griffin.
Simply I want to show how we do communication with web services when using WP7Contrib.
When using web services from WP7 devices you have several options on how you are going to communicate with the service. What follows are the steps required to achieve this using the WP7Contrib. We show how to use a third party web service and how this pattern is very advantageous in this scenario.
We aren't advocating this is a better approach than using WCF data services (or any of other implementation), we've just been burnt before by WCF and prefer to possibly go through the pain of hand crafting resources (DTOs) than deal with WCF configs and it's short comings in Silverlight.
In Silverlight as we all know communication with web services has to be asynchronous, this in it's self is not a problem, but it can make the code ugly at best and difficult to understand. This is where Reactive Extensions come to the rescue, they allow you to handle asynchronous calls in a synchronous programming manner - I can write the code in a synchronous manner and it will execute in an asynchronous manner.
In the example below I'm using one of the 'secret' services available via the Google API - there's a great post here giving more info. The example uses the Google Weather API, this is a read only service that gives weather information for any location around the world, you access the data via a HTTP GET request.
Below is the code to make a HTTP request and debug out when the response is returned:
weatherResource.Get<xml_api_reply>("london")
.ObserveOnDispatcher()
.Subscribe(weather =>
{
Debug.WriteLine("we got weather news!");
});
As you can see the code is very simple and has abstracted away the complexity of using the HttpWebRequest class. The other thing to note is the use of 'ObserveOnDispatcher' and 'Subscribe', these are method provided by the Reactive Extensions framework, if you're not familiar I would recommend doing some research. The 'ObserveOnDispatcher' method makes sure the asynchronous method invocation is on the dispatcher thread so we don't get any surprises when binding data. The 'Subscribe' method allows you to register as an observer.
Below is the code to initialise the 'weatherResource':
weatherResource = new ResourceClient()
.ForType(ResourceType.Xml)
.UseUrlForGet("http://www.google.com/ig/api?weather={0}");
We use a class called 'ResourceClient' which implements an interface IHandleResources. The methods POST & PUT have 2 generic types, one for the request resource and one for the response resource. The reason why we don't just a single generic type is because this pattern is not just for making RESTful calls to REST services but can be used to make calls to SOAP services. The 2 other methods of interested are used to defined how the resource is serialized (JSON or XML) - 'ForType' and the templated URL to use for a HTTP GET request. The parameters passed in the previous example to the 'Get' method are combined with the templated URL to create a valid url - http://www.google.com/ig/api?weather=london (make sure you 'view source' to see what is returned).
Below is the code defining the 'weatherResource':
private IHandleResources weatherResource;
As you can see we define the interface 'IHandleResources<TRequest, TResponse>' this defines the operations that are supported - GET, PUT, POST & DELETE, along with a set of methods for configuring the URLs (for the operations), authentication, namespaces etc. The interface definition is shown below:
public interface IHandleResources<TRequest, TResponse> where TRequest : class, new() where TResponse : class, new()
{
ResourceType Type { get; }
IHandleResources ForType(ResourceType type);
IHandleResources UseUrl(string url);
IHandleResources UseUrlForGet(string getUrl);
IHandleResources UseUrlForPost(string postUrl);
IHandleResources UseUrlForPut(string putUrl);
IHandleResources UseUrlForDelete(string deleteUrl);
IHandleResources WithNamespace(string prefix, string @namespace);
IHandleResources WithBasicAuthentication(string username, string password);
IObservable<TResponse> Get<TRequest>();
IObservable<TResponse> Get<TRequest>(params object[] @params);
IObservable<TResponse> Put<TRequest, TResponse>(TRequest resource);
IObservable<TResponse> Put<TRequest, TResponse>(TRequest resource, params object[] @params);
IObservable<TResponse> Post<TRequest, TResponse>(TRequest resource);
IObservable<TResponse> Post<TRequest, TResponse>(TRequest resource, params object[] @params);
IObservable<TResponse> Delete<TRequest>();
IObservable<TResponse> Delete<TRequest>(params object[] @params);
IHandleResources WithHandlerDefinitions(JsonHandlerDefinitions definitions);
}
As you can see the request & response resources used in the examples are of type 'xml_api_reply' - I generated this automatically from an example XML response using XML Schema Definition Tool (xsd.exe). This was then included in the demo project and I removed manually the attributes which aren't supported by Silverlight in WP7.
If I was using a RESTful service which returned JSON I would have handcrafted the request & response resources as required - we use JSON.NET to handle the serialisation of JSON, so any request or response resources have to support serialization\deserialization by JSON.NET when communication with JSON based services.
That pretty much covers the basics of what is required to make a HTTP request using this pattern. You can find the demo application 'CommunicationDemo' in the Spikes directory of the WP7Contrib code base. Shown below is a screenshot from the demo application.
For completeness I've included a more detailed class on how to use this pattern - this is in the demo application. It shows how we don't use the 'ResourceClient' or the resources directly in a view model - we map the resources into a model and encapsulate this and the 'ResourceClient' class inside a 'Service' class. The service class then uses it's own IObservable<T>
public class WeatherService : IProviderWeather
{
private readonly IHandleResources<xml_api_reply, xml_api_reply> weatherResource;
public WeatherService()
{
weatherResource = new ResourceClient()
.ForType(ResourceType.Xml)
.UseUrlForGet("http://www.google.com/ig/api?weather={0}");
}
public IObservable<WeatherSummary> Get(string location)
{
try
{
// TODO service related stuff before call...
var observable = new Subject<WeatherSummary>();
this.weatherResource.Get<xml_api_reply, xml_api_reply>(location)
.Subscribe(response =>
{
var weather = ProcessResponse(response);
// TODO other service related stuff like caching
observable.OnNext(weather);
},
observable.OnError,
observable.OnCompleted);
return observable;
}
catch (Exception exn)
{
throw new Exception("Failed to get Weather!", exn);
}
}
private WeatherSummary ProcessResponse(xml_api_reply response)
{
var summary = new WeatherSummary();
summary.Current = new Weather();
summary.Current.Temperature = Convert.ToInt32(response.weather[0].current_conditions[0].temp_c[0].data);
return summary;
}
}
So that pretty much covers it, keep your eyes open for a post on applying this principle to the MS Bing Maps API by Rich Griffin.
Can you follow up on following thread.
ReplyDeletehttp://social.msdn.microsoft.com/Forums/en-US/rx/thread/355706c1-5406-42f4-958f-8382ea4a61f2?prof=required
Someone is saying that the code is confusing.. Perhaps you can chime in wrt you intentions..
I'd recommend using Select rather than piping the result through a subject, that way you keep deferred execution and you allow the request to be cancelable.
ReplyDeleteHello. I've just installed WP7contrib NuGet package and trying to use ResourceClient. The problem is I'm getting "Could not load type 'WP7Contrib.Communications.ResourceClient' from assembly 'WP7Contrib.Communications, Version=1.0.0.16, Culture=neutral, PublicKeyToken=null'." at runtime when trying to create an instance of it. What could be a problem? I'm using LocationService and ApplicationFrameNavigationService without any problem. Thanks.
ReplyDelete