Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Talk to Facebook Graph API VIA FQL,C#

, 3 Jan 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This post is here to help you talk to Facebook’s Graph API through FQL and save the JSON results to a Database VIA C#. FQL stands for Facebook Query Language,whose sematics are on similar lines of SQL but supports only a subset of it. Before starting you should have few assembilies/permissions

This post is here to help you talk to Facebook’s Graph API through FQL and save the JSON results to a Database VIA C#.

FQL stands for Facebook Query Language,whose sematics are on similar lines of SQL but supports only a subset of it.

Before starting you should have few assembilies/permissions in HAND….

FOUNDATION:

I know that there will be an Angry bird rounding your head Q’ing-‘Why do i need these Assemblies?’

Let me answer that by lying a Foundation stone.

  • As per FB’s Documentation

The Graph API presents a simple, consistent view of the Facebook social graph, uniformly representing objects in the graph (e.g., people, photos,events, and pages) and the connections between them (e.g., friend relationships, shared content, and photo tags).

Every object in the social graph has a unique ID. You can access the properties of an object by requesting

https://graph.facebook.com/ID

. For example, the official page for the Facebook Platform has id 19292868552, so you can fetch the object at https://graph.facebook.com/19292868552:

Full Read @ http://developers.facebook.com/docs/reference/api/

  • There are two ways you can talk to Graph API -Querystring and FQL

Here,I will be talking about the FQL version

Heads up About FQL @ http://developers.facebook.com/docs/reference/fql/

Now,let me tell you why we need these Assemblies/permissions

  1. FB C# SDK is to talk to the Graph API VIA C# .
  2. Json.NET is to play with the JSON objects resulting from your API/FQL calls to Graph API.
  3. Graph API Explorer is the testing platform to check your FQL Queries for proper/perfect Data.

THE MAIN STORY :

To make you understand better i will use an example of pulling Facebook Page Insights (Stats) from Graph API Via C# and FQL.

  • If you are familiar with Facebook pages like Coca-Cola or any other brands ,you should have surely heard about the term ‘Insights‘-They are the statistics about a page,which only an Admin can see statistically.An user can pull the stat details if and only if ADMIN provides you with an ACCESS TOKEN with appropriate permissions.

Facebook Page Insights-An Admin View

FB C# SDK:

Creating a Facebook Application

Before you even begin using the Facebook C# SDK you must create a Facebook application. To do so navigate tohttp://developers.facebook.com/apps and click the ‘Create New App’ button. Follow the steps to create an app and record your AppId for use later.

Installation

The easiest way to get started using the Facebook C# SDK is to install it using Nuget. If you don’t already have it installed, download it from nuget.org. If you do already have NuGet installed make sure you have the most recent version. So of the features used in the Facebook C# SDK will not work with old versions of NuGet.

Adding the Facebook NuGet Package

To add the package to your project simply right click on the references folder and select ‘Manage Nuget Packages…’. Search for the packaged title ‘Facebook’, select it, and then click ‘install’.

Configuring the Facebook C# SDK

After you install the package you must configure the application. The only setting we need to change is the ‘Site URL’ under the ‘Website’ settings. The Site URL must match the url you are using for local development. Set this URL to http://localhost:#### where #### is the port you are using for local development.

WARNING: There is a bug in the Facebook Javascript SDK that prevents you from performing logins when running on non-standard ports on localhost in Internet Explorer. You must either use port 80 or test this in a browser other than Internet Explorer.

Making Your First Request

Retrieving data form the Facebook Graph API is very easy using the Facebook C# SDK. The following code shows how to call the Graph API to retrieve MusicNLoud‘s public information.

var client = new FacebookClient();
dynamic me = client.Get("183306468352624");

The result of this request is a dynamic object containing various properties such as first_name, last_name, user name, etc. You can see the values of this request by browsing to http://graph.facebook.com/183306468352624 in your web browser. The JSON result is shown below.

{
  "id": "183306468352624",
  "name": "MUSICnLOUD-Musical Blog",
  "picture": "http://profile.ak.fbcdn.net/hprofile-ak-ash2/157983_183306468352624_1192116727_s.jpg",
  "link": "http://www.facebook.com/pages/MUSICnLOUD-Musical-Blog/183306468352624",
  "likes": 140,
  "cover": {
    "cover_id": 437125029637432,
    "source": "http://sphotos.xx.fbcdn.net/hphotos-ash3/s720x720/541296_437125029637432_876448059_n.jpg",
    "offset_y": 51
  },
  "category": "Entertainment",
  "is_published": true,
  "website": " Http://MusicNLoud.Blogspot.in Http://MusicNLoud.Wordpress.com",
  "description": "MUSIC LYRICS REVIEWS",
  "about": "THE MAGIC OF MUSIC-A blog that breathes music,thinks music.We talk about all kinds of music bcoz we believe music has no color no religion no language & no boundaries",
  "can_post": true,
  "talking_about_count": 6,
  "type": "page"
}

Accessing User Information

Now that you have seen how to make a request of public information using the Facebook C# SDK you probably want to do something a little more interesting. In order to access any information that is not public such as a user’s profile details, friends list, or Time Line posts you need to provide a valid access token when making the request.

Obtaining an Access Token

For the purposes of this walk through we are going to start by obtaining an access token from Facebook’s Graph API tool. You can find that tool at https://developers.facebook.com/tools/access_token/.

Retrieving Profile Data

Now that you have obtained a valid access token you are ready to make a request for private data. Because this access token did not request any special permissions (discussed later) we will only be able to access limited details from the user.

var accessToken = "your access token here";
var client = new FacebookClient(accessToken);
  • You must have read_insights and read_stream permissions on the page before using the FQL Queries below.The access token should be generated with these permissions.
dynamic resultsFBFQL = client.Get("fql",
                                new
                                {
                                    q = new
                                    {
                                        Date = "SELECT created_time FROM stream WHERE source_id= " +   Pageid + " AND actor_id= " + Pageid,
                                        Description = "SELECT description FROM stream WHERE source_id=" + Pageid + " AND actor_id=" + Pageid,
                                        Message = "SELECT message FROM stream WHERE source_id=" + Pageid + " AND actor_id=" + Pageid,
                                        Reach = "SELECT metric,value FROM insights WHERE  object_id IN (SELECT post_id from stream Where source_id=" + Pageid + " AND actor_id=" + Pageid + ")AND metric='post_impressions_unique'  AND period=0",
                                        Engaged = "SELECT value FROM insights WHERE object_id IN (SELECT post_id from stream Where source_id=" + Pageid + " AND actor_id=" + Pageid + ") AND metric='post_engaged_users'  AND period=0",
                                        TalkingAbout = "SELECT value FROM insights WHERE  object_id IN (SELECT post_id from stream Where source_id=" + Pageid + " AND actor_id=" + Pageid + ") AND metric='post_storytellers'  AND period=0"

                                    }
                                });
                //Json.NET Object
                JObject o = JObject.Parse(Convert.ToString(resultsFBFQL));
                Int32 Count = 0;
                if (o.SelectToken("data[0].fql_result_set") != null)
                {
                    String CountValue = o.SelectToken("data[0].fql_result_set").Count().ToString();
                    Count = Int32.Parse(CountValue);
                }

                for (int value = 0; value < Count; value++)
                {

                    Int32? Date = (Int32?)o.SelectToken("data[0].fql_result_set" + "[" + value + "]" + ".created_time") ?? 0;
                    string Message = (String)o.SelectToken("data[3].fql_result_set" + "[" + value + "]" + ".message") ?? null;
                    string Description = (String)o.SelectToken("data[1].fql_result_set" + "[" + value + "]" + ".description") ?? null;
                    Int32? Reach = (Int32?)o.SelectToken("data[4].fql_result_set" + "[" + value + "]" + ".value") ?? 0;
                    Int32? Engaged = (Int32?)o.SelectToken("data[2].fql_result_set" + "[" + value + "]" + ".value") ?? 0;
                    Int32? TalkingAbout = (Int32?)o.SelectToken("data[5].fql_result_set" + "[" + value + "]" + ".value") ?? 0;
                    //JArray Dates = (JArray)o["data"];
                    DateTime NewDate = ConvertFromUnixTimestamp((double)(Date));
                    string ShortDate = NewDate.ToShortDateString();
                    double virality = 0;
                    if (TalkingAbout != 0 && Reach != 0)
                    {
                        virality = ((double)TalkingAbout / (double)Reach) * 100;
                    }
//If the message is null or empty use Description
}

 
  • The above FQL query format is called FQL Multiquery,which will return JSON objects as Name-Value Pairs.
  • These queries will return insights data which we saw in the Image above.
  • To understand more about Insights table,Periods and other columns please go through http://developers.facebook.com/docs/reference/fql/insights/   which will also give info about other tables and limitations.
  • Page_id and anchor_id (both same in this case) is the page id of the FB page whose insights you want to pull.
  • Run these queries in the FB GRAPH API explorer with proper table permissions and Access Token before using them in your code.

GRAPH API EXPLORER running a FQL Query



Filed under: C# Tagged: Facebook C# SDK, Facebook graph API, FQL, Insights

License

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

Share

About the Author

Vidyasagar MSC
Software Developer (Senior)
India India
Microsoft MVP (Games for Windows)
Developer | Blogger | Mentor | Gamer
Coder by profession | Gamer By Heart
Technical Blog : http://onestopdotnet.wordpress.com/
About me: http://about.me/mscvidyasagar
Follow on   Twitter

Comments and Discussions

 
Questionthanx [modified] Pinmembersanjay bathre20-Aug-14 1:33 
AnswerRe: thanx PinprofessionalVidyasagar MSC20-Aug-14 6:15 
GeneralRe: thanx Pinmembersanjay bathre21-Aug-14 2:56 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150301.1 | Last Updated 3 Jan 2014
Article Copyright 2014 by Vidyasagar MSC
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid