Now that we are connected, we can retrieve any data for which we have the permissions. There is a single method for that : GetTaskAsync. This method takes as a parameter the object(s) you want to retrieve. To get user’s information, you just have to pass « me » as a parameter.
To get a complete list of objects you can request, take a look at the Graph API page.
var me = await _client.GetTaskAsync("me");
As the GetTaskAsync method is « generic », it does not return a strongly typed object. In fact, it returns a dictionary where each key represents a piece of data. For instance, when requesting « me », you get a dictionary with an ID entry, a name entry, a first_name one, and so on.
var me = await _client.GetTaskAsync("me");
var result = (IDictionary<string, object>)me;
string firstName = result["first_name"].ToString();
string lastName = result["last_name"].ToString();
You can also use a generic version of the GetTaskAsync method to get a strongly typed object. Here’s an example:
[DataContract]
class FacebookUser
{
[DataMember(Name="id")]
public string ID { get; set; }
[DataMember(Name="first_name")]
public string FirstName { get; set; }
[DataMember(Name = "last_name")]
public string LastName { get; set; }
}
var me = await _client.GetTaskAsync<FacebookUser>("me");
Retrieving user’s friends
You can retrieve a list of friends using the GetTaskAsync method with the request « me/friends ». Once again, the GetTaskAsync method will return a dictionary. This dictionary contains two entries:
- data : result of the request
- paging : request to get more results
public class FacebookFriend
{
public string ID { get; set; }
public string Name { get; set; }
}
var friendsTask = await _client.GetTaskAsync("/me/friends");
var result = (IDictionary<string, object>)friendsTask;
var data = (IEnumerable<object>)result["data"];
List<FacebookFriend> friends = new List<FacebookFriend>();
foreach (var item in data)
{
var friend = (IDictionary<string, object>)item;
friends.Add(new FacebookFriend
{
ID = friend["id"].ToString(),
Name = friend["name"].ToString()
});
}
As with the first request, we can use the generic version of GetTaskAsync to get a strongly type object so that we don’t have to deal with all these cast operations.
[DataContract]
public class FriendsResult
{
[DataMember(Name = "data")]
public List<FacebookFriend> Friends { get; set; }
}
[DataContract]
public class FacebookFriend
{
[DataMember(Name = "id")]
public string ID { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
}
var friends = await _client.GetTaskAsync<FriendsResult>("/me/friends");