Windows Phone Store 8.1: FaceBook Integration Sample (C# XAML)

Introduction

This article shows how to easily integrate Facebook into your Windows Phone Store 8.1 application.

This topic contains the following sections:

  • Installation of Facebook SDK
  • Linking App with Facebook
  • Work with Facebook Login Page
  • Post status message on Facebook Wall
  • Logout from Facebook Page

Facebook

Why Facebook Integration

Facebook users increasingly rely on their Facebook identity to access apps, play games with friends, share playlists or comment in a forum. As a developer, you may also rely on a Facebook Login to tap into the Facebook social graph to enhance your app's experience, enable new scenarios and open up the app to new customers, resulting in better revenue opportunities.

Requirements

  • This sample is targeted for the Windows Phone Store 8.1 OS, so be sure you've downloaded and installed the Windows Phone 8.1 SDK. For more information, see Get the SDK.

  • I assume you're going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you need to use an additional procedure. For more info, see Register your Windows Phone device for development.

  • This article assumes you're using Microsoft Visual Studio Express 2013 for Windows.

Description

First of all, open Microsoft Visual Studio Express 2013 for Windows and then create a new project type Blank App (for example: FaceBookWp8.1).

blankapp

1.1 Installation of Facebook SDK

Install the Facebook Nuget package into the solution by starting the Package Manager PowerShell by following:

Tools -> Library Package Manager -> Package Manager console

Package Manager console

Once the powershell command prompt is running, enter the following command.

Install-Package Facebook

Install Package Facebook

This will add the Facebook SDK into the current project as in the following.

reference

1.2 Linking App with Facebook

First of all, you need to create a Facebook application on the website. Here is the link to do so. Click the "Add New App" button.

add a new app

Enter the Display Name, namespace (optional) and then click "Create App ID".

Create App ID

Now go to Settings. There click on add platform.

add platform

Please note the preceding App Id. You must select Windows App as a platform, because in this sample we are trying to connect Windows Phone 8.1 store apps.

Windows App

And now the most important step is we need to fill in the Windows Store ID.

There are a couple of ways to get the value to be put into that field, for one of them in this sample I will use the WebAuthenticationBroker class like this:

Uri _callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

In my case the preceding statement returns the following URI, you may check the preceding code by downloading the sample and looking at the "FaceBookHelper.cs" class from the "Helpers" folder in a project.

FaceBookHelper

We proceed to copy that URI, on the page Facebook App "facebookwptest" a new platform and select Windows App. There two fields appear, since this app is creating for Windows Phone 8.1 and then we place the URI Windows Store ID. If I were developing a Silverlight App Windows Phone 8.1 we should use another field and a different URI.

For the URI we must place there the GUID by copying everything from "s-" without inclkuir rl "/" end being something like:

Guid copying

Note: Since we are creating a Windows Phone Store app, ignore the field for Windows Phone and we look only at the Windows Store ID.

1.3 Work with Facebook Login Page

Before going to login any social networks, oAuth is the common authentication method nowadays for Apps and Websites. In this article I am interested in using WebAuthenticationBroker.

Note: Unlike the Windows WebAuthenticationBroker, the Phone version does not use the AuthenticateAsync method. It uses AuthenticateAndContinue instead. This is related to the lifecycle on the phone, since it is more likely that an WINPRT app is suspended than on Windows (at least that's the official reason).

But we are able to get it working, no worries. First, we need the so called ContinuationManager. This class brings the user back to the app where the fun begun. So create a folder named "Helpers" and add the following class.

  1. namespace FaceBookWp8._1.Helpers    
  2. {    
  3.     class ContinuationManager    
  4.     {    
  5.         public void ContinueWith(IActivatedEventArgs args)    
  6.         {    
  7.             var rootFrame = Window.Current.Content as Frame;    
  8.             if (rootFrame == null)    
  9.                 return;    
  10.     
  11.             switch (args.Kind)    
  12.             {    
  13.                 case ActivationKind.PickFileContinuation:    
  14.                     break;    
  15.                 case ActivationKind.PickFolderContinuation:    
  16.                     break;    
  17.                 case ActivationKind.PickSaveFileContinuation:    
  18.                     break;    
  19.                 case ActivationKind.WebAuthenticationBrokerContinuation:    
  20.                     var continuator = rootFrame.Content as IWebAuthenticationBrokerContinuable;    
  21.                     if (continuator != null)    
  22.                         continuator.ContinueWithWebAuthenticationBroker((WebAuthenticationBrokerContinuationEventArgs)args);    
  23.                     break;    
  24.                 default:    
  25.                     break;    
  26.             }    
  27.         }    
  28.     }    
  29.     interface IWebAuthenticationBrokerContinuable    
  30.     {    
  31.         void ContinueWithWebAuthenticationBroker(WebAuthenticationBrokerContinuationEventArgs args);    
  32.     }    
  33. }    
Here the only thing you need to do is to add your app's namespace into it (here in my case the namespace is FaceBookWp8._1.Helpers).

The next step we need to do is some modifications into the App.xaml.cs file.
  1. protected async override void OnActivated(IActivatedEventArgs args)    
  2. {    
  3.     CreateRootFrame();    
  4.   
  5.     if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)    
  6.     {    
  7.         try    
  8.         {    
  9.             await SuspensionManager.RestoreAsync();    
  10.         }    
  11.         catch { }    
  12.     }    
  13.   
  14.     if (args is IContinuationActivatedEventArgs)    
  15.         _continuator.ContinueWith(args);    
  16.   
  17.     Window.Current.Activate();    
  18. }   
Add a CreateRootFrame() method with some little changes to the default behavior.
  1. private void CreateRootFrame()    
  2. {    
  3.     Frame rootFrame = Window.Current.Content as Frame;    
  4.     if (rootFrame == null)    
  5.     {    
  6.         rootFrame = new Frame();    
  7.         SuspensionManager.RegisterFrame(rootFrame, "AppFrame");    
  8.         Window.Current.Content = rootFrame;    
  9.     }    
  10. }    
First, we check the SuspensionManager and let him restore a saved state, if there is one. If you do not have a Folder "Common" with the SuspensionManager, just add a new Basic page. This will generate the Common folder with the SuspenstionManager class for you. However in this sample I added a SuspensionManager class in the "Helpers" folder.

Then, we are checking if the activation is a Continuation. We need this check there, otherwise the app will not be able to receive the Tokens after returning from the WebAuthenticationBroker.

Note: declare the ContinuationManager globally in App.xaml.cs with this to avoid multiple instances (that will crash the app for sure). 
  1. ContinuationManager _continuator = new ContinuationManager();   
Of the suspension system responsible, the event will fire OnSuspending found in the App case: App.xaml.cs that at the moment looks like this (there is no need to do anything).
  1. private async void OnSuspending(object sender, SuspendingEventArgs e)    
  2. {    
  3.     var deferral = e.SuspendingOperation.GetDeferral();    
  4.     await SuspensionManager.SaveAsync();    
  5.     deferral.Complete();     
  6. }    
Add the following class in the "Helpers" folder. Which is useful to login into Facebook using WebAuthenticationBroker.
  1. namespace FaceBookWp8._1.Helpers    
  2. {    
  3.     public class FaceBookHelper    
  4.     {    
  5.         FacebookClient _fb = new FacebookClient();    
  6.         readonly Uri _callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();    
  7.         readonly Uri _loginUrl;     
  8.         private const string FacebookAppId = "xxxxxxxxxxxxxxx";//Enter your FaceBook App ID here    
  9.         private const string FacebookPermissions = "user_about_me,read_stream,publish_stream";    
  10.         public string AccessToken    
  11.         {    
  12.             get { return _fb.AccessToken; }    
  13.         }    
  14.     
  15.         public FaceBookHelper()    
  16.         {    
  17.             _loginUrl = _fb.GetLoginUrl(new    
  18.                     {    
  19.                         client_id = FacebookAppId,    
  20.                         redirect_uri = _callbackUri.AbsoluteUri,    
  21.                         scope = FacebookPermissions,    
  22.                         display = "popup",    
  23.                         response_type = "token"    
  24.                     });    
  25.             Debug.WriteLine(_callbackUri);//This is useful for fill Windows Store ID in Facebook WebSite    
  26.         }    
  27.         private void ValidateAndProccessResult(WebAuthenticationResult result)    
  28.         {    
  29.             if (result.ResponseStatus == WebAuthenticationStatus.Success)    
  30.             {    
  31.                 var responseUri = new Uri(result.ResponseData.ToString());    
  32.                 var facebookOAuthResult = _fb.ParseOAuthCallbackUrl(responseUri);    
  33.     
  34.                 if (string.IsNullOrWhiteSpace(facebookOAuthResult.Error))    
  35.                     _fb.AccessToken = facebookOAuthResult.AccessToken;    
  36.                 else    
  37.                 {//error de acceso denegado por cancelación en página    
  38.                 }    
  39.             }    
  40.             else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)    
  41.             {// error de http    
  42.             }    
  43.             else    
  44.             {    
  45.                 _fb.AccessToken = null;//Keep null when user signout from facebook    
  46.             }    
  47.         }    
  48.         public void LoginAndContinue()    
  49.         {    
  50.             WebAuthenticationBroker.AuthenticateAndContinue(_loginUrl);    
  51.         }    
  52.         public void ContinueAuthentication(WebAuthenticationBrokerContinuationEventArgs args)    
  53.         {    
  54.             ValidateAndProccessResult(args.WebAuthenticationResult);    
  55.         }    
  56.     }    
  57. }   
Note: Please enter your Facebook App ID in the preceding code. Otherwise you will get an error as in the following.

FaceBook App ID in above code

Now our project hierarchy will be like this.

project hierarchy will be like

Wow! Now we are nearly done, let's make the following UI in the MainPage.xaml page to use the preceding helpers.
  1. <StackPanel>    
  2.        <!--Title-->    
  3.        <TextBlock Text="FaceBook Integration in WP8.1:" FontSize="28" Foreground="Gray"/>    
  4.        <!--Buttons for Login & Logout-->    
  5.        <Button Name="BtnLogin" Content="FaceBook Login" HorizontalAlignment="Stretch" Background="#FF00A9CF" Click="BtnFaceBookLogin_Click"/>    
  6.        <Button Visibility="Collapsed" Name="BtnLogout" Content="FaceBook Logout" HorizontalAlignment="Stretch" Background="#FF00A9CF" Click="BtnFaceBookLogout_Click"/>    
  7.            
  8.        <StackPanel Visibility="Collapsed" Name="StckPnlProfile_Layout">    
  9.            <!--Display facebook profile info-->    
  10.            <TextBlock Text="User Profile :" FontSize="30" TextWrapping="Wrap"  Foreground="White"/>    
  11.            <Image Stretch="None" x:Name="picProfile"  HorizontalAlignment="Left" />    
  12.            <TextBlock FontSize="20" Name="TxtUserProfile" TextWrapping="Wrap"  Foreground="White"/>    
  13.            <!--Post wall-->    
  14.            <TextBox Name="TxtStatusMsg" MinHeight="150" TextWrapping="Wrap" Header="Status Message:" FontSize="18" Foreground="Black"/>    
  15.            <Button Content="Post Status on FaceBook" HorizontalAlignment="Stretch" Background="#FF00A9CF" Click="BtnFaceBookPost_Click"/>    
  16.        </StackPanel>    
  17.            
  18.    </StackPanel>   
Here in the preceding XAML code, there are four sections:  
  1. For displaying sample title.
  2. Buttons for Login and Logout.
  3. UI for displaying user profile info, after successfully logging into Facebook.
  4. Post message to wall.

In the MainPage.cs file, create the following two global objects for the "FaceBookHelper.cs" class and FacebookClient.

  1. FaceBookHelper ObjFBHelper = new FaceBookHelper();   
  2. FacebookClient fbclient = new FacebookClient();   
Ok, let's write some code for Facebook login upon the BtnFaceBookLogin_Click Event:
  1. private void BtnFaceBookLogin_Click(object sender, RoutedEventArgs e)    
  2. {    
  3.      ObjFBHelper.LoginAndContinue();    
  4. }  
When clicking on the Login button from the UI, WebAuthenticationBroker will get the Facebook login URL from the FaceBookHelper constructor and the screen will be shown as in the following.

FaceBookHelper constructor

The Facebook username and password entered will be processed for authentication and then will be ask for your permissions. Press OK to successfully log into the Facebook page.

logon to facebook page

After successfully logging into the Facebook page, add the following method for fetching the user profile data in the MainPage.cs file.
  1. public async void ContinueWithWebAuthenticationBroker(WebAuthenticationBrokerContinuationEventArgs args)    
  2. {    
  3.     ObjFBHelper.ContinueAuthentication(args);    
  4.     if (ObjFBHelper.AccessToken != null)    
  5.     {    
  6.         fbclient = new Facebook.FacebookClient(ObjFBHelper.AccessToken);    
  7.   
  8.         //Fetch facebook UserProfile:    
  9.         dynamic result = await fbclient.GetTaskAsync("me");    
  10.         string id = result.id;    
  11.         string email = result.email;    
  12.         string FBName = result.name;    
  13.   
  14.         //Format UserProfile:    
  15.         GetUserProfilePicture(id);    
  16.         TxtUserProfile.Text = FBName;    
  17.         StckPnlProfile_Layout.Visibility = Visibility.Visible;    
  18.         BtnLogin.Visibility = Visibility.Collapsed;    
  19.         BtnLogout.Visibility = Visibility.Visible;    
  20.     }    
  21.     else    
  22.     {    
  23.         StckPnlProfile_Layout.Visibility = Visibility.Collapsed;    
  24.     }    
  25.         
  26. }     
To get the user profile image, add the following method:
  1. private void GetUserProfilePicture(string UserID)    
  2. {    
  3.     string profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", UserID, "square", ObjFBHelper.AccessToken);    
  4.     picProfile.Source = new BitmapImage(new Uri(profilePictureUrl));    
  5. }    
user profile

1.4 Post status message on Facebook Wall

When clicking on the Post Status button, add the following code to the MainPage.cs file:
  1. private async void BtnFaceBookPost_Click(object sender, RoutedEventArgs e)    
  2. {    
  3.     var postParams = new    
  4.     {    
  5.         name = "Facebook Post Testing from App.",    
  6.         caption = "WindowsPhone 8.1 FaceBook Integration.",    
  7.         link = "http://bsubramanyamraju.blogspot.in",    
  8.         description=TxtStatusMsg.Text,    
  9.         picture = "http://facebooksdk.net/assets/img/logo75x75.png"    
  10.     };    
  11.     try    
  12.     {    
  13.         dynamic fbPostTaskResult = await fbclient.PostTaskAsync("/me/feed", postParams);    
  14.         var responseresult = (IDictionary<stringobject>)fbPostTaskResult;    
  15.         MessageDialog SuccessMsg = new MessageDialog("Message posted sucessfully on facebook wall");    
  16.         await SuccessMsg.ShowAsync();    
  17.     }    
  18.     catch (Exception ex)    
  19.     {    
  20.         //MessageDialog ErrMsg = new MessageDialog("Error Ocuured!");    
  21.             
  22.     }    
  23. }   
status message

close

After posting status, we will get a found status message on the Facebook timeline as in the following:

status message on your Facebook

1.5 Logout from Facebook Page

When clicking on the Logout button, add the following code to the MainPage.cs file:
  1. private async void BtnFaceBookLogout_Click(object sender, RoutedEventArgs e)    
  2. {    
  3.     _logoutUrl = fbclient.GetLogoutUrl(new    
  4.     {    
  5.         next = "https://www.facebook.com/connect/login_success.html",    
  6.         access_token = ObjFBHelper.AccessToken    
  7.     });    
  8.     WebAuthenticationBroker.AuthenticateAndContinue(_logoutUrl);    
  9.     BtnLogin.Visibility = Visibility.Visible;    
  10.     BtnLogout.Visibility = Visibility.Collapsed;     
  11. }   
Summary

From this article we have learned "Facebook Integration in Windows Phone 8.1 application". I hope I wrote this article with my best level. When writing this article, I tried really hard to make a nice presentation and make the article understandable at the beginner's level.

This article is also available at my original blog.