Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Thursday, 17 March 2011

WP7Contrib: RESTful communications using HttpWebRequest & Rx extensions

Posted on 14:50 by Unknown
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.



Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in CodePlex, REST HTTP, WP7, WP7Contrib | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Unit testing Rx methods Timeout & Retry with moq
    Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
  • Understanding RefCount in Reactive Extensions
    A couple of weeks ago  @LordHanson  & I ran into an issue converting a stateless async service exposed as an Rx cold observable to a  co...
  • StructureMap: ILifecycle
    The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextS...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • How many pins can Bing Maps handle in a WP7 app - part 1
    part2 -  http://awkwardcoder.blogspot.com/2011/10/how-many-pins-can-bing-maps-handle-in.html part3 -  http://awkwardcoder.blogspot.com/2011/...
  • Bad developers love 'The Daily WTF'
    When 'The Daily WTF' started up back in 2003/2004 it was a great laugh looking at shocking code other developers wrote, but after a ...
  • Using CompositeDisposable in base classes
    To help make an object eligible for collection by the GC (garbage collector) one would implement the IDisposable interface. Executing the di...
  • 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 whil...
  • Daily Dilbert Service - the most important service I've ever written...
    NuGet package available here ... First off a big shout to  @hamish  &  @leeoades  on this one - I'm just blogging about it. At work ...
  • Comparing performance of .Net 4.5 to .Net 4.0 for WPF
    Currently I'm working on a .Net 4.0 WPF app and we've had some discussion about moving to .Net 4.5, we don't get to make the dec...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ►  2013 (16)
    • ►  November (5)
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ►  2012 (44)
    • ►  November (2)
    • ►  October (8)
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ▼  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ▼  March (5)
      • Calling 'HtmlPage.Window.Invoke' from a background...
      • Considerations when building a caching mechanism f...
      • WP7Contrib: RESTful communications using HttpWebRe...
      • WP7Contrib: Why we use SilverlightSerializer inste...
      • WP7Contrib: Trickling data to a bound collection
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ►  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ►  September (11)
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile