WindowsPhone Store 8.1 : FaceBook Integration Sample (C#-Xaml)

Advertisemen

Introduction:

In previous article i was explained the concept of facebook login support for windowsphone 8.0,Now this article will show you how to easily integrate Facebook to 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 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 windowsphone store 8.1 OS,So make sure you’ve downloaded and installed the Windows Phone 8.1 SDK. For more information, see Get the SDK.
  • I assumes that you’re going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you have to take some additional steps. For more info, see Register your Windows Phone device for development.
  • This post 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 new project type Blank App(Ex: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, type the following command
Install-Package Facebook, 
This will add Facebook SDK in the current project like below.

1.2 Linking App with facebook:
First of all, you need to create Facebook Application on website. Here is the link to do so https://developers.facebook.com/apps Click at "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 above App Id,and You must select Windows App as a platform,because in this sample we are trying to connect windowsphone 8.1 store apps.
And now the most important step is we need to fill Windows Store ID.
There are a couple of ways to get the value to be put in that field, one of them in this sample i am going to take help of WebAuthenticationBroker class like this
Uri _callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

In my case the above statement return following URI,you may check above code by downloading the sample and observe in 'FaceBookHelper.cs' class from 'Helpers' folder in a project
We proceed to copy that Uri, on page Facebook App 'facebookwptest' a new platform and select Windows App there two fields appear, since this app are creating the Windows Phone 8.1 and then we place the Uri Windows Store ID. If I were a Silverlight App Windows Phone 8.1 we should use another field and a different Uri.
The Uri must place there Guid copying everything from "s-" without inclkuir rl "/" end being something like:
Note: As we are creating a windowsphone store app ignore the field talking about 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 to use 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 phone, as 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 name is 'Helpers' and add 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 namespace is FaceBookWp8._1.Helpers).

The next step we need to do: some modifications at 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 SuspensionManager class in 'Helpers" folder.

After that, 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 (which will crash the app for sure).

  1. ContinuationManager _continuator = new ContinuationManager();  


Of the suspension system is responsible, the event will fire OnSuspending found in the App case: App.xaml.cs , which at the moment looks like this (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 following class in 'Helpers' folder.Which is useful to login facebook with help of 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 above code.otherwise you will get error like below.

Now our project hierarchy will be like this.


 Wow! Now we are done almost,Let's make following UI in MainPage.xaml page to use above 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 above 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 logon to facebook.
4)Post message to wall.

In MainPage.cs file , create following two global object for 'FaceBookHelper.cs' class and FacebookClient.

  1. FaceBookHelper ObjFBHelper = new FaceBookHelper(); 
  2. FacebookClient fbclient = new FacebookClient(); 

Ok,Let's write code for facebook login on BtnFaceBookLogin_Click Event:

  1. private void BtnFaceBookLogin_Click(object sender, RoutedEventArgs e)  
  2.        {  
  3.            ObjFBHelper.LoginAndContinue();  
  4.        }  
When clicking on Login button from UI,WebAuthenticationBroker will get facebook login url from the FaceBookHelper constructor and screen will be appeared like below.
Entered facebook username and password will be processed for authentication,and then will be ask for your permissions.Press ok for successfully logon to facebook page.
After successfully logon to facebook page,Add following method for fetching user profile data in 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 user profile image,add 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.         }  

1.4 Post status message on FaceBook Wall:

When click on Post Status button,add following code in 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.         }  

After posting status,we will be found status message on your facebook timeline like below,

1.5 Logout from Facebook Page:

When click on Logout button,add following code in 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.         }  

FacebookIntegrationWP8.1

Summary:
From this article we have learned "Facebook Integration in windowsphone 8.1 application".Hope i wrote this post with my best level,When writing this article, i had taken lot of hard works and making nice presentation to understand the article at beginners level.


FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)




Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Tutorial Unity 3D