Develop Your Social Networking Skills

Create a Facebook Application with ASP.NET

CoverStory

LANGUAGES: C#

ASP.NET VERSIONS: 3.5

Develop Your Social Networking Skills

Create a Facebook Application with ASP.NET

By Oscar Peli

Facebook is one of the most popular online social networks available today. Many of you probably have a Facebook account. And even if you don t use Facebook, you ve likely heard of it. Facebook is very user friendly, but in this article we ll go behind the scenes and explore the developer side of this popular social networking environment.

We ll start from developers.facebook.com/, to learn how to build applications on Facebook Platform that millions of people use everyday. The first order of business is to set up the application in Facebook Platform (even if it is not yet developed), then develop the application using the .NET Facebook Developer Toolkit that wraps the platform APIs and lets us manage users interaction. You must host the application on an Internet-reachable server (it may be your machine, too, if you have a public dial-up IP address), so you ll be able to test how the application works in Facebook.

Set Up the Application

You need a Facebook account to get started; go to www.facebook.com to sign up if you don t already have an account.

Developing an application starts from developers.facebook.com/, where you ll find all the information you need. We ll skip some redundant steps here so we can fully describe, and pay attention to, the ASP.NET content involved in the development of our application.

Once logged in, you need to add the Developer application to your account; go to www.facebook.com/developers, then click the Allow button (see Figure 1); in this way you can set up a new application.

Figure 1

Figure 1: Allow the developer application

On the Developer page click the Set Up New Application button; this leads you to a page where you can define your application name (in this example, oscarforaspnetpro ) and agree to the terms of service; click Save Changes when you are finished (see Figure 2).

Figure 2

Figure 2: The first step to create your application

This step leads you to the settings page of your application; here you ll find the API Key and the Secret that you ll use inside the web.config file of your application and will be used to identify your application (see Figure 3; note that some private items are partially hidden).

Figure 3

Figure 3: Application settings

There are many settings you can define for your application; here, for sake of space, you ll define only the mandatory fields (refer to the online documentation for a detailed description of all the settings). The settings you must define are:

  • on the Basic tab: Callback URL. This is the remote address of your application; if you have a private domain you can insert something like yourdomain.com/yourapp; otherwise, you can insert the IP address of your machine.
  • on the Canvas tab: Canvas Page URL. This is the Facebook address of your application; your users will reach your application typing http://apps.facebook.com/yourapp.
  • on the Canvas tab: set the Render Method to IFrame.

Note: About the last setting; you can choose to render your application canvas using the Facebook Markup Language (FBML) or inside an IFrame. The Facebook Markup Language is an evolved subset of HTML with some elements removed and others that have been added to support Facebook Platform. Here we want to explore how to develop the application with ASP.NET, so we ll not deal with this alternative approach. Surf the developer wiki starting from wiki.developers.facebook.com/index.php/FBML if you want to learn more about the Facebook Markup Language.

You can leave Facebook after the above changes are saved; it is now time to start the application development.

Develop a Purchasing Group Application

Before we start the development phase you need to spend some time getting a better understanding of what we are going to do. Inside Facebook you can create Groups where people can meet to share common interests. In the following sample we suppose that there exists the group named oscarforaspnetpro, which is a purchasing group; in this group, people come together to make the same purchases to obtain better prices. We want to develop an application that allows all (and only all) the members of the oscarforaspnetpro group to post their orders, based on a default list of products. Only the group officers will be able to view and commit all the pending orders. The application will send a notification to every officer every time a group member posts an order, and will send a notification to every group member every time an officer commits a pending order.

As you can imagine, you must interact with the platform API to identify group users and officers, manage notifications, and so on. So, first of all, you must download the Facebook Developer Toolkit, which is a wrapper of the Facebook API. You can download the toolkit starting from www.codeplex.com/FacebookToolkit. At the CodePlex site you ll find all the binaries you need, as well as the project sources and documentation. To develop the Purchasing Group Application, you only need the Binaries.zip download that contains, among others things, the following files you ll bring inside your application s Bin directory: facebook.dll, facebook.web.dll, facebook.web.xml, facebook.xml, and Microsoft.Xml.Schema.Linq.dll. Note that the current version of this toolkit (2.0) requires .NET Framework 3.5, so you must use Visual Studio 2008 as your development environment.

We don t want to spend too much time discussing the orders database, so we ll be so bold as to assume you can use SQL Server (2005 or above) as your database management system, with a simple database structure like the one shown in Figure 4.

Figure 4

Figure 4: The application database

As you can see, there are only three tables where we store the application users, the products, and the orders. You can find in the accompanying download a script file (createDB.sql) containing all the code to create the database.

We now can start to build the application, but first must create a new website with Visual Studio 2008. First add the Bin directory and place there the five files you downloaded with the toolkit (facebook.dll, facebook.web.dll, facebook.web.xml, facebook.xml, and Microsoft.Xml.Schema.Linq.dll). Then open the web.config file and add these lines:

APIKeyUID and SecretUID are the UIDs assigned to the application by Facebook in the set-up step (again, see Figure 3).

Add to the code-behind file of the first page (Default.aspx.cs) the references to the Facebook assemblies (facebook, facebook.Schema, and facebook.web). Then develop the page so it can be rendered inside an IFrame (as stated in the application set-up process). To do so, change the class definition from:

public partial class _Default : System.Web.UI.Page

to:

public partial class _Default :

facebook.web.CanvasIFrameBasePage

Note that if you want to use Master Pages, the definition of your master must be derived from facebook.web.CanvasIFrameMasterPage.

The interaction between the application and Facebook Platform is performed starting from the API class that represents the Toolkit root class; you can find extended documentation about the Facebook API starting at the Facebook developer wiki (wiki.developers.facebook.com/index.php/API); note that the wiki documentation is specific for the PHP library, but it s useful enough even for .NET developers.

Moving to methods, Figure 5 shows the Page_Load method of the Default.aspx page; after some basic settings, call the private method _CreateSessionInfo where we store some useful session information (we ll see it in a moment).

protected void Page_Load(object sender, EventArgs e)

{

// Call the base

base.Page_Load(sender, e);

// Blank System Messages

lblMsg.Text = "";

// Create DB connection

_conn = new SqlConnection(_ConnString);

// Add the event Handler to Submit Button

btnSubmit.Click += new EventHandler(btnSubmit_Click);

try

{

// Store Facebook most used info

_CreateSessionInfo();

lblUserName.Text = sUserName;

// Get user's groups

int IsUserInGroup = API.groups.get(lUserUID,

llOscarGroup).Count;

// Show the Officer panel to Officers

pnlOfficer.Visible = bUserIsOfficer;

// if the user is a group member ...

if (IsUserInGroup > 0)

{

// Insert the user in users table

string sqlInsUser = "EXEC spInsUser "

+ API.users.getInfo().uid

+ ", '" + API.users.getInfo().name + "'";

_ExecSQL(sqlInsUser);

// Show the user Panel

pnlUser.Visible = true;

// Hide the Guest Panel

pnlNotUser.Visible = false;

}

else

{

// Hide the user Panel

pnlUser.Visible = false;

// Show the Guest Panel

pnlNotUser.Visible = true;

}

}

catch

{

// Connects to Facebook

API.ConnectToFacebook();

}

}

Figure 5: The Page_Load method

To check if the user is a member of the oscarforaspnetpro group, use the API.groups.get method that returns all the groups of which the user is a member; in our sample, we use an overload of this method that lets us filter the groups we want to locate; of course, we ll look only for the oscarforaspnetpro group.

If the user is a group member, we must store his/her name and his/her UID inside the users table. The users class of the main API class lets us access that information through the getInfo method that returns a wide array of user-specific information. In this case, we need the name and UID values. A group member will see a form like the one shown in Figure 6.

Figure 6

Figure 6: The order form for a group user

The form contains a Repeater control that binds to the products table and shows the product list with the quantities of the last pending order; of course, if you are first to access the application, or if your last order was committed by an officer, you will not see any quantity set (see the file Default.aspx in the accompanying download files).

Session Info and FQL

Now we must to take a step back and look at the _CreateSessionInfo private method that lets us store some useful information in some private variables.

The code in Figure 7 first shows that you must hard code the group UID inside your code. This is because you cannot derive that UID from the Groups page; neither can you leverage on the group name because you can change it every time you want.

private void _CreateSessionInfo()

{

// The group UID is hard coded

lOscarGroup = 45200598206L;

// Gets the user UID

lUserUID = Convert.ToInt64(API.users.getInfo().uid);

// Gets the user name

sUserName = API.users.getInfo().name;

try

{

// Gets the Officers list

IList officers = API.groups.getMembers(lOscarGroup).

officers.uid;

foreach (long l in officers)

{

sOfficers += l.ToString() + ",";

}

sOfficers = sOfficers.Substring(0, sOfficers.Length - 1);

}

catch

{

sOfficers = "";

}

llOscarGroup = new List { lOscarGroup };

// Build the FQL string to check

// if the user is an Officer

string sFQL = "SELECT uid, gid, positions "

+ "FROM group_member WHERE gid="

+ lOscarGroup.ToString()

+ " AND uid="

+ lUserUID.ToString();

// Executes the FQL query

string sUserIsOfficer = _ExecuteFQL(sFQL);

bUserIsOfficer = sUserIsOfficer.Contains("OFFICER");

}

Figure 7: The _CreateSessionInfo method

You can use the useful API Test Console to find the group UID (available at developers.facebook.com/tools.php; use this tool to try several APIs).

Another useful piece of information is the list of group officers; the API.groups.getMembers method returns information about all the group members. Here we need only the officers UIDs that we ll use to send notifications. We can filter the above information using the officers.uid property, which returns exactly an IList of UIDs.

The next bit of information gathered by this method, the officer position of the current user, gives us a chance to explore another tool from Facebook Platform: the Facebook Query Language. This is a way to query the same Facebook data you can access through the API functions, but with a SQL-style interface.

There are situations where it may be more convenient to use this approach to query for data. For example, you can filter or build complex queries that let you get all the data with a single call. Because of space constraints it is not possible to cover the entire Facebook Query Language topic here, but you can find exhaustive information inside the developer wiki starting at wiki.developers.facebook.com/index.php/FQL.

Run the following query in the sample:

SELECT uid, gid, positions

FROM group_member

WHERE gid = groupGID

AND uid = userUID

In this example, groupGID is the group identifier and userUID is the user identifier. The result is a string containing a combination of the following three values: OWNER, ADMIN, and OFFICER, depending on the user positions. From this string you can check if the user is a group officer simply by calling the string-related Contains method.

To run the query, call the private method _ExecuteFQL (see Figure 8), where we must create a new instance of the fql class (pass the current API instance to the constructor). The query results can be returned in XML (default) or JSON format; choose the JSON format to make the string parse more easily. The query method of the fql object, finally, runs the query.

private string _ExecuteFQL(string sFQL)

{

// Create a FQL object

fql oFQL = new fql(API);

// Set the query's results format

oFQL.UseJson = true;

// Execute the query

return oFQL.query(sFQL);

}

Figure 8: The _ExecuteFQL method

Notifications

One of the more interesting features of Facebook Platform is relative to notifications. Every time you are dealing with role-based applications, you need a message system that informs the application users about the activities. The easiest way to send messages is through the send method of the API.notifications class. This method takes a comma-separated string of users UIDs (the recipients) as the first parameter and the string message as the second parameter. The message will be sent in the Notifications box of each user s Inbox, together with friendship acceptance, write-on-the-Wall alerts, and so on.

You must be careful, however, because your application can send a number of notifications to a user in a day, based on a number of metrics (or buckets). To get this number you can use the API.admin.getAllocation method or you can check the Allocations tab on the Insights dashboard for your application (see Figure 9); you can reach that page by following the Statistic link on the application summary page.

Figure 9

Figure 9: The application s Allocations tab

As you can read on the just-mentioned page, depending on how users interact with your application , you ll be able to send more or fewer notifications to users.

Another way to notify your application s users is through API.notifications.sendEmail. In this case, though, users must grant your application extended permission. You can read more about extended permissions on the developer wiki (wiki.developers.facebook.com/index.php/Extended_permissions). In a nutshell, there are some API functions that require a greater level of trust from the user. In this case, you easily can comprehend that this need is to limit spam. For the same reason, from Figure 9 you can read that emails are subjected to greater restrictions. On this basis, the current example used the first approach.

Try It

The last aspect of the application is the Manage Orders page that can be accessed by officers to submit pending orders. Because this page (Officer.aspx) does not contain any relevant material related to Facebook Platform, it is enough to show it and to talk a little about it (see Figure 10). Readers can find this page in the article s accompanying download files.

Figure 10

Figure 10: The Manage Orders page

The page contains an initial GridView control, where all the pending orders are shown. The order execution is a trivial operation because it transforms a pending order in an old order. All old orders may be recalled using a DropDownList control that contains all the submission dates; the selection of a date will show the relative orders inside a second GridView control. Of course, when an officer commits an order, a notification is sent to every user that posted an order.

Open your browser and type apps.facebook.com/oscarforaspnetpro to try a live version of the application. If you re not yet logged in, you must do so through the login form that automatically appears. Then you must allow the application in the same way you did the Developer application (again, see Figure 1). Finally, you ll see the guest message (see Figure 11).

Figure 11

Figure 11: The application s guest message

Simply join the oscarforaspnetpro group and come back to the application; as a group member, you ll see the order form (again, see Figure 6) and you ll be able to send orders. You ll receive the relative notification as soon as an officer commits your order. If you d like to become an officer, simply drop me a line and I ll promote you.

Go Viral

Developing an application is worthwhile if it will be used by many users. When you develop a Facebook application, you have millions of potential users that are already Facebook members.

Once you ve completed your application, you may submit it to the Application Directory following the submit link you can find in the summary page of your application. Most think this is the most important step in the application lifecycle. You must pay attention when compiling the submission form (see Figure 12); you must choose an attractive logo, as well as a smart icon. You also must select some noteworthy screenshots to post in the About page of your application.

Figure 12

Figure 12: Submit your application

You can find many suggestions that deal with how to maximize your application s exposure in the following article: www.insidefacebook.com/2007/06/07/10-tips-for-releasing-your-facebook-application-and-maximizing-growth/.

Conclusion

Facebook is one of the most important social networks on the Internet. You can find millions of users throughout the world, so you can imagine the opportunities in developing an application for such a wide audience. In this article we saw how to develop and deliver a Facebook application. You can develop a Facebook application in several ways; here we used ASP.NET and the Facebook Developer Toolkit, a .NET wrapper for the Facebook API. We saw how to use the Facebook APIs to integrate our application with groups, users, and notifications, and how to query for Facebook-related information.

In the last section, we learned how to submit the application to the Facebook Application Directory. This last step may be the most important in the lifecycle of your application; the most captivating aspect is your application s presentation—after all, you want to be able to attract as many users as possible.

Source code accompanying this article is available for download.

Oscar Peli ([email protected]) is a .NET Solution Architect and director of mobile devices development at the Municipality of Ancona (Italy).

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish