Sunday, 8 September 2013

C# - POST a messge in Facebook account using Facebook App

Today social networking plays major role in Communication and Business ads.In this tutorial we are going to see how to post a message in a Facebook account.

For this we have to create a Facebook App first, From that use the App_id and App_Secret_Key for access the access the Facebook account.

Following the below steps.
1. Open the visual studio 2010
2. Create a new web application project
3. Click Menu Tools->Library Package Manager->Package Manager console 
     If Library Package Manager is not present in menu then install Nuget Packages from the following link
     Nuget Package Manager

4. Type the following command in console of library manager. "install-package facebook"
5. Now Facebook API is add in Reference.]
6. Go to the Facebook app create and select your and edit.
7. Assign the website url value of local hosted url in the section of facebook App.

protected void Page_Load(object sender, EventArgs e)

private void Authorize()
  string app_id = "49772742030276";
  string app_secret = "4ddb76a956e0c0b28456e744d59174";
  string scope = "publish_stream,manage_pages";

  if (Request["code"] == null)
    string uri = string.Format("{0}&redirect_uri={1}&scope={2}", app_id, Request.Url.AbsoluteUri, scope);
    Dictionary<string, string> Res_tokens = new Dictionary<string, string>();
    string uri = string.Format("{0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                    app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);

    HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string values = reader.ReadToEnd();
        foreach (string token in values.Split('&'))
Res_tokens.Add(token.Substring(0, token.IndexOf("=")), token.Substring(token.IndexOf("=") + 1));

       string access_token = Res_tokens["access_token"];
       Facebook.FacebookClient client = new Facebook.FacebookClient(access_token);
       client.Post("/me/feed", new { message = "This post is sample testing from C# program : Testing = Success ;) " });


At the first time, page loads there is no code is present in request. we are sending the id and request.url.AbsoulteUri which is mention in Facebook app it is automatically taken from that.When you  launch the page you will see the following screens. if not already login in Facebook  then login page will come.after finish the login following UI will launch finally it is posted in your FB account with your app .
Here "/me/feed" refers the my account , if you want to post some one than give the corresponding id.

From this article i hope you will learn how to use the FB app to post the message in FB account.

1 comment:

  1. This comment has been removed by a blog administrator.