Google Data API with RestSharp on WP7 Update

Special thanks to John Sheenan who pointed out an error in my code. First of all, calling Dispatcher.BeginInvoke is redundant since the callback action will be invoked on the main thread.

Secondly, there is a powerful deserialization feature in RestSharp. Create a simple class that will correspond to the deserialized JSON object:

public class oauth2_device_code
{
    public string device_code { get; set; }
    public string expires_in { get; set; }
    public string interval { get; set; }

    public string user_code { get; set; }
    public string verification_url { get; set; }
}

You can execute request using the generic version of RestClient.ExecuteAsync:

_clientOAuth.ExecuteAsync<oauth2_device_code>(request, (response) =>
{
	IsolatedStorageSettings.ApplicationSettings["device_code"] = response.Data.device_code;
	IsolatedStorageSettings.ApplicationSettings["expires_in"] = response.Data.expires_in;
	IsolatedStorageSettings.ApplicationSettings["interval "] = response.Data.interval;
	IsolatedStorageSettings.ApplicationSettings.Save();
}

This class matches the following JSON response:

{
  "device_code" : "...",
  "user_code" : "...",
  "verification_url" : "http://www.google.com/device",
  "expires_in" : 1800,
  "interval" : 5
}

However, if you form a bad request, you might get the following JSON response:

{
  "error" : "invalid_client"
}

By adding another property to the oauth2_device_code class (see example below), RestSharp will fill it and you can use the request’s StatusCode property to determine if there was an error. The library will try to match as many properties as it can and fill them accordingly. The best thing is that the C# property names do not need to be named the same way their corresponding fields in JSON are. E.g. the device_code field in JSON will match and fill the DeviceCode class property in the C# code.

public class oauth2_device_code
{
    // ...
    public string error { get; set; }
}

RestSharp can also deserialize XML responses in the same vein. This powerful feature does not impact your naming convention, which is clearly a benefit.

Advertisements

About programabilan

Profesionalni programer, amaterski programer...

Posted on January 23, 2012, in Development and tagged , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: