Skip to main content

WP7Contrib: RESTful communications using HttpWebRequest & Rx extensions

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:

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> via the Subject<T>class. If you're not come across the idea of 'services' before check out Eric Evans Domain Driven Design book.

    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.



Comments

  1. Can you follow up on following thread.

    http://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..

    ReplyDelete
  2. 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.

    ReplyDelete
  3. Hello. 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

Post a Comment

Popular posts from this blog

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example below

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v

Custom AuthorizationHandler for SignalR Hubs

How to implement IAuthorizationRequirement for SignalR in Asp.Net Core v5.0 Been battling this for a couple of days, and eventually ended up raising an issue on Asp.Net Core gitHub  to find the answer. Wanting to do some custom authorization on a SignalR Hub when the client makes a connection (Hub is created) and when an endpoint (Hub method) is called:  I was assuming I could use the same Policy for both class & method attributes, but it ain't so - not because you can't, because you need the signatures to be different. Method implementation has a resource type of HubInnovationContext: I assumed class implementation would have a resource type of HubConnectionContext - client connects etc... This isn't the case, it's infact of type DefaultHttpContext . For me I don't even need that, it can be removed completely  from the inheritence signature and override implementation. Only other thing to note, and this could be a biggy, is the ordering of the statements in th