Thursday, 2 August 2012

Post To FaceBook Page in asp.net


First Register Your Application and  get Client Id

Then after user authenticate Your App you will get Access Token

User authentication Process

First place Two buttons For Authorization  on web form
In authorization button click Event Write the following code
We set Offline access ,Publish stream Permission,manage Pages Permission   of users to post on page
protected void Authorization_Click(object sender, EventArgs e)
        {
         
       //     Your Website Url which needs to Redirected
              string callbackUrl = "xxxxxxx";

       //Client Id Which u Got when you Register You Application
       string   FacebookClientId="xxxx";
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri{1}&scope=offline_access,publish_stream,read_stream,publish_actions,manage_pages",FacebookClientId, callbackUrl));
         

        }
After user Authorizes  U will Receive Oauth code.use the below  URL to get  Access token For that user

           https://graph.facebook.com/oauth/access_token?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
     client_secret=YOUR_APP_SECRET&code=The code U got from face book after Redirecting


This will Return User Access token save it For Further use


Then After We need to  get Pages information of user

Use Below Method to get Page tokens and IDs



             public void getpageTokens()

            {
                // User Access Token  we got After authorization

               string UserAccesstoken="xxxxxx";
                string url = string.format("https://graph.facebook.com/me/accounts?access_token={0}",UserAccesstoken);

                webRequest.ContentType = "application/x-www-form-urlencoded";

                webRequest.Method = "Get";

           
                 var webResponse = webRequest.GetResponse();

                 StreamReader sr = null;

                   
                 sr = new StreamReader(webResponse.GetResponseStream());

                 string returnvalue = sr.ReadToEnd();

               //using Jobject to parse result
                
                 JObject mydata = JObject.Parse(returnvalue);
              
                JArray data = (JArray)mydata["data"];
             
               
            
                PosttofacePage(data);
            }



  I used   Json.net dll to Parse information from facebook,The dll can be found in http://json.codeplex.com/releases/view/89222
 Now its time to Post Data to Pages




          public void PosttofacePage(JArray obj)
            {

                for (int i = 0; i < obj.Count; i++)
                {
                    string name = (string)obj[i]["name"];
                    string Accesstoken = (string)obj[i]["access_token"];
                    string category = (string)obj[i]["category"];
                    string id = (string)obj[i]["id"];

                    string Message = "Test message";

                    if (string.IsNullOrEmpty(Message)) return;
                   
                    // Append the user's access token to the URL
                  string  path=String.Format("https://graph.facebook.com/{0}",id);
                    
                   var url = path+"/feed?" +
                       AppendKeyvalue("access_token",AccessToken);

                    // The POST body is just a collection of key=value pairs, the same way a URL GET string might be formatted

                    var parameters = ""

                        + AppendKeyvalue("name", "name")

                        + AppendKeyvalue("caption", "a test caption")

                        + AppendKeyvalue("description", "test description ")

                        + AppendKeyvalue("message", Message);

                    // Mark this request as a POST, and write the parameters to the method body (as opposed to the query string for a GET)

                    var webRequest = WebRequest.Create(url);

                    webRequest.ContentType = "application/x-www-form-urlencoded";

                    webRequest.Method = "POST";

                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);

                    webRequest.ContentLength = bytes.Length;

                    System.IO.Stream os = webRequest.GetRequestStream();

                    os.Write(bytes, 0, bytes.Length);

                    os.Close();

                    // Send the request to Facebook, and query the result to get the confirmation code

                    try
                    {

                        var webResponse = webRequest.GetResponse();

                        StreamReader sr = null;

                        try
                        {

                            sr = new StreamReader(webResponse.GetResponseStream());

                            string PostID = sr.ReadToEnd();

                        }

                        finally
                        {

                            if (sr != null) sr.Close();

                        }

                    }
                    catch (WebException ex)
                    {

                        // To help with debugging, we grab the exception stream to get full error details

                        StreamReader errorStream = null;

                        try
                        {

                            errorStream = new StreamReader(ex.Response.GetResponseStream());

                            this.ErrorMessage = errorStream.ReadToEnd();

                        }
                        finally
                        {

                            if (errorStream != null) errorStream.Close();

                        }

                    }

                }
            }
 



  I Used AppendKeyvalue Mehod to Append Key value Pairs

  public static string AppendKeyvalue(string key, string value)
        {
            return string.Format("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value));
        }


 The above code Returns post id if posted successfully.
 Note: Access tokens are different For Different users
 That’s it We posted a new post on users page
 Happy coding






No comments:

Post a Comment