×
Namespaces

Variants
Actions

How to use Facebook Graph API in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

This article explains how to use Facebook Graph API in Windows Phone 7.

WP Metro Icon Web.png
SignpostIcon XAML 40.png
SignpostIcon WP7 70px.png
Article Metadata
Compatibility
Platform(s): Windows Phone 7.5
Windows Phone 7.5
Article
Created: weiwei2 (21 Feb 2012)
Last edited: hamishwillee (27 Jun 2013)

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

This page was last modified on 27 June 2013, at 14:23.
387 page views in the last 30 days.