“Facebooksdk” – C#.NET Library For Facebook API


 “Facebooksdk” – C#.NET Library For Facebook API  
 

If you are already developing facebook application in .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 consumes times/complexity in development and also be less stable. However, developers community has helped in this kind of situations for long since and its a common tradition now a days. Similarly, with a goal 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 contexts and increased the flexibility for developers to create a robust Facebook application quickly. Here, in this tutorial, I will try to give an overview on 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 of this project, in my opinion, are as follows:

  • Authentication is a lot easier: This is one of the best feature to me of this library. The authentication implementation wasn’t provided by official sdk. 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 extra extensions for silverlight, asp.net web, asp.net web mvc, winform , wpf – each of these platforms. So, its became very much easy to get a quick start development in any of these platforms without much hassle.
  • Others: NuGet Packages are provided here also. Even, its providing sample applications for each of the platforms which is a great 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 its gonna be eliminated very soon(already deprecated).

Now, lets discuss some common example with source code samples.

Authentication Example With FacebookSDK:

As I said, this is one of the most amazing features facebooksdk provides. If you are Asp.NET MVC developer, and developing 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 like as follows:

[CanvasAuthorize(Perms = "user_about_me")]
public ActionResult Index()
        {
           //other statements
            return View();
        }

If you need the authentication for all functions(most of the Facebook applications does this), you can add this filter to the class itself like 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 facebook authentication page if there is not url parameters named ‘code’. after user allows the application and return to your application page, then pass this ‘code’ value to the ‘ExchangeCodeForAccessToken’ method of ‘FacebookOAuthClient’ class. It will do the rest of the part. Its 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 already using that, you won’t have to provide much efforts to adapts its work flow of making the api calls. Rather it makes much more simpler. Lets consider a simple code example of make a call to Facebook API for access 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;

Upload Photo Using Facebook Graph API With FacebookSDK Library:

Uploading photos to facebook via graph API is often seems as 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, facebooksdk 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

The ‘FacebookMediaObject’ is the object provide by facebooksdk 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 official site for facebook c# sdk. If you have a question to ask for, you can either do it on their stackoverflow discussions.

One thing that I am not still happy much with them is that, their documentation aren’t much rich. Many of the times, they are outdated also as they are releasing versions more often. But I am hoping, they will become stable very soon and documentation will also be rich enough to get help for a developer. Most positive point it, it helps a lot to start developing a high quality facebook application with easy graph api access. So, be with it. Happy coding :)

Comments

  1. 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.

    • 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?

  2. 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.

  3. 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

Trackbacks

  1. […] Full meaning of FQL is 'Facebook Query Language'. This is used to retrieve filtered data from facebook api similarly as sql query works with database. You won't find it exactly like SQL query syntax all the time, and not all kind of operations too. But, it definitely meets the demand. In this tutorial, i will try to explain using fql in your c# application. I am assuming, you are familiar with using facebook graph api through c#. If you are a beginner Facebook api developer in c#, you should better start by another article about getting started with Facebook graph api in c#. Also, you should be familiar with facebooksdk library also to use the examples here. If not yes, please read another tutorial about getting started with facebooksdk/c# […]

Leave a Reply