Rest Web Services In Windows Phone 7

I’ve been messing around with some Window Phone 7 development lately and thought I would share how I have been calling web services with RestSharp (I’ve written a little about RestSharp previously using the google weather api).

restsharp For those who don’t know RestSharp is a REST client for .NET which has recently added silverlight and Windows Phone 7 support. RestSharp has some really great features to simplify calling web services including:

  • Automatic XML and JSON deserialization
  • Fuzzy name matching (‘product_id’ in XML/JSON will match property named ‘ProductId’)
  • Automatic detection of type of content returned
  • GET, POST, PUT, HEAD, OPTIONS, DELETE supported

Windows Phone 7 basically enforces (with good reason) async web requests – luckily RestSharp has our back on that front. I’m going to use some example code from the Google Reader app I’ve been playing around with – GREAD. Here is a simple example of asynchronously calling a web service using RestSharp to authenticate with with google accounts:

var client = new RestClient("https://www.google.com");

var request = new RestRequest("accounts/ClientLogin", Method.POST);
request.AddParameter("service", "reader", ParameterType.GetOrPost);
request.AddParameter("accountType", "GOOGLE", ParameterType.GetOrPost);
request.AddParameter("source", _source, ParameterType.GetOrPost);
request.AddParameter("Email", _username, ParameterType.GetOrPost);
request.AddParameter("Passwd", _password, ParameterType.GetOrPost);

client.ExecuteAsync(request, (response) =>
{
    var auth = ParseAuthToken(response.Content);
});

RestSharp will automatically build the request with the parameters it is given. These can be get/post, cookies or http headers. The ExecuteAsync method takes the request to make and an action to execute when finished.

I come from a web development background living the good life making synchronous requests. Developing in Silverlight requires a bit of an adjustment with a big focus on event driven asynchronous programming. The pattern I am using I’ve tried to avoid all the plumbing involved in hooking up and firing off event handlers. Here is the basic pattern I use for api calls, in this instance I am grabbing all the feed items for the given label:

public void GetLabelFeed(string label, Action<Model.Feed> success, Action<string> failure)
{
    string resource = "reader/api/0/stream/contents/user/-/label/" + label;

    var request = GetBaseRequest();
    request.Resource = resource;
    request.Method = Method.GET;
    request.AddParameter("n", 20); //number to return

    _client.ExecuteAsync<Model.Feed>(request, (response) =>
    {
        if (response.ResponseStatus == ResponseStatus.Error)
        {
            failure(response.ErrorMessage);
        }
        else
        {
            success(response.Data);
        }
    });
}

I pass two callbacks to the method, one for success and one for failure. In this example I am using RestSharp’s auto deserialzation into the class Model.Feed by calling ExecuteAsync<Model.Feed>(). Depending on the status of the request either failure or success action is called.

To use these methods in my wp7 application I use inline delegates to handle the events. One thing to be aware of is the code on these callbacks will run in the background thread and you wont see anything change on the UI. To fix this make sure the data binding code is executed in the UI thread using the dispatcher. I use a DispatcherHelper class borrowed from the MVVM Light Toolkit.

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
	api.GetLabelFeed(
    	feedId,
    	(items) => DispatcherHelper.SafeDispatch(() =>
    	{
        	this.DataContext = items;
        	progressBar.Visibility = System.Windows.Visibility.Collapsed;
    	}),
    	(error) => DispatcherHelper.SafeDispatch(() =>
    	{
        	MessageBox.Show(error);
        	progressBar.Visibility = System.Windows.Visibility.Collapsed;
    	}));

    	base.OnNavigatedTo(e);
}

I found this structure has kept my code reasonable clean and has handled all cases in the simple web requests I have made but since I’m new to Silverlight I’m sure it could be better.

19 Responses

  1. Vvv says:

    Is it free to use restsharp in your application?

  2. Benjii says:

    Nice, wrapping my head around the delegates was tough, but you’ve done a good job explaining it.

  3. Pingback: DotNetShoutout

  4. great article,
    but there was a bug in restsharp sync and async methods http://github.com/johnsheehan/RestSharp/issues#issue/53

    now that it has been fixed, you will have to change your codes a bit.

    because even if response.ResponseStatus is Completed it may still be an error, as your request was completed but was a bad request.

    so u will have to check the response.StatusCode==HttpStatusCode.OK, to make sure your request was executed successfully and that there was no error.

  5. R says:

    How did you get around to the issue of Newtonsoft.Json.Compact not being a Windows Phone library? I can’t reference it in my Phone project.

  6. R says:

    The error I’m getting when trying to use ExecuteAsync is: Could not load type ‘Newtonsoft.Json.Linq.JArray’ from assembly ‘Newtonsoft.Json.Compact, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30AD4FE6B2A6AEED’.

  7. Pingback: Дайджест технических материалов #5 (Windows Phone 7) - Oleksandr Krakovetskiy blog - Microsoft User Group Винница

  8. Koti reddy says:

    you may use the silverlight version of the same library.

  9. Pingback: Pierre’s weblog » Blog Archive » Server side / Framework choice (part 1)

  10. Pingback: Push Notifications in Windows Phone 7 – #1 Code on the Device

  11. tkc says:

    Hi,

    Possible to provide the complete code? thanks.

  12. Sid says:

    Hi,

    I’m trying to do the same sample here (google calendar api) but after getting the token whenever I try to retrieve any data it fails each time.
    The error says that the token is invalid.

    Could you please share the code of how you use the token to retrieve some weather data?

    Thanks.

  13. Pingback: Windows Phone 7 Unleashed All Day Hands-on Programming, B.Y.O. Laptop! « Technology and Information Blog

  14. Nick says:

    Thanks, this was a huge help getting my windows phone 7 app going!

  15. Pingback: Free Training on Windows Phone App Development - News & Announcements - Softec

  16. amar says:

    how can we send the captured images to asmx services from windows phone7 and store it on sql server.

  17. Pingback: New Developer Contest: Windows Phone 7 – Ends Sunday August 15th | Twilio Cloud Communications Blog

  18. Pingback: Behind the XAML of the Windows Phone Silverlight Game – Numbertap | lukencode

  19. Luke Lowrey says:

    Restsharp is free and open source

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>