Subscribe RSS Join our Facebook Group Follow us on Twitter!
in Search

Izzuddin Gumilar's Blog

#Using Facebook C# SDK for Windows Phone 7

Hi! In this blog post I will show you how to integrate facebook graph API to our .net application. In this case I will use Facebook C# SDK to post feed into my wall from Windows Phone 7. Facebook C# SDK is an open source library that help .Net developer to build web, desktop, Silverlight, and Windows Phone 7 application integrate it with facebook. We can download this library from http://facebooksdk.codeplex.com/ and I use Facebook SDK V4.2.1 to build demo application in this blog post. Oke let’s start…


First, we create new windows phone page name it “MainPage.xaml” and put WebBrowser control named “FacebookLoginBrowser” into that page like this preview. This page is used to show facebook login form to get access token from facebook graph API. After we success login in this authentication form, we get a facebook graph API access token so this application can access our facebook account data like wall post, photo, link, friends, etc depend on request facebook permission that our application have. For the details about Facebook Graph API we can go to http://developers.facebook.com/docs/reference/api/


MainPage preview


Then, we create another windows phone page name it “Page1.xaml” to publish some text into our facebook wall post. We put textbox and button control into Page1.xaml like this.
Page1 Preview
Okey, let’s start code some script to build our application so it can post some text into our wall post. Don't forget add reference facebook c# sdk library into this project - Facebook.dll, Microsoft.Contract.dll, Newtonsoft.Json.WindowsPhone.dll.

Add Reference 

First, we set some variable that are used to get facebook authentication for our application. There are two important variables wich has an impact to get user access token that accessible for the application. “ApiKey” variables is our facebook application key point to what application that access user facebook graph information. If you haven’t that key yet, you can register your facebook application first in http://developers.facebook.com/setup/.  “requestedFbPermissions” variable is used if your app needs more than this basic information to function, you must request specific permissions from the user like user_checkins, friends_checkins, publish_checkins, etc.

  1 private const string apiKey = "your app ID";
2 private string requestedFbPermissions = "user_checkins,friends_checkins,publish_checkins,user_about_me,user_photos,user_videos,publish_stream"; //email,user_likes,user_checkins"; //"email,user_likes,user_checkins,publish_checkins"; //etc
3 private string accessToken;
4
5 private const string successUrl = "http://www.facebook.com/connect/login_success.html";
6 private const string failedUrl = "http://www.facebook.com/connect/login_failure.html";
7 private bool loggedIn = false;
8 private FacebookApp fbApp;
9 PhoneApplicationService appService = PhoneApplicationService.Current;
10
11 public MainPage()
12 {
13 InitializeComponent();
14 fbApp = new FacebookApp();
15 FacebookLoginBrowser.Loaded += new RoutedEventHandler(FacebookLoginBrowser_Loaded);
16 }
17
18 private void loginSucceeded()
19 {
20 NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.RelativeOrAbsolute));
21 }
22
23 private void LoginToFacebook()
24 {
25 var parms = new Dictionary<String, object>();
26 parms["display"] = "touch";
27 parms["client_id"] = apiKey;
28 parms["redirect_uri"] = successUrl;
29 parms["cancel_url"] = failedUrl;
30 parms["scope"] = requestedFbPermissions;
31 parms["type"] = "user_agent";
32
33 var loginUrl = fbApp.GetLoginUrl(parms);
34 FacebookLoginBrowser.Navigate(loginUrl);
35 }
36

We must add some Control event that load facebook authentication page, get authenticataion result when web result completely load, and redirect page base on that result.

  1 void FacebookLoginBrowser_Loaded(object sender, RoutedEventArgs e)
2 {
3 if (!loggedIn)
4 {
5 LoginToFacebook();
6 }
7 }
8
9 protected override void OnNavigatedFrom(NavigationEventArgs args) // used to set fbApp variables to another page.
10 {
11 appService.State["fbApp"] = fbApp;
12 base.OnNavigatedFrom(args);
13 }
14
15 protected override void OnNavigatedTo(NavigationEventArgs args)
16 {
17 base.OnNavigatedTo(args);
18 }
19
20 private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
21 {
22 FacebookAuthenticationResult authResult;
23 if (FacebookAuthenticationResult.TryParse(e.Uri, out authResult))
24 {
25 fbApp.Session = authResult.ToSession();
26 loginSucceeded();
27 }
28 }
29
30 private void FacebookLoginBrowser_LoadCompleted(object sender, NavigationEventArgs e)
31 {
32 try
33 {
34 FacebookLoginBrowser.InvokeScript("eval", "(function() { var aboveFooter=document.getElementById('platform_dialog_bottom_bar').previousSibling; document.getElementById('platform_dialog_bottom_bar').style.top=aboveFooter.offsetHeight + aboveFooter.offsetTop + 'px' })()");
35 }
36 catch (Exception ex) { }
37 }
38

 And the code for Page1.xaml is

  1 PhoneApplicationService appService = PhoneApplicationService.Current;
2 private FacebookApp fbApp;
3
4 public Page1()
5 {
6 InitializeComponent();
7 }
8
9 private void postLink()
10 {
11 try
12 {
13 var linkDetails = new Dictionary<string, object>();
14 linkDetails.Add("message", textBox1.Text);
15
16 fbApp.PostAsync(@"/me/feed", linkDetails, (fbResult) =>
17 {
18 var result = (IDictionary<string, object>)fbResult.Result;
19 //var albumID = result["id"];
20 });
21 MessageBox.Show("The news has posted successfully..");
22 }
23 catch (Exception e)
24 {
25 MessageBox.Show("Sorry, there's an error occured, please try again.");
26 }
27
28
29 }
30
31 protected override void OnNavigatedFrom(NavigationEventArgs args)
32 {
33 //appService.State["linkUrl"] = ((ItemViewModel)lbTalks.SelectedItem).LinkUrl;
34
35 base.OnNavigatedFrom(args);
36 }
37
38 protected override void OnNavigatedTo(NavigationEventArgs args)
39 {
40 if (appService.State.ContainsKey("fbApp"))
41 fbApp = (FacebookApp)appService.State["fbApp"];
42
43 base.OnNavigatedTo(args);
44 }
45
46 private void button1_Click(object sender, RoutedEventArgs e)
47 {
48 postLink();
49 }
50

 Oke let’s test this application..

 Facebook Authentication Page Posting to facebook

 Download source code here.

4,506 Views, 0 Comment(s), Published on: 03-10-2011 19:38 by izzuddin to Izzuddin Gumilar's Blog

Comments

No Comments

About izzuddin

Izzuddin Gumilar Aprilian
Business System Application Services - PT. Berau Coal
ex-Microsoft Student Partner Lead - East Java Regional

Web : http://izzuddin.net/
Blog : http://students.netindonesia.net/blogs/izzuddin/
Facebook : http://www.facebook.com/izzuddin.cs
Email : izzuddin_cs@yahoo.co.id