If you are already developing a Facebook application on the .NET platform, you must have noticed that the official c# SDK for Facebook API isn’t quite enough for most of the developers as still many common implementations are to be handled by developers themselves that consume times/complexity in development and also be less stable. However, the developers’ community has helped in this kind of situation for a long since, and it’s a common tradition nowadays. Similarly, to provide a better interface in using Facebook c# sdk, an open source project has been developed which enhanced the official SDK in a huge context and increased the flexibility for developers to create a robust Facebook application quickly. Here, in this tutorial, I will try to give an overview of the FacebookSDK library and provide some examples to show how it works and help you have a better start.
Features Of FacebookSDK Library:
FacebookSDK has released first at the end of July 2010. From then, several revisions/versions are released. The latest is 5.0.3 (BETA). I am focusing on this latest version and the features which should be most attractive/interesting and helpful for this project, in my opinion, are as follows:
- Authentication is a lot easier: This is one of the best features to me of this library. The official SDK didn’t provide the authentication implementation. This library fulfills the lagging. Even it provides tools for authentication on desktop client applications also. You can do the authentication parts almost in no time using this library. It supports Cookies, OAuth 2.0 and Signed Requests.
- Most of the platforms supported: Besides common functionality, this library includes extensions for Silverlight, asp.net web, asp.net web MVC, WinForms, and WPF – each of these platforms. So, it became very much easy to get a quick start on development in any of these platforms without much hassle.
- Others: NuGet Packages are provided here also. Even it provides sample applications for each of the platforms, which is an excellent benefit for starters. Besides, It’s currently supporting both Facebook REST API and Facebook Open Graph API. Though, my suggestion will be to avoid REST API as it’s gonna be eliminated very soon(already deprecated).
Now, let’s discuss some common examples with source code samples.
Authentication Example With FacebookSDK:
As I said, this is one of the most amazing features facebook SDK provides. If you are an Asp.NET MVC developer, and developing a Facebook iframe application, then it will feel just like drinking water to you. You will simply have to put a filter to the controller methods you want to be authenticated. A code sample is as follows:
[CanvasAuthorize(Perms = "user_about_me")]
public ActionResult Index()
{
//other statements
return View();
}
Code language: PHP (php)
If you need the authentication for all functions(most of the Facebook applications do this), you can add this filter to the class itself as follows:
[HandleError]
[CanvasAuthorize(Perms = "user_about_me")]
public class HomeController : Controller
{
public ActionResult Index()
{
FacebookApp fbApp = new FacebookApp();
if (fbApp.Session != null)
{
//call authenticated methods
}
return View();
}
public ActionResult About()
{
return View();
}
}
Using other frameworks or platforms? No worry. You will have to code minimal. First, redirect the user to the Facebook authentication page if there are no URL parameters named ‘code’. after the user allows the application and returns to your application page, then pass this ‘code’ value to the ‘ExchangeCodeForAccessToken’ method of ‘FacebookOAuthClient’ class. It will do the rest of the part. It’s much similar to my previous tutorial, Get Facebook access token in c# sdk.
Call API Methods:
This library keeps the API calls pretty much similar to the original official c# sdk. So, if you are already using that, you won’t have to provide much effort into adapting its workflow of making the API calls. Rather it makes it much simpler. Let’s consider a simple code example of making a call to Facebook API to access the user’s all information:
//using official sdk
JSONObject result = fbApp.Get("/me");
ViewData["Firstname"] = result.Dictionary["first_name"].String;
ViewData["Lastname"] = result.Dictionary["last_name"].String;
//usinf facebooksdk
dynamic result = fbApp.Get("me");
ViewData["Firstname"] = result.first_name;
ViewData["Lastname"] = result.last_name;
Code language: JavaScript (javascript)
Upload Photo Using Facebook Graph API With FacebookSDK Library:
Uploading photos to Facebook via graph API often seems like a major issue to many developers as it’s not like other simple ‘post’ or publish data operations. Here we also need to pass an image object’s details information along with the API call. However, the facebook SDK library makes this easier for us to do that task in c#. We can now upload a photo to Facebook using graph API in a much simpler way. Here is a code sample to upload an image:
string photoAlbumID = "{youralbumid}";
FacebookMediaObject facebookUploader = new FacebookMediaObject { FileName = "funny-image.jpg", ContentType = "image/jpg" };
var bytes = System.IO.File.ReadAllBytes(Server.MapPath("~") + facebookUploader.FileName);
facebookUploader.SetValue(bytes);
var postInfo = new Dictionary<string, object>();
postInfo.Add("message", "test photo");
postInfo.Add("image", facebookUploader);
var fbResult = fbApp.Post("/" + photoAlbumID + "/photos", postInfo);
dynamic result = (IDictionary<string, object>)fbResult;
//do other works like successful messages/etc
Code language: JavaScript (javascript)
The ‘FacebookMediaObject’ is the object provided by Facebook SDK to contain the image(or other media information like video) information. now just need to add that object as the FB API’s ‘image’ parameter. This time, the return result will contain only the id of the image uploaded. so you can use the “result.id” at the finishing statement if you need to use it anymore.
References:
To learn more about this Facebook c# sdk library, please visit the official site for Facebook c# sdk. If you have a question to ask, you can either do it on their stackoverflow discussions.
One thing that I am still not happy with them is that their documentation isn’t much rich. Many of the times, they are outdated also as they are releasing versions more often. But I hope they will become stable very soon, and the documentation will also be rich enough to get help for a developer. The most positive point is it helps a lot to start developing a high-quality Facebook application with easy graph API access. So, be with it. Happy coding 🙂
joe says
Have you been able to get this to work with the silverlight version of the facebook sdk? I cannot seem to get a post with a photo to an album or to the wall.
Rana says
Hi, no I haven’t tried the silver-light version yet. Did you debug it, what happens? Is it throws any exception while doing the photo upload operation?
ashsih says
Hi,
I am not able understand fully this source code . I want to get AccessToken to upload the images into my Facebook album , I coudn’t get any clear code till now. see the below line:
string code = Request.QueryString[“code”];”
I m confused from where I get this “Code” , didn’t mention in your code that
how to get this “Code” to pass to get the access token.
Pl.s help me .
Thanks.
Rana says
If you are using facebooksdk, you shouldn’t be needed such code for authentication, those are handled internally. On the other hand, if you are looking for a custom solution for yourself, you can refer to my another article about facebook api authentication in c#
Ratnam says
how to create a facebook fan page from a web application which is developed in C#.
Rana says
I will write an article on it very soon. Stay tuned 🙂 . Thanks.
Omar M says
Looking forward for that as well.
Parul says
i want to see facebook post at my C# web application. anybody help me regarding this.
Parul says
hello sir,
i want to fetch facebook post at my bussiness page. plz help me regarding this.
Md Ali Ahsan Rana says
If you have been successful in exercising my facebook c# api tutorials and examples, the you should get it easily with facebook’s reference documentation of pages here: http://developers.facebook.com/docs/reference/api/page/ . Thanks.
Lee Trung says
Hi Admin,
Thank you for your post. It’s a great artical. So i have one question :
Does it possible if i want to upload more than one photo for per post. i use PostGroup but only 1 photo for per post ?
Thank you
ali says
hi,Facebook c# Sdk Friend Tags Who? Hep me plz?
Ademir says
Hi Rana, i’m developing a windows form application where i need post pictures in facebook, but i did not find any examples, everything that i read was about C#.net, do you know where i can find something or example? thanks alot and sorry about my english…
r.petroff says
Hi, would you share a code sample for uploading a video WITH THUMBNAIL in Facebook?
I have already tried to add to “thumb” parameter for the custom thumbnail, which is associated to the video, a Bitmap object, a byte array, a base64 string but an (OAuthException – #100) (#100) Exception for invalid parameter had been thrown. Lastly, I also tried to add as thumb parameter a FacebookMediaObject for the custom thumbnail and than the videos uploads successfully to Facebook without the thumbnail picture.
Do you know the solution?
Please, share it!
Thanks in advance 🙂