Getting Started With Facebook C# SDK

In my previous post, I’ve mentioned a relatively new Facebook SDK available for .NET.  Here’s a quick example of how to install and use it to post a message to an FB user’s wall and then Like it, using an MVC application.

 

Install Facebook C# SDK via NuGet.

1.  First add a package reference to your project.

add_package_reference

 

2.  Filter packages by “Facebook” and install:  Facebook, FacebookWeb, and FacebookWebMvc.

facebook_packages

 

3.  Check that references were added to your project:

facebook_references_added

 

Configure web application:

Most of these settings get added to the web.config when you add the Facebook package references.  However, you may need to add the canvas settings yourself.

  <configSections>
    <section name="facebookSettings" type="Facebook.FacebookConfigurationSection"/>
    <section name="canvasSettings" type="Facebook.Web.CanvasConfigurationSettings"/>
  </configSections>
  <facebookSettings
    apiKey="1111111111111111111111111111111"
    apiSecret="22222222222222222222222222222222"
    appId="3333333333333"
    cookieSupport="false" />
  <canvasSettings
    canvasPageUrl="http://apps.facebook.com/mvc_application_one/"
    authorizeCancelUrl="" />

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
      <add name="facebookredirect.axd" verb="*" path="facebookredirect.axd"
           type="Facebook.Web.FacebookAppRedirectHttpHandler, Facebook.Web" />
    </handlers>
  </system.webServer>


Posting a message to user’s wall/feed.

The Site.Master view:

Per this discussion, the authorization process is not included in this SDK, therefore you can write your own extension to do so or just use Facebook’s JavaScript SDK.  I prefer to use what’s already available.  So here’s a simple FB init call that lets us access the currently logged in user’s session (this assumes the user is already logged in and is obviously missing the authentication functionality).
    <script type="text/javascript">
        $(document).ready(function () {

            FB.init({ appId: '<%:FacebookSettings.Current.AppId %>', status: true, 
cookie: true, xfbml: true }); }); var getAccessToken = function () { var accessToken = null; var session = FB.getSession(); if (session != null) { accessToken = session.access_token; } return accessToken; }; </script
>

The Index view:

Ideally, the Ajax call’s post URL is relative to your application root, so disregard this ugliness.

    <script type="text/javascript">
        var postId = null;

        $(document).ready(function () {

            $('#postTest').click(function () {
                $.ajax({
                    url: 'http://localhost/MvcApplication1/Home/Post',
                    data: { message: 'Hi, how are you?', 
accessToken: getAccessToken() }, success: function (response) { alert(response); postId = response; }, error: function (e) { alert(e.responseText); } }); }); }); </script
> <p> <input type="button" id="postTest" value="Post it" /> </p> <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js"></script>

The action method in the Home controller, which is invoked by our Ajax call:

public JsonResult Post(string message, string accessToken)
{
    FacebookApp app = new FacebookApp(accessToken);

    var args = new Dictionary<string, object>();
    args["message"] = message;
    args["caption"] = "This is caption!";
    args["description"] = "This is description!";
    args["name"] = "This is name!";
    args["picture"] = "http://itsmagic.files.wordpress.com/2009/11/stewie1.jpg";
    args["link"] = "http://apps.facebook.com/mvc_application_one";

    JsonObject result = (JsonObject)app.Api("/me/feed", args, HttpMethod.Post);

    return new JsonResult { Data = (result as dynamic).id, 
JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }

Note here that an access token needs to be passed into the FacebookApp contructor, as this helps maintain Facebook’s session state and thus the user’s authorization between requests, which is most likely required to post to the user’s wall.  The access token was retrieved from FB user’s session object on the client side (see getAccessToken above).

The returned result is our new post’s ID.  And our wall/feed post looks like this:

wall_post

 

I did mention that I’d show how to Like a post, didn’t I?

A new button:

        <input type="button" id="likeTest" value="Like it" />

 

Another Ajax call:

Note that we’re reusing the postID that was returned from the initial Post call – that’s what we’re going to Like.

$('#likeTest').click(function () {
    var session = FB.getSession();
    var accessToken = null;

    if (session != null) {
        accessToken = session.access_token;
    }

    $.ajax({
        url: 'http://localhost/MvcApplication1/Home/Like',
        data: { postId: postId, accessToken: getAccessToken() },
        success: function (response) {
            alert(response);
        },
        error: function (e) {
            alert(e.responseText);
        }
    });
});

A new action method:

public JsonResult Like(string postId, string accessToken)
{
    FacebookApp app = new FacebookApp(accessToken);

    bool result = (bool)app.Api(String.Format("/{0}/likes", postId), null, 
HttpMethod.Post); return new JsonResult { Data = result,
JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }

 

And once executed, the post looks like this:

wall_post_liked

Published Monday, November 15, 2010 11:25 AM by fallen888
Filed under: , , , , ,

Comments

# re: Getting Started With Facebook C# SDK

Tuesday, November 16, 2010 12:05 AM by Rakesh

This is a good post

# Buen art??culo sobre c??mo comenzar a usar el API de Facebook &laquo; dotNetMan??a

Pingback from  Buen art??culo sobre c??mo comenzar a usar el API de Facebook &laquo; dotNetMan??a

# re: Getting Started With Facebook C# SDK

Wednesday, November 17, 2010 8:36 AM by lquinteo

Interesante articulo

# re: Getting Started With Facebook C# SDK

Wednesday, November 24, 2010 8:36 AM by tugberk_ugurlu_

hi,

is there any othere resources on this that we could get more out of it !

# re: Getting Started With Facebook C# SDK

Wednesday, November 24, 2010 8:53 AM by fallen888

Other than the links (containing demos) provided, you can always Google for more information.  Is there something in particular you are looking for?

# re: Getting Started With Facebook C# SDK

Thursday, December 02, 2010 8:07 PM by Abe Miessler

Do you know if it's possible to include a link in a post?  I tried replacing args["link"] but it won't let me post unless it's a link to my app.  I noticed the javascript API has: action_links: [

     { text: 'fbrell', href: 'http://fbrell.com/' }

   ]

Can I use this in the C# sdk?

# re: Getting Started With Facebook C# SDK

Tuesday, December 07, 2010 8:25 AM by fallen888

I've noticed that as well.  I haven't tried anything else to post a link to a different site, but you can do this...  Have the link go to your site with a query string parameter, which you parse and redirect user to the appropriate site.

# re: Getting Started With Facebook C# SDK

Tuesday, January 11, 2011 5:18 AM by vondiplo

Say, where did you get the option to right click the project reference and :

"add a package reference".

I am using vs 2010, and no such options exists

# re: Getting Started With Facebook C# SDK

Tuesday, January 11, 2011 5:26 AM by fallen888

You have to install NuGet first.  Alternatively you can just download the SDK directly from Codeplex - facebooksdk.codeplex.com

# Can't Like a Page? Seriously??

Thursday, January 13, 2011 6:16 PM by Kon's Blog

We've previously talked about programmatically liking a post. But I recently tried to like a page, and

# re: Getting Started With Facebook C# SDK

Thursday, March 17, 2011 1:49 PM by Bogdanel

it doesn't work ... i found 1 error

the error say : The type or namespace 'FacebookApp' could not be found....pls help

# re: Getting Started With Facebook C# SDK

Thursday, March 17, 2011 4:08 PM by fallen888

Sounds like you didn't add the reference or import the namespace.

# ???????????? Facebook C# SDK ???????????????????????? &laquo; Coding ?????????????????????

Pingback from  ???????????? Facebook C# SDK ???????????????????????? &laquo; Coding ?????????????????????

# re: Getting Started With Facebook C# SDK

Tuesday, June 07, 2011 11:33 PM by Eduardo

Can you provide the source?

Thank you.

# re: Getting Started With Facebook C# SDK

Sunday, July 03, 2011 12:00 AM by DrTJ

Great article... Thank you so much! :)