Facebook C# SDK - Writing your first Facebook Application
This is first tutorial on Facebook C# SDK. Over the upcoming days I will be blogging about how to use the Facebook C# SDK to create different types of Facebook Applications whether it is a Windows application, MVC application or even a Silverlight and Windows Phone applications.
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.)
So let’s get started.
Getting the Facebook C# SDK binaries:
You will need to get the latest Facebook C# SDK from https://github.com/facebook-csharp-sdk/facebook-csharp-sdk or from nuget.
There are 3 NuGet packages for Facebook C# SDK – Facebook, FacebookWeb and FacebookWebMvc. You can see the list of available NuGet packages using the following command in the package manager console.
List-Package -Remote -Filter Facebook
I will be using v5.0.1 in this sample. To install the latest Facebook package execute the following command.
Install-Package Facebook
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 download 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 …”.
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 require 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.We have also migrated all the aouth related features from FacebookClient (FacebookApp) to FacebookOAuthClient.
Generating the Login Url:
string appId = "xxx";
string[] extendedPermissions = new[] { "publish_stream", "offline_access" };
var oauth = new FacebookOAuthClient { ClientId = appId };
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "popup" }
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.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 starting from v5. (Though you will require to change certain parameters like dispaly=touch for Windows phone to maximize user experience). By default the redirect_uri is set to http://www.facebook.com/connect/login_success.html which you can also change. For the current windows app the default redirect is more than enough.
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, 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)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Url, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
}
To ease the authentication process another helper class called FacebookOAuthResult has been added. TryParse 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
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”.
Hope this tutorial helps you get started with the Facebook C# SDK. I will be posting more tutorials in the upcoming days. Make sure to checkout this post on making requests to Facebook server. http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx
Here is the complete working sample. (make sure you put the appropriate application id before running the sample).
Preferred Download: https://github.com/prabirshrestha/FB-CSharp-SDK-First-FB-Application (I try to update this sample in github with the latest Facebook C# SDK)
Click here to learn more on how to make requests using Facebook C# SDK
FacebookCSharpSdk-FirstFacebookApplication.zip (4.57 mb)
Please ask general questions related to Facebook C# SDK at stackoverflow and tag it with "facebook" or "facebook-c#-sdk". Use comments only to discuss the matter related to this blog post.