« December 2007 | Main | February 2008 »

January 2008

January 31, 2008

Your First Facebook Application

Writing a Facebook Application

With the rise of social network applications such as Facebook over the last 3 - 5 years, it's become very attractive to be present in that space.  Facebook applications are most often games that allow users to play against each other, or themselves in the case of solo-games, but there is no technology limit to this. The application could easily be an extension of your own application.

One of the many great things you get from using the Facebook platform, is an enormous list of potential clients who already have user/login info for your application! Couple this with the outsourcing of user login/management/authentication to another provider (Facebook), access to the Facebook messaging API, and it's easy to see the return on investment.

Getting Started

Assuming you have a Facebook account , you will need to install the Facebook developer application . Once you have the developer application installed, you should be directed to the developer home page, and here you can apply for an application key. When you apply for an application key, it asks for an application name, we'll call ours Hello World. Now that you have a Facebook application registered, you can retrieve your API key, and secret key from the installed applications page.

We will be building a .NET application using the .NET Facebook dev kit from Microsoft , but you can use any modern language. There are development libraries available for all of them, and the developers wiki is a great resource... here is the link.

Assuming you will be developing using your local machine, we need to configure a couple values in your Facebook application, which can be done on the application settings you can access from the applications page here

  • Set your Callback URL to your local instance url (e.g. http://localhost/); if you are using Visual Studio's built in server/debugging, then you will need to fix the port that it uses, and enter that as your Callback URL. If you are using a public server, then enter the URL for that server in this box.
  • Set your Canvas Page URL to anything you like, this is the url that Facebook users will use to access your application.
  • Set the application to iFrame - This allows you to have any content you choose, without being limited by the FBML (Facebook Markup Language) and it's slow rendering times.
  • Set the application type to Website.

There are many more options there that you can play with , but these are the ones you need to get your application running.

After installing the Facebook Dev Kit from Microsoft, you will have the Facebook libraries located in the install location (C:\Program Files\Facebook Developer Toolkit). There will now be Facebook components available in Visual Studio, but we will do our example by hand.

The Code

Create a new web page project, and open Default.aspx to insert the following content:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloWorld.aspx.cs" Inherits="HelloWorld._default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>FaceBook Hello World</title>
</head>
<body>
    <form id="form1" runat="server">
        <h1>Ours</h1>
    <asp:Repeater ID="friendList" runat="server">
    <HeaderTemplate>
    <table>
    <tr>
    <td><b>Name</b></td><td><b>Photo</b></td>
    </tr>
    </HeaderTemplate>
    <ItemTemplate><tr><td><%#DataBinder.Eval(Container.DataItem,"Name")%></td>
    <td><img src="<%#DataBinder.Eval(Container.DataItem,"PictureUrl")%>" /></td></tr></ItemTemplate>
    <FooterTemplate>
    </table>
    </FooterTemplate>
    </asp:Repeater>
    </form>
</body>
</html>

Now open the code behind file Default.aspx.cs , and populate it with this

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.ObjectModel;
namespace
HelloWorld
{
    public partial class _default : System.Web.UI.Page
    {
        private Facebook.Components.FacebookService _facebookApi = new Facebook.Components.FacebookService();

        protected void Page_Load(object sender, EventArgs e)
        {

            // ApplicationKey and Secret are acquired when you sign up for
            _facebookApi.ApplicationKey = "[YOUR KEY]";
            _facebookApi.Secret = "[YOUR SECRET KEY]";
            _facebookApi.IsDesktopApplication = false;

            string sessionKey = Session["Facebook_session_key"] as String;
            string userId = Session["Facebook_userId"] as String;

            // When the user uses the Facebook login page, the redirect back here will will have the auth_token in the query params

            string authToken = Request.QueryString["auth_token"];

            if (!String.IsNullOrEmpty(sessionKey))
            {
                _facebookApi.SessionKey = sessionKey;
            }
            else if (!String.IsNullOrEmpty(authToken))
            {
                _facebookApi.CreateSession(authToken);
                Session["Facebook_session_key"] = _facebookApi.SessionKey;
            }
            else
            {
                Response.Redirect(@"http://www.Facebook.com/login.php?api_key=" + _facebookApi.ApplicationKey + @"&v=1.0");
            }

            if (!IsPostBack)
            {
                // Get our list of friends
                Collection<Facebook.Entity.User> friends = _facebookApi.GetFriends();

                //bind our repeater
                friendList.DataSource = friends;
                friendList.DataBind();
            }
        }
    }
}

The basics here should be clear. You set your application and secret keys, and then your basically good to go! The Facebook.Components.FacebookService class provides access to the current user, and if they aren't logged in you can bounce them to the Facebook login screen.

To go live with your project, simply move the code to a public server, change your callback url in the application settings page within Facebook and select the 'add application to directory' check box on that same page.

Now that you have the user authenticated, and access to their friends list, the sky is the limit. We chose to store user keys in our database for customizations which we simply did using their Facebook ID.

In Conclusion

In practice I found the Facebook API to be very usable, and there were no unexpected hurdles to work around. We did have an occasional user authentication error, which may have been caused by having mutliple users logged in on the same machine, but this was an edge case.

In all, I wouldn't hesitate to recommend the platform as an extension of an existing business giving a low-cost, low-risk entry into the seemingly persistent world of Social Networking Applications. However, I would hesitate before putting serious development into a FBML application, or anything that specifically required Facebook, for the same reasons I wouldn't want to own a million dollar application that only ran in Friendster, Tribe.net or any of the other Social Networking sites that had their time in the sun.

January 13, 2008

The Rise of Utility Computing?

Many years ago, companies like IBM and Sun promised us that the age of utility computing was here, and that we would soon be purchasing computing time in the same manner as we currently purchase electricity, gas, telephone and water. However, people laughed at the idea, and it faded into the backs of peoples' minds.

Codesta recently helped to create a brand new startup company called Jamloop (found at http://www.jamloop.com) which aggregates and geolocates new and used musical instruments. JamLoop came to Codesta and asked us to help make their idea reality. Based upon their requirements we decided to go with a JBoss-based web application with Spring and Hibernate underpinnings, which is (I believe) a pretty common choice and is not revolutionary. When deciding on how to bring this site to production however, we tried something different. We researched Amazon's EC2 (Elastic Compute Cloud), and we found it to be a good fit for both us and for our client. For 10 cents an hour ($2.40 a day) we could have a server available to us to do anything we wanted. We elected to go this route, and it has paid off handsomely for both us and the customer.

From our perspective, the key advantages that EC2 provide are:

  • JamLoop didn't need to purchase expensive hosting space or hire any IT people, or take a risk with a cheap hosting site - Amazon is a big enough name that we felt we could trust them
  • JamLoop can adapt to changing traffic patterns - if they suddenly get more popular or see a traffic spike, they can instantiate new EC2 instances on demand and still be paying just $0.10/hour/server
  • If JamLoop has a normal traffic load which 20 servers can handle, and a peak that 100 servers can handle, they don't need to always have 100 servers - they can scale up and down when needed
  • Since this site operates as an aggregator, it needs to import external data - JamLoop can spawn up some instances which do harvesting, keep them around for as long as needed, and shut them down when the task is complete.
  • The cost is really low - $2.40 per day of server time works out to about $72/month per server, which seems like a good price especially given that there are no contracts and it's a pay-as-you-go model
  • JamLoop can run any operating system or software that they want since these are their boxes - they aren't constrained to what a provider will set up for them e.g. Apache and PHP
  • Using the EC2 API was really easy - they have an excellent tutorial and a well-built set of tools

One of my coworkers, Oliver Chan, will be posting about what we did with EC2 from a technical perspective very soon - however, the business ramifications I found too interesting to pass by. I think that we're entering the realm of utility computing which was described and dismissed in the past, and I think it makes the barrier to entry for new companies much lower. If I decide tomorrow that I have a great idea and I want to create a new website/company around it, I don't need to think about production problems - I can just use EC2, and pay less per month for a dedicated server than I pay for electricity at home. Amazon is my ops team, and my costs are predictable and clear.

January 08, 2008

An Adventure with Google OpenSocial

Pretty much every company that I know of has an annual company-wide meeting and ours is no different, however we do a little bit more than just meet somewhere for food and drink. We gather everybody in the company together in one place for a few days. This year it was in the Toronto office, and last year it was in the Palo Alto office. In addition to a dinner, we discuss the past year's achievements and progress we've made as a company. We also have a programming competition, in which we divide the developers up into two teams and pit them against each other in a race against time. This is something that I really enjoy, and that I look forward to every year.

This year, the challenge was to build a game which would exist on a social networking site. The game would be a two-player, turn-based game which would share state (the game board). Our team was assigned Google's OpenSocial platform as our development environment, and our competitors were assigned the Facebook API. Both teams chose Battleship as their game of choice, and with a little over 24 hours available to construct our masterpieces, the teams set to work.

First, I'll give you a quick OpenSocial overview. OpenSocial is an API created by Google which is based off of the Orkut social networking site. The idea behind OpenSocial is that multiple websites can implement the OpenSocial API (such as MySpace, hi5, Plaxo and LinkedIn) and this gives each of them access to all of the OpenSocial widgets that have been written. In effect, you can write one widget to one API specification, and have it work on many websites. It's an interesting idea, but what is the implementation like?

The first hurdle that we encountered ended up being the biggest. In order to develop an application using the Google OpenSocial API, you have to sign up for an Orkut sandbox account. This doesn't seem like much of a hurdle, until you discover that the registration process is apparently not automatic. You submit a request, and at some point in the future you hear back from Orkut that your account has been activated and that you can now access the sandbox. In our case, we registered at 11:00 a.m. on Monday, and the competition was scheduled to end at 3 p.m. on Tuesday. We didn't hear back that our accounts had been activated until after 2 p.m. on Tuesday, which made using Orkut's sandbox impossible.

As soon as we realized that we would have a delay with the Orkut sandbox, we started looking around for other OpenSocial implementations. The only one that we found was hi5's sandbox, and it's fair to say that their sandbox environment was a bit of a mess. The sandbox site was obviously a live development environment, with fairly random things floating about on the pages and assorted debugging strings embedded in different locations. We ended up stumbling upon the application preview section by pure chance. It was a small upload box hidden on the bottom right side of the application preview pane, and it would occasionally throw errors at us just to keep us on our toes. We also discovered that the only portion of the OpenSocial API that seemed to be implemented in the hi5 sandbox was the part which allowed access to your own profile. The portions which allowed access to friends, messages and other profiles appeared to not be implemented yet. This made it impossible for us to do what was originally scoped out in the contest guidelines, so we adapted by implementing an AI which enabled a usable single-player game.

OpenSocial widgets are built on top of Google's Gadget API, which is quite nice. A gadget is written in HTML and JavaScript, and it's stored in a publicly-accessible XML file. There are a fair number of powerful and useful APIs available (such as a drag-and drop system), and the choice of HTML and JavaScript as the development languages are a natural fit for a web-resident application. It allows for a lot of flexibility, and it also lets you take advantage of all of the existing libraries (such as Dojo). We ended up writing a fairly detailed Battleship game, with highlighted ship-placement mode, in-game animations, a multi-phasic adaptive AI and a high score board, however our erstwhile compatriots took the prize.

Overall, it feels like OpenSocial is not yet really ready for people to use. The platform has a lot of promise, if some of the discussions and promises which are flying about are to be believed, but at this point there are still numerous wrinkles to sort out which make it very difficult to actually develop to the platform. While these sorts of issues are common with a new platform, given the massive popularity of Facebook, OpenSocial is going to have to get it's act together in a relatively short period of time otherwise they may end up being consigned to history as another footnote technology.

-->

January 31, 2008

Your First Facebook Application

Writing a Facebook Application With the rise of social network applications such as Facebook over the last 3 - 5 years, it's become very attractive to be present in that space. Facebook applications are most often games that allow users to play against each other, or themselves in the case of solo-games, but there is no technology limit to this. The application could easily be an extension of your own application. One of the many great things you get from using the Facebook platform, is an enormous list of potential clients who already have user/login info for your application! Couple this with the outsourcing of user login/management/authentication to another provider (Facebook), access to the Facebook messaging API, and it's easy...read more

Categories: Web/Tech

January 13, 2008

The Rise of Utility Computing?

Many years ago, companies like IBM and Sun promised us that the age of utility computing was here, and that we would soon be purchasing computing time in the same manner as we currently purchase electricity, gas, telephone and water. However, people laughed at the idea, and it faded into the backs of peoples' minds. Codesta recently helped to create a brand new startup company called Jamloop (found at http://www.jamloop.com) which aggregates and geolocates new and used musical instruments. JamLoop came to Codesta and asked us to help make their idea reality. Based upon their requirements we decided to go with a JBoss-based web application with Spring and Hibernate underpinnings, which is (I believe) a pretty common choice and is...read more

Categories: Web/Tech

January 8, 2008

An Adventure with Google OpenSocial

Pretty much every company that I know of has an annual company-wide meeting and ours is no different, however we do a little bit more than just meet somewhere for food and drink. We gather everybody in the company together in one place for a few days. This year it was in the Toronto office, and last year it was in the Palo Alto office. In addition to a dinner, we discuss the past year's achievements and progress we've made as a company. We also have a programming competition, in which we divide the developers up into two teams and pit them against each other in a race against time. This is something that I really enjoy, and that I...read more

Categories: Web/Tech

Privacy Policy| Sitemap| Contact Us

Copyright 2002-2007 Codesta LLC. All rights reserved.