Free Information Technology Magazines and eBooks

Thursday, October 07, 2010

Develop Your Own Facebook Application In ASP.NET C#

Last week I shared a coding tip on how to use Google Open ID authentication in your ASP.NET application. I was trying to the same with Facebook but ended up creating my very first application on Facebook platform. There are lots of tutorials and sample codes about Facebook coding but on this article, I'll try to simplify them in few words. The full sourcecode of the sample project is also available on the link below. The sample project is written in C# under MS Visual Studio 2008. Let start by downloading the Facebook Developer Toolkit from CodePlex. Now once you have the binaries on your local computer, next task is to set up your Facebook application.

How To Setup a Facebook Application
1. Go to Facebook Developer Application page.
2. Click the Go to Application button and click Set Up New Application.
3. Enter the basic information such as Application Name, Description, Privacy Policy URL, TOS URL and etc.
How To Setup a Facebook Application

4. Jump to Facebook Integration tab and enter these important information:
Canvas Page - main URL of your application on Facebook.
Canvas URL - the URL where Facebook pulls the content. (hosting site)
Canvas Type - Either IFrame or FBML

Develop Your Own Facebook Application In ASP.NET C#

5. Click Save Changes button to commit changes.


Now lets create our ASP.NET project.

1. Create a blank ASP.NET website project.
2. On the Solution explorer, add reference to the binaries we downloaded earlier (facebook.dll, facebook.web.dll & Microsoft.Xml.Schema.Linq.dll).



3. Still on the Solution Explorer, double click the web.config file and add the following to appSettings element.


<appSettings>
<add key="APIKey" value="ddf950b3710efb605e4319cab075deb1"/>
<add key="Secret" value="6e8ef246d5328dda31465c21fa6692a7"/>
<add key="Callback" value="http://morefreesoftware.com:36698/FacebookIntegrationSample/"></add>
</appSettings>


Take note that you have to change the values of these settings with your own. You can get it from your application page as shown below.

How to get your Facebook API Key and Application Secret

4. Next is to edit the default.aspx, to add the following codes under the body tag.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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 runat="server">
<title>Facebook Integration Sample</title>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="login">
Welcome to Fryan's facebook test application <br />
<asp:Panel ID="pnlLogin" runat="server">
<fb:login-button length="long" onlogin="window.location.reload()">
</fb:login-button><br />
</asp:Panel><br />
<asp:label id="lblMessage" runat="server" text="Not authenticated. Click Button to authenticate"></asp:label>
<br /><br />
<asp:Image ID="imgPic" runat="server" AlternateText="" />
</div>
</form>

<script type="text/javascript">
FB.init("ddf950b3710efb605e4319cab075deb1", "fb_receiver.htm");
</script>
</body>
</html>


This code displays the Facebook Connect button when the application is not yet authorized on the user's account. When the button is clicked, Facebook will ask for confirmation to allow the application to access the user's data.

7. Now add a html file and name it as "fb_receiver.htm". Paste the following code.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cross-Domain Receiver Page</title>
</head>
<body>
<script src="http://static.ak.facebook.com/js/api_lib/v0.4/XdCommReceiver.debug.js" type="text/javascript"></script>
</body>
</html>


What is this file for? This file is required to allow Facebook to save a cookie that you have access to. In Short, it allows Facebook Connect to work.

6. Create a class and name it as "fbConnect.cs". Paste the following code:


using System.Configuration;
using System.Web;

public class fbConnect
{
public fbConnect()
{

}

public static bool isConnected()
{
return (SessionKey != null && UserID != -1);
}

public static string ApiKey
{
get
{
return ConfigurationManager.AppSettings["APIKey"];
}
}

public static string SecretKey
{
get
{
return ConfigurationManager.AppSettings["Secret"];
}
}

public static string SessionKey
{
get
{
return GetFacebookCookie("session_key");
}
}

public static int UserID
{
get
{
int userID = -1;
int.TryParse(GetFacebookCookie("user"), out userID);
return userID;
}
}

private static string GetFacebookCookie(string cookieName)
{
string retString = null;
string fullCookie = ApiKey + "_" + cookieName;

if (HttpContext.Current.Request.Cookies[fullCookie] != null)
retString = HttpContext.Current.Request.Cookies[fullCookie].Value;

return retString;
}
}



Ofcourse you can change its name to whatever you like. Just make sure to use the same name on the other codes that refers to this class. This class put together the authentication verification process.

7. Open Default.aspx.cs. Paste the following code.

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using facebook;
using facebook.web;

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

protected void Page_Load(object sender, EventArgs e)
{
if (fbConnect.isConnected()) // Check if this application is authenticated
{
API api = new API();

api.ApplicationKey = fbConnect.ApiKey;
api.SessionKey = fbConnect.SessionKey;
api.Secret = fbConnect.SecretKey;
api.uid = fbConnect.UserID;

// hide the facebook button
pnlLogin.Visible = false;

//Get the data of the signed user.
string fullName = api.users.getInfo().first_name.ToUpper() + " " + api.users.getInfo().last_name.ToUpper();
lblMessage.Text = "You are login as " + fullName;
imgPic.ImageUrl = api.users.getInfo().pic_big;


}
else
{
pnlLogin.Visible = true;
}

}
}



Here what this code do:
- First, we reference facebook and facebook.web in our "usings" directive to give us access to the Toolkit libraries.
- Second, we checked if the application is already connected/authenticated.
- Lastly, we retrieved some data from the user's profile such as fullname and profile picture.

8. Test the application. Take note that since Facebook disallows to test application on localhost, you have to edit your computer's hosts file for the testing to work. You can read how to configure it here. What it does is to redirect any request to remote domain to your local host server fooling Facebook that your running on a remote server.

Download the full sourcecode

To stay up-to-date on Coding Tips & Tricks, subscribe now.

2 comments:

matt said...

Fryan,

i'm trying to do exactly what you did, but get the application to work in a tab for a business page. any information you could pass my way about that, my application works just fine on the apps.facebook.com/MYAPPNAME, but not on the application tab, and there is so much conflicting information out there due to the way fb is changing their stance on fbml and iframes....

thanks,
matt

Sangeeta said...

i m doing exactly wat u did bt having a problem..
even if i m authenticated with facebook n opens the app page it shows page with login button, now again if i clicks on login button it shows user info on page..

dont know why it shows login button even i m logged in ??
wts reason n its solution ??