
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 time, and it’s a common tradition nowadays. Similarly, an open-source project has been developed to provide a better interface for using Facebook c# sdk, which enhanced the official SDK in a huge context and increased the flexibility for developers to create a robust Facebook application quickly. 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 was released first at the end of July 2010. From then on, several revisions/versions will be 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 of this library. The official SDK didn’t provide an authentication implementation. This library fulfills the lagging. It also provides tools for authentication on desktop client applications. 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. So, it became very easy to get a quick start on development in any of these platforms without much hassle.
- Others: NuGet Packages are also provided here. It also 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. However, my suggestion is to avoid the REST API as it’s going to 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 Facebook SDK’s most amazing features. 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 worries. You will have to code minimally. 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, pass this ‘code’ value to the ‘ExchangeCodeForAccessToken’ method of the ‘FacebookOAuthClient’ class. It will do the rest of the part. It’s very 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 put much effort into adapting its API call workflow. 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 for many developers as it’s unlike other simple ‘post’ or publish data operations. Here, we also need to pass an image object’s details along with the API call. However, the Facebook SDK library makes it 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 the Facebook SDK to contain the image(or other media information like video) information. Now, you 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. If you have a question, you can ask it on their StackOverflow discussions.
One thing that I am still not happy with is that their documentation isn’t very rich. Many times, they are outdated as they release versions more often. But I hope they will become stable very soon, and the documentation will also be rich enough to get help from a developer. The most positive point is that it helps to develop a high-quality Facebook application with easy graph API access. So, be with it. Happy coding 🙂
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
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.
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?
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.
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#
how to create a facebook fan page from a web application which is developed in C#.
I will write an article on it very soon. Stay tuned 🙂 . Thanks.
Looking forward for that as well.
i want to see facebook post at my C# web application. anybody help me regarding this.
hello sir,
i want to fetch facebook post at my bussiness page. plz help me regarding this.
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.
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
hi,Facebook c# Sdk Friend Tags Who? Hep me plz?
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…
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 🙂