Am enthralled with the new Facebook API. It’s awesomely simple to use. I mean really simple to use. They have changed the authentication process as well, and fuck me it’s so so much simpler than before.

Previously I integrated Facebook Connect with iMapFlickr, to allow uses to post to their own wall automatically, saying that they had created a new map about cheese and bunny rabbits.  But it was such a pain in the ass to use.  But I did it, although am a little balder for it!!

Facebook – now with added thought

The new Facebook API throws essentially everything they have done out the window, rewriting everything and using oAuth to authenticate a user.  They have even made oAuth simpler, which leads me to think it’s not really the full oAuth specification, but hey it works nicely!

But one thing they forgot to do was let .NET developers in on the secrets.  They released all the libraries and code and examples for other programming languages but .NET is sitting outside of Facebook Towers crying, not being allowed into the party as it has “Microsoft” as part of it’s name.  Fuckers.  I sold me soul to Microsoft a long time ago, so I have spent some time working this out.

Facebook Applications

But it turns out, not that much time as although their documentation revolves around other languages, Facebook have written it in a quite clean and clear manner.

Where do you start?  First you need to create a Facebook application.  This is because you need to have certain codes – Client Id and Client Secret – which are available once you create an application in Facebook.  It is real simple to do, they may ask you for authentication via email or mobile/cell phone, but once that’s done you should have a nice application running in Facebook.  You don’t even need to submit it to directories or let anyone know it exists.  All you need is the Application Id (which is called the ClientId in the new API…why!! Fuck wits!!) and Application Secret (again called the Client Secret in the new API…bit annoying no?).

Once you have your application setup, and these 2 codes in hand you can set up your website to authenticate a user.  This basically involves a user coming to your website, hit a “allow” style button, you redirecting the user back to Facebook, the user hitting the “allow” button at Facebook, Facebook sending the user back to your website, you calling another url (without redirecting the user) and gaining something called an access_token!! Phew!  But it’s really straightforward to do so here is how I did it.

Facebook Authentication Process

1.  Create your application

2.  Get your codes e.g. Client Id = `1234567890`, Client Secret = `shhhh it’s a secret`.  Save these in the web.config.

3.  Build the URL that will redirect the user to Facebook:

string host = Request.ServerVariables["HTTP_HOST"];
string facebookClientId = System.Configuration.ConfigurationManager.AppSettings["FacebookClientId"];
litAuthorise.Text = @"<a href=""https://graph.facebook.com/oauth/authorize?client_id=" + facebookClientId + "&redirect_uri=http://" + host + @"/complete_authorisation.aspx&scope=user_photos,user_videos,publish_stream,offline_access,user_photo_video_tags"">Authorise user</a>";

This url contains all the permissions I require on the user’s account, via the scope parameter

- view the user’s personal photos;
- the user’s personal videos;
- it allows me to publish to their stream (wall);
- and also access photos that they have been tagged in, but not necessarily own.

You can find a list of all items you are allowed to access, as long as you ask permission first, here.  What would be nice, is if they had grouped this into logical groups – all the photos into a “all_photos” instead of having to ask for 2 different types.  But that’s a very very minor point.

4.  User clicks on link, goes to Facebook, and get’s redirected back to the URL specified in the redirect_uri parameter in the query string above.  When the user get’s redirected back to your website, you can get the “code” that Facebook has generated.  This is a time critical code, and must be used straight away.

string facebookClientId = System.Configuration.ConfigurationManager.AppSettings["FacebookClientId"];
string facebookSecret = System.Configuration.ConfigurationManager.AppSettings["FacebookSecret"];
string host = Request.ServerVariables["HTTP_HOST"];
string code = Request.QueryString["code"];

var url = string.Concat("https://graph.facebook.com/oauth/access_token?client_id=" + facebookClientId,            �
"&redirect_uri=http://" + host + "/admin/facebook/auth.aspx",
"&client_secret=" + facebookSecret,
"&code=" + code);

string response = Tools.CallUrl(url);

Facebook fb = new FacebookService().GetById(99);
fb.FacebookAccessToken = response.Replace("access_token=", ""); // save the access token you are given
fb.FacebookId = new FacebookService().User_GetDetails(fb.FacebookAccessToken).id; // call facebook for the profile id
new FacebookService().Save(fb); // save it (puts stuff into session for the time being)
Response.Redirect("get_photos_of_me.aspx"); // redirect to see all the photos of me (or you)

This builds up the exact URL you will need; calls the url with a helper class; get’s the response as plain text; removes what I don’t need; and saves it into my Facebook object in the database!  Notice the redirect_uri parameter in the url above.  It needs to be the same as the first time it was used, not sure why it’s needed but it is.

So we should be all good to go.  You can now call almost anything in the API with the details received above, and you will get everything back as a nicely formatted Json string.  But how to make calling the API easier…build our own API!

The Facebook Graph API…erm API

Let’s call our new API something crazy like FacebookAPI.  With everything above completed, we now want to retrieve all the photos that the user has been tagged in, all you’d need to call is:

    // calls facebook and retrieves all the pictures that "username" has been tagged in
    public FacebookPhotos Photos_FetchAllOfMe(string userName, string accessToken)
    {
        string url = "https://graph.facebook.com/" + userName + "/photos?access_token=" + accessToken;
        return CallUrl<FacebookPhotos>(url);
    }

    // helper method that makes things simpler
    private T CallUrl<T>(string url)
    {
        try
        {
            string result = Helper.CallUrl(url, string.Empty, "GET");
            T items = result.FromJson<T>();
            return items;
        }
        catch
        {
            return default(T);
        }
    }

What is happening here is we build up the URL call to Facebook, and then using a helper method, or two, I retrieve the result from Facebook.  As previously stated, this comes back from Facebook as a Json string.  Not very much use if you are needing a .NET object, but .NET to the rescue.

Above in the CallUrl method there is a lovely extension method on every string – FromJson<T>().  By calling this method, a method I wrote and isn’t part of the .NET lib, it will rebuild the object T with whatever it finds in the string.  But careful now.  You need to be very exact with names as .NET will ignore anything it can’t find, without throwing an error.  So here are the objects I would need to work the above code…

public class FacebookPhotos
{
    public List<FacebookPhoto> data { get; set; }
    public Paging paging { get; set; }
}

public class FacebookPhoto
{
    public string id { get; set; }
    public From from { get; set; }
    public Tags tags { get; set; }
    public string picture { get; set; }
    public string source { get; set; }
    public string height { get; set; }
    public string width { get; set; }
    public string link { get; set; }
    public string icon { get; set; }
    public string created_time { get; set; }
    public string updated_time { get; set; }
}

public class Paging
{
    public string next { get; set; }
    public string previous { get; set; }
}

public class From
{
    public string name { get; set; }
    public string id { get; set; }
}

public class Tags
{
    public List data { get; set; }
}

public class Tag
{
    public string id { get; set; }
    public string name { get; set; }
    public double x { get; set; }
    public double y { get; set; }
    public DateTime created_time { get; set; }
}

So once you have all those objects in place in your code, and you call the extension method .FromJson<T>(); then you should have a perfectly formed object.  The extension method to reform the Json string looks like this:

using System.Web.Script.Serialization;

public static T FromJson<T>(this string s)
{
    JavaScriptSerializer ser = new JavaScriptSerializer();
    return ser.Deserialize<T>(s);
}

Just make sure it is somewhere top level ish in the namespace heirarchy so that all strings benefit from it.  All that is left, is the CallUrl helper method, but that’s nothing fancy and you can find it in the code I will give you soon.

So what’s next – well the code that I wrote

Well if you like coding you should be able to take what I have shown you above and implement the rest of the Facebook Graph API.  In the code that is available, I have a few more classes.  I didn’t do them all as I currently don’t need them all, and truthfully I went to the pub instead.  So here is the code. Remember to change it to use your development environment details; to create a facebook application with the correct ports; and place in the web.config the proper settings.  Otherwise it might not work and it won’t be my fault.