Querying Facebook Comment Table with FQL.Query and C#

Here’s a code snippet for querying the Facebook Comment table using the Facebook C# SDK. Note that this query uses an app signed request, so you’ll get results whether your user is logged in to Facebook or not. This code queries for all comments xids used by your application. If you have more than one like I did, you can then filter through the results to get counts, latest post information, or whatever you need. For more info about the Comment table, read the official documentation.

public void GetFacebookComments()
    var appId = ConfigurationManager.AppSettings["AppID"];
    var appSecret = ConfigurationManager.AppSettings["Secret"];
    // use app signed api key
    FacebookAPI api = new FacebookAPI(appId + "|" + appSecret);

    string url = String.Format("https://api.facebook.com/method/fql.query?query=SELECT fromid, text, id, time, username, xid, object_id FROM comment WHERE xid IN (SELECT xid FROM comments_info WHERE app_id = {0}) ORDER BY time desc&access_token={1}&format=json", appId, api.AccessToken);

    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        StreamReader reader = new StreamReader(response.GetResponseStream());
        comments = reader.ReadToEnd();
    JSONObject fbComments = JSONObject.CreateFromString(comments);
    if (fbComments.Array != null)
        String[] xidArray = new String[] { "xid1", "xid2", "etc" };

        foreach (var xid in xidArray) {
            var xidComments = fbComments.Array.Where(m => m.Dictionary["xid"].String == xid);

            if (xidComments != null && xidComments.Count() > 0)
                var lastDiscussBy = xidComments.First().Dictionary["fromid"].String;
                var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var lastDiscussTime = dtDateTime.AddSeconds(Convert.ToDouble(chzComments.Last().Dictionary["time"].String)).ToLocalTime();

About the author

Abby Sims

Copyright © 2016, Abby Sims