• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / “Facebooksdk” – C#.NET Library For Facebook API

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

February 24, 2011 by Rana Ahsan 16 Comments

Facebooksdk C#

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: .net, c#, facebook

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. joe says

    March 9, 2011 at 11:57 pm

    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.

    Reply
    • Rana says

      March 10, 2011 at 1:56 am

      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?

      Reply
  2. ashsih says

    May 26, 2011 at 7:54 am

    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.

    Reply
    • Rana says

      May 26, 2011 at 9:24 pm

      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#

      Reply
  3. Ratnam says

    September 7, 2011 at 4:37 am

    how to create a facebook fan page from a web application which is developed in C#.

    Reply
    • Rana says

      December 22, 2011 at 11:13 pm

      I will write an article on it very soon. Stay tuned 🙂 . Thanks.

      Reply
      • Omar M says

        December 29, 2011 at 12:34 am

        Looking forward for that as well.

        Reply
  4. Parul says

    June 11, 2013 at 3:43 am

    i want to see facebook post at my C# web application. anybody help me regarding this.

    Reply
  5. Parul says

    June 11, 2013 at 4:17 am

    hello sir,

    i want to fetch facebook post at my bussiness page. plz help me regarding this.

    Reply
    • Md Ali Ahsan Rana says

      June 13, 2013 at 4:58 am

      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.

      Reply
  6. Lee Trung says

    July 20, 2014 at 12:14 am

    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

    Reply
  7. ali says

    August 21, 2014 at 6:19 am

    hi,Facebook c# Sdk Friend Tags Who? Hep me plz?

    Reply
  8. Ademir says

    November 9, 2015 at 1:10 pm

    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…

    Reply
  9. r.petroff says

    August 2, 2017 at 9:20 am

    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 🙂

    Reply

Trackbacks

  1. windows phone | Pearltrees says:
    March 13, 2012 at 9:03 am

    […] Authentication is a lot easier: This is one of the best feature to me of this library. Facebook C# SDK Samples With FacebookSDK .NET | codesamplez.com […]

    Reply
  2. FQL Tutorial In C#/FacebookSDK | codesamplez.com says:
    December 20, 2012 at 3:49 am

    […] 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# […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023