How to use Facebook Graph API in Windows Phone
This article explains how to use Facebook Graph API in Windows Phone 7.
Article Metadata
Compatibility
Article
Contents |
Introduction
This article shows how to access the Facebook Graph API in Windows Phone 7, using an adapted version of the Facebook C# SDK (tested with v5.3.2.0).
The Facebook C# SDK is designed for using with the desktop client. Although the SDK mentions that it can be used on Windows Phone, documentation is lacking and some changes are needed to make it usable. This article provides this missing information.
The Facebook C# SDK can be downloaded from here. Description about Facebook Graph API can be found here.
Installation
The first step is to install the Facebook C# SDK. Do this in the Visual Studio Package Manager Console by typing the following:
PM> Install-Package Facebook -Pre
Detailed description of using the Package manager is found here.
Implementation
There are two parts of the code. First, we need to create Facebook app in order to use authorization capability of Facebook Graph API. After that, we create the Visual C# project that encapsulates all the codes to use Facebook Graph API
Creating the Facebook App
The Facebook Graph API uses OAuth 2.0 for authorization. We need to request permissions from a user and obtain an access token. After obtaining the access token for the user, we can perform authorized requests on behalf of that user by including the access token in the Graph API requests.
For example, https://graph.facebook.com/btaylor?access_token=xxx returns additional information about Bret Taylor, where xxx is the access token.
For this, we create a Facebook App. The app doesn't need to contain any code - but we do need the app_id, which is to be used in the Visual C# code. To create a Facebook App - please follow the first step given here.
Creating the Visual C# project
I have created a Visual C# project that uses the Facebook Graph API to check the nearby location and return some shop information via http asynchronous request from a database hosted on a www server. The app is called RewardME. This article is not for describing how the app works but rather on the steps needed on using Facebook Graph API. As such I will only describe the codes associated with the latter. Firstly, I need a login page and a logout page
Login
I create a login page and here is the code in LoginPage.xaml.cs. take note on the assembly reference Facebook which is added to the file a webBrowser control webBrowser1 is necessary to handle the authorization process:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using Microsoft.Phone.Controls;
using Facebook;
namespace RewardME
{
public partial class LoginPage : PhoneApplicationPage
{
private Uri loginUrl;
public FacebookOAuthResult FacebookOAuthResult { get; private set; }
public LoginPage()
{
var appId = "xxxxxxx"; //xxxxxxxx is the appID for you facebook app
string[] extendedPermissions = new[] { "user_about_me", "offline_access" };
var oauth = new FacebookOAuthClient { AppId = appId };
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "wap" } //"popup works, touch not works
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
this.loginUrl = oauth.GetLoginUrl(parameters);
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
webBrowser1.Navigate(this.loginUrl);
}
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
this.FacebookOAuthResult = result;
PageTitle.Text = "successful login ";
//var fb = new FacebookClient(this.FacebookOAuthResult.AccessToken);
//var fbClient = new FacebookClient(this.FacebookOAuthResult.AccessToken);
var a = App.Current as App;
a.isLoggedIn = true;
a.myToken = this.FacebookOAuthResult.AccessToken;
PageTitle.Text = "welcome ";
// don't exit from this page here, call populateDataApp instead
this.populateDatatoApp();
}
else
{
this.FacebookOAuthResult = null;
PageTitle.Text = "fail login";
}
}
/*
*this function will fill up the App data
* */
private void populateDatatoApp()
{
getName();
}
private void getName()
{
var a = App.Current as App;
//return name
if (a.isLoggedIn)
{
//MessageBox.Show("you are login as");
var fbClient = new FacebookClient(a.myToken);
fbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(onGetNameCompleted);//another example
fbClient.GetAsync("/me", new Dictionary<string, object> { { "fields", "id,name,first_name,last_name,picture" }, { "access_token", a.myToken } });
}
else
{
MessageBox.Show("you are not login. login first");
}
}
private void getShop()
{
var a = App.Current as App;
//return name
if (a.isLoggedIn)
{
//MessageBox.Show("you are login as");
var fbClient = new FacebookClient(a.myToken);
fbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(onGetShopCompleted);//another example
Dictionary<string, object> searchParams = new Dictionary<string, object>();
//searchParams.Add("q", "coffee");
a.latitude = "3.062246"; a.longitude = "101.616064";//temporary hard code the lat and long
searchParams.Add("center", a.latitude + "," + a.longitude);
searchParams.Add("type", "place");
searchParams.Add("distance", "1000");
fbClient.GetAsync("/search", searchParams);
}
else
{
MessageBox.Show("you are not login. login first");
}
}
private void onGetNameCompleted(object sender, FacebookApiEventArgs e)
{
var a = App.Current as App;
if (e.Error == null)
{
var result = (IDictionary<string, object>)e.GetResultData();
// Get user name
a.usrName = result["name"].ToString();
a.usrID = result["id"].ToString();
//pass control to getShop
this.getShop();
}
else
{
//MessageBox.Show(e.Error.Message);
}
}
private void onGetShopCompleted(object sender, FacebookApiEventArgs e)
{
var a = App.Current as App;
if (e.Error == null)
{
var result = (IDictionary<string, object>)e.GetResultData();
// JSON extraction here
var model = new List<Place>();
foreach (var place in (JsonArray)result["data"])
model.Add(new Place()
{
Id = (string)(((JsonObject)place)["id"]),
Name = (string)(((JsonObject)place)["name"])
});
a.placeList = model;//store the list to the app
Dispatcher.BeginInvoke(() => {NavigationService.Navigate(new Uri("/RewardMePivot.xaml", UriKind.Relative)); });
//exit the current page. look at explanation at http://csainty.blogspot.com/2010/10/windows-phone-7asynchronous-programming.html
}
else
{
//MessageBox.Show(e.Error.Message);
}
}
}
}
Logout
We also need a logout page to handle a logout request. Again, we need to use a webBrowser control for this. Here is listing of code contains on a logout page called LogoutPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using Microsoft.Phone.Controls;
using Facebook;
namespace RewardME
{
public partial class LogoutPage : PhoneApplicationPage
{
private Uri navigateUrl;
public FacebookOAuthResult FacebookOAuthResult { get; private set; }
public LogoutPage()
{
var appId = "173963872698818";
string[] extendedPermissions = new[] { "user_about_me", "offline_access" };
var oauth = new FacebookOAuthClient { AppId = appId };
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "wap" } //"popup works, touch not works
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
var logoutParameters = new Dictionary<string, object>
{
{ "next", loginUrl }
};
//Redirect to the following url.
// https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN
//this.navigateUrl = oauth.GetLogoutUrl(logoutParameters);
var a = App.Current as App;
string absoluteURI = " https://www.facebook.com/logout.php?next=http://www.fengshuiexplorer.host56.com&access_token=" + a.myToken;
this.navigateUrl = new Uri(absoluteURI);
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
webBrowser1.Navigate(this.navigateUrl);
}
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
this.FacebookOAuthResult = result;
var a = App.Current as App;
a.isLoggedIn = false;
NavigationService.GoBack();
}
else
{
this.FacebookOAuthResult = null;
}
}
}
}
Summary
The Facebook C# SDK can be used for using Facebook Graph API on WP7 with some adaptation


Contents
Vineet.jain - Nice Article
Hello weiwei2,
This looks a very nice article & i am sure its going to help lot of people as Facebook integration has become almost a significant part of each app these days. Just to mention few points :
1) About the XAML, if you can also please add the code for it.
2) Adding a sample running project would also be good.
Thanks
Vineetvineet.jain 07:48, 21 February 2012 (EET)
Croozeus - Cool
Hi Wei,
Cool article. Nice to see you playing with WP7 :)
I gave it a light subedit and added few links. Please check if OK.
A buildable project would be a good addition to this!
//Pcroozeus 08:11, 21 February 2012 (EET)
Lseidman -
I'm sorry to tell you, this code is all wrong. A lot of things here are not right. You should be using public strings for one thing and other items as well.
I can build you a real login example but this will definitely fail on Mango.lseidman 05:36, 17 April 2012 (EEST)
Hamishwillee - weiwei2 Buildable project, and changes to the SDK, Lseidman , what?
Hi Lseidman, weiwei2
Lseidman, thanks for your comments. Can you be more specific about the errors in this project and where you think it will fail as this will help weiwei2 improve it and others recognise bad coding practises.
weiwei2, it would really help if you provided your code as a buildable project (ie a project stored in a Zip file and attached to the page- that way we could try it out and see how well it works. In terms of the documentation, you also state that the SDK needs to be adapted to work with Windows Phone, however there is no information on what changes need to be made. Can you be more precise.
On the face of it this is a useful document, but we really do need more information in order to be able to assess its value.
Regards
Hamishhamishwillee 07:25, 30 April 2012 (EEST)
Weiwei2 -
Let me clean up my code before i post a build able project. right now it is build able, but it contains some webservice call to my own customized online database that is not relevant to the facebook usage.
Hi Lseidman appreciate if you can be more elaborative about errors that you mention and what would be the improvement or correct ways for using the facebook API?
i finished up this code (login to facebook) and webservice call to my database in a 2 days hackhaton so i wouldn't say it is perfect, but the code does run on Mango.weiwei2 08:16, 30 April 2012 (EEST)