Facebook Graph Api

Facebook Graph Api

1. Create a facebook application,

a. Create a facebook account and login to that account.

b.  To do so navigate tohttp://developers.facebook.com/apps  . In App Menu , Click `Add a new app`

c. In the platform select “Website”

d. Fill required details and hit “Create AppId”

e. The added app is shown under Menu.Click it, It opens the Dashboard of the app.Take a note of AppId and AppSecret.

2. Get an authToken

a. Get temporary  authToken that will end for 2 hours and after that gives a “Session expire” error. For temperory authToken hit URL:

https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&APP_ID=838633376158890&App_Secret=810d98813d1ed458c584aab43310a496a

where mention AppId and AppSecret of your app as shown on App Dashboard.

Another way to obtain short lived token is to naviagete to url  https://developers.facebook.com/tools/explorer?method=GET&path=me%3Ffields%3Did%2Cname&version=v2.2  and select your app in Application and press “Get Access Token” button.

Facebook Graph Api

b. Get a long lived authToken that exists for 6 months:

https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN

where mention AppId and AppSecret of your app as shown on App Dashboard.EXISTING_ACCESS_TOKEN is the temporary token generated for 2 hours.Copy it from Step 1.

authToken Link : https://developers.facebook.com/docs/facebook-login/access-tokens/

C# code:

var accessToken = “/* add your long lived token here*/“;
var client = new FacebookClient(accessToken);

client.AppId = applicationId; //APP_ID
client.AppSecret = applicationSecret;//APP_SECRET

dynamic parameters= client.Get(page + “/posts”, new { limit = “25”, offset = “0” }); //replace page by page name from facebook that is mentioned in URL after facebook.com/ or by ID mentioned in page URL after facebook.com/

//Set the limit accordingly .Max limit that can be set is 250 posts.To get more pages get data from paging by following next and prev links

foreach (dynamic item in parameters.data)
{

Dictionary<string, object>.KeyCollection keys = item.Keys;

if (keys.Contains<string>(“message”))
{
int comment_count = 0;
int like_count = 0;
dynamic parm = item.comments;

int share_count=item.shares.count;

bool flag = true;
while (flag)
{
if (parm.paging.next == null)
{
flag = false;
}
comment_count += parm.data.Count;

//Similarly calculate likes count
if (flag)
{
parm = client.Get(parm.paging.next);
}
}

foreach (dynamic comment in item.comments.data)
{

// get remaining info from posts,comments by parsing the data.

}

}

}