What is Facebook Connect?

Facebook Connect is Facebook’s latest addition to its development platform.  It enables developers to leverage the power of Facebook’s social context in existing, third-party web sites.  The platform features seamless, one-click authentication, Facebook friend account linking, distribution back into Facebook streams and the full power of the Facebook REST-like API and FQL.  Utilizing Facebook Connect for authentication has proven to dramatically increase site exposure and new user registrations.

From Facebook Connect Developer Home:

 

With the Facebook Connect APIs you gain access to:

·         Identity: a user’s name, photos, and more.

·         Friends: data about a user’s friends.

·         Distribution: all of the integration points within Facebook, like stream stories and notifications.

·         Integration: profile boxes, profile tabs, and publishers just like apps on Facebook

 

Use these APIs to enable users to easily share your content and the actions users take on your site with their friends on Facebook. With more data about a user and their friends, you have the power to create a more social and engaging experience on your site.

connect

 

Creating A New Facebook Connect ASP.NET Application

·      Create a new ASP.NET web site: 

o    In Visual Studio 2008, create a new ASP.NET Web Application.

o    Right-click on the project in the Solution Explorer and select Properties.  In the web application properties window, navigate to the Web tab.

o    Verify “Use Visual Studio Development Server” is selected, and select the “Specific Port” radio button.  For the port number, enter 48284 (the port used when creating the Facebook application above).  Save the changes and close the Properties page.  Note:  IIS can also be used for development, but for brevity the Visual Studio web server is used in this walkthrough.

 

·      Add Reference to the Facebook Developer ToolKit

o    Download the Facebook Developer Toolkit (FDT):  http://facebooktoolkit.codeplex.com

o   Add a reference to the FDT assembly.  (Right-click on project, Add Reference, select Browse tab, browse to Facebook.dll)

 

·      Configuring Cross-Domain Support

o    In order for the web application to communicate with the Facebook Connect platform, a cross-domain communications channel file must be created and added to the web application domain.  This file references the JavaScript cross-domain library provided by Facebook which establishes and handles the transfers between Facebook and third-party web sites.  Implementation is simple:

o    Add a new HTML page to your root of the web application named “xd_receiver.htm”

o    Open xd_receiver.htm and replace all markup with the following:

 

<!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"> 

        <body> 

             <script src=

              "http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" 

              type="text/javascript"></script> 

           </body>

         </html>

o    For more information, visit http://wiki.developers.facebook.com/index.php/Cross-domain_communication_channel

 

Adding the Facebook Connect Components to HTML Markup

·         Open Default.aspx.

·         Reference the Facebook XML Schema by modifying the <HTML> tag:

<html xmlns=http://www.w3.org/1999/xhtml xmlns:fb="http://www.facebook.com/2008/fbml">

 

·         Reference the Facebook script library inside the <HEAD> section:

<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>

 

·         Add the Facebook Login button into the <BODY> of the page. 

<fb:login-button onlogin="window.location.reload()"></fb:login-button>

 

Note that the onlogin event will trigger the page to reload after Facebook login completes, which will allow the web application to re-examine the authentication status during its Page_Load event to apply authenticated/not authenticated conditional code.

 

·         Add a simple ASP.NET label control to display the current authentication status:

<asp:label id="lblStatus" runat="server" />

 

·         At the very bottom of the markup, (just before the closing </HTML> tag, add the following to initialize the Facebook JavaScript library:  (Change the API Key to the key you generated for your application in Facebook)

<script type="text/javascript">

FB.init("[PASTE API KEY HERE]", "xd_receiver.htm"); 

</script>

 

·         Note: other (non-Facebook) markup has been added to the sample for formatting and display; download and view the sample source code to view the full markup.  Binding Facebook objects to ASP.NET controls is covered in more depth later in this walkthough.  The finished sample markup creates a form capable of creating new Facebook Events and displaying the RSVP status of invited guests.

 

Authentication and Initiating A Session

The sample application now contains all of the components requires to communicate with Facebook Connect.  This section adds the code-behind required for the application to affect changes based on authentication status, create a Facebook Developer Toolkit ConnectSession object and prepare the Toolkit’s API object that will be used for all future calls against the Facebook REST-like API.

Facebook Connect places cookies, including the Session Secret, Session Key and User ID on the browser after the user authenticates.  The ConnectSession class in the Facebook Developer Toolkit handles retrieving these cookie values and manages formatting these values for submission to the Facebook platform. 

For more information on Facebook Connect authentication, see http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works

·      Adding Code-Behind Logic

o    Open the Default.aspx.cs code-behind class.

o    Add private members to store the API Key & Application Secret, Connect Session and the Facebook Toolkit object (Note that this is for demo purposes only, a production application should store these in the web.config or use another means of securing the keys).  A generic List of the custom type EventUser is declared to store a collection of users for an existing Event.

 

private const string ApplicationKey = "[Application Key]";

private const string SecretKey = "[Application Secret Key]";

private Api _facebookAPI;

private ConnectSession _connectSession;

private List<EventUser> _eventUsers;

 

o    Edit the Page_Load event handler as follows.  A ConnectSession object is instantiated on each load by passing in the Application Key and Secret Key (this could also be a stored, reusable object).  The ConnectSession.IsConnected method is examined and directs code flow to the appropriate behaviors: If not connected, the page simply displays the sign-in message.  If authenticated, a Facebook Developer Toolkit API object is initialized using the ConnectSession instance.  The user is retrieved and the object is now fully enabled to issue calls against the Facebook API.  Finally, the status is updated with a simple message showing we have authenticated the user.

         protected void Page_Load(object sender, EventArgs e)

         {

            // Authenticated, created session and API object

            _connectSession = new ConnectSession(APPLICATION_KEY, SECRET_KEY);

 

            if (!_connectSession.IsConnected())

            {

                // Not authenticated, proceed as usual.

                lblStatus.Text = "Please sign-in with Facebook.";

            }

            else

            {

                // Authenticated, create API instance

                _facebookAPI = new Api(_connectSession);

 

                // Load user

                user user = _facebookAPI.Users.GetInfo();

 

                if (!Page.IsPostBack)

                {

        // Display the user’s name

                    lblStatus.Text = string.Format("Signed in as {0} {1}",

                        user.first_name, user.last_name);

                   

 

                    // Set the NavigateUrl target address for granting this application

  // the create_event extended permission

                    NewEventGrantPermission.NavigateUrl =  

                        string.Format("http://www.facebook.com

                                      /authorize.php?api_key={0}&v=1.0

                                      &ext_perm={1}",

                                      APPLICATION_KEY,

                                      Enums.ExtendedPermissions.create_event);

 

  // Set dummy event date

                    NewEventDate.Text = DateTime.Now.AddDays(7).ToString();

                   

 

  // Set a default host name (user’s name)

  NewEventHost.Text = string.Format("{0} {1}",

                                        user.first_name, user.last_name);

 

                    // Load existing Facebook Events

                    LoadExistingEvents();

                }

            }

 

            if (!Page.IsPostBack)

            {

                // Set section visibility

                ToggleSectionVisibility();

            }

         }

Using the Facebook Toolkit to Access API Methods

The Facebook Developer Toolkit (FDT) was created to ease the use of Facebook’s development platform and APIs for .NET developers.  A list of Facebook APIs and methods can found at http://wiki.developers.facebook.com/index.php/API.  The FDT wraps the functionality of the REST, Batching, Data Store, Facebook Connect and Permissions APIs.

For example, to retrieve all of the current user’s Events and bind them to an ASP.NET control, use the FacebookAPI object’s Events instance to invoke one of the available API method calls (in this case, Events.Get is used in order to retrieve the event object collection from the Facebook API).

Example 1:  RetrIEve and Bind Events Via Facebook Developer Toolkit

// Get user's events via Facebook Toolkit API object

var facebookevents = _facebookAPI.Events.Get();

 

// Bind list to existing events

EventList.DataSource = facebookevents;

 

// Set the display and value fields

EventList.DataTextField = "name";

EventList.DataValueField = "eid";

 

// Bind the data to control

EventList.DataBind();

 

Example 2:  Binding Objects to Complex ASP.NET Controls

A slightly more complex example demonstrates how to bind FDT result objects to an ASP.NET ListView control:

The LoadEventMembers method retrieves the selected Event ID of the Existing Events dropdown, and calls the FDT method Events.GetMembers to return an EventMemberInfo instance containing the RSVP lists (of User IDs) for the specified Event.  The current list of event users is reset, and for each RSVP status, LoadUsers is called.  The LoadUsers method simply issues a request to Users.GetInfo for the current list of User IDs, which in turn populates an instance of our custom EventUser object (used only for binding to the ListView).  A simple sort is performed by last name, and the List is bound to the ListView ASP.NET control:

private void LoadEventMembers()

{

// Get the currently selected Event ID

      long eid;

      if (!long.TryParse(EventList.SelectedValue, out eid)) return;

      if(eid <= 0) return;

 

// Reset

      var eventMemberInfo = _facebookAPI.Events.GetMembers(eid);

 

      // Reset event users

      _eventUsers = new List<EventUser>();

 

      // Load for each response type

      LoadUsers(eventMemberInfo.attending.uid, EventUser.EventUserStatus.Attending);

      LoadUsers(eventMemberInfo.declined.uid, EventUser.EventUserStatus.Declined);

      LoadUsers(eventMemberInfo.not_replied.uid, EventUser.EventUserStatus.NoResponse);

      LoadUsers(eventMemberInfo.unsure.uid, EventUser.EventUserStatus.Undecided);

 

      // Sort by last name

      _eventUsers.Sort((x, y) => x.LastName.CompareTo(y.LastName));

 

      ExistingEventFriendsList.DataSource = _eventUsers;

      ExistingEventFriendsList.DataBind();

}

 

private void LoadUsers(List<long> uids, EventUser.EventUserStatus eventUserStatus)

{

var users = _facebookAPI.Users.GetInfo(uids);

      foreach(var u in users)

      {

            _eventUsers.Add(new EventUser(u, eventUserStatus));

      }

}

 

The markup below demonstrates how to bind our custom object to the ListView and renders the layout of our custom table:

 

<asp:ListView ID="ExistingEventFriendsList" runat="server" DataKeyNames="UserID">

  <LayoutTemplate>

    <table cellpadding="2" border="1" style="margin:6px 0 0 0;">

      <tr id="Tr1" runat="server">

        <th id="Th1" runat="server"></th>

        <th id="Th2" runat="server"></th>

        <th id="Th3" class="ExistingEventResponseCell" runat="server">Attending</th>

        <th id="Th4" class="ExistingEventResponseCell" runat="server">No Response</th>

        <th id="Th5" class="ExistingEventResponseCell" runat="server">Undecided</th>

        <th id="Th6" class="ExistingEventResponseCell" runat="server">Declined</th>

      </tr>

      <tr runat="server" id="itemPlaceholder" />

    </table>

  </LayoutTemplate>

  <ItemTemplate>

  <tr>

    <td>

      <img src="<%# ((EventUser)Container.DataItem).PicSquare %>" height="30px"

           width="30px" alt="profile pic" />

    </td>

    <td valign="top">

      <asp:Label ID="LastNameLabel" runat="Server" Text='<%# string.Format("{0} {1}",

                                   ((EventUser)Container.DataItem).FirstName,

                                   ((EventUser)Container.DataItem).LastName) %>' />

    </td>                   

    <td class="ExistingEventResponseCell">

      <asp:CheckBox ID="Attending" runat="Server" Enabled="false"

                    Checked='<%# ((EventUser)Container.DataItem).IsAttending %>' />

    </td>

    <td class="ExistingEventResponseCell">

      <asp:CheckBox ID="NoResponse" runat="Server" Enabled="false"

                      Checked='<%# ((EventUser)Container.DataItem).IsNotResponded %>' />

    </td>

    <td class="ExistingEventResponseCell">

      <asp:CheckBox ID="Undecided" runat="Server" Enabled="false"

              Checked='<%# ((EventUser)Container.DataItem).IsUnsure %>' />

    </td>

    <td class="ExistingEventResponseCell">

      <asp:CheckBox ID="Declined" runat="Server" Enabled="false"

              Checked='<%# ((EventUser)Container.DataItem).IsDeclined %>' />

    </td>                   

  </tr>

  </ItemTemplate> 

</asp:ListView>  

 

For every Event invitee, a record will be added to the ListView with the user’s RSVP status:

invite

 


 

Extended Permissions

Extended Permissions are actions requiring specific voluntary opt-in from the current user.  These methods require a greater level of trust from the user, and must be granted on an individual basis.  The Extended Permissions are:

·         Public_stream

·         Read_stream

·         Email

·         Offline_access

·         Create_event

·         RSVP_event

·         SMS

·         Status_update

·         Photo_upload

·         Video_upload

·         Create_Note

·         Share_Item

For more detail on Extended Permissions, visit http://wiki.developers.facebook.com/index.php/Extended_permission

Requesting Extended Permissions from The User

An application can prompt for an Extended Permission by navigating the user to the facebook authorization url containing the desired extended permission as one of the query parameters.  The sample application requires the create_event extended permission to add new Events: 

NewEventGrantPermission.NavigateUrl =                         string.Format("http://www.facebook.com/authorize.php?api_key={0}&v=1.0&ext_perm={1}", APPLICATION_KEY, Enums.ExtendedPermissions.create_event);

Note: the hyperlink control’s Target should be set (in markup) as “_blank” to pop the NavigateUrl in a new window.

When the user clicks the link, the resulting page is displayed, and access is granted or denied by the user:

extended

 


 

Testing the Application

·         Verify Default.aspx is the startup page, build the solution and Start Debugging (F5).  The Facebook Connect button should appear on the page: (Remember to download the sample project for full source code)

connect

·         Clicking the button will bring up the Facebook Authentication screen:

connect auth

·         Enter the password for your Facebook account and press “Connect”.

After a successful authentication the page will be reloaded and the page should display the Create Event form and Existing Events dropdown.  The user can create new Facebook Events and view the RSVP status of any of the user’s current Events.

 

create event

 

Resources

Facebook Developer Toolkit:  http://facebooktoolkit.codeplex.com

Facebook Connect Developer Site:  http://developers.facebook.com/connect.php

Facebook Connect WIKI Page:  http://wiki.developers.facebook.com/index.php/Facebook_Connect

 

Other Useful Links:

http://www.somethingtoputhere.com/therunaround/   (Facebook’s Facebook Connect example site)

http://fbconnectauth.codeplex.com/   (CodePlex Facebook Signature validation project)

http://wiki.developers.facebook.com/index.php/Trying_Out_Facebook_Connect (Intro to Facebook Connect)

http://wiki.developers.facebook.com/index.php/Cross-domain_communication_channel (Cross-domain detail)

 

Bill Konrad’s excellent series on Facebook development with connect:

http://devtacular.com/articles/bkonrad/how-to-integrate-with-facebook-connect

http://devtacular.com/articles/bkonrad/how-to-retrieve-user-data-from-facebook-connect-in-aspnet