Working with the Facebook SDK from Windows Phone 7

Facebook has become a vital part of modern application development, both as a means to link users with their pre-existing social data, add to their social data, and as a form of validation.  In our new app we are developing, we are supporting both Facebook based authentication as well as normal authentication.
Within .NET there exists the Facebook C# SDK which is hosted on GitHub.  It is installed via nuget, but lacks documentation for what is available and how to use it.  Example code is available, but its very hard to find, and I have to succeeded in returning to where I found it.
Before we talk about Facebook, we need to talk about the authentication protocol being used by Facebook that allows it to be used in such a way: OAuth.  OAuth is widely used by many of the popular social networking sites such as Twitter, Foursquare, and Facebook.  Using OAuth we can obtain an “access token” which allows us to use the Facebook API.  For the app I am writing, I don’t plan to access Facebook directly, just use the token as a means to authenticate.  One quick side note, while I have not seen it in practice, I am told these “access tokens” do expire, most likely with lack of usage.
So, at this point, you’ve gone out to the website and seen the nuget statement, ran that to add Facebook Client SDK to your project.  Now lets use it.  I am just going to show you how to authenticate and then make a simple call using that authentication.  In addition, we will store the access token so it can be used again.

Authenticating

The important thing to understand is, when authenticating with OAuth, more often then not you will have to display the Facebook login page to collect the credentials.  But you should only have to do this once.  This is the code I used to generate the URL and then feed my Web Browser control:

var client = new FacebookClient();
var parameters = new Dictionary<string, object>();
parameters["client_id"] = AppId;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
 
var uri = client.GetLoginUrl(parameters);
webBrowser.Visibility = Visibility.Visible;
webBrowser.Navigate(uri);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This code simply generate the URI we will pass to our web browser. Generally if a user has already granted access to the app, the call will simply redirect.  This is where our Navigated event handler comes into play.

FacebookOAuthResult oauthResult;
var client = new FacebookClient();
if (client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
    if (oauthResult.IsSuccess)
    {
        string accessToken = oauthResult.AccessToken;
        ((WebBrowser) sender).Visibility = Visibility.Collapsed;
 
        SaveAccessToken(accessToken);
    }
    else
    {
        // user cancelled
        MessageBox.Show(oauthResult.ErrorDescription);
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This is a common way of handling this case.  The FacebookClient class, in this case, hides what is really happening.  If we get back the redirect URL we were looking for, then the operation completed.  The Access Token can then be acquired from that query string.
Notice the call to SaveAccessToken, ideally you would put this in the database, but in this case we are just storing it to IsolatedStorage.  This will also allow us to read it again later when we reaccess the application so that we can by pass having to ask Facebook for it again.

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (var stream = new IsolatedStorageFileStream("fb_access_token", FileMode.Create, FileAccess.Write, store))
    {
        using (var writer = new StreamWriter(stream))
        {
            writer.Write(accessToken);
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Very simple and straightforward.

Usage

Using the Facebook Client class to make a request to Facebook is very simple.  Simply provide the AccessToken to the client via the constructor or by updating the appropriate property.  Keep in mind that UI blocking methods are not allowed on Windows Phone 7, thus we need to use the Async version (this predates the async and await keywords, so we cant use them).

string accessToken = ReadAccessToken();
var fb = new FacebookClient(accessToken);
fb.GetCompleted += fb_GetCompleted;
fb.GetAsync("/me");

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Don’t forget to handle the completed event, the return is a JSON object.  With the client, if the call works you will get the JSON object as mentioned, null if it does not work.

Conclusion

Granted this example is ultra simplistic, it nevertheless demonstrates what is likely the most common usage of the Facebook API, authentication.  The truth is that over 900 million people/groups have Facebook accounts, thus it is a very handy authentication mechanism that can save the time involved in creating, and securing, your own authentication mechanism.

Advertisements

One thought on “Working with the Facebook SDK from Windows Phone 7

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