Home / C#.NET / Facebook Integration with C#.NET
Heading

Facebook Integration with C#.NET

Hi everyone, This is a simple step by step guide to integrate Facebook to your windows App.

First of all, Create a Windows forms project and download the Facebook SDK using NuGet. Go to Tools -> NuGet Package Manager -> Package Manager Console.

 NuGet

This will open up the console in side the Visual Studio. Then type the below command to download the FB SDK.

Install-Package Facebook – Pre

Why we are using -Pre, In this example I’m using FB SDK v6.0.2 Alpha. Since V6.0 is still in the pre release we need to pass “-Pre” with the command. 

Once you successfully downloaded the  SDK, you can see the Facebook dll is added in the reference.


Now we have to do the authentication and the authorization.  Since we are doing a windows app ,we need to create an App ID in the Facebook. Apart form that We need to change some default configuration in the FB App settings. In order to do so, Please login to the below URL and Create a New App.

https://developers.facebook.com/

When you login to the developers.facebook.com you will see your profile picture and a dropdown menu in the top right hand corner of the page. Expand the menu and select Add New App.

NewFBAPP

Then New App Popup will open and click on the basic setup link.

NewAppPopup

 

Then in the basic setup popup, give an appropriate name for your App and select a category. Then Press Create App ID

Basic Setup

Once you are done with that ,You will be redirected to the dashboard and you will see your APP ID is created and visible in the dashboard.

 


Now you are done with your APP ID creation.

In this sample ,when you run the application it will ask for the FB login and permission to the profile information. This operation will happen in a browser view. So We need to change a configuration in your App level.

Go to Settings -> Advance -> Client OAuth Settings   

When you go to Client OAuth Settings, you will see a toggle buttons for Embedded Browser OAuth Login. Please change it to YES

OAuthSettings

 

How we can start coding. In this sample I’m going to make two forms basically. One for the FB login and get the Authentication Token. Second one is to display the Data.

In the first form, Please add a web browser component and Make it full stretch in the form. In the form load we need to regenerate the FB Login URL and navigate to it.

You can find the below code to pass the AppID and the Extended Permissions (required permissions from your profile) to the GenerateLoginURL method.

 

  private void Form1_Load(object sender, EventArgs e)
        {
            Uri Fb = GenerateLoginUrl("[YOUR APP ID]", "public_profile,user_birthday,publish_actions,user_posts,user_about_me,user_location,user_status");
            webBrowser.Navigate(Fb);
        }

        private Uri GenerateLoginUrl(string appId, string extendedPermissions)
        {
            dynamic parameters = new ExpandoObject();
            parameters.client_id = appId;
            parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";

            // The requested response: an access token (token), an authorization code (code), or both (code token).
            parameters.response_type = "token";

            // list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
            //parameters.display = "popup";

            // add the 'scope' parameter only if we have extendedPermissions.
            if (!string.IsNullOrWhiteSpace(extendedPermissions))
                parameters.scope = extendedPermissions;

            // generate the login url
            var fb = new FacebookClient();
            return fb.GetLoginUrl(parameters);
        }

After that, there is an event in WebBrowser control called “Navigated”. Create the method and do the below code. In this part we are gaining the access token from Facebook. If the authentication is not successful,  oauthResult.IsSuccess will return as false. So you can manage your errors. If it is successful as you can see in the below sample code I’m redirecting the user to the second form.

 private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {

            try
            {
                // whenever the browser navigates to a new url, try parsing the url.
                // the url may be the result of OAuth 2.0 authentication.

                var fb = new FacebookClient();
                FacebookOAuthResult oauthResult;
                if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
                {
                    // The url is the result of OAuth 2.0 authentication
                    if (oauthResult.IsSuccess)
                    {
                       //Getting the AccessToken and Redirecting user to the Second form.
                        var accesstoken = oauthResult.AccessToken;                        
                        Wall wall = new Wall(accesstoken.ToString());
                        wall.Show();
                        this.Hide();                        
                    }
                    else
                    {
                        var errorDescription = oauthResult.ErrorDescription;
                        var errorReason = oauthResult.ErrorReason;
                    }
                }
                else
                {
                    // The url is NOT the result of OAuth 2.0 authentication.
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
            }
        }

Now you have the access token and you can use it at your liberty 🙂 . In this example I’m just taking some basic information of the user. Facebook has controlled the access levels and functions of the service due to security reasons. You can Check their developer guide to read more and use the service. okay now lets move on.

As you can see in my above code I’m passing the accesstoken parameter in to the Wall form’s constructor. Then im assigning it to a public variable. please see the below code.

 

 string clientToken = string.Empty;
        public Wall(string token)
        {
            InitializeComponent();           
            clientToken = token;
        } 

Then in the Form load, I’m pulling some Profile information. In order to do that, use the below code. FacebookClient object gives a method called “Get“. You can pass the field parameters and get the result in JSON format. Then you deserialize it and store the data in your objects. If you want to download the images like Profile Pic or the Cover Pic, you can use the “https://graph.facebook.com/v2.5/” URL to call and get Image data. Please refer to the below code for getting Profile details and Downloading the Profile Pic.

 private void GetUserDetails()
        {
            FacebookClient fb = null;
            object data = null;
            DVO.UserDvo user = null;
            try
            {
                fb = new FacebookClient(clientToken);
                data = fb.Get("/me?fields=devices,first_name,gender,installed,last_name,link,locale,location");
                user = new DVO.UserDvo();
                user = new JavaScriptSerializer().Deserialize<DVO.UserDvo>(data.ToString());               
                profilePic.Image = DownloadImage("https://graph.facebook.com/v2.5/" + user.id + "/picture?height=100&width=100&type=album&access_token=" + clientToken);                

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                fb = null;
                data = null;
                user = null;
            }

        }
  private static Image DownloadImage(string url)
        {
            WebClient wc = null;
            Image img = null;
            MemoryStream ms = null;
            try
            {
                wc= new WebClient();
                byte[] bytes = wc.DownloadData(url);
                ms = new MemoryStream(bytes);
                img = System.Drawing.Image.FromStream(ms);
                return img;
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                wc.Dispose();
                ms.Dispose();
            }
           
        }
 

Below is the User Property Objects

 
  public class UserDvo
    {
        public Cover cover { get; set; }
        public List<Device> devices { get; set; }
        public string first_name { get; set; }
        public string gender { get; set; }       
        public bool installed { get; set; }      
        public string last_name { get; set; }
        public string link { get; set; }       
        public Location location { get; set; }
        public string id { get; set; }

    }

    public class Cover
    {
        public string id { get; set; }
        public int offset_y { get; set; }
        public string source { get; set; }
    }

    public class Data
    {
        public bool is_silhouette { get; set; }
        public string url { get; set; }
    }

    public class Picture
    {
        public Data data { get; set; }
    }
    public class Device
    {
        public string hardware { get; set; }
        public string os { get; set; }
    }

    public class Location
    {
        public string id { get; set; }
        public string name { get; set; }
    }

Now you have the data. You have successfully integrated Facebook in your C#.Net code.


Extended Permission levels-
If you have only specific permissions to request then only you have to pass the scope parameter (extended permissions) in the request.
Below are the permission types-

  Permissions

 

Please read the below article for more knowledge about Facebook Graph API.

https://developers.facebook.com/docs/graph-api/using-graph-api/


 

Hope this is helpful. If you have any questions or doubts  , you cna reach me at kasunkoswattha@gmail.com

You can download the full source code from the GitHub.

https://github.com/KasunKoswattha/Facebook

 

Thank you.

 

 

 

About Kasun Koswattha

Kasun Koswattha
Kasun Koswattha (Kasun) a .NET Engineer | a Gamer from United States. Join with the c2k community to share your knowledge. Like and share...

Check Also

GeoHeadingSmall

C#.NET Getting Current Location and Implementing Reverse Geocoding

Hello everyone.  Today I’m going to do a sample program to get user’s current location …

2 comments

  1. Trying your code. After the call to webbrowser1.Navigate I receive a script error popup: ‘LinkshimAsyncLink is undefined’

    The webbrowser_navigated event never happens.

    I am running your code in Visual Studio 2015

    Any ideas what could be causing this error?

Leave a Reply