Facebook’s Graph API and ASP.net

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.

36 thoughts on “Facebook’s Graph API and ASP.net”

  1. Hi Colin,

    Can you post your sample in a zip file rather than the rar file?

    I am starting to work on the .net and facebook rather than php or classic asp.

    I still strugling to understand all of this. Thanks for the blog post.

  2. Hi Colin,

    Im getting a message “connect to facebook” while redirecting the user to get the authorization before asking for the access token. If the user waits, the page is redirect to my app without the need of clicking on the facebook logo. Do you have an idead why this is happening?

    You can see it if you go to my website link:
    http://apps.facebook.com/tomatocracia

  3. Hey Augusto, it could be that the user you are trying to authorise is already authorised on the application. Facebook is smart and makes this check so it doesn’t need to update things. I would deauthorise the application from your user’s account first, and then try.

  4. Hi! Trying to compile the code to have a quick start on facebook app development. I’m targeting on .NET 3.5 (but also tried .NET 4) but always getting the following error:

    Compiler Error Message: CS0121: The call is ambiguous between the following methods or properties: ‘WiseCMS.Tools.FromJson(string)’ and ‘WiseCMS.Tools.FromJson(string)’

    Source Error:

    Line 76: {
    Line 77: string result = Tools.CallUrl(url);
    Line 78: T items = result.FromJson();
    Line 79: return items;
    Line 80: }

    Source File: c:\Software\Clutter\Facebook\App_Code\FacebookService.cs Line: 78

    Any suggestions?
    Thanks!

  5. This sounds like there is a temporary file hiding somewhere, as there is only 1 instance of that method, in the Tools class. Do an IIS reset, and clean up your temporary files, restart your machine, make a coffee, come back later. If you have added it to a solution, clean up the solution (right click the solution in the right hand column, and click “clean solution”. Just do all those standard things a techy like yourself should know how to do 🙂

  6. Hey Jesus,

    Yeah that one is a bit trickier in some respects. If you want to do it simply, then you build a form, and use the url like so:

    https://graph.facebook.com/userId/feed?access_token=session key

    and yeah that’s dead simple. But if you want to do it automatically then it get’s a bit trickier.

            string url = "https://graph.facebook.com/" + userId + "/feed?access_token=" + sessionKey;
            string parameters = string.Format("message={0}&link={1}", message, "http://yourwebsite.com");
    
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);
    
            //Add these, as we're doing a POST
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
    
            //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
            req.ContentLength = bytes.Length;
    
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();
    
            System.Net.WebResponse resp = req.GetResponse();
    

    And that should do the trick…well it does here.

  7. I am confused about what I need to save for each authenticated user. You save ‘FacebookId’ (along with ‘access_code’) which then gets plugged back into url as ‘username’. It appears that the ‘access_code’ already contains the user identifier and that I can replace ‘username’ with ‘me’ in my url. Am I understanding this correctly?

  8. Hi,
    I have changed the settings but i wonder if there is any way to open page in facebook frame. now it does not load facebok master page.
    Thanks in advance.

  9. HI, love the fact you’ve posted this. I tried your code, but I got an http bad request error when I clicked the link. Could you suggest something? Has the facebook authentication page moved?

  10. The resource cannot be found.

    Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

    Requested URL: /complete_authorisation.aspx

    I got this error… i uploaded Complete_authorisation.aspx with the other aspx files… But it couldn’t be found ? What is the problem ?

  11. Well when you get a 404 error it means your page is missing. Have you uploaded it to the wrong place?

  12. I am using this code and it works great for reading info. I am working to set a status on my site using the below function, which does not error, however my status is not updated. Any suggestions?

    code is:

    public FacebookStatusMessage SetStatus(string userName, string accessToken, string message)
    {
    string url = “https://graph.facebook.com/” + userName + “/feed?&access_token=” + accessToken + “&message=” + message;
    return CallUrl(url);
    }

    class is:

    public class FacebookStatusMessage
    {
    public string from { get; set; }
    public string id { get; set; }
    public string message { get; set; }
    public string updated_time { get; set; }
    public string type { get; set; }
    }

  13. You may need to send it as a POST:

    return CallUrl(url, string.Empty, “POST”);

    try that and let me know?

  14. Great article, exactly what I’m looking for. But I’m having problem getting the Access Token. I have tried changing the CallUrl line to:

    string response = Tools.CallUrl(url, "POST");

    Also, the querystring code from facebook seems weird to me, can you let me know if this code looks OK?


    URoFQRFcKGiFXppF1kYMh-reFL3RmcUPgXJZv6M1BT8.eyJpdiI6DjBJT0Z0anNwWGNUV1FCNl9wLTZib1EifQ.TUJb86NXUD5yqba_TgNuZK-OaEaH7FLQoBRGtWqluwTnPQaEUpEuXcKFyr2Ve5ERE_suAYYG3D1XxYtfsDD6XcYqrfT8ZVz0Mx1qpELXAxoJ-8mROkoPIKvNcGsard5w

    Thanks!

  15. Facebook fb = new FacebookService().GetById(99);
    Please why we have to pass 99? What it is referring here.
    Please explain me a bit

    Thanks for great post

    Regards
    Padma

  16. 99 is just a random number i picked. basically what that line should read as is “get my facebook data out of the database, my id is 99”. I have set the code up so that you can have multiple facebook details set up in the database – one for each user, or client or whatever – so you can update different facebook profiles from the one set of code.

  17. hi colin, firstly thanks for your codes.

    i’m new to facebook api and i didn’t understand the “remember to fix the Url for your own development environment” section. what will i write on your code?

    thanks for your helps.
    hakan

  18. I am trying out your code first time,
    I get this error ,
    what does this mean?
    My Authorize user link is following.

    https://graph.facebook.com/oauth/authorize?client_id=275519642475425&redirect_uri=http://localhost:50942/complete_authorisation.aspx&scope=user_photos,user_videos,publish_stream,offline_access,user_photo_video_tags

    {
    “error”: {
    “type”: “OAuthException”,
    “message”: “Invalid redirect_uri: Given URL is not allowed by the Application configuration.”
    }
    }

  19. It says the you have given an invalid URL. And looking at it, it shows you have used localhost. When you set up your application with facebook, you gave a real URL. You need to replace localhost with your development/staging/live URL. I think it is rubbish the don’t allow localhost as we need to develop!!!

  20. Hi Colin,

    I am a vb.net programmer and I am looking for vb.net code to connect with Facebook for over a week.

    I read your article and I find it quite clear, I hope after I will try to implement things will look even clearer.

    Thanks,

    p.s.
    pub is always a good idea.

  21. Hi Colin,
    Rocking code,,thanks.

    I am not able to get photo caption with the facebook albums photos.
    facebookphoto class does not have caption field.
    Is it possible to get the caption.

    tanks a lot.

  22. AS Colin
    First, Thanks alot . the article is great.
    but i have problem i can’t get the code so the response is empty ??

    string code = Request.QueryString[“code”];

    string url = string.Concat(“https://graph.facebook.com/oauth/access_token?client_id=” + facebookClientId,”&redirect_uri=http://” + host + “/Default.aspx”,
    “&client_secret=” + facebookSecret,
    “&code=” + code);
    string response = Tools.CallUrl(url);

  23. Hi I tried to run your code but I have got the following error:
    HTTP Error 404.3 – Not Found
    The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

    I apprecite your help. Thanks

  24. Hi Colin, I have a requirement where I need to get the posts and comments from facebook page to my dotnet application..how can i do that?? pls help me..

  25. Hey Ravi,

    The Facebook Graph API has changed a lot since I wrote this article. You might be easier off finding an API that already does what you need, as am sure this is one. (A quick google of “Facebook .net api” came up with this http://csharpsdk.org/)

    Colin

  26. Thanks a bunch for sharing this with all of us you actually recognize what you’re talking approximately!
    Bookmarked. Kindly additionally visit my website =). We may have a hyperlink exchange contract between
    us

Leave a Reply

Your email address will not be published.