Accessing and posting on Facebook feed


Welcome to a new episode of the Facebook integration for Windows Store App series. Christophe Nasarre, a French Premier Field Engineer is explaining how to get access to a Facebook feed and post messages and links.


For your convenience, here’s the video timeline:

[0:17] Demo of the expected feed/post features

[1:47] How to test via a Facebook Graph Explorer session and the required permissions

[2:44] Details of the /me/feed request

[4:42] Changes to the login permissions in C#

[5:02] Parsing of feed Json and dedicated C# types

[8:14] How to provide a different background color for someone else post

[9:28] Hybrid pagination management

[11:25] Integration into the MainPage

[12:28] How to post a message via the Facebook Graph Explorer session

[14:22] C# implementation for posting a message via Uri.EscapeUriString and HttpClient

[18:01] How to post a link via the Facebook Graph Explorer session

[20:59] C# Implementation of posting a link


App preview

Here is what I want to achieve:

image

When the user clicks the Feed button, its Facebook posts are listed with their details. The Post button allows a new message and link to be posted. Like photos, Facebook is returning only a subset of posts and the user can navigate between chunks with the Previous/Next buttons.

Exploring the feed Facebook API

As explained in the previous episodes, you should always start by looking at the Facebook developer documentation and the Graph Explorer. However, there is no feed related endpoint there! You need to click the Common Scenario Guide to figure out that you need to go to https://developers.facebook.com/docs/graph-api/reference/v2.1/user/feed.

Go to the Reading Section and start a Graph Explorer session and create a token with read_stream as extended permission and publish_actions if you want to publish a post

image

Don’t forget to add the “publish_actions” permission to your C# login code before calling the rest of the API.

Posts are retrieved via a GET /me/feed request.

image

And submit to get the list of posts via a Json list with the usual “data” root

image

Click a post id to see its fields definition:

image

In addition to its name, you get who posted it with the from structure (both id and name) and with which application. The content can be a single message or having a link with caption and description. The picture field points to a thumbnail of the associated image if any.

You should note that a few posts are only status updates without any interesting details and they are filtered out by the App.

Like with the photos case explained in the previous episode, posts are retrieved in chunk. However, the mechanism is different, based on time with since and until fields. In my case, I just keep track of each chunk in a stack in which the code navigates when the Previous button is clicked:

"previous": "https://graph.facebook.com/v2.1/773904895975304/feed?limit=25&since=1409672371",
"next": "https://graph.facebook.com/v2.1/773904895975304/feed?limit=25&until=1400162460"

The next field of the paging section helps me to build the query to be sent when the Next button gets clicked by passing the navigationSuffix to the GetPostAsync method:

if (string.IsNullOrEmpty(navigationSuffix))

{

    path = "/me/feed";

}

else

{

    path = string.Format("/me/feed?{0}", navigationSuffix);

}

 

dynamic feedTaskResult = await FbClient.GetTaskAsync(path);

var result = (IDictionary<string, object>)feedTaskResult;

var data = (IEnumerable<object>)result["data"];

foreach (var item in data)

{

This method builds a list of Post objects

publicclassPost

{

    publicstring Id { get; set; }

    publicstring FromId { get; set; }

    publicstring FromName { get; set; }

    publicbool IsSelfPublication { get; set; }

    publicSolidColorBrush PublicationBackground { get; set; }

    publicstring Name { get; set; }

    publicstring Message { get; set; }

    publicstring PictureUrl { get; set; }

    publicBitmapImage Picture { get; set; }

    publicstring Link { get; set; }

    publicstring Caption { get; set; }

    publicstring Description { get; set; }

    publicstring Type { get; set; }

    publicDateTime CreationTime { get; set; }

    publicDateTime UpdateTime { get; set; }

    publicstring Application { get; set; }

 

    public Post(string id, string name)

    {

        Name = name;

        Id = id;

    }

}

that are stored in PostBatch:

publicclassPostBatch

{

    publicList<Post> Posts { get; set; }

    publicstring Previous { get; set; }

    publicstring Next { get; set; }

    publicbool HasPrevious

    {

        get

        {

            return !string.IsNullOrEmpty(Previous);

        }

    }

    publicbool HasNext

    {

        get

        {

            return !string.IsNullOrEmpty(Next);

        }

    }

 

 

    public PostBatch(List<Post> posts)

    {

        Posts = posts;

    }

}

 

Posting a message

To post a message on your feed, you need to send a POST http request with message in the query string:

image

and the call returns the id of the created post:

image

As you have probably noticed, the message string must be encoded into the query string. Since the System.Net.WebUtility class is not available for Windows Store Apps, you need to call Uri.EscapeUriString instead.

The FacebookClient class exposes the PostTaskAsync method but it crashes… So you need to send the POST request “manually”. Hopefully, WinRT provides the HttpClient class that supports sending requests with OAuth token

var client = newHttpClient();

client.DefaultRequestHeaders.Authorization = newHttpCredentialsHeaderValue("OAuth", FbClient.AccessToken);

HttpStatusCode status = HttpStatusCode.Ok;

Uri uri = newUri("https://graph.facebook.com/v2.1/me/feed");

 

var response = await client.PostAsync(uri, newHttpStringContent(queryString));

status = response.StatusCode;

 

if (response.IsSuccessStatusCode)

{

    var results = Windows.Data.Json.JsonObject.Parse(

           await response.Content.ReadAsStringAsync()

        );

    id = results["id"].GetString();

}

The query string has the following format: “message=xxx” with xxx Uri encoded.

Posting a link

The process is very similar to publish a post with link details

image

Here is the resulting post:

image

So, the publishing C# code is the same as for a message except that link related fields should be provided via the query string:

queryString =

    string.Format("message={0}{1}{2}{3}",

        message,

        (string.IsNullOrEmpty(link)) ? "" : "&link=" + link,

        (string.IsNullOrEmpty(name)) ? "" : "&name=" + name,

        (string.IsNullOrEmpty(description)) ? "" : "&description=" + description

    );

 

References

 

Happy coding!

Comments (0)

Skip to main content