Welcome to Pete Brown's 10rem.net

First time here? If you are a developer or are interested in Microsoft tools and technology, please consider subscribing to the latest posts.

You may also be interested in my blog archives, the articles section, or some of my lab projects such as the C64 emulator written in Silverlight.

(hide this)

How to Build Facebook Applications with Silverlight 2 RTW – Part 1 of 2

Pete Brown - 16 October 2008

I’m about to embark on some very different Silverlight application development projects (primary around data-driven UI, and one potential one even about kiosk/digital sign work). Before I do that, I wanted to give you all a brain-dump primer from my last project – MSDN East Coast News.

MSDN East Coast News is a Silverlight 2 application which runs inside the Facebook chrome, ergo a two-parter on building Facebook apps with Silverlight.

Note. If you’re interested in more information, or have questions, be sure to join the MSDN geekSpeak on October 22, 2008, where I’ll be covering this topic. I’ll also have a session at the Fall CMAP Code Camp for all the locals.

Architecture Overview

We’re going to build an application that has Silverlight on the client, surfaced through an iframe in Facebook, and which uses a WCF service to proxy calls to the Facebook API through our own server.

See the post I did on MSDN East Coast News for additional architecture information for a real application.

Background Work and Plumbing

Create the Facebook Application

First, make sure you add the Developer application in Facebook. The dev app is what allows you to create, configure and manage your own applications.

Once in the developer application, click the “Set Up New Application” button

image

Next, you want to enter the application name

image

Submit at this point, as we’ll need to do some more local work before we can complete the remaining fields. Once you submit, you’ll see this page:

image

The most important information on that page is the API key and Secret. Note that you probably won’t have the canvas URL set yet, I skipped ahead a step when I started this app :)

Install the Toolkit and Starter Kit

If you haven’t yet done them, there are two more key steps you’ll want to do:

  1. Download and install the Facebook Developer Toolkit for .NET
  2. Download and install the Facebook Developer Toolkit Starter Kit

The are other toolkits and options available, but I found that combination the easiest to use to get up and running quickly. However, be warned: none of the toolkits offer the entire API surface area Facebook provides, in part because that is a moving target.

The starter kit hasn’t been updated in a bit, but still serves as a good starting point for your app development. Keep in mind that you can always do plain old REST-based API development if you wish.

Create the Visual Studio Solution

Open up Visual Studio 2008 and create a new web site:

image

Click “Yes” when prompted to upgrade the site to .NET 3.5 from 2.0. We’ll be using some 3.5 goodies in our application.

image

You’ll then be presented with the starter kit readme. The configuration is slightly more involved with the new API, but the information there is still generally correct and important. To keep things clear, I’ll go through the configuration options we use further on in this post.

Correct the References

Remove the Facebook references from your web site’s bin folder. Now right-click and add a reference to the facebook.dll, facebook.web.dll, and Microsoft.Xml.Schema.Linq.dll from the place where you unpacked the Facebook Developer Toolkit.

image

Set appKey and Secret in Web.Config

Now crack open the web.config and locate the appkey and secret values in the configuration sections. You’ll need to paste in the values from your facebook developer application page. Put the API Key in the appkey value and the secret in the secret.

<add key="appkey" value="aa442b07602d1e8e5ecd311dbcf180db"/>
<add key="secret" value="bigoldhexkeygoeshere"/>

As the name suggests, keep your secret a secret from anyone outside your development team. Otherwise, other people can impersonate your application.

Pin Your Port

Since we’re going to have to rely on a known port when debugging your application, we’ll need to keep Visual Studio from changing the numbers around. Select your web site in the project explorer and change “Use dynamic ports” to False. Take note of the port number while you’re there.

image

Configure the Facebook Application

Next we need to tell Facebook how to instantiate our application. In the Facebook Developers app, select your new application and view the property page for it. On that page, select “Edit Settings”. Here are the key settings you’ll need:

Callback URL This is the URL to your site on your own server. Do not leave off the trailing slash or you’ll likely get the unfortunate result of an infinite loop of redirects.

For development and debugging, this is where we put in our local webserver’s address:
http://localhost:41038/FacebookGeekSpeakDemo02/

All facebook URLs in your application will be relative to this.
Canvas Page URL This is the unique URL for your application on Facebook. Logically, this will map directly to the callback URL.

Pick a unique name for your application and plop it in this field.
FBML/iframe radio buttons For a Silverlight app that you wish to be able to debug locally, you’ll need to use an iframe. This is a plus in that you can shove most any content inside the iframe. It’s a minus in that you lose some of the interesting facebook FBML-only functions like the share button.

For this example, choose iframe
Application Type Website
Can your application be added on Facebook? Yes (if you leave this at “no” you will not get the Installation Options)
Icon Create a small icon (jpg, gif or png) for use in facebook and set it here. This is the icon that will be used in application lists and in the short story format for stories posted by your application
Logo This is the larger logo you’ll see in medium/long stories as well as in other places in facebook. This should bear some resemblance to the small icon so that they are obviously connected.
Developer Mode (under Installation Options) Check the box to only allow developers to install the application. We can revisit the other options later.

Save the options

Fix API Breaking Changes in Your Application

Now go back to your solution and compile. You’ll notice three errors due to changes in the API since the creation of the template:

image

In Site.master.cs, change the using Facebook.Web.Controls statement to

using facebook.web;

In the same file, change the code in Page_Init to

base.API.ApplicationKey = ConfigurationManager.AppSettings["appkey"];
base.API.Secret = ConfigurationManager.AppSettings["secret"];

Next, in default.aspx, change the content to look like this:

<%@ Page Language="C#" MasterPageFile="~/Site.master" 
         AutoEventWireup="true" 
         CodeFile="Default.aspx.cs" Debug="true" 
         Inherits="_Default" Title="Untitled" %>

<%@ Register Assembly="facebook.web" 
             Namespace="facebook.web" TagPrefix="cc1" %>

<asp:Content ID="Content1" 
             ContentPlaceHolderID="MainContentPlaceHolder" 
             runat="Server">
             
  <h1>ASP.NET Starter Kit Application</h1> 
  <asp:PlaceHolder ID="friendNames" runat="server" />
</asp:Content>

Now do a global search and replace in your project for:

using Facebook

Replace with

using facebook

Then go into Default.aspx.cs and replace “using facebook.Entity” with “using facebook.Schema” and using “using facebook.WebControls” with “using facebook.web”

Next, replace “FacebookAPI” with “API”

Finally, we’ll change the code in Page_Load and SelectedIndexChanged and change FacebookAPI to API. The resulting Default.aspx.cs should look like this:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Web;
using facebook;
using facebook.Schema;
using facebook.web;

public partial class _Default : System.Web.UI.Page
{
    API facebookAPI;

    protected void Page_Load(object sender, EventArgs e)
    {
        facebookAPI = ((CanvasIFrameMasterPage)Master).API; 

        if (!IsPostBack)
        {
            // Use the FacebookService Component to populate Friends
            IList<user> Friends = facebookAPI.friends.getUserObjects();
            for (int i = 0; i < Friends.Count; i++)
                friendNames.Controls.Add(new System.Web.UI.LiteralControl(Friends[i].first_name.ToString() + "<br/>"));
        }
    }

    /// <summary>
    /// In IE, if a parent frame has a different domain than the child page, the session data 
    /// (stored in the Session object) is not preserved as a security precaution.
    /// http://wiki.developers.facebook.com/index.php/ASP.NET
    /// </summary>
    /// <param name="e"></param>
    protected override void OnPreRender(EventArgs e)
    {
        Response.AppendHeader("P3P", "CP=\"CAO PSA OUR\"");
        base.OnPreRender(e);
    }
}

That takes care of all the API breaking changes. I know that was a lot of annoying little changes, but I don’t control the source to the starter kit. I had planned to create my own Silverlight Facebook starter kit but had too many other things come up.

Test Your Application

Open a browser and point to www.facebook.com, making sure you are logged in with the “keep me logged in” option. If you are logged-out, development gets a bit messier.

Now run the application. You’ll be prompted by Facebook for permission for the application to access your information. Grant it.

Until Facebook fixes it, you’ll also get a “channelManager is undefined” javascript error. As annoying as that error is, there’s nothing you can do about it right now as it is an error with their own code. Just skip past it.

image

You should get something that looks like this (but with your friends’ first names)

image 

If you see something like that, great! You now have a working Facebook application. Part 2 will cover how to integrate Silverlight into your solution.

The code from this half of the sample is available here. Remember to change the apikey and secret to the ones in your application.

     
posted by Pete Brown on Thursday, October 16, 2008
filed under:      

23 comments for “How to Build Facebook Applications with Silverlight 2 RTW – Part 1 of 2”

  1. Devin Rosesays:
    I am going through the tutorial currently, Pete, and so far all has worked great.

    One small bug in the tutorial: When copying the code from Default.aspx.cs on this webpage, the intellisense light bulb gets copied as "Idea" and so the code reads FriendIdea.first_name and doesn't compile. I changed the line to:

    friendNames.Controls.Add(new System.Web.UI.LiteralControl(Friends[i].first_name.ToString() + "<br/>"));

    adding in the Friends[i] which must be what your code actually said, and all is well.

    If I run into anything else, I will let you know. The only other small confusion on my part was the link to Steve's blog that has the Facebook Developer Toolkit Starter Kit:
    "Download and install the Facebook Developer Toolkit Starter Kit".

    That page has several links that have toolkit or starter kit or both in them and it is a bit confusing as to which one you mean. I figured it out but was briefly befuddled.

    Thanks again!
  2. Pete Brownsays:
    Thanks Devin. I'll modify the article soruce to remove the lightbulb. That's really odd that it made it through the "paste from Visual Studio" setting. I'm not sure if it was LiveWriter or CommunityServer that did that. It should read
    Friends[i].first_name.ToString()

    Steve's site/blog is hard for me to negotiate. He has great material there, but the structure is a bit lacking. I've considered building my own starter kit, but just haven't had the time.

    In any case, I'm glad you found the starter kit :)

    Pete
  3. Hocsays:
    I got this below error in line 21. Anyone knows why?

    Session key invalid or no longer valid
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: facebook.Utility.FacebookException: Session key invalid or no longer valid

    Source Error:

    Line 19: {
    Line 20: // Use the FacebookService Component to populate Friends
    Line 21: IList<user> Friends = facebookAPI.friends.getUserObjects();
    Line 22: for (int i = 0; i < Friends.Count; i++)
    Line 23: friendNames.Controls.Add(new System.Web.UI.LiteralControl(Friends[i].first_name.ToString() + "<br/>"));


  4. Joansays:
    Hi

    Can you help me out?

    Is it possible to access user's score count of an FB App Game via IFrame?

    Do we need to host our app if I want my friend's to add the application?

    pls reply
  5. Pete Brownsays:
    @Joan

    I don't believe you can access the data for any other applications in facebook, unless you wrote the other app.

    You just about always need to host a Facebook application somewhere, so yes, you would need to host it.

    Pete
  6. Joansays:
    Hey TPete,


    i know it would not be pretty fair to give another post about an FB App i started to create.But seriously I did not what to do either.I have the following code :


    facebookAPI = ((CanvasIFrameMasterPage)Master).API;
    facebookAPI.data.createObjectType("FBGameApp");
    facebookAPI.data.defineObjectProperty("FBGameApp", "UserName", 1);
    facebookAPI.data.defineObjectProperty("FBGameApp", "GameScore", 2);


    and getting the error:

    facebook.Utility.FacebookException: Invalid parameter: name: FBGameApp at facebook.API.SendRequest(IDictionary`2 parameterDictionary, Boolean useSession) at facebook.API.SendRequest(IDictionary`2 parameterDictionary) at facebook.data.createObjectType(String name) at _Default.defineFBObjects() in c:\GameDemoApp\Default.aspx.cs:line 63


    I really don't what to do.. can you help?


    AM terribly sorry if this mail had bothered you in anyway.Do the Facebook Storage API's work anyway?How else to store & retrieve information? Database?

    Thanks
    Joan
  7. Hiteshsays:
    Hi greate article.I have Also developed same application but I am not able to submit it on facebook.For submitting this app it requires 5 users.for adding users for my app what should I have to do?
  8. Deepssays:
    Hi,

    Thanks a ton for the application, I am getting an error message as

    'The page you requested was not found.'

    Does that mean I need to reset the secret key and canvas URL.

    Please let me know.

    Thanks
  9. Anonymoussays:
    Has anyone not used the canned API on CodePlex and rolled their own Auth? I'd be interested to see how you did this and caught the session after the user logs into Facebook then redirect to another page other than the callback on your hosted site.

    We are not using either of the Facebook APIs. We want control of our code. Also, we're not going to use something that Clarity Consulting developed (Facebook Developer Toolkit)...would not touch anything they develop with a 100 foot pole.
  10. Bensays:
    Thanks for the wonderful article, Pete! This is just what I needed to put a Silverlight on Facebook. Anyway, the updated Starter Kit by Steve Trefethen has rendered small part of your post irrelevant (e.g. API breaking changes with facebook namespace). If you get time later you may consider updating this a little bit :)

    Nice work there, keep it up!
  11. flouzjesays:
    Hi,

    I'm looking for a way to connect to facebook from a webservice. (I want to update the facebook stream, based on some input I received on my site)
    I'm not looking for a user interface Iframe integration, but just for a way to connect to facebook by supplying app id & secret I want to receive a sessionid.

    I tried Facebook Connect Authentication for ASP.NET from Codeplex but this gives me an error "not signature found". On the facebook developer site I can't find a way to authenticate myself either. Anybody can help me please, it's driving me nuts.

    Thanks
  12. Alex Limpaechersays:
    Are there any new online tutorials for combining Facebook and Silverlight that uses Silverlight 4.0 and the Facebook C# SDK? I'm assuming the instructions here might be a bit out of date.

    Thanks!
  13. Petesays:
    @Alex

    These are definitely out of date. Facebook changed their API surface area so many times, that most authors just stopped updating their toolkit/wrappers. I haven't seen anything in quite a while, truthfully.

    Pete

Comment on this Post

Remember me

9 trackbacks for “How to Build Facebook Applications with Silverlight 2 RTW – Part 1 of 2”

  1. POKE 53280,0: Pete Brown's Blogsays:
    In Part 1 , we created a Facebook application using ASP.NET. Now, in Part 2, we’ll cover how to add Silverlight
  2. POKE 53280,0: Pete Brown's Blogsays:
    Be sure to join me, Glen Gordon and Andrew Duthie on October 22 for our MSDN geekSpeak . We’ll be covering
  3. Community Blogssays:
    In this issue: Tim Heuer, Pete Brown, Mike Taulty, NikhilKothari, Dan Wahlin, Laurence Moroney, Arturo
  4. Khurram Azizsays:
    Announcements http://weblogs.asp.net/scottgu/archive/2008/10/14/silverlight-2-released.aspx http://www.hanselman.com/blog/Silverlight2IsOut.aspx
  5. Khurram Azizsays:
    It is a Wiki-Like-Page listing Silverlight Resources for beginners (like me), I will keep it updated as more such resources are discovered or told by community, peers and buddies
  6. Dr. Z's Blogsays:
    Pete Brown has put together a two-part series ( Part I & Part II ) on how to create Facebook Silverlight
  7. POKE 53280,0: Pete Brown's Blogsays:
    The Facebook Developer Toolkit has hit an important milestone: 2.0 RTW. I’m upgrading the MSDN East Coast
  8. gOODiDEA.NETsays:
    .NET Code better – measure your code with NDepend C# Tutorial - Writing a .NET Wrapper for SQLite
  9. Community Blogssays:
    .NET Code better – measure your code with NDepend C# Tutorial - Writing a .NET Wrapper for SQLite