Facebook C# SDK - Writing your First Facebook Application (v6)

This is an update to my old blog post on Writing your First Facebook Application using Facebook C# SDK v5. Due to the popularity of the post which has allowed developers to jump start on using Facebook C# SDK for creating Facebook Application, I have decided to update parts of the samples in order to reflect changes in v6. If you are using v5, I would recommend you to read the original post on Writing your First Facebook Application.

We will start up with a simple WinForms application which will include the authorization process and making requests to the Facebook server. Along the way I will also be explaining some of the Facebook and OAuth terminologies which I think will come as an added bonus if you are writing Facebook applications. (Even though this is a Windows application I highly recommend you to go through this particular tutorial whether you are developing a Facebook web application, Silverlight application or even Windows Phone application or Windows 8 Metro Style Apps.)

So let’s get started.

Getting the Facebook C# SDK binaries: Starting from v6, we will only be providing compiled binaries via NuGet. (If you are on older versions of Visual Studio or editions where NuGet package manager is not supported, you will need to download the Facebook.dll using the NuGet command line tool.)

Starting from v6 we are dropping FacebookWeb and FacebookWebMvc NuGet packages.

I will be using v6.0.2-alpha in this sample. Since v6 is still at a pre-release stage you will need to pass an extra –Pre option.

Install-Package Facebook –Pre

Rather then going through all File>New Project, I will rather explain the core features that I have used in the sample to keep this post small before all you start getting bored. You can find the download link of the complete sample at the end of this post.

Summary of the Facebook App: We will create a simple WinForm C# 4.0 application that contains the login button. When clicked it will ask the user to authorize the application with specified permissions. Once authorized it will display a message box saying "hi ...". We will also display the logout button once the user has logged in.

Authentication: If you haven’t created a Facebook application you will need to do so at http://www.facebook.com/developers/createapp.php. (This Facebook application is also referred to as client in OAuth 2). For windows app you would require only the application id (also referred to as client id).

Starting from v5 we have migrated all platforms (desktop,web, silverlight and wp7) to use the new Facebook OAuth Dialog. In v5 all the oauth related features are in FacebookOAuthClient. In the process of simplifying v6, we have removed FacebookOAuthClient and moved its features to FacebookClient.

Generating the Login Url:

private Uri GenerateLoginUrl(string appId, string extendedPermissions)
{
    // for .net 3.5
    // var parameters = new Dictionary<string,object>
    // parameters["client_id"] = appId;
    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);
}

Whether it is a silverlight or windows phone app or desktop app, this is the unified standard way of generating the login url. (Though you will require to change certain parameters like dispaly=touch for Windows phone to maximize user experience). Unlike v5, no default parameters are set. You will need to manually set all the parameters required for login.

If you are on a .NET Framework where dynamic is not supported, you can use IDictionary<string, object>. Starting from v6 we also support passing anonymous objects instead of IDictionary<string,object>.

var fb = new FacebookClient(); var loginUrl = fb.GetLoginUrl(new { client_id= "...", redirect_uri = "...", .....);

Extended permissions are also known as scope in OAuth 2. You can read more about this at available Facebook permissions at http://developers.facebook.com/docs/authentication/permissions/

By default the display is set to page by Facebook, we overwrite it to popup so that it consumes less space. More information about the display mode can me found at http://developers.facebook.com/docs/reference/dialogs/#display

Response Type is the result given by the Facebook Server on successful authorization. For native windows and windows phone app it is safe to set it as token. But if you are using web applications it is recommend to set it as code because when the Facebook Application redirect after authentication it appends the access_token to the redirect_uri. This means this url along with access token is stored in the browser’s history. (In case you are using a hosted browser control in Windows app, the url is not stored in the browser’s history. So it is safe to use token in desktop apps as compared to websites).

Using the browser user control you would then navigate to the generated login url.

webBrowser.Navigate(loginUrl);

Each time the page changes you would need to listen to it and check if the authorization process is completed.

private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
    // 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 (result.IsSuccess)
        {
            var accesstoken = result.AccessToken;
        }
        else
        {
            var errorDescription = result.ErrorDescription;
            var errorReason = result.ErrorReason;
        }
    }
    else
    {
        // The url is NOT the result of OAuth 2.0 authentication.
    }
}

To ease the authentication we can parse the callback url using ParseOAuthCallbackUrl / TryParseOAuthCallbackUrl. TryParseOAuthCallbackUrl returns true if it is recognized as a valid OAuth2 Authentication result. This means even if there was an OAuth 2 error such as user denied, it would still be able to parse it and return true. Thus there is another property called IsSuccess which is set to true if the oauth result was successful in the sense we have the access token or code. Scenario when the IsSuccess is false can be when the user clicks don’t allow. You can then access ErrorDescription and ErrorReason properties to show useful information to the user. So make sure to check it even if TryParse retruns true.

Making requests to Facebook server:

Now that you have the access token you can use that access token to make the request.

If you are using .net 3.5 (or any other platforms that doesn’t support dynamic keyword) then you can the cast it to IDictionary<string, object> and make a request. (If it is an array you can cast it to IList<object>)

var fb = new FacebookClient("access_token");

var result = (IDictionary<string, object>)fb.Get("me");
var name = (string)result["name"];

MessageBox.Show("Hi " + name);
If you are using dynamic you could write it as:

var fb = new FacebookClient("access_token");

dynamic result = fb.Get("me");
var name = result.name;

MessageBox.Show("Hi " + name);

Notice the dynamic keyword in dynamic result.

Prior to v6 you also had to use IDictionary<string, object> (or ExpandoObject) to pass parameters as follows.

var parameters = new Dictionary<string,object>();
parameters["fields"] = "id,name,picture";
var result = fb.Get("me", parameters);

Starting from v6 you can use anonymous objects. (IDictionary<string, object> or ExpandoObject will continue to work.)

var result = fb.Get("me", new { fields = new [] { "id", "name", "picture" } });

Note: If you are passing anonymous objects in Windows Phone as parameters, make sure to set [assembly:InternalsVisibleTo("Facebook")]. This is due to the security model of Windows Phone, as anonymous objects are actually a compile generated internal classes.

Logging out:

In order to logout, you will need to generate the logout url using GetLogoutUrl and then navigate to the the generated url.

var fb = new FacebookClient();
var logouUrl = fb.GetLogoutUrl(new { access_token = _accessToken, next = "https://www.facebook.com/connect/login_success.html" });
webBrowser.Navigate(logoutUrl);

Hope this tutorial helps you get started with the Facebook C# SDK. Make sure to checkout this post on making requests to Facebook server.

Here is the complete working sample. (make sure you put the appropriate application id before running the sample). I try to update this sample in github with the latest Facebook C# SDK.

https://github.com/prabirshrestha/FB-CSharp-SDK-First-FB-Application (For v5 you can checkout the v5 branch.)

Please ask general questions related to Facebook C# SDK at facebook.stackoverflow.com and tag it with "facebook" or "facebook-c#-sdk". Use comments only to discuss the matter related to this blog post.