Click here to Skip to main content
15,886,362 members
Articles / Web Development / ASP.NET

Publish a post on Facebook wall using Graph API

Rate me:
Please Sign up or sign in to vote.
4.85/5 (17 votes)
30 Mar 2013CPOL3 min read 151.5K   9.4K   43   12

Introduction

We can easily integrate Graph API with our .net Projects and easily we can post our status on Facebook wall. Not only we can post status but also we can easily share Image, video and Link on Facebook wall. In this post I’ll walk through the steps required to register a Facebook app, and post to your own Facebook wall using C#, MVC3 and Visual Studio 2010.

Background

The Graph API is the primary way that data is retrieved or posted to Facebook. It enables the developer to read and write Facebook data. Now I’ll discuss step by step to register a Facebook app, and how to post to your own Facebook wall.

Step 1: Firstly you’ll need to log on to the Facebook developer site and select Apps from the toolbar, then select +Create New App:

Image 1

Step 2: Enter the App Name, App Namespace and Web Hosting for the application. App Namespace and Web Hosting is not mandatory.

Image 2

After creating your App you’ll get App ID and App Secret these will need to post your status on Facebook wall.  

Step 3: After creating your App obviously you have to enter Site URL that you can see if you expand Website with Facebook Login menu. In Site URL you have to enter your application’s home page url. In addition you have to obviously enter Canvas URL and Secure Canvas URL otherwise will not work properly your Application. Normally you can enter this URL "http://www.veenx.com/fb/ApplicationFactory/app/73725/"  for Canvas URL and "https://www.veenx.com/fb/ApplicationFactory/app/73725/" for Secure Canvas URL.

Image 3

Facebook app registration has completed now you can start to build your application to post status on Facebook wall for that you have to follow some steps.

Firstly you have to create a Project and add FB.Graph Library as a reference and you can write a class for setting up the Facebook object, setting up the permissions and so on.

The code would be look like this:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ImpactWorks.FBGraph.Connector;
using ImpactWorks.FBGraph.Core;

namespace PostToFacebookWall
{
    public class Authentication
    {
        public Facebook FacebookAuth()
        {
            //Setting up the facebook object
            Facebook facebook = new Facebook(); 
            facebook.AppID = "xxxxxxxxxxxx";
            facebook.Secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            facebook.CallBackURL = "http://localhost:1846/PostStatus/Success/";
            
            //Setting up the permissions
            List<FBPermissions> permissions = new List<FBPermissions>() {
                FBPermissions.user_about_me, // to read about me               
                FBPermissions.user_events,
                FBPermissions.user_status,
                FBPermissions.read_stream,
                FBPermissions.friends_events,
                FBPermissions.publish_stream
            };

            //Pass the permissions object to facebook instance
            facebook.Permissions = permissions;
            return facebook;
        }
    }
}

Now you have to add a PostStatusController in controller folder and you can write Index, Success and PostStatus action methods within PostStatusController where Index action method return view page when you run the Application. PostStatus action method fire when you click Post Status button that create authLink URL and return authLink URL .Also authLink URL contains some information that will need to redirect the specific user authenticate location. If you give permission then automatically redirect your application with encrypted value that you have to hold in your application to get AccesToken and this AccessToken will need to post status on your Facebook wall. Using “Request.QueryString ["code"];” this syntax you can get the encrypted value. When redirect your application that time fire Success action method because you specified this action within CallBackURL. So Success action finally posts your status on your own Facebook wall.

The PostStatusController’s code scenario is given bellow.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ImpactWorks.FBGraph.Connector;
using ImpactWorks.FBGraph.Core;
using ImpactWorks.FBGraph.Interfaces;

namespace PostToFacebookWall.Controllers
{
    public class PostStatusController : Controller
    {
        //
        // GET: /PostStatus/

        public ActionResult Index()
        {
            return View();
        }

        Authentication auth = new Authentication();
        public ActionResult Success()
        {
            if (Request.QueryString["code"] != null)
            {
                string Code = Request.QueryString["code"];
                Session["facebookQueryStringValue"] = Code;
            }
            if (Session["facebookQueryStringValue"] != null)
            {
                Facebook facebook = auth.FacebookAuth();
                facebook.GetAccessToken(Session["facebookQueryStringValue"].ToString());
                FBUser currentUser = facebook.GetLoggedInUserInfo();
                IFeedPost FBpost = new FeedPost();
                if (Session["postStatus"].ToString() != "")
                {
                    FBpost.Message = Session["postStatus"].ToString();
                    facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);
                }
            }
            return View();
        }

        public JsonResult PostStatus(string msg)
        {
            Session["postStatus"] = msg;


            Facebook facebook = auth.FacebookAuth();
            if (Session["facebookQueryStringValue"] == null)
            {
                string authLink = facebook.GetAuthorizationLink();
                return Json(authLink);
            }

            if (Session["facebookQueryStringValue"] != null)
            {               
                facebook.GetAccessToken(Session["facebookQueryStringValue"].ToString());
                FBUser currentUser = facebook.GetLoggedInUserInfo();                
                IFeedPost FBpost = new FeedPost();
                if (Session["postStatus"].ToString() != "")
                {
                    FBpost.Message = Session["postStatus"].ToString();
                    facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);
                }
            }
            return Json("No"); 
        }
    }
}

Now you have to add a View page where you can put your html. The View page will be looks like this:

HTML
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


@using (Html.BeginForm())
{ 
    <fieldset style="color: Black;">
        <legend>Message</legend>
        <div>
            <label style="font-style: italic; color: Gray;">
                Write your status</label><br />
            @Html.TextArea("txtPostStatus", new { maxlength = 100, style = "height:100px;width:500px;" })
        </div>
        <div style="text-align: left;">                   
            <input id="btnPost" type="button" value="Post Status" onclick="PostStatus();" />
        </div>
    </fieldset>
}

Some jQuery you have to add your view page that i have written for calling PostStatus method and showing popup. The code looks like this:

JavaScript
<script type="text/javascript">

    function PostStatus() {
        var msg = $('#txtPostStatus').val();   

        if (msg != '') {
            $.ajax({
                url: '/PostStatus/PostStatus',
                type: 'POST',
                data: { msg: msg },
                success: function (authLink) {
                    if (authLink != 'No') {
                        window.open(authLink, 'title', 'width=660,height=500,status=no,scrollbars=yes,toolbar=0,menubar=no,resizable=yes,top=60,left=320');
                    }
                }
            });
        }
        else {
            alert('please write your message.');
        }
    }  
</script>

Some jQuery has written for Ajax calling the PostStatus method from PostStatusController and to show the Facebook Login page as a popup if successfully return the authLink from PostStatusController.


For Link, Image and Video Sharing you just have to add some code within Success action method. The code looks like this:

Link Share:

C#
FBpost.Action = new FBAction { Name = "test link", Link = "http://blog.impact-works.com/" };
                FBpost.Caption = "Test Image Share";
                 FBpost.Description = "Test Image Desc";
                FBpost.ImageUrl = "http://www.theadway.com/wall.jpg";
                FBpost.Message = "Check out test post";
                FBpost.Name = "Test Post";
                FBpost.Url = "http://blog.impact-works.com";
 
                var postID = facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);

Video Share:

C#
FBpost.Url = "http://www.youtube.com/watch?v=hmxgM3sXqDs";
  FBpost.Message = "Sharing a Youtube video";
 
var postId =   facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);

Image Share:

FBpost.Caption = "Image Share";
 
                FBpost.ImageUrl = "http://www.theadway.com/wall.jpg";
 
                FBpost.Name = "Great Image";
                FBpost.Url = "http://www.theadway.com/wall.jpg";
 
              var postId =   facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);

Conclusion:

Hopefully, you’ll be able to use this for your applications and it will make you little bit easier to make this type of application. For more information I’d recommend you visit the Facebook Docs.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) IT Consultants Ltd (QCash).
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionError on facebook page Pin
kabijoy126-Feb-20 5:56
kabijoy126-Feb-20 5:56 
QuestionNot working..!! Pin
Tushar khairnar28-May-16 22:20
Tushar khairnar28-May-16 22:20 
QuestionWould not open in Visual Studio 2012 Pin
Johnny Fever30-Jun-14 9:36
Johnny Fever30-Jun-14 9:36 
Question403 forbidden error PinPopular
Abhijit pandya3-Jun-14 2:50
Abhijit pandya3-Jun-14 2:50 
QuestionUploading photo Pin
Member 107038781-Apr-14 23:23
Member 107038781-Apr-14 23:23 
GeneralMy vote of 1 Pin
jadeer16-Feb-14 23:23
jadeer16-Feb-14 23:23 
QuestionBad request error Pin
Mifla Mashood7-Dec-13 20:09
Mifla Mashood7-Dec-13 20:09 
QuestionHow to POST On facebook Page Not a Wall.........? Pin
loinheart5-Nov-13 7:59
loinheart5-Nov-13 7:59 
Questionhow to Hosting this application Pin
Mohamed Satti20-Sep-13 3:10
Mohamed Satti20-Sep-13 3:10 
GeneralGive It A Try Pin
Tareq Newaz Shahriar15-Sep-13 19:13
Tareq Newaz Shahriar15-Sep-13 19:13 
GeneralMy vote of 5 Pin
cdelvillar11-Sep-13 12:35
cdelvillar11-Sep-13 12:35 
QuestionAbout getting wall update Pin
csharpbd20-May-13 21:05
professionalcsharpbd20-May-13 21:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.