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
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).
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
Once the powershell command prompt is running, enter the following command.
Install-Package Facebook
This will add the Facebook SDK into the current project as in the following.
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.
Enter the Display Name, namespace (optional) and then click "Create App ID".
Now go to Settings. There click on 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.
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.
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:
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.
- namespace FaceBookWp8._1.Helpers
- {
- class ContinuationManager
- {
- public void ContinueWith(IActivatedEventArgs args)
- {
- var rootFrame = Window.Current.Content as Frame;
- if (rootFrame == null)
- return;
-
- switch (args.Kind)
- {
- case ActivationKind.PickFileContinuation:
- break;
- case ActivationKind.PickFolderContinuation:
- break;
- case ActivationKind.PickSaveFileContinuation:
- break;
- case ActivationKind.WebAuthenticationBrokerContinuation:
- var continuator = rootFrame.Content as IWebAuthenticationBrokerContinuable;
- if (continuator != null)
- continuator.ContinueWithWebAuthenticationBroker((WebAuthenticationBrokerContinuationEventArgs)args);
- break;
- default:
- break;
- }
- }
- }
- interface IWebAuthenticationBrokerContinuable
- {
- void ContinueWithWebAuthenticationBroker(WebAuthenticationBrokerContinuationEventArgs args);
- }
- }
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.
- protected async override void OnActivated(IActivatedEventArgs args)
- {
- CreateRootFrame();
-
- if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
- {
- try
- {
- await SuspensionManager.RestoreAsync();
- }
- catch { }
- }
-
- if (args is IContinuationActivatedEventArgs)
- _continuator.ContinueWith(args);
-
- Window.Current.Activate();
- }
Add a CreateRootFrame() method with some little changes to the default behavior.
- private void CreateRootFrame()
- {
- Frame rootFrame = Window.Current.Content as Frame;
- if (rootFrame == null)
- {
- rootFrame = new Frame();
- SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
- Window.Current.Content = rootFrame;
- }
- }
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).
- 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).
- private async void OnSuspending(object sender, SuspendingEventArgs e)
- {
- var deferral = e.SuspendingOperation.GetDeferral();
- await SuspensionManager.SaveAsync();
- deferral.Complete();
- }
Add the following class in the "Helpers" folder. Which is useful to login into Facebook using WebAuthenticationBroker.
- namespace FaceBookWp8._1.Helpers
- {
- public class FaceBookHelper
- {
- FacebookClient _fb = new FacebookClient();
- readonly Uri _callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
- readonly Uri _loginUrl;
- private const string FacebookAppId = "xxxxxxxxxxxxxxx";
- private const string FacebookPermissions = "user_about_me,read_stream,publish_stream";
- public string AccessToken
- {
- get { return _fb.AccessToken; }
- }
-
- public FaceBookHelper()
- {
- _loginUrl = _fb.GetLoginUrl(new
- {
- client_id = FacebookAppId,
- redirect_uri = _callbackUri.AbsoluteUri,
- scope = FacebookPermissions,
- display = "popup",
- response_type = "token"
- });
- Debug.WriteLine(_callbackUri);
- }
- private void ValidateAndProccessResult(WebAuthenticationResult result)
- {
- if (result.ResponseStatus == WebAuthenticationStatus.Success)
- {
- var responseUri = new Uri(result.ResponseData.ToString());
- var facebookOAuthResult = _fb.ParseOAuthCallbackUrl(responseUri);
-
- if (string.IsNullOrWhiteSpace(facebookOAuthResult.Error))
- _fb.AccessToken = facebookOAuthResult.AccessToken;
- else
- {
- }
- }
- else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
- {
- }
- else
- {
- _fb.AccessToken = null;
- }
- }
- public void LoginAndContinue()
- {
- WebAuthenticationBroker.AuthenticateAndContinue(_loginUrl);
- }
- public void ContinueAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
- {
- ValidateAndProccessResult(args.WebAuthenticationResult);
- }
- }
- }
Note: Please enter your Facebook App ID in the preceding code. Otherwise you will get an error as in the following.
Now our project hierarchy will be like this.
Wow! Now we are nearly done, let's make the following UI in the
MainPage.xaml page to use the preceding helpers.
- <StackPanel>
-
- <TextBlock Text="FaceBook Integration in WP8.1:" FontSize="28" Foreground="Gray"/>
-
- <Button Name="BtnLogin" Content="FaceBook Login" HorizontalAlignment="Stretch" Background="#FF00A9CF" Click="BtnFaceBookLogin_Click"/>
- <Button Visibility="Collapsed" Name="BtnLogout" Content="FaceBook Logout" HorizontalAlignment="Stretch" Background="#FF00A9CF" Click="BtnFaceBookLogout_Click"/>
-
- <StackPanel Visibility="Collapsed" Name="StckPnlProfile_Layout">
-
- <TextBlock Text="User Profile :" FontSize="30" TextWrapping="Wrap" Foreground="White"/>
- <Image Stretch="None" x:Name="picProfile" HorizontalAlignment="Left" />
- <TextBlock FontSize="20" Name="TxtUserProfile" TextWrapping="Wrap" Foreground="White"/>
-
- <TextBox Name="TxtStatusMsg" MinHeight="150" TextWrapping="Wrap" Header="Status Message:" FontSize="18" Foreground="Black"/>
- <Button Content="Post Status on FaceBook" HorizontalAlignment="Stretch" Background="#FF00A9CF" Click="BtnFaceBookPost_Click"/>
- </StackPanel>
-
- </StackPanel>
Here in the preceding XAML code, there are four sections:
- For displaying sample title.
- Buttons for Login and Logout.
- UI for displaying user profile info, after successfully logging into Facebook.
- Post message to wall.
In the MainPage.cs file, create the following two global objects for the "FaceBookHelper.cs" class and FacebookClient.
- FaceBookHelper ObjFBHelper = new FaceBookHelper();
- FacebookClient fbclient = new FacebookClient();
Ok, let's write some code for Facebook login upon the BtnFaceBookLogin_Click Event:
- private void BtnFaceBookLogin_Click(object sender, RoutedEventArgs e)
- {
- ObjFBHelper.LoginAndContinue();
- }
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.
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.
After successfully logging into the Facebook page, add the following method for fetching the user profile data in the MainPage.cs file.
- public async void ContinueWithWebAuthenticationBroker(WebAuthenticationBrokerContinuationEventArgs args)
- {
- ObjFBHelper.ContinueAuthentication(args);
- if (ObjFBHelper.AccessToken != null)
- {
- fbclient = new Facebook.FacebookClient(ObjFBHelper.AccessToken);
-
-
- dynamic result = await fbclient.GetTaskAsync("me");
- string id = result.id;
- string email = result.email;
- string FBName = result.name;
-
-
- GetUserProfilePicture(id);
- TxtUserProfile.Text = FBName;
- StckPnlProfile_Layout.Visibility = Visibility.Visible;
- BtnLogin.Visibility = Visibility.Collapsed;
- BtnLogout.Visibility = Visibility.Visible;
- }
- else
- {
- StckPnlProfile_Layout.Visibility = Visibility.Collapsed;
- }
-
- }
To get the user profile image, add the following method:
- private void GetUserProfilePicture(string UserID)
- {
- string profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", UserID, "square", ObjFBHelper.AccessToken);
- picProfile.Source = new BitmapImage(new Uri(profilePictureUrl));
- }
1.4 Post status message on Facebook WallWhen clicking on the Post Status button, add the following code to the MainPage.cs file:
- private async void BtnFaceBookPost_Click(object sender, RoutedEventArgs e)
- {
- var postParams = new
- {
- name = "Facebook Post Testing from App.",
- caption = "WindowsPhone 8.1 FaceBook Integration.",
- link = "http://bsubramanyamraju.blogspot.in",
- description=TxtStatusMsg.Text,
- picture = "http://facebooksdk.net/assets/img/logo75x75.png"
- };
- try
- {
- dynamic fbPostTaskResult = await fbclient.PostTaskAsync("/me/feed", postParams);
- var responseresult = (IDictionary<string, object>)fbPostTaskResult;
- MessageDialog SuccessMsg = new MessageDialog("Message posted sucessfully on facebook wall");
- await SuccessMsg.ShowAsync();
- }
- catch (Exception ex)
- {
-
-
- }
- }
After posting status, we will get a found status message on the Facebook timeline as in the following:
1.5 Logout from Facebook PageWhen clicking on the Logout button, add the following code to the MainPage.cs file:
- private async void BtnFaceBookLogout_Click(object sender, RoutedEventArgs e)
- {
- _logoutUrl = fbclient.GetLogoutUrl(new
- {
- next = "https://www.facebook.com/connect/login_success.html",
- access_token = ObjFBHelper.AccessToken
- });
- WebAuthenticationBroker.AuthenticateAndContinue(_logoutUrl);
- BtnLogin.Visibility = Visibility.Visible;
- BtnLogout.Visibility = Visibility.Collapsed;
- }
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.