Developing a Facebook FBML Canvas App in ASP.NET


Share 
 
 
As the title suggests, this article will demonstrate the development of an FBML Facebook application in ASP.NET using the Facebook Development Toolkit. We will create a simple application that accesses the user's profile and displays a list of the user's Facebook friends and their profile photos in a Facebook "Application Invite" container. Before jumping in, it's probably a good idea to define a couple of the terms we're going to be throwing around:

  • FBML (Facebook Markup Language): Somewhat similar to other markup languages like HTML and XML, FBML exposes the Facebook API to developers, enabling access to user profile data. Facebook interprets the FBML code, performs the requested operations, and renders the results to the client browser as HTML.
  • Facebook Canvas: The container provided by Facebook which hosts the FBML application.
  • Facebook Development Toolkit (FDT): An ASP.NET implementation of the Facebook API. The current version as of this writing is 3.0.
There are several steps we will need to take. I'll list them first, and then we'll go into detail:
  1. Register your application with Facebook
  2. Download and install the Facebook Development Toolkit
  3. Develop the application
Register your application with Facebook

In order to have an application run in the Facebook Canvas, you need to first register it with Facebook using their Developer Application on their web site. It's free, but of course, in order to do this you must have a Facebook account.

The Facebook Developer Application is where you enter information about your application. I'm not going to go into too much detail about the Facebook Developer App - there's enough documentation on the Facebook web site - but I will go over which tabs are essential and explain a little about each of those:
  • Basic Tab: The Basic tab is where you enter the name of your application and a short description of your application. You also must upload an image to serve as your application's logo. The Basic Tab is also where you can find your Application ID, your API Key, and your Secret Key. It will be necessary for your application to pass this data to Facebook in order to identify itself.
  • Authentication Tab: This tab allows you to specify how Facebook users will be able to install your application. There are two installation options - "Users" and/or "Facebook Pages". These options refer to whether a user can install the application to his or her profile, and whether a user can install the application to their Facebook page. A user can select one or both of these options. The Authentication Tab contains two other fields named Post-Authorized Callback URL and Post-Removal Callback URL. These fields enable you to specify URL's to pages on your web site which will get called upon a user's installation and removal of your application.
  • Canvas Tab: The next essential tab is the Canvas Tab. The Canvas tab is where you specify things like the Facebook URL of your application, the actual URL of your application on your web server (to which users will be redirected if they link to your application's Facebook URL), and a Render Method, which can be either IFrame or FBML. This article is not concerned with the IFrame method, but it should be noted that, of the two, the IFrame method is simpler, albeit less tightly integrated with Facebook than the FBML method. The FBML method however, allows a developer greater access to Facebook's API, enabling you to include a Facebook user's profile information, friends' names and photos, etc.
  • Advanced Tab: The Advanced Tab allows you to specify whether your application is a web or desktop application. It also gives you the option of enabling Sandbox mode. If Sandbox mode is enabled, only those users you designate as developers of your app will have access to it. Typically you would enable Sandbox mode while your application is still in development. Once it's ready to go live, you can go to the Advanced Tab to disable Sandbox mode, thereby granting access to all Facebook users.
Download and install the Facebook Development Toolkit

This step speaks for itself. Just download the FDT, unzip it, and place the extracted binaries in a convenient location. There are five DLL's included in FDT 3.0. We'll be using only three of them for this demo; Facebook.dll, Facebook.Web.dll, and Facebook.Web.Session.dll. You can download the FDT here: http://facebooktoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=35534.

Develop the application

The application we develop here will not require much coding, but it will do some pretty interesting things; sort of a "Hello World" on steroids. I'll get you started and show you how to do the integration with Facebook by showing you how to retrieve the logged in Facebook user's profile information, as well as their list of friends along with their friends' profile photos. Once you've gotten that down, the rest is just a matter of learning the rest of the Facebook API.

First, create a new Web Application project in Visual Studio 2008. Then, in order to make use of the Facebook Development Toolkit, we'll need to add references to two of the DLL's contained in the FDT - Facebook.dll and Facebook.Web.dll.

Next, add a new Webform to the project, and name it Helloworld.aspx. Since this is going to be a Canvas application (it runs within the Facebook canvas), the first thing we need to do with the helloworld.aspx file is to remove the <head> tags (opening and closing) and everything within them. We also need to remove the opening and closing <body> tags. Yes, it's weird, but it's necessary. The reason for this is that since your app will be running within Facebook, and the Facebook page will already have its own <head> and <body> tags... well, you get the idea. Just so you know, this is going to cause Visual Studio to complain about some of your code. Without the <head> and <body> tags, VS gets a little confused about what's valid markup and what isn't. Ignore it. Although the editor complains, the compiler builds everything just fine with no errors or warnings.

And now for some code. Take a look at the listing below. Explanation to follow:

Helloworld.aspx

<%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="helloworld.aspx.cs" Inherits="MHT_Web_Site.helloworld" %>
<
form id="form1" runat="server">
<
div style="float:left">
<
asp:label ID="labelUser" runat="server" text=""></asp:label>
</
div>
<
div style="float:right">
<
asp:label ID="labelFriends" runat="server" text=""></asp:label>
</
div>
</
form>

The listing above is the complete Helloworld.aspx file. As you can see, it consists solely of two <asp:Label> server-side controls. The interesting part comes next when we populate those labels in the code-behind file. Take a look at Helloworld.aspx.cs below:

Helloworld.aspx.cs

using
Facebook;
using Facebook.Web;
using Facebook.Web.Session;
using Facebook.Rest;namespace MHT_Web_Site
{
    public partial class Helloworld : CanvasFBMLBasePage
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            base.RequireLogin = true;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FBMLCanvasSession sess = new FBMLCanvasSession(
                ConfigurationSettings.AppSettings["APIKey"],
                ConfigurationSettings.AppSettings["Secret"]);
                Api fbAPI = new Api(sess);
                user loggedInUser = fbAPI.Users.GetInfo(fbAPI.Users.GetLoggedInUser());
                labelUser.Text = "<img src=\"" + loggedInUser.pic_square + "\" /> " +
                "Hello " + loggedInUser.first_name + "!";
                labelUser.Style["font-size"] = "medium";
                string lsFriends = ShowApplicationInvite(sess.UserId.ToString());
                labelFriends.Text = lsFriends;
            }
        }
        private string ShowApplicationInvite(string facebookUserID)
        {
            string inviteContent = "<fb:name uid='" + facebookUserID + "' "
                "firstnameonly='true' shownetwork='false' />" +
                " Wants to say "Hello!" to you!" +
                    "<fb:req-choice url='http://www.facebook.com/add.php?api_key="
                    ConfigurationSettings.AppSettings["APIKey"] + "' " +
                    " label='Say Hello!' />";
            inviteContent = Server.HtmlEncode(inviteContent);
            string inviteForm = "<fb:request-form type=\"Hello World\" "
                "invite=\"true\" method=\"POST\" " +
                " action=\"http://apps.facebook.com/helloworld/\" " +
                " content=\"" + inviteContent + "\">";
            inviteForm += "<fb:multi-friend-selector actiontext=\""
                "Share Loan Star with friends\" showborder=\"true\" rows=\"3\" " +
                "cols=\"2\" email_invite=\"false\" max=\"10\" />";
            inviteForm += "</fb:request-form>";
            return inviteForm;
        }
    }
}

By examining the above listing, we can see that first we need to include the two DLL's from the Facebook Development Toolkit, Facebook and Facebook.Web. Next, instead of extending System.Web.UI.Page as we normally would, we extend Facebook.Web.CanvasFBMLBasePage. As we begin the interaction, we first create an FBMLCanvasSession instance by passing in the API Key and Secret Key parameters to the constructor. These are the parameters you got from Facebook when you registered your Facebook application. In this example I've stored them in the web.config file, so I'm reading them using the ConfigurationSettings object. Next we pass our FBMLCanvasSession instance to a Facebook.Rest.Api constructor to obtain a valid Api object on which to operate.

Now that we have that Api object we're ready to rock and roll. The fbAPI.Users.GetLoggedInUser() method returns the logged in user's user id. Passing that user id to the fbAPI.Users.GetInfo() method gets you the user object for that user. You can get pretty much any user information you might need from the user object. In our example, I'm using it to return the user's profile photo and first name. Pretty cool, huh? And not too difficult either.

Now it gets even cooler. In our ShowApplicationInvite() function, we build a string that contains the Facebook API call (in FBML) that we need to make in order to display an Application Invite Box within our application. This Application Invite Box will contain a list of the logged in user's friends along with their pictures. The user will have the ability to choose which of their friends to share your application with. Next we build a string that contains the API functions (again in FBML) which create a request-form, and pass it the content we received in the first API call. Finally, we close the request-form, by appending another api call to the string. We then return that entire string back through our Page_Load function and assign it's value to the text property of labelFriends. When you compile this and publish it to your server, assuming you have some Facebook friends, you can log into your Facebook account, run your program (http://apps.facebook.com/helloworld) and be amazed.

Hopefully this article makes this topic somewhat less confusing, rather than more.