Writing Custom Facebook Applications - Creating Your Application with Visual Studio 2010

3/5/2012 11:22:16 AM

1. Creating and Registering Your Application with Facebook

Facebook (www.facebook.com) is a social media networking site launched in 2006 that allows anyone over the age of 13 with a valid e-mail address to create an account. At the time of this writing, Facebook had approximately 400 million users, a number that is growing rapidly.

After you have an account on Facebook, you can join any number of networks created according to geographical location, workplace, church affiliation, high school or college, and so on. Once on Facebook, you can search for classmates, coworkers, colleagues, or any other person you want to keep in touch with. To connect with another user, you simply ask that person to be your friend; if he accepts, you're now connected. After you're connected, you and your new friend can begin sharing messages and photos. You can also see who the friends of your friends are so that in no time you have developed a substantial social network of friends, coworkers, colleagues, and any other person that shares the same interests as you.

Applications such as games, quizzes, puzzles, and others have become popular on Facebook. The applications allow you to share information with others on Facebook as well as interact directly with other users while you are playing. Besides games, you can create any other kind of application and utilize Facebook information to enhance the experience of that application. Say, for example, you have a mapping application where users can enter someone's location and see on a map where that user lives. With Facebook, you can get information for all your friends and place a pin on the map for each user's location. So now at a glance you can see where all of your Facebook friends are living.

Facebook allows any registered user to develop applications for Facebook. If you don't have an account on Facebook, you can create one for free at www.facebook.com. Before your code can use the Facebook platform, you first have to create and register the application with Facebook. Facebook requires you to give them some information about your application and also your contact information so they may contact you about your application if necessary.

To create an application on Facebook, you go to http://developers.facebook.com/get_started.php. The Facebook developers page opens. Here, you find all the information needed to get you started with your application, including a detailed description of configuration options for your application. Most importantly, you need an ApplicationPrivateKey and ApplicationSecret for your application to connect to Facebook. The ApplicationPrivateKey and ApplicationSecret let Facebook know about your application and that it has authorized access to Facebook information.

2. Creating Your Application with Visual Studio 2010

Facebook provides a developer Software Development Kit (SDK) for application development. The current version is 3.0, and you can download this SDK from the CodePlex site at http://facebooktoolkit.codeplex.com. Once downloaded, you can extract the SDK to any directory you choose. After it's installed, your SDK directory looks something like Figure 1.

In this example, you create an ASP.Net application that provides the current weather forecast for the logged-in user, as well as the current weather forecast for a friend's current location. The weather forecast data come from Google.

Figure 1. Files installed for the Facebook SDK.

You can download the complete program for this example from this book's companion Web site at www.dummies.com/go/vs2010.

Creating a Facebook application is as simple as creating any other type of application with Visual Studio. To create an ASP.NET Facebook Web application:

  1. Choose File=>New=>Project and choose the ASP.Net Web Application from the list of project templates under Visual C#.

    Visual Studio creates a new C# ASP.Net Web Application.

  2. From the Solution Explorer, right click the References node and choose Add New Reference from the context menu.

    The File Open dialog box appears.

  3. Navigate to the directory where you installed the Facebook SDK and choose the files Facebook.dll and Facebook.Web.dll.

    You should see these references in the Solution Explorer, as shown in Figure 2.

The Facebook SDK supports Web, desktop, and mobile development. The Facebook.dll contains the main classes used for the Facebook SDK. The Facebook.Web.dll adds classes that developers use to create ASP.Net Web applications. There is also Facebook.Silverlight.dll for Silverlight applications and Facebook.Winforms.dll for Windows Forms desktop application development.

Figure 2. Solution Explorer shows the references for the Facebook SDK.

2.1. Writing your application code

After you have an ASP.Net project created and the necessary Facebook assemblies referenced in the project, you can get to work writing your application code.

To begin, you need to provide Facebook with the ApplicationPrivateKey and ApplicationSecret codes you obtained when you created and registered your application with Facebook. Without these keys, your application won't be able to connect to Facebook. A simple way of providing these keys to Facebook is to put them in your web.config file:

    <add key="APIKey" value="Your Application Key"/>
    <add key="Secret" value="Your Application Secret"/>
    <add key="Callback"value=" http://localhost:5795/Weather2.aspx"/>
    <add key="Suffix" value="mylocalweather"/>

Don't share your application key or application secret with those who aren't developing your application. Doing so allows unscrupulous application developers to impersonate your application on Facebook, possibly causing your account to be revoked and damaging your reputation.

The Callback and Suffix keys tell Facebook how to call back to your application. Users access your application though Facebook, which then uses the Callback key to know which page of your application to load. The Suffix key is the suffix you want Facebook to use in the URL to access your application. In this example, the suffix is mylocalweather. When users access your application on Facebook it uses the URL http://apps.facebook.com/mylocalweather to load your application.

Facebook then calls into this application by loading the page specified in the Callback key, and your application executes and serves the resulting HTML to Facebook.

To ensure that your application can run in Facebook when launching from Visual Studio 2010, you need to set your project to execute under the same URL and load the page that you provided to Facebook in the Callback key in web.config. Your project settings should look like Figure 3.

Figure 3. Project settings match specific page and specific port settings.

2.2. Connecting your application to Facebook

On Facebook, you can create two types of Web applications: IFrames and Facebook Markup Language (FBML). FBML lets you quickly start building an application from scratch and has fewer moving parts making it easy for the beginning developer. IFrames applications are easier and faster if you have an existing application or widget developed. IFrames applications are also faster than FBML applications and allow you to use JavaScript, HTML, and CSS as well as popular JavaScript libraries like jQuery. You can find more information at http://wiki.developers.facebook.com/index.php/Choosing_between_an_FBML_or_IFrame_Application.

This example is an IFrames Facebook application. To allow your application to connect to Facebook, modify your Site.master.cs code file to have your master page class derive from Facebook.Web.CanvasIFrameMasterPage:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CurrentLocalWeather
    public partial class SiteMaster : Facebook.Web.CanvasIFrameMasterPage
        public SiteMaster()
            RequireLogin = true;
        protected void Page_Load(object sender, EventArgs e)


Set RequireLogin to true so that your application requires users to be logged in for your application to access Facebook information. Without being logged in, your application will be limited on the information it can access.

Now your application has all it needs to connect to Facebook. The CanvasIFrameMasterPage class contains all the plumbing necessary for connecting to and authenticating your application on Facebook.

2.3. Laying out your application

After your application is connected to Facebook, you'll want it to do some real work. First, you need a page to display to the user when Facebook loads your applicationChoose Project=>Add New Item=>Web Form using Master Page and call the Master Page Weather2.aspx.

Next, to create a reusable Web User Control that does the work of accessing and displaying the weather data from Google, choose ProjectAdd New Item, select Web User Control, and call it WeatherControl.ascx. This control contains text labels and image server controls to display forecast data and images associated with the forecast information.

You also can create style sheets to control the rendering of the HTML for this Web User Control. The following listings show the HTML and CSS code to render the Web User Control.


    width: 350px;
    margin-left: auto;
    margin-right: auto;
    font-family: Segoe UI Arial Lucida Sans Unicode Sans-Serif;
   text-align: center;
   width: 100px;
   margin-left: auto;
   margin-right: auto;
    text-align: center;
    width: 100px;
    margin-left: auto;
    margin-right: auto;

    float: left;
    width: 60px;
    border: 1px solid #999;
    margin: 0 15px 15px 0;
    text-align: center;
    clear: both;


.ascx code:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WeatherControl.ascx.
    cs" Inherits="CurrentLocalWeather.WeatherControl" %>

<div class="thumbnail">
       <asp:Image ID="CurrentProfileImage" runat="server" Height="60px"
    Width="60px" /><br />

      <asp:Label ID="CurrentProfileName" runat="server" Text="" Font-
    Names="Segoe UI"></asp:Label>

   <div class="current_container">


<div class="current">
        <asp:Image ID="CurrentConditionsImage" runat="server" Height="60px"
       Width="60px" /><br />

       <asp:Label ID="CurrentTempLabel" runat="server" Text="Current Temp"
              Font-Names="Segoe UI"></asp:Label><br />
      <div class="city">
      <asp:Label ID="City" runat="server" Text="City" Font-Names="Segoe UI"></
      <br />

      <div class="thumbnail">
      <asp:Label ID="ForecastLabel1" runat="server" Text="Label" Font-Names="Segoe
       UI"></asp:Label><br />

          <asp:Image ID="ForecastImage1" runat="server" Height="60px" Width="60px"
       /><br />

      <asp:Label ID="ForecastTemp1" runat="server" Text="Min/Max" Font-Names="Segoe


      <div class="thumbnail">
        <asp:Label ID="ForecastLabel2" runat="server" Text="Label" Font-Names="Segoe
        UI"></asp:Label><br />

            <asp:Image ID="ForecastImage2" runat="server" Height="60px" Width="60px"
        /><br />

      <asp:Label ID="ForecastTemp2" runat="server" Text="Min/Max" Font-Names="Segoe


      <div class="thumbnail">
         <asp:Label ID="ForecastLabel3" runat="server" Text="Label" Font-
        Names="Segoe UI"
              ></asp:Label><br />

      <asp:Image ID="ForecastImage3" runat="server" Height="60px" Width="60px" /><br

      <asp:Label ID="ForecastTemp3" runat="server" Text="Min/Max" Font-
     Names="Segoe UI"></asp:Label>


      <div class="thumbnail">
        <asp:Label ID="ForecastLabel4" runat="server" Text="Label" Font-Names="Segoe
              ></asp:Label><br />

        <asp:Image ID="ForecastImage4" runat="server" Height="60px" Width="60px"
      /><br />


<asp:Label ID="ForecastTemp4" runat="server" Text="Min/Max" Font-Names="Segoe



   <div class="spacer">

<asp:Label ID="Label1" runat="server" Text="Select Friend:"></asp:Label>

   <asp:DropDownList ID="DropDownFriendList" runat="server" AutoPostBack="True"
    Font-Names="Segoe UI"


After you insert your server controls and define your layout and styles, you can start coding to make it all work. In the code behind file WeatherControl.ascx.cs, you write the C# code that accesses the weather data and populates the server controls.
  •  Xen Virtualization : Installing Xen from Source
  •  Xen Virtualization : Installing Xen from Binary Packages
  •  Introducing IBM BPM and ESB : IBM SOA Reference Architecture & Introducing IBM WebSphere Process Server
  •  Introducing IBM BPM and ESB : Achieving success through BPM enabled by SOA
  •  Separating BPM and SOA Processes : Example-Process for Handling Credit Card Disputes
  •  Separating BPM and SOA Processes : The Model Stack & Design Tips on Separating BPM and SOA
  •  BizTalk 2006 : Editing and Resubmitting Suspended Messages (part 2) - Pseudo-Walkthrough to Perform Edits and Resubmits
  •  BizTalk 2006 : Editing and Resubmitting Suspended Messages (part 1)
  •  BizTalk 2006 : Building a Resequencing Aggregator
  •  Windows System Programming : Listing Registry Keys and Contents
  •  Windows System Programming : Registry Management
  •  .NET Debugging : PowerDbg (part 2) - Send-PowerDbgCommand & Extending PowerDbg
  •  .NET Debugging : PowerDbg (part 1) - Installing PowerDbg & Analyze-PowerDbgThreads
  •  Sharepoint 2010 : Business Connectivity Services Deployment Types (part 3) - Configure Indexing & Performing a Search
  •  Sharepoint 2010 : Business Connectivity Services Deployment Types (part 2) - Creating a Profile Page to Display BCS Results
  •  Sharepoint 2010 : Business Connectivity Services Deployment Types (part 1) - Code-Based Solutions
  •  Sharepoint 2010 : BCS Architecture - Presentation & Core Components
  •  Collaborating via Web-Based Communication Tools : Evaluating Instant Messaging Services
  •  Collaborating via Web-Based Communication Tools : Evaluating Web Mail Services
  •  Developing the SAP Data Center : Data Center Physical Requirements
    Top 10
    Windows Vista : Installing and Running Applications - Launching Applications
    Windows Vista : Installing and Running Applications - Applications and the Registry, Understanding Application Compatibility
    Windows Vista : Installing and Running Applications - Practicing Safe Setups
    Windows Server 2003 : Domain Name System - Command-Line Utilities
    Microsoft .NET : Design Principles and Patterns - From Principles to Patterns (part 2)
    Microsoft .NET : Design Principles and Patterns - From Principles to Patterns (part 1)
    Brother MFC-J4510DW - An Innovative All-In-One A3 Printer
    Computer Planet I7 Extreme Gaming PC
    All We Need To Know About Green Computing (Part 4)
    All We Need To Know About Green Computing (Part 3)
    Most View
    All You Need To Know About iOS 6 (Part 3)
    Upgrade Power - Guidelines For PSU Buyers (Part 4) - Cooler Master Silent Pro Gold 800W, Corsair Enthusiast Series Modular TX850M
    Just My Type (part 2) - ZAGGfolio,Writer Plus, keyPAD, Professional Workstation
    VLC Player : What Tricks This Great Little Player Can Do
    How To Buy…A NOTEBOOK PC (Part 2)
    Design and Deploy High Availability for Exchange 2007 : Design Edge Transport and Unified Messaging High Availability
    ROG G55VW Gaming Laptop
    The Best iPad Cases
    Troubleshooting Reference : Tablets & Smartphones
    Externalizing BLOB Storage in SharePoint 2010 (part 1)
    Dell Inspiron 14R 5420 Review (Part 1)
    Top 10 Smartphones August – September (Part 1) - Samsung Galaxy S III, HTC One X, Apple iPhone 4S,Nokia Lumia 800,Sony Xperia S
    H8-1090D Desktop PC - Elite Class
    Ditch Your Laptop For Your Phone (Part 2)
    Algorithms for Compiler Design: THE ARRAY REFERENCE
    Managing SharePoint 2010 Data : Content Types
    Seagate Backup Plus Portable HDD
    Samsung LED TV ES8000 - The SMART in Smart TV
    Lenovo IdeaPad Z580 - Keeps Up The Tradition
    Windows Server 2008 Server Core : Working with Scripts - Using the Scripting Objects