Friday, 15 February 2013

FaceBook Cover Albums Access Through Asp.net c#



Create one appication in facebook from Developers page.

Then Create these pages:


oAuthFacebooks.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Net;
using System.IO;

/// <summary>
/// Summary description for oAuthFacebooks
/// </summary>
public class oAuthFacebook
{
    public enum Method { GET, POST };
    public const string AUTHORIZE = "https://graph.facebook.com/oauth/authorize";
    public const string ACCESS_TOKEN = "https://graph.facebook.com/oauth/access_token";
    public const string CALLBACK_URL = "http://localhost:3160/WebSite17/fbcallback.aspx";

    private string _consumerKey = "";
    private string _consumerSecret = "";
    private string _token = "";

    #region Properties

    public string ConsumerKey
    {
        get
        {
            if (_consumerKey.Length == 0)
            {
                _consumerKey = "############"; //Your application ID
            }
            return _consumerKey;
        }
        set { _consumerKey = value; }
    }

    public string ConsumerSecret
    {
        get
        {
            if (_consumerSecret.Length == 0)
            {
_consumerSecret = "###########"; //Your application secret
            }
            return _consumerSecret;
        }
        set { _consumerSecret = value; }
    }


    public string Token { get { return _token; } set { _token = value; } }

    #endregion

    /// <summary>
    /// Get the link to Facebook's authorization page for this application.
    /// </summary>
    /// <returns>The url with a valid request token, or a null string.</returns>
    public string AuthorizationLinkGet()
    {
        return string.Format("{0}?client_id={1}&redirect_uri={2}&scope={3}", AUTHORIZE, this.ConsumerKey, CALLBACK_URL,"user_photos");
    }

    /// <summary>
    /// Exchange the Facebook "code" for an access token.
    /// </summary>
    /// <param name="authToken">The oauth_token or "code" is supplied by Facebook's authorization page following the callback.</param>
    public void AccessTokenGet(string authToken)
    {
        this.Token = authToken;
        string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}",
        ACCESS_TOKEN, this.ConsumerKey, CALLBACK_URL, this.ConsumerSecret, authToken);

        string response = WebRequest(Method.GET, accessTokenUrl, String.Empty);

        if (response.Length > 0)
        {
            //Store the returned access_token
            NameValueCollection qs = HttpUtility.ParseQueryString(response);

            if (qs["access_token"] != null)
            {
                this.Token = qs["access_token"];
            }
        }
    }

    /// <summary>
    /// Web Request Wrapper
    /// </summary>
    /// <param name="method">Http Method</param>
    /// <param name="url">Full url to the web resource</param>
    /// <param name="postData">Data to post in querystring format</param>
    /// <returns>The web server response.</returns>
    public string WebRequest(Method method, string url, string postData)
    {

        HttpWebRequest webRequest = null;
        StreamWriter requestWriter = null;
        string responseData = "";

        webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
        webRequest.Method = method.ToString();
        webRequest.ServicePoint.Expect100Continue = false;
        //webRequest.UserAgent = "[You user agent]";
        webRequest.UserAgent = "http://localhost:3160/website17/";
       
        webRequest.Timeout = 20000;

        if (method == Method.POST)
        {
            webRequest.ContentType = "application/x-www-form-urlencoded";

            //POST the data.
            requestWriter = new StreamWriter(webRequest.GetRequestStream());

            try
            {
                requestWriter.Write(postData);
            }
            catch
            {
                throw;
            }

            finally
            {
                requestWriter.Close();
                requestWriter = null;
            }
        }

        responseData = WebResponseGet(webRequest);
        webRequest = null;
        return responseData;
    }

    /// <summary>
    /// Process the web response.
    /// </summary>
    /// <param name="webRequest">The request object.</param>
    /// <returns>The response data.</returns>
    public string WebResponseGet(HttpWebRequest webRequest)
    {
        StreamReader responseReader = null;
        string responseData = "";

        try
        {
            responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
            responseData = responseReader.ReadToEnd();
        }
        catch
        {
            throw;
        }
        finally
        {
            webRequest.GetResponse().GetResponseStream().Close();
            responseReader.Close();
            responseReader = null;
        }

        return responseData;
    }
}


Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        oAuthFacebook oFB = new oAuthFacebook();
        Response.Redirect(oFB.AuthorizationLinkGet());
    }
}


Fbcallback.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class FBcallback : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["code"] != null)
        {
            string code = Request.QueryString["code"].ToString();
            oAuthFacebook fbAC = new oAuthFacebook(); //Standard FB class file available on net in c#
            string respnse = "";
            try
            {
                fbAC.AccessTokenGet(code);
                respnse = fbAC.Token;
            }
            catch (Exception ex)
            {
                Response.Redirect("http://localhost:3160/WebSite17/SiteLogin.aspx?error=" + ex.Message);
            }

            if (Session["RedirectURL"] != null && Session["RedirectURL"].ToString() != "")
            {
                Response.Redirect(Session["RedirectURL"].ToString() + "?token=" + respnse + "&source=FB");
            }
            else
            {
                Response.Redirect("http://localhost:3160/WebSite17/SiteLogin.aspx?token=" + respnse);
            }
        }
        else
        {
            Response.Redirect("http://localhost:3160/WebSite17/SiteLogin.aspxerror=code not found" +
                              Request.QueryString["error_reason"].ToString());
        }              
                
    }
}



SiteLogin.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class SiteLogin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string token = Request.QueryString["token"];       

        string HitURL = string.Format("https://graph.facebook.com/me/albums?fields=name&access_token={0}", token);

        oAuthFacebook objFbCall = new oAuthFacebook();
        string JSONInfo = objFbCall.WebRequest(oAuthFacebook.Method.GET, HitURL, "");   


        JObject Job = JObject.Parse(JSONInfo);
        JToken Jdata = Job.Root;
        JArray jsonVal = Job.Root["data"] as JArray;
      
        string Coverphotoid = null;
        foreach (var j1 in jsonVal)
        {
            if (j1.Value<string>("name").Equals("Cover Photos"))
                Coverphotoid = j1.Value<string>("id");
        }

        HitURL = string.Format("https://graph.facebook.com/{0}/photos?access_token={1}", Coverphotoid, token);

        objFbCall = new oAuthFacebook();
        JSONInfo = objFbCall.WebRequest(oAuthFacebook.Method.GET, HitURL, "");
        Job = JObject.Parse(JSONInfo);
        Jdata = Job.Root;
        jsonVal = Job.Root["data"] as JArray;
        foreach (var j1 in jsonVal)
        {
      Response.Write(Coverphotoid = j1.Value<string>("source") + " <br />" );
        }
    }
}


Click here for Download Newtonsoft.dll

No comments:

Post a Comment