Welcome to irritatedVowel.com Sign in | Help

POKE 53280,0: Pete Brown's Blog

Silverlight, WPF, Woodworking, .NET Programming, CNC, Nature, and other topics.

Pete Brown writes on a number of topics including Silverlight, WPF, .NET, woodworking and working as a consultant in the DC area. On most forums, Pete goes by the name Psychlist1972. Pete has worked at Applied Information Sciences (AIS) since 1996 where he currently performs as a lead architect and project manager.

Subscribe to my feed

Add to Technorati Favorites
Applied Information Sciences - My Employer

Community Events



World Domination

who's online

Networks


View Pete Brown's profile on LinkedIn

AddThis Social Bookmark Button

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

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(FriendsIdea.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.

  Add to Technorati Favorites
Posted: Thursday, October 16, 2008 12:27 AM by Pete.Brown
Filed under: , ,

Comments

Pete.Brown said:

I'll most likely post part 2 tomorrow night (evening of the 16th). It's half completed already.

Pete

# October 16, 2008 1:03 AM

Hillwaaa said:

Great article - I look forward to the second part!
# October 16, 2008 5:05 AM

Devin Rose said:

Yes! This is exactly what I want to do next: build a silverlight facebook app. Thanks a ton for sharing your experience building one. Let's light up the web!
# October 16, 2008 10:37 AM

POKE 53280,0: Pete Brown's Blog said:

In Part 1 , we created a Facebook application using ASP.NET. Now, in Part 2, we’ll cover how to add Silverlight
# October 16, 2008 11:46 PM

Pete.Brown said:

@Devin

Part 2 is now up. Enjoy!

Pete

# October 17, 2008 12:54 AM

POKE 53280,0: Pete Brown's Blog said:

Be sure to join me, Glen Gordon and Andrew Duthie on October 22 for our MSDN geekSpeak . We’ll be covering
# October 17, 2008 12:47 PM

Community Blogs said:

In this issue: Tim Heuer, Pete Brown, Mike Taulty, NikhilKothari, Dan Wahlin, Laurence Moroney, Arturo
# October 18, 2008 1:26 AM

Devin Rose said:

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(FriendsIdea.first_name.ToString() + "
")); adding in the FriendsIdea 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!
# October 18, 2008 3:09 PM

Pete.Brown said:

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

FriendsIdea.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

# October 18, 2008 4:44 PM

Pete.Brown said:

Turns out it was community server doing autoreplace on "smilies". Fixed for folks who find the article now.

Pete

# October 18, 2008 4:50 PM

Khurram Aziz said:

Announcements http://weblogs.asp.net/scottgu/archive/2008/10/14/silverlight-2-released.aspx http://www.hanselman.com/blog/Silverlight2IsOut.aspx
# October 20, 2008 4:00 PM

Khurram Aziz said:

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
# October 20, 2008 4:28 PM

John Smith said:

This information seems really useful. I hope this will help me out.
# October 28, 2008 7:21 AM

Dr. Z's Blog said:

Pete Brown has put together a two-part series ( Part I & Part II ) on how to create Facebook Silverlight
# October 28, 2008 4:57 PM

Hoc said:

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 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() + "
"));
# October 29, 2008 1:20 AM

Joan said:

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
# November 4, 2008 5:19 AM

Pete.Brown said:

@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

# November 4, 2008 9:53 AM

Joan said:

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
# November 5, 2008 8:04 AM

POKE 53280,0: Pete Brown's Blog said:

The Facebook Developer Toolkit has hit an important milestone: 2.0 RTW. I’m upgrading the MSDN East Coast
# November 8, 2008 10:55 PM

gOODiDEA.NET said:

.NET Code better – measure your code with NDepend C# Tutorial - Writing a .NET Wrapper for SQLite
# November 10, 2008 9:37 PM

Community Blogs said:

.NET Code better – measure your code with NDepend C# Tutorial - Writing a .NET Wrapper for SQLite
# November 10, 2008 9:56 PM

Hitesh said:

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?
# November 26, 2008 6:07 AM

Deeps said:

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
# December 15, 2008 12:27 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Enter the text you see in the image:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS