Friday 22 April 2011

How to Integrate Facebook with Windows Application


Ever wondered how to integrate Facebook into your application? Just how cool would it be to have Facebook button on your application? Lets do it then...

We will be using an awesome C# Facebook API  called facebooksdk which will make our task extremely easy.

First, In order to use your application to post on Facebook, you need to register your application and get the App ID. The registration is absolutely free. This App ID will help Facebook recognize (and authorize) your application each time a communication is made from the application to Facebook.

To Register your application with Facebook, go to http://www.facebook.com/developers/ and click on "Set Up New App"

Next, we need to give a name to our application, Lets name it DemoApp. Select the Agree button and click on "Create App".



Interesting fact: If the name of your application contains the word "face", Facebook will show you this little number:

When your Application is created, you will be presented with the following screen:
Select various details about you application such as description, Icon , logo, administrator email etc. Then click on "Save Changes".

Now we have come to the most Important screen from our point of view: The MyApps Page where you will be provided with the App Id and other important IDs for your application. You will only require the App Id to successfully authenticate your windows application with Facebook.


Now that you we have our App Id, we need to create a windows application from which we will share our link on Facebook. We will be using the C#, .NET framework 4 and Visual Studio 2010 for our Application. Create a new Windows Application Project in C# and name it something Relevant. Lets name our project as "FacebookDemo"


Once the Windows application is created, Drag a WebBrowser Control and a Button Control on to the Form. These will be the only two controls we will be using in our application.



Next, we need to reference a couple of DLLs which we will be using in our project. Make sure you have the Facebook.dll  and System.Web Assembly referenced in your project.



OK. Enough of screenshots. Time to do some actual coding!



The Facebook SDK provides us with a variety of inbuilt functions. The actual code won't be difficult at all and it will be extremely easy to understand.
The first step we will do is creating a login URL which will help us authenticate our application with Facebook. The following code snippets will create a login URL for us:
(In the Demo Application, I have written this code on the Button Click event of the Button on our Windows Form)

First, we need to create an Instance of the FacebookOAuthClient. The parameters we will be passing will be your App ID which you got when you registered for Facebook and the Redirect Uri which is the Uri to which our Browser will get redirected to when we are successfully authenticated with Facebook.
 The default Uri is http://www.facebook.com/connect/login_success.html but we will override it with http://www.facebook.com/ so that you are redirected to your Facebook homepage when the wall post is made.

var oauth = new FacebookOAuthClient
                   {
                       ClientId = "",
                       RedirectUri = new Uri("http://www.facebook.com/")

                   };

Next, we will create a Dictionary object which will determine the Display type and the Respose type which will be returned.
Display type is the method by which the Authentication dialog will be rendered. It is set to “page” by default. We will override it to popup so that it consumes less space.
You can find the various display options here:

The response type is the result given by Facebook on successful authentication.




                var parameters = new Dictionary<string, object>
                                {
                                    { "display", "popup" },
                                    { "response_type", "token" }
                                };

Next, we define the permissions which our application will have to access the user’s data. Right now, since we only need to share a link on the wall of the user, we will require only one permission from the user which is the “publish stream” permission. With this permission, our application can post on the wall of the user. The complete list of allowed permissions is available here:

                var extendedPermissions = "publish_stream";

                if (!string.IsNullOrEmpty(extendedPermissions))
                {
                    parameters["scope"] = extendedPermissions;
                }

Finally, we will pass the parameters to the GetLoginUrl function of the FacebookOAuthClient class which will return the login uri.


                var loginUri = oauth.GetLoginUrl(parameters);

                                               
We will navigate to the generated loginUri with the webbrowser control which we created on our windows form.
webBrowser1.Navigate(loginUri);


The next step we are going to take is that we are going to check if our login uri is authenticated. We are going to do this by checking the authentication status each time the page changes. The Navigated event of the webbrowser control will be extremely helpful here as it is triggered each time there is a page change.
(In the Demo Application, I have written the following code in the webBrowser1_Navigated event of the webbrowser control so it will get called and check if authenticated each time there is a page change)

First we need to create an instance of the FacebookOAuthResult class which is designed to check and return the result of the authentication request sent to Facebook. TryParse returns true if it is recognized as a OAuth2 Authentication result. There is a property of the FacebookOAuthResult called IsSuccess which is set to true if the OAuth result was successful and we have the access token. You can use the ErrorDescription property to show the user why the error occurred in the authentication.

FacebookOAuthResult authResult;

if (FacebookOAuthResult.TryParse(e.Url, out authResult))
{
       if (authResult.IsSuccess)
       {
            //Code to post an update to the wall of the user. (Code is given in the next part)
                    
       }
       else
       {
            System.Windows.Forms.MessageBox.Show(authResult.ErrorDescription);
       }
}

Next, when we are successfully authenticated by Facebook, we will get an access token which can be used to make the wall post.

         var accessToken = authResult.AccessToken;


The FacebookClient Class is used to get and post updates once we are successfully authenticated. So we will create an object of that class with help of the accessToken which we got from the successful authentication earlier.

            FacebookClient fbc = new FacebookClient(accessToken);


            string encodeaccesstoken = HttpUtility.UrlEncode(accessToken);

            var me = fbc.Get(encodeaccesstoken);


Next, we need to create post. This post can be created the same way as you did earlier by creating a Dictionary object and then adding the different parameters to it. The entire list of parameters you can add to your post can be found here:

            var post = new Dictionary<string, object>
            {
                     { "display", "popup" },
                     { "response_type", "token" }
            };
            post.Add("link", "http://vrdmn.blogspot.com");
            post.Add("message", "The Message You want to Post on Facebook");

I have only added the link (which points to this blog) and the sample message parameters. You can add whichever ones you want.

And the last step is to publish the actual post on Facebook with the Post method of the FacebookClient Class. The parameters passed are the “me/feed” which tells the API where to publish the post and the actual post dictionary object which contains the details about the post.

           fbc.Post("me/feed", post);

You can download the Sample project from here. Be sure to have Visual Studio 2010 Installed.

1 comment:

Anonymous said...

thanx it is so helpful