Developing an Application for Facebook

Discover, and learn to use, some of the behind-the-scenes technologies used with Facebook, and learn how to write an application that interfaces with Facebook.

Social Networking seems to be the latest buzz word on the internet these days. Facebook is just one of many Social Networking sites available on the web today. With this article, I will try to explain some of the behind-the-scenes technologies used with Facebook, and how to write an application that interface with Facebook.

If you have followed any of my articles, you will know by now that I always cover the theoretical elements first, before you do a sample application. So, don't let me waste any more of your time.

Technologies Used

FBML

Facebook Markup Language (FBML) is an evolved subset of HTML with some elements added (which are specific to Facebook), and some elements removed.

Facebook tags

The following is a list of some of the Facebook tags found in FBML (as shown in the Facebook Developers Wiki):

fb:name

Gets the name of the user specified

fb:grouplink

Displays the specified group's name linked to the group's page

fb:user

Forces enclosed content to be restrained to site privacy checks, based on the viewer of the information

fb:pronoun

Renders a specific pronoun for a user. For example: You, they, he are / is doing something

fb:profile-pic

Turns into an <img> tag of the specified user's profile picture. The tag itself is treated like a standard img tag, so attributes valid for img are valid with fb:profile-pic as well

fb:is-in-network

Displays content inside the tag only if the user is in a given network

fb:if-can-see

Displays the enclosed content if the logged in user can see the specified what attribute of the specified user. For example: profile, friends, wall

fb:if-can-see-photo

Displays the enclosed content only if the logged in user can see the photo specified

fb:if-is-app-user

Displays the enclosed content only if the specified user has accepted the terms of service of the application

fb:if-is-friends-with-viewer

Displays the enclosed content only if the specified user is friends with the logged-in user

fb:if-is-group-member

Displays the enclosed content only if the specified user is a member of the specified group. For example: admin, member, officer

fb:if-is-user

Only renders the content inside the tag if the viewer is one of the specified user(s)

fb:if-user-has-added-app

Used to determine whether the user has added the application to their account

fb:wide

Renders the content contained by the tag only if the profile box is in the wide column of the profile

fb:narrow

Renders the content contained by the tag only if the profile box is in the narrow column of the profile

fb:profile-action

Renders a link on the user's profile under their photo (such as "View More photos of..")

fb:user-table

Renders a table, each cell of which contains a thumbnail and name for a particular user, similar to the Mutual Friends table on profile pages

fb:user-item

Specifies the user to display in fb:user-table

fb:subtitle

Defines the subtitle for the profile box. The enclosed content is interpreted purely as plain text. For example: "Displaying 20 Wall Posts"

fb:action

Renders a link, usually for navigational purposes. Its appearance depends on its container.

fb:visible-to-owner

Displays content inside only if the viewer of the profile matches the profile owner

fb:visible-to-user

Only displays the content inside the tag if the viewer is the specified user

fb:visible-to-app-users

Displays the enclosed content only if the viewer has granted full permissions to the application

fb:visible-to-added-app-users

Displays the enclosed content only if the viewer has added the application to their account

fb:wall

Emulates a wall environment

fb:wallpost

Renders a wall-style post

fb:wallpost-action

Displays a link at the bottom of a wall post

Valid HTML tags in FBML

The following list shows some of the most common HTML tags that are still valid (can be used with) FBML.

FQL

Facebook Query Language is a way to query any Facebook data you can access through the Facebook API functions, but with a SQL-style interface.

Some of the benefits of using FQL instead of the Facebook APIs are that it reduces bandwidth, you can get more specific data by changing some of the constraints within the queries, and you can work with a more relevant subset of data, instead of processing tons of information you will not use in any case.

Example

SELECT name, affiliations FROM user
WHERE uid = 666873192

The above statement will return the name and affiliations based on my User ID.

SELECT pic FROM user
WHERE uid=666873192 OR uid=648902231

The above statement will return the picture of either user me or user Andre (my brother).

That wasn't so complicated, was it?

How Do I Get Started?

The Step by step guide walks you through all the necessary steps to set up your application.

The first step is to Create the New application. Here, you have to click set up new application; this will take you to the next page. On this page, you give the application a name, and then remember to agree to the terms of the Facebook platform. Once done, click Submit.

The next page you'll see is the My Applications page. It shows you all your current applications, along with their Keys and Secrets. Without the keys and secret, you won't be able to connect to Facebook from within your program (it will need to be authorised with these keys).

On the My Applications page, you have various options next to your application's title. These options include:

Edit Settings

This is possibly the most important option. Here, you can specify the Application type (Website or Desktop), and you can specify whether you are using FBML or IFrame, to name but a few options. Some other options include:

Application Name: The name of your application

Support E-mail: Facebook will contact you at this address if there are any problems or important updates.

Callback Url: After logging into Facebook, users are redirected to the callback URL.

Feed Templates

Here, you can add feed stories for your application, through an existing template, or a new one.

Register New Template

This page shows the feed story templates you have registered for your application. By default, feed stories for your application are displayed in the Mini-Feed of the acting user, and they also may be displayed in the News Feeds of friends of the acting user, but only if those friends have added your application.

Delete App

Quite obviously, this will delete your application.

Stats

This shows the current statistics about your application. Some statistics include:

Users Engaged

Total Users

Adds

Removes

Blocks

Unblocks

On the My Applications page, there are also various links to various resources you can use to develop your application, as well as a handy sample application.

Application Types

Once you have set up your application on Facebook, you obviously need to create your application. There are several options you can utilise here:

Desktop application

This application will reside on a user's desktop, and they will be able to interface with Facebook via the use of the Facebook APIs or the FQL.

Web Application

Here, you have four options:

IFRAME Canvas application: With this type of canvas page, Facebook will host an iframe containing the content for your application.

FBML Canvas application: With an FBML canvas, the developer is essentially developing an FBML web service that the Facebook server can invoke and the service will emit FBML that can be rendered as HTML by the displayed page.

AJAX in IFRAME Canvas: AJAX from an IFrame is not supported in Facebookwithout Framework 3.5 installed on the WebServer.

Silverlight

Fine. You can use all these technologies to create a Facebook application, but how?

To answer this question, you can look at the FaceBookDeveloperToolkit, available here. This toolkit provides you with three main DLL files:

FaceBook.dll

This DLL is the most important of the three. It contains the following items:

The Login information, such as the authorization token, session key, and application key

The Entity information, such as the user's information (School history, Work, Photo, Location, and Notifications)

All The Exceptions

The Parser information, which assists in getting all the desired information into the correct format

The Utility information, such as StringHelper, Imagehelper, and XMLHelper, which assist the Parser classes

FaceBook.Controls.dll

This DLL contains components that you can use in your Desktop application. For example, it includes the following controls:

EventList: Contains an EventListItem; this component allows you to programmatically create Facebook events

FriendList and FriendMap: Allows you to get a nice list/map of your friends

InviteeList: Allows you to see who has accepted or declined invitations you sent out

PhotoAlbum: Displays a user's photo's in an album format

FaceBook.WebControl.dll

This DLL contains the same components as the Facebook.Controls.dll, except that it is to be used on a web platform.

Apart from the binaries (mentioned above), the FaceBookDeveloperToolkit also includes a very handy sample application that you can download and play around with and learn from. Lastly, the Facebookdevelopertoolkit has a small manual you can download as well. This mini-book explains all the intricacies of all these applications, technologies (FBML FQL), and components in great detail.

Your Program

Again, if you have read any of my articles in the past, you will also know that I'm quite a lazy person—not really lazy; I just like to make things easier for myself, so what I will be attempting here is a small (yet powerful) desktop application, notifying me if I have any new group invites, any new friend requests, or any new messages. This program will also list all my friends, and all my events I have subscribed to. Sound exciting?

Setup on Facebook

The first step is to add the Facebook developer application to your Facebook account. To do this, you can go to the getting started page.

Make sure to select the checkbox that asks whether you have read the terms and conditions.

Select the Optional Fields link. This will show you more details you can put in (as explained earlier).

If necessary, fill in your email address as the Support E-Mail.

Select Desktop under the section entitled Application Type.

Select Submit.

On the My Applications page, make sure to write down your API Key, and your Secret. You will need them to log on to Facebook from within your program.

In my case, my API Key and secret looked like the following:

[NotifierKeys.png]

Figure 1: The API Key and Secret

Another thing you could play around with (after you have created this application) is the About page for the application. If I were to click Edit About Page, I'd be able to add information about the application. With Notifier, the About page can be found here.

That's it. Obviously, your API Key and Secret will be different than mine if you have followed these steps, but in the sample program, I will use my Key and Secret.

The Design

The first step, obviously, is to open Visual Studio 2005, or VB 2005 Express.

Create a new Windows Application named Notifier.

The next step is to add the Facebook components found in the FaceBookDeveloperToolkit. So, if you haven't downloaded them yet, do so now.

To add the components, follow these steps:

Right-click the Appropriate toolbox tab, and select Choose Items....

On the .NET Framework Componentstab, select Browse.

Navigate to the location where you have downloaded the FacebookDeveloperToolkit binaries to, and select Facebook.dll. Once done, there will be two more items in your Toolbox, namely AsyncFaceBookservice and FaceBookService.

Repeat the above steps to add the rest of the Facebook components. This time, add Facebook.Controls.dll. After this step, you will notice six more items in your Toolbox, namely FriendList, InviteeList, EventList, FriendMap, PhotoAlbum, and Profile.

For your application, add the following to your form, and change the properties as explained in the following table.

Control

Property

Value

FaceBookService

Name

fbService

ApplicationKey

b16aa3671bcab67bc648a69c050ae6f9

Secret

2d643a38ebe13dc289549759b3e2041a

FriendList

Name

fbFriend

Size

Any size you feel is appropriate

EventList

Name

fbEvent

Size

Any size you feel is appropriate

Textbox

Name

txtNotifier1

AcceptsReturn

True

MultiLine

True

ScrollBars

Both

Textbox

Name

txtNotifier2

Same Properties as txtNotifier1

LinkLabel

Name

lklMessages

Text

Messages

LinkLabel

Name

lklFriends

Text

Friends

LinkLabel

Name

lklGroups

Text

Groups

The Code

Imports

First, you will need a couple of Imports statements at the top of your Code Window.

Declarations

The Modular variables I'm creating here will be used in more than one procedure. MsgNot will be used to determine how many unread messages I have. FriendNot will hold the number of new friend requests I have. Lastly, GroupNot, will store the number of new Group Invitations I received. EvColl is your events Collection object. It will not only store the number of upcoming events I have, it will also store the Event details.

Form1_Load

Here, you set everything up. You get the possible unread messages' count, the new Friend Request details, Group Invite details, as well as all the Events details.

Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
'Populate FriendList Through The Use Of The GetFriends Method
'Of fbService
fbFriend.Friends = fbService.GetFriends()
'Retrieve Unread Message Count
MsgNot = fbService.GetNotifications.UnreadMessageCount
'Retrieve Friend Requests Count
FriendNot = fbService.GetNotifications.FriendRequests.Count
'Retrieve Group Invites Count
GroupNot = fbService.GetNotifications.GroupInvites.Count
'Get Our Own Events, If There Are, Store It In Our Events
'Collection
EvColl = fbService.GetEvents(fbService.UserId)
If EvColl.Count > 0 Then 'If We Have Events
'Populate EventList With Retrieved Events, IOW, Our Events
'Collection
fbEvent.FacebookEvents = EvColl
Else 'If There Are No New Events
Dim TempControl As Control 'Declare A Temporary Control
'Loop Through All Controls In Events List
For Each TempControl In fbEvent.Controls
'If Current Control Is Named lblEventCount
If TempControl.Name = "lblEventCount" Then
'Write Our Own Text
TempControl.Text = "No New Events"
End If
Next
End If
'If We Have received A New Message
If MsgNot > 0 Then
'Change Message LinkLabel's Text
lklMessages.Text = "Read New Message(s)"
End If
If FriendNot > 0 Then 'If We Have A New Friend Request
'Change Friend LinkLabel's Text
lklFriends.Text = "See New Friend(s)"
End If
If GroupNot > 0 Then 'If We Have A New Group Invite
'Change Group LinkLabel's Text
lklGroups.Text = "See New Group(s)"
End If
End Sub

One segment of Form_Load is quite interesting. If you have looked closely at the EventsList component (as well the FriendList), you would have noticed that it is comprised of more than one control. The whole idea behind the If segment is to provide a custom message if I don't have any current events. If I were to run the above code, and I didn't have any current events, it would produce the following:

[EventCustomMessage.png]

Figure 2: Show custom message, if you have no events.

If I didn't have any new events, and modified the above code to look like the following:

Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
'Populate FriendList Through The Use Of The GetFriends Method Of
'fbService
fbFriend.Friends = fbService.GetFriends()
'Retrieve Unread Message Count
MsgNot = fbService.GetNotifications.UnreadMessageCount
'Retrieve Friend Requests Count
FriendNot = fbService.GetNotifications.FriendRequests.Count
'Retrieve Group Invites Count
GroupNot = fbService.GetNotifications.GroupInvites.Count
'Get Our Own Events, If There Are, Store It In Our Events
'Collection
EvColl = fbService.GetEvents(fbService.UserId)
If EvColl.Count > 0 Then 'If We Have Events
'Populate EventList With Retrieved Events, IOW, Our Events
'Collection
fbEvent.FacebookEvents = EvColl
End If
If MsgNot > 0 Then 'If We Have received A New Message
'Change Message LinkLabel's Text
lklMessages.Text = "Read New Message(s)"
End If
If FriendNot > 0 Then 'If We Have A New Friend Request
'Change Friend LinkLabel's Text
lklFriends.Text = "See New Friend(s)"
End If
If GroupNot > 0 Then 'If We Have A New Group Invite
'Change Group LinkLabel's Text
lklGroups.Text = "See New Group(s)"
End If
End Sub

It would have shown the default "built in" message You have 0 upcoming events, and looked like the following picture:

[NoEvents.png]

Figure 3: EventList showing default message with no Events

If it so happened that I did have upcoming events, and run the original code, it would have produced a form similar to the following:

[NewEvents.png]

Figure 4: EventList displays the new Events.

The last part of Form_Load basically checks whether MsgNot and FriendNot and GroupNot are greater than 0, meaning we have received a new message, friend, or group request/invite. If any of these are greater than 0, it will change the appropriate LinkLabel's text. A more advanced version of Notifier could include a Timer, checking these periodically, and then update the display appropriately.

fbEvent_Load

The above event loads the EventList with your EventList collection. Only after this, you will be able to run the program. You must use the Load event of an EventList (if one is present). This (as said) loads all the events details. So, after you have added this event, you can feel free to run Notifier. The very first time Notifier is run, it will produce a screen similar to the following:

[LogonNotifier.png]

Figure 5: Log in confirmation

If you were to select Keep me logged in to Notifier, this screen will not be shown again. It will show a blank form momentarily; then, it will proceed to load Notifier, which might take some time. After it has loaded Notifier into memory, Notifier will be displayed and may look similar to Figures 2, 3, or 4, depending on those events stipulated earlier.

fbEvent_EventSelected

The EventSelected event handles the clicking of an event in the EventList. If you were to select a particular event in fbEvent, it will show the following details in your txtNotifier2 textbox:

fbFriend_FriendSelected

The FriendSelected method of your FriendList basically handles the selection of a friend inside the FriendList. By selecting a friend in fbFriend, it will show the following details inside txtNotifier1, as shown in Figure 7:

The next three methods I will cover are the Clicking of your LinkLabels. When you have a new Message, new Friend Request, and a new Group Invite, a screen similar to the following will be shown:

[NewEverything.png]

Figure 8: New Notifications

As you can see, the LinkLabels indicate that youe have a new Message, new Friend Request, and a new Group Invite. If you haven't received any of these, a screen similar to the following will be displayed:

[NoMessFriendGroup.png]

Figure 9: Nothing received:(

lklMessages_Click

This event fires when you click the "Messages" LinkLabel. When you have a new message, you show the Most Recent Message ID inside txtNotifier1. Irrespective of whether or not you have a new message, once clicked, it will launch the default browser and navigate to the Facebook Inbox page.

When you click your Messages label, a screen similar to Figure 10 will be displayed. Here you can see the new Message's ID. Your default browser will also be launched, and you will be navigated to your Facebook Inbox.

If you have received a new Friend Request, and you clicked your Friends LinkLabel, your Browser will navigate to the request page that will show you who wants to be your friend:

[FriendReq.png]

Figure 12: New friend Confirmation page.

If you haven't received a new Friend request, you simply display a MessageBox stating that there are no new friend requests :(.

lklGroups_Click

When you get a new Group Invite, you can click this label to navigate the new Group's details on Facebook. If you haven't received a new Group Invite, you just simply navigate to the groups you already belong to. txtNotifier1 also will show the new group's ID.

When you click the Groups LinkLabel, it will also follow suit, meaning, it will also open up your default Internet browser and take you to the appropriate page. If you click on the Groups LinkLabel, and there are no new Group Invites; it will only show the list of groups you already belong to (if any), as shown in Figure 13:

[NoNewGroups.png]

Figure 13: Showing the Groups I belong to already, if I have no New Group Invites.

Conclusion

The accompanying zip includes this project. I hope that you have benefitted from this article, and now realise how simple it can be to write an application for Facebook. Till next time!