Getting Started with the Facebook C# SDK

Facebook recently announced the release of the Facebook C# SDK. The SDK allows .NET developers to create Facebook applications by directly calling their API. To get started with the SDK, follow these steps:

  1. Download the source and build the FacebookAPI project.
  2. Create your Facebook application from the Developer Section of your Facebook profile’s Application Settings.
  3. Coding your application to use the FacebookAPI.

In this example, I’ll demonstrate the creation of a simple .NET application that communicates with Facebook to pull my profile and friends list.

Building the FacebookAPI Project

First, download the source of the Facebook API project. Open the solution FacebookAPI.sln in Visual Studio and build the project. You will later use Facebook API assembly to interact with Facebook via .NET.

Creating the Application on Facebook

In order to successfully make calls to Facebook, you have to first register your application with Facebook and obtain authentication keys to be used with OAuth 2.0.

1. Go to http://developers.facebook.com/setup/ to begin registering your application. Make sure you use Internet Explorer. I ran into problems when attempting to register using Firefox (application would register, but a blank page was displayed).

2. Register the application using a site name and URL of the path relative to your authenticating logic. The redirect_url parameter you provide to the Facebook Graph API needs to match the path used to register the application.

create facebook application

In this example, I’ve registered the application as:

    Site Name: Dave Test
    Site URL: http://localhost/Facebook/oauth/

3. Once registered, you can view your application’s configuration settings and authentication keys. These details will be referenced in the example code to make requests to Facebook.

my application overview

Coding the Application

To accomplish the task of pulling my Facebook profile and friends list, I need to do the following:

  • Redirect from my local web application to Facebook with my application id and URL of my redirect handler
  • Construct the redirect URL handler to accept the access token provided by Facebook
  • Instantiate the FacebookAPI object with the access token above
  • Access my Profile via the FacebookAPI

1. Redirecting to Facebook

We need to send Facebook our application id and URL of the handler for Facebook’s redirect, containing our access token.


protected void btnAuthenticate_Click(object sender, EventArgs e)

{

    string clientId = "117342178314989";

    string redirectUrl = "http://localhost/Facebook/oauth/oauth-redirect.aspx";

 

    Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", clientId, redirectUrl));

}

Notice that the variable clientId matches the field Application Id in my Facebook Application configuration settings and the relative path in the variable redirectUrl matches the path defined in the field Connect URL.

After redirecting, a response is sent back to http://localhost/Facebook/oauth/oauth-redirect.aspx containing a code in the query string parameters of the URL. Successfully making a call, results in the following URL:

http://localhost/Facebook/oauth/oauth-redirect.aspx?code=2.UwNcNB5FfO69d_l5S1j76Q__.3600.1280984400-1427490881%7CGE2JRQaeMDwAZHwZMkk0NUiMQD4.

Notice the parameter code. This value will be used to request an access token from Facebook’s Graph API.

2. Building the Handler for Facebook’s Redirect

In step 1, we’ve created the request to Facebook. In step 2, we need to build the handler to accept the access token provided by Facebook to successfully make API calls.

Currently, there’s nothing built into the API that requests the access token, so I had to build one. The code below calls the Facebook Graph API, requesting an access token.


private Dictionary<string, string> GetOauthTokens(string code)

{

    Dictionary<string, string> tokens = new Dictionary<string, string>();

 

    string clientId = "117342178314989";

    string redirectUrl = "http://localhost/Facebook/oauth/oauth-redirect.aspx";

    string clientSecret = "bc7996cfc4f0c66d0417b54eea73f4e7";

    string scope = "read_friendlists,user_status";

 

    string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&scope={4}",

                    clientId, redirectUrl, clientSecret, code, scope);

 

    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)

    {

        StreamReader reader = new StreamReader(response.GetResponseStream());

        string retVal = reader.ReadToEnd();

 

        foreach (string token in retVal.Split('&'))

        {

            tokens.Add(token.Substring(0, token.IndexOf("=")),

                token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));

        }

    }

 

    return tokens;

}

Variables clientId and clientSecret should match fields Application Id and Application Secret, respectively, in the Facebook Application Settings page.

Scope defines the scope of the request. These values are considered Extended Permissions which means requesting access to data not marked as public to everyone in a user’s Facebook profile.

3. Instantiate FacebookAPI with an Access Token

The method GetOauthTokens accepts a parameter code. We’ll pass in the code value obtained in the query string param of the response in step 1 and cache the response for the time defined by the expiration value in Facebook’s Graph API response.


protected void Page_Load(object sender, EventArgs e)

{

    if (Request.Params["code"] != null)

    {

        Facebook.FacebookAPI api = new Facebook.FacebookAPI(GetAccessToken());

        ...

    }

}

 

private string GetAccessToken()

{

    if (HttpRuntime.Cache["access_token"] == null)

    {

        Dictionary<string, string> args = GetOauthTokens(Request.Params["code"]);

        HttpRuntime.Cache.Insert("access_token", args["access_token"], null, DateTime.Now.AddMinutes(Convert.ToDouble(args["expires"])), TimeSpan.Zero);

    }

 

    return HttpRuntime.Cache["access_token"].ToString();

}

4. Access My Facebook Profile

Now that we have an active connection with Facebook, we can use the API in step 3 to request my profile information. Doing so is as easy as a few lines of code:


JSONObject me = api.Get("/me");

JSONObject meFriends = api.Get("/me/friends");

making Get requests to Facebook via the API returns JSON containing profile information. The first requests my profile while the second obtains my friends list.

Placing a watch on these objects gives us
a watch on me

a watch of variable meFriends

As you can see, the variable me contains all of my public profile attributes. The variable meFriends has all 188 of my friends in an array of dictionary items. Each friend is stored in an id/name combo. If we wanted, we could take this another level deeper and get all friends profiles by requesting the id via the Graph API like so (1427490881 is my Facebook id):


JSONObject me = api.Get("/1427490881");

Full Source

/Default.aspx.cs

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

 

namespace Facebook

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void btnAuthenticate_Click(object sender, EventArgs e)

        {

            string clientId = "117342178314989";

            string redirectUrl = "http://localhost/Facebook/oauth/oauth-redirect.aspx";

 

            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", clientId, redirectUrl));

        }

    }

}

/oauth/oauth-redirect.aspx.cs


using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using Facebook;

using System.IO;

using System.Net;

using System.Collections.Generic;

 

namespace Facebook

{

    public partial class oauth_redirect : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (Request.Params["code"] != null)

            {

                Facebook.FacebookAPI api = new Facebook.FacebookAPI(GetAccessToken());

 

                JSONObject me = api.Get("/me");

                JSONObject meFriends = api.Get("/me/friends");

            }

        }

 

        private string GetAccessToken()

        {

            if (HttpRuntime.Cache["access_token"] == null)

            {

                Dictionary<string, string> args = GetOauthTokens(Request.Params["code"]);

                HttpRuntime.Cache.Insert("access_token", args["access_token"], null, DateTime.Now.AddMinutes(Convert.ToDouble(args["expires"])), TimeSpan.Zero);

            }

 

            return HttpRuntime.Cache["access_token"].ToString();

        }

 

        private Dictionary<string, string> GetOauthTokens(string code)

        {

            Dictionary<string, string> tokens = new Dictionary<string, string>();

 

            string clientId = "117342178314989";

            string redirectUrl = "http://localhost/Facebook/oauth/oauth-redirect.aspx";

            string clientSecret = "bc7996cfc4f0c66d0417b54eea73f4e7";

            string scope = "read_friendlists,user_status";

 

            string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&scope={4}",

                            clientId, redirectUrl, clientSecret, code, scope);

 

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)

            {

                StreamReader reader = new StreamReader(response.GetResponseStream());

                string retVal = reader.ReadToEnd();

 

                foreach (string token in retVal.Split('&'))

                {

                    tokens.Add(token.Substring(0, token.IndexOf("=")),

                        token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));

                }

            }

 

            return tokens;

        }

    }

}

About these ads

About Dave
Certified Sitecore Developer.

40 Responses to Getting Started with the Facebook C# SDK

  1. Pingback: Tweets that mention Getting Started with the Facebook C# SDK « Everything Web -- Topsy.com

  2. Mitch says:

    Hey Dave, great article! I was looking around for exactly this – code works great. Cheers! Mitch

  3. Fenil Desai says:

    I m using the exact same code as urs , but getting this error :

    The remote server returned an error: (400) Bad Request. – This happens when after clicking the login button it redirects to the oauth-redirect page.aspx page.

    pls help…

    • Dave says:

      Seems to me that it could be your settings in Facebook’s application configuration page. The fact that you’re getting a 400 error leads me to believe that Facebook is sending your request back to a page it believes exists, but doesn’t. Make sure that the “Site URL” (from the “Create an Application” page) and the “Connect URL” (from the main application settings page) both are set to the path that contains your oauth-rediect page. So, my settings are as follows:

      My redirect handler: http://localhost/Facebook/oauth/oauth-redirect.aspx
      Site URL: http://localhost/Facebook/oauth/
      Connect URL: http://localhost/Facebook/oauth/

      Notice how both Site URL and Connect URL both have the path relative to the page you’re attempting to redirect to. Also – VERY IMPORTANT – do not forget to add the trailing “/” in your Site URL/Connect URL.

      If all else fails, clear your cookies and try again to ensure no strange caching of credentials are causing this error.

      • Kes says:

        Hi Dave,

        I’m facing the same problem as Fenil Desai. I can’t seem to find a Connect URL in my app settings like you mentioned. Has fb made changes?

        Thanks for the guide anyway. Nice write up.

      • Dave says:

        Looks like fb has decided to change their developer center and menus since I wrote this article. I haven’t tried the code with their new layout, but it looks like you could potentially use the value in field “Site URL”.

      • Kes says:

        Thx for the reply Dave, and yea, Site URL is already set accordingly.

      • George Litinas says:

        Hi Dave…..

        I checked the siteURL and Connect URL to be the same, and clear the cookies but i still have the same 400 error….!!!

        Any other idea????

        Thanx

  4. coder says:

    but what if we want to request realtime data from a webpage to show, are we required to pass a redirecturi?

  5. Skatox says:

    thanks for this tutorial, i tried with like other 5 tutorial and oly this worked.

  6. Greetings Dave

    This is a great method.
    However, I am getting trouble in displaying data that require extended permision, somehow, my access token is not granting the extended permission porsion. I declared this in the scope string. Is this the correct way to do it right?

  7. Mitch says:

    Hey Dave, nicely done! For those having the 400 Bad Request issue, there is apparently a bug in the C# SDK provided by Facebook. You can find the solution here: https://github.com/facebook/csharp-sdk/issues#issue/2 Regards, Mitch

  8. Don says:

    Hi,

    Very useful code, thanks! In the GetAccessToken method it appears that the ‘expires’ value is no longer included. Am I doing something wrong, or has FB changed the format of the returned value?

    My code (in VB.Net) here: http://pastebin.com/HpdiwdSn

    Cheers,
    Don

  9. Me says:

    With latest 4.1.1 I could not find “FacebookApi” anywhere….?

    • Me says:

      OK, seems to be “FacebookAPP” now (instead of “FacebookAPI”)

      • Hello,
        I am still getting the error “e remote server returned an error: (400) Bad Request” when it is executing the code below, can anyone please help me

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string retVal = reader.ReadToEnd();

        foreach (string token in retVal.Split(‘&’))
        {
        tokens.Add(token.Substring(0, token.IndexOf(“=”)),
        token.Substring(token.IndexOf(“=”) + 1, token.Length – token.IndexOf(“=”) – 1));
        }
        }

  10. Sangeeta Saharan says:

    hii..

    can i use the c# Sdk with vs2008??

  11. Nelson N says:

    Hi there, thank you for your manual, it helps me a lot, but I have an small question, I can’t find FACEBOOK.FACEBOOKAPI or FACEBOOK.FACEBOOKAPP anywhere, do you know if it has a different name now?

    Thanks!!!

  12. Chad Nash says:

    Hi guys… I am also having the 400 error. Everything works great for posting to a wall but I can’t post to the checkins page without receiving the error.

    Dim placeID As String = “152690088091280”

    ‘ Coordinates of where they user “is”…
    Dim coordinates As [String] = “{“”latitude””:””32.747201″”, “”longitude””:””-117.127036″”}”

    Dim message1 As [String] = “CheckInTest”

    Dim postData As [String] = “”
    ‘postData += “access_token=” & accessToken
    postData += “&message=” & message
    postData += “&place=” & placeID
    postData += “&coordinates=” & Server.UrlDecode(coordinates)

    Dim encoding As New ASCIIEncoding()
    Dim data As Byte() = encoding.GetBytes(postData)

    Dim myRequest As HttpWebRequest = DirectCast(WebRequest.Create(“https://graph.facebook.com/” & MyuserID & “/checkins?access_token=” & accessToken), HttpWebRequest)
    myRequest.Method = “Post”
    myRequest.ContentType = “application/x-www-form-urlencoded”

    ‘ myRequest.ProtocolVersion = HttpVersion.Version10

    myRequest.ContentLength = data.Length
    Dim newStream As System.IO.Stream = myRequest.GetRequestStream()
    ‘ Send the data.
    newStream.Write(data, 0, data.Length)
    newStream.Close()

    Dim response1 As WebResponse = myRequest.GetResponse()
    Dim responseStream As System.IO.Stream = response1.GetResponseStream()

    Dim reader As New StreamReader(responseStream)
    Dim output As [String]
    output = reader.ReadToEnd()

    Response.Write(“OutPut:” & output)

    Catch ex As Exception
    Response.Write(“*******ERROR:” & ex.Message.ToString)
    End Try

    Any ideas? Again the post works great until I try and post to checkins.

    -Chad

  13. Chad Nash says:

    Nevermind… I think I got it working!!!

    Only problem is… The location and coordinates has to be EXACT or a 400 error will be returned. So, you have to first view someones checkin ID and the coordinates that go with that, and then you should be ok.

    -Chad

  14. kathir says:

    HI Dave ,
    My Objective is to Verify Authentication and don’t need any UI . How to do that ?

  15. Tom Dacquin says:

    Great Article! Thumbs up

  16. Irishmaninusa says:

    @chadnash how did you make this work, the code that you have written is vb.net, but when I use that code as you have it, it blows up with a 400 error

  17. Zach Girod says:

    If anyone finds this page because they are / were getting a 400 error with facebook the problem for me was that my redirect URL ended with a /.

    So, for your redirect URL:

    http://www.website.com/oauth/callback/ – Bad
    http://www.website.com/oauth/callback – Good

    I hope that helps someone..

  18. Tien says:

    I get this error: The remote certificate is invalid according to the validation procedure.

    Source Error:

    Line 105: HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    Line 106:
    Line 107: using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    Line 108:
    Line 109: {

    Any idea? Pls help me.

  19. Pingback: Create Facebook Application 2010 | AllGraphicsOnline.com

  20. trying the comments

  21. Hello,
    Great Article, I am however getting an error. “The remote server returned an error: (407) Proxy Authentication Required.”

    in this line of code:
    “Line 48:
    Line 49: HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    Line 50: using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    Line 51: {
    Line 52: StreamReader reader = new StreamReader(response.GetResponseStream());”

  22. Swathi says:

    Hi
    Thank u a lot for your code.

  23. JC says:

    Hi guys,

    For those that still get the same error 400;

    I have follow this example and I got the same result, first say that you need to be very careful with the path used to redirect and so on.

    I have just follow the current doc from facebook https://developers.facebook.com/docs/authentication/ changing
    seems like on the first authentication is where you need to request the scope, not on the second, and the url is not using the graph api.

    the token request is the same but without the scope.

    I have changed the first request for this one and remove the scope from the second one and that works for me.

    Hopes it helps someone,

    Cheers,

    JC

  24. Sathish says:

    can any one please help me to post to the wall using c#

  25. Alpa says:

    I don’t think I’ve enough words to express my gratitude towards you Dave. 3 Sleepless days and here I got what I wanted.
    Thank you so very much. Hats off to you sir.

  26. Swathi says:

    how to retrieve the user profile details as listed in the Graph API using the SDK http://developers.facebook.com/docs/reference/api/user/

    kindly help

    Thanks & Regards
    Swathi K

  27. how to create a facebook fan page from a web application which is developed in C#.

  28. 400 Error FIX (as of 09/15/2011)

    On the default.aspx replace the last line iwth:

    Response.Redirect(string.Format(“https://www.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}”, clientId, redirectUrl));

    Notice that the url has changed.

  29. Hi,

    Im receiving a 400 Bad request error in the following piece of code (resides in FacebookAPI.cs) while getting the response.

    Though the code works sometime, it is not consistent. And Im executing from localhost with specific port(5455).

    try
    {
    using (HttpWebResponse response
    = request.GetResponse() as HttpWebResponse)
    {
    StreamReader reader
    = new StreamReader(response.GetResponseStream());

    return reader.ReadToEnd();
    }
    }

    Please help me out.

    – Karthik

  30. Onkar says:

    thank u sir its working perfect for me … :)

  31. Srigurusankar says:

    Great, Very helpful to us. Thanks Dave.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: