The move to ubuntu Using .net to parse a csv with quote delimination

Your First Facebook Application

22 Apr 2008

Reposted from an article I wrote for Codesta.com article here


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

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.