Posting to your Facebook wall from your app

A while ago, I posted a blog post which described how you could integrate a Windows Phone 8 Silverlight application with the Facebook Graph API.

This is an update to the post which will show you how to integrate with Facebook with a Windows Phone 8.1 RT application.

Facebook C# NuGet Package

Facebook Client for WinRT

NuGet Facebook Client for WinRT

The Facebook client NuGet package is currently in pre-release however is functional with WinRT so will work with both your Windows Phone and Windows 8 applications if you’re developing a universal app.

As with the image above, in the NuGet Package Manager Console, paste in the following line and make sure your target project is the one you’re wanting to add the package too (in this case, the Windows Phone project).

Install-Package Facebook.Client -Pre

Setting up your app with the Facebook Developers platform

To get started, you’ll want to navigate to the Facebook Developers page. Click on the “Add a New App” button in the top right corner once you’ve logged in.

After the pop-up shows, click on “Advanced Setup” link and you’ll be shown the following prompt:

Create a Facebook App

Create a Facebook App

Fill in the Display Name with the name of your app, and provide a relevant Namespace identifier. You can also say whether this is a test app or not, but for this tutorial, leave it set to ‘No’. You will also be able to pick the app category.

When you’ve created your app, you’ll be taking to the dashboard for it where you can play with the settings, adding icons and any other miscellaneous changes you’d like to make.

To add Windows as an option, click on the ‘Settings’ option in the left hand menu and click the ‘+ Add Platform’ button.

Add a Windows App

Add a Windows App

You’ll want to select the ‘Windows App’ option from the pop-up that is displayed on clicking the button.

There will now be two options for you to enter into the settings for the Windows App which are the Windows Store ID and the Windows Phone Store ID. As this is a WinRT based Windows Phone app, we will only need to populate the Windows Store ID field.

To get the ID of your application, you can call the following line of code in your app:

var callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
Callback Uri

Callback Uri

You’ll want to extract the value in this URI which will result in the Windows Store ID you need to input into the field on the Facebook settings page, i.e. ‘s-1-15-2-3443981231-109823124-37161859-3786543125-4169911182-126701396-2785855364’. You’ll want to save your changes and now we will get your app authenticating with Facebook.

Working with the Web Authentication Broker

Windows Phone RT apps work with a similar WebAuthenticationBroker to that of Windows Store apps, however due to the lifecycle process of Windows Phone apps, you’re going to need to implement a ContinuationHelper which will be called back into when your app has finished authenticating. This is the same implementation as my previous blog post on authentication with Microsoft Azure.

Firstly, you’ll need an interface to use in the areas of your app that you wish the continuation to resume at.


namespace FacebookIntegrationSample.Common
{
    using Windows.ApplicationModel.Activation;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    public interface IContinuable
    {
        void Continue(WebAuthenticationBrokerContinuationEventArgs e);
    }
}

You’ll then implement the continuation helper as follows:


namespace FacebookIntegrationSample.Common
{
    using Windows.ApplicationModel.Activation;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    public class ContinuationHelper
    {
        public void Continue(IActivatedEventArgs e)
        {
            var frame = Window.Current.Content as Frame;

            if (frame == null)
            {
                return;
            }

            switch (e.Kind)
            {
                case ActivationKind.WebAuthenticationBrokerContinuation:
                    var continuable = frame.Content as IContinuable;

                    if (continuable != null)
                    {
                        continuable.Continue(e as WebAuthenticationBrokerContinuationEventArgs);
                    }

                    break;
            }
        }
    }
}

If you’re using a framework like MVVM Light, you’ll want to declare this class within your container or if you’re not, you will want to create it in your App.xaml.cs file.

You’ll then want to set-up your app to call into the ContinuationHelper when the OnActivated method is called. This can be done by creating an override for the OnActivated method as follows:


        protected override void OnActivated(IActivatedEventArgs args)
        {
            var rootFrame = Window.Current.Content as Frame;
            if (rootFrame == null)
            {
                rootFrame = new Frame();
                Window.Current.Content = rootFrame;
            }

            if (args is IContinuationActivatedEventArgs)
            {
                ContinuationHelper.Continue(args);
            }

            Window.Current.Activate();
        }

We’ll now create a helper class for working with the Facebook .NET libraries so we can grab the tokens returned when the app returns from authenticating the user. Here is the helper you can implement in your app:


namespace FacebookIntegrationSample.Common
{
    using System;

    using Facebook;

    using Windows.ApplicationModel.Activation;
    using Windows.Security.Authentication.Web;

    public class FacebookHelper
    {
        private readonly Uri callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

        private readonly Uri loginUri;

        private const string AppId = "INSERT FACEBOOK APP ID HERE";

        private const string AppPermissions = "user_about_me,read_stream,publish_stream,publish_actions";

        public FacebookHelper()
        {
            this.Client = new FacebookClient();

            this.loginUri =
                this.Client.GetLoginUrl(
                    new
                        {
                            client_id = AppId,
                            redirect_uri = this.callbackUri.AbsoluteUri,
                            scope = AppPermissions,
                            display = "popup",
                            response_type = "token"
                        });
        }

        public FacebookClient Client { get; private set; }

        public string AccessToken
        {
            get
            {
                return this.Client.AccessToken;
            }
        }

        public void LoginContinuation()
        {
            WebAuthenticationBroker.AuthenticateAndContinue(this.loginUri);
        }

        public void ContinueAuth(WebAuthenticationBrokerContinuationEventArgs args)
        {
            this.Validate(args.WebAuthenticationResult);
        }

        private void Validate(WebAuthenticationResult result)
        {
            switch (result.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    {
                        var responseUri = new Uri(result.ResponseData.ToString());

                        var oauthResult = this.Client.ParseOAuthCallbackUrl(responseUri);

                        if (string.IsNullOrWhiteSpace(oauthResult.Error))
                        {
                            this.Client.AccessToken = oauthResult.AccessToken;
                        }
                        else
                        {
                            // ToDo: Handle error.
                        }
                    }

                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    break;
                default:
                    this.Client.AccessToken = null;
                    break;
            }
        }
    }
}

You’ll want to add the AppId from your Facebook app into the constant App ID string variable in the helper otherwise you will get an error when authenticating.

Logging into Facebook from your app

Logging into Facebook from your app

Now all of the hard work is done for authenticating, you’ll want to add a UI to this so that you can prompt your users to login to your Facebook enabled app. I’m going to use code-behind in this sample but I highly recommend using the MVVM pattern with data binding.

Here is the XAML for your page.


<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
            <TextBlock Text="Facebook Sample" Foreground="#FFFFFFFF" HorizontalAlignment="Center" Style="{StaticResource SubheaderTextBlockStyle}" />
        </StackPanel>

        <StackPanel Name="ProfilePanel" Visibility="Collapsed" Grid.Row="1" Margin="24,0">
            <TextBlock Text="Profile" Style="{StaticResource GroupHeaderTextBlockStyle}" Foreground="#FFFFFFFF"/>
            <Image Stretch="None" x:Name="ProfilePicture" HorizontalAlignment="Left" />
            <TextBlock Name="Username" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="Wrap" Foreground="#FFFFFFFF"/>

            <TextBox Name="StatusMessageBox" MinHeight="140" VerticalAlignment="Stretch" TextWrapping="Wrap" Header="Status Message:" FontSize="18" Foreground="Black"/>
            <Button Content="Post to Facebook" HorizontalAlignment="Stretch" Background="#FF3B5999" Click="OnPostToFacebookClicked"/>
        </StackPanel>

        <Grid Grid.Row="2" Margin="24,0">
            <Button Name="LoginButton" Content="Login" HorizontalAlignment="Stretch" Background="#FF3B5999" Click="OnLoginButtonClicked"/>
        </Grid>
    </Grid>

And this will be your code-behind:


namespace FacebookIntegrationSample
{
    using System;
    using System.Collections.Generic;

    using Facebook;

    using FacebookIntegrationSample.Common;

    using Windows.ApplicationModel.Activation;
    using Windows.UI.Popups;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Media.Imaging;
    using Windows.UI.Xaml.Navigation;

    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : IContinuable
    {
        private FacebookClient client;

        private readonly Uri loginUri;

        private FacebookHelper facebookHelper;

        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        public FacebookHelper FacebookHelper
        {
            get
            {
                return this.facebookHelper ?? (this.facebookHelper = new FacebookHelper());
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void OnLoginButtonClicked(object sender, RoutedEventArgs e)
        {
            this.FacebookHelper.LoginContinuation();
        }

        public async void Continue(WebAuthenticationBrokerContinuationEventArgs e)
        {
            this.FacebookHelper.ContinueAuth(e);

            if (this.FacebookHelper.AccessToken != null)
            {
                LoginButton.Visibility = Visibility.Collapsed;

                this.client = new FacebookClient(this.FacebookHelper.AccessToken);

                dynamic result = await this.client.GetTaskAsync("me");

                var id = result.id;
                var name = result.name;

                this.SetProfilePic(id);

                this.Username.Text = name;

                ProfilePanel.Visibility = Visibility.Visible;
            }
            else
            {
                this.ProfilePanel.Visibility = Visibility.Collapsed;
            }
        }

        private void SetProfilePic(dynamic id)
        {
            var profilePicUri = this.FacebookHelper.GetProfilePic(id);

            this.ProfilePicture.Source = new BitmapImage(new Uri(profilePicUri));
        }

        private async void OnPostToFacebookClicked(object sender, RoutedEventArgs e)
        {
            var post =
                new
                    {
                        name = "How to integrate Facebook with your Windows Phone 8.1 app",
                        caption = "Learn how to integrate with Facebook in your Windows Phone 8.1 RT application!",
                        link = "http://wp.me/p5uBdN-Hx",
                        description = StatusMessageBox.Text
                    };

            try
            {
                dynamic postResult = await this.client.PostTaskAsync("/me/feed", post);

                var responseResult = (IDictionary<string, object>)postResult;

                var dialog = new MessageDialog("Successfully posted to your Facebook wall.");

                await dialog.ShowAsync();
            }
            catch (Exception ex)
            {
                // ToDo: Handle exception
            }
        }
    }
}

If you’re working in an MVVM fashion, remember to add the interface for continuation into your viewmodel like the above code-behind.

Authenticating with your Facebook app

Authenticating with your Facebook app

Looking through the code above, you’ll notice that when the button for login on the UI is clicked, it will call into the login method of our helper class. This will launch the WebAuthenticationBroker, suspending the app. When the app returns, it will call into the OnActivated method in the App.xaml.cs class file which will grab the last known page in view and check if it’s content is an IContinuable. It will then call the continue method which will give us back the result. From that result, we can build up the user’s profile.

Successfully logged into app

Successfully logged into app

You’ll also want to add a new method to your Facebook helper class to get the profile picture URL as follows:


public string GetProfilePic(string userId)
        {
            var result = string.Format(
                "https://graph.facebook.com/{0}/picture?type={1}&access_token={2}",
                userId,
                "square",
                this.AccessToken);

            return result;
        }

Congratulations! Your app is now Facebook connected and you can add functionality into your app that can further integrate with the Facebook API such as posting to walls, uploading photos and sending game requests to friends.

If you have any questions or would like me to cover more of the Facebook API integration (i.e. getting friends list, etc.), let me know in the comments below!

Author James Croft

James is a .NET developer for Black Marble Ltd. with over 5 years app development experience in Microsoft platforms. He enjoys blogging, helping others learn to code, making YouTube videos, spending time with his girlfriend but most of all, penguins.

More posts by James Croft

Join the discussion 7 Comments

  • Dharmendra Singh says:

    (OAuthException – #200) (#200) The user hasn’t authorized the application to perform this action :-

    I have this ERror in Posting Wall …..

  • Mahmoud Hamad says:

    Hey, Thanks for this great tutorial,

    Can you make a tutorial about how to like a post and comment on a post
    ‘Cause I think these feature are really interesting and there is no single tutorial tell you what you need !!!

    Best Regards,
    Mahmoud

  • Jan Deman says:

    Hey James! I’ve a few questions for you. I’m currently making a Windows universal app and I’m using an Azure mobile service as well.
    So I followed the following tutorial to include facebook authentication into my app:
    http://azure.microsoft.com/nl-nl/documentation/articles/mobile-services-javascript-backend-windows-universal-dotnet-get-started-users/
    I’ve kind of run into a few problems now though, I want to retrieve some additional user information when authenticating with Facebook such as hometown, birthday, gender and profile picture. When requesting this information using the following url:
    var url = ‘https://graph.facebook.com/me?fields=id,name,gender,birthday,hometown,email&access_token=’ + identities.facebook.accessToken;
    I do not receive the information I asked for aside from the Id, name and gender. I believe this has something to do with the user not having given his permission for that information but I’m not sure? Do you have any idea what could be the problem?
    And would you say your implentation has advantages over the one described in the azure tutorial? If so what are the advantages?

    Thanks in advance!

    My best regards Jan

  • Ewerton says:

    In my code gave the following error:

    Error 1 The type or namespace name ‘WebAuthenticationBrokerContinuationEventArgs’ could not be found (are you missing a using directive or an assembly reference?)

    Could you please help me

    • James Croft says:

      Are you working with a Windows Phone 8.1 Runtime project? If so, the WebAuthenticationBrokerContinuationEventArgs is definitely available.

      If you’re working on a universal app and have this code in your App.xaml.cs in the Shared project, you’ll have to wrap it like this:

      #if WINDOWS_PHONE_APP
      // Code here for Windows Phone.
      #endif

  • […] 18, 2015 Tags:   windows-phone , wpdev , facebook , james-croft Read original post at James Croft's BlogA while ago, I posted a blog post which described how you could integrate a Windows Phone 8 […]

Leave a comment