Implement a Facebook photo album using the Flex SDK Skill Level: Intermediate

Joe Lennon ([email protected]) Software Developer Core International

18 Nov 2008

Adobe® has released the free, open source Flex SDK framework to enable developers to create Rich Internet Applications (RIAs). The Flex framework provides you with a method of creating cross-browser, cross-platform Web applications that is quick and simple. Flex applications run in the Flash player, which is installed on the majority of Internet-connected computers, but Flex also provides you with an object-oriented user interface framework similar to Java™ Swing. In this tutorial, develop a Facebook application in Adobe Flex that displays a slideshow of a user's Facebook photo albums. The Facebook application will contain a profile box listing all of the user's photo albums, each a link to a Flex slideshow of that album. The Flex application will use the Facebook REST API to fetch the photos of the selected Facebook album and dynamically generate the slideshow.

Section 1. Before you start

This tutorial is for Web developers who are looking to create interactive Facebook applications using the free Adobe Flex SDK. Although not required, a basic knowledge of PHP, HTML, and development would be of great benefit to readers. No prior experience with Flex development or Facebook development is required.

About this tutorial

This tutorial provides you with a foundation in developing Facebook applications

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 49 developerWorks® .com/developerWorks

using the Adobe Flex SDK and the Facebook development platform. You'll first be introduced to the concepts of Adobe Flex, in particular MXML and ActionScript. Then we'll look at Facebook applications and the tools available to developers, such as FBML (Facebook Markup Language), FQL (Facebook Query Language), and the REST API. Next, we'll set up the development environment by installing the Flex SDK, and I'll explain the structure of a Flex application and show you how to create a Facebook application. We then create a basic Flex application, which lays the foundation for the sample application that follows, a Facebook slideshow application.

Prerequisites

You'll need the following tools to follow along with this tutorial:

• The latest stable build of the Flex 3 SDK. • An account on Facebook with the Developer application added. • A Web server with PHP 5 or later installed. • Facebook PHP Client Library. • Facebook ActionScript API. The latest version is V0.9.1. • Adobe Flash Player Version 9 or later.

Section 2. Introduction to Adobe Flex

I'll start by introducing Adobe Flex and looking at the different options for developing Flex applications, in particular, the free Adobe Flex SDK. We can then look at the technologies used to create a Flex application: MXML and ActionScript.

What is Flex?

Adobe Flex is a framework that allows you to create powerful Flash applications using traditional application development techniques. Flex includes a rich component library that allows you to easily create stunning Rich Internet Applications (RIAs). These applications can be developed using the open source Flex SDK and a basic text editor, such as Notepad. Adobe has a commercial IDE available called Flex Builder, which is based on the platform. In this tutorial, however, we will simply be using the free Flex SDK.

Implement a Facebook photo album using the Flex SDK Page 2 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

What is the Flex SDK?

The Flex SDK is an open source framework that can be used to develop Flash applications using a standards-based language that should be easy to learn for developers of all disciplines. The Flex SDK is available in two forms: the open source Flex 3 SDK and the Adobe Flex 3 SDK. Both are available free of charge, but differ in terms of the license. The open source Flex 3 SDK contains everything you need to develop Flex applications and is entirely licensed under Version 1.1 of the Mozilla Public License (MPL). The Adobe Flex 3 SDK contains everything in the open source Flex 3 SDK, as well as additional components such as the Adobe AIR runtime and the debugger version of the Adobe Flash Player. These additional components are licensed under the Adobe Flex SDK license.

This tutorial only covers the open source Flex 3 SDK. Whichever version you choose to download should not impact your ability to follow along with the sample applications. If you wish to install the debugger version of the Adobe Flash player, you will find a link to more information about doing so in the Resources section.

MXML and ActionScript

MXML is an XML-based user interface markup language that is mainly used to layout a Flex application and to add rich components to it, much like Swing in the Java language. MXML is also used to create data sources and to bind the user interface components to these sources. One of the greatest advantages of MXML is that it allows the developer to create animations, states, transitions, and styles very simply, resulting in reduced UI development time and greater productivity on the development of the application functionality itself. A very useful feature of MXML is its extensible nature, allowing developers to easily create reusable components.

ActionScript is a based on ECMAScript, with syntax similar to that of JavaScript, which should make it relatively simple for Web developers to learn. ActionScript was traditionally used to control Flash animations, but nowadays is used in the creation of full-blown procedural and object-oriented applications. In terms of Flex, ActionScript allows you to provide an application with interactivity, and you will be using it extensively in the sample application later in this tutorial.

MXML files are created with the extension .mxml and can include ActionScript in a CDATA section within tags. Alternatively, ActionScript code can be stored in an external file, with the extension .as. MXML and ActionScript code is compiled into Flash bytecode, resulting in a .swf file. This file can then be included in HTML files or AIR applications and deployed to the Web or to the desktop.

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 49 developerWorks® ibm.com/developerWorks

Section 3. Introduction to Facebook applications

Now let's examine the concept of a Facebook application and the tools that allow you to create these applications and to retrieve data from Facebook.

What is a Facebook application?

Facebook is a social networking site that was launched in 2004. At the time of this writing, Facebook has over 36 million users and, according to Alexa, is the fifth-most visited Web site on the Internet. Facebook allows users to create a profile of themselves with personal information, photos, and so on. It also allows users to communicate with each other using the "Wall", present on every Facebook user's profile.

In 2007, Facebook launched the Facebook Platform, which included a set of tools that would allow developers to create custom applications that interact with Facebook data and that users can add to their profile. At present, over 33,000 Facebook applications are available, including popular applications such as iLike and Scrabble.

Profile boxes and canvas pages

As mentioned, in this tutorial you will create a sample application that resides on a Facebook user's profile. To do this, you will create what is known as a profile box. Profile boxes in Facebook can be added to the Wall or to the Boxes tab of a user's profile and are generally the starting point for a Facebook application. An example of a profile box is the Friends box, highlighted in Figure 1 below.

Figure 1. Facebook profile box

Implement a Facebook photo album using the Flex SDK Page 4 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

A canvas page is a dedicated page for a Facebook application, giving it enough space to present more information than can fit into a profile box. A Facebook application can have an unlimited number of canvas pages. Typically users will navigate to a canvas page by clicking on a link in a profile box. Figure 2 shows an example of a Facebook application (in this instance, the Twitter application) in a canvas page.

Figure 2. Facebook canvas page

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 49 developerWorks® ibm.com/developerWorks

FBML, FQL, and the Facebook API

To build a Facebook application, developers leverage the power of the Facebook Platform's tools, including Facebook Markup Language (FBML), Facebook Query Language (FQL), and the Facebook API. The sample application in this tutorial will use all three of these concepts.

FBML is basically a modified version of HTML, with some new Facebook-only tags added and some tags modified or removed as required. FBML can be used on both profile boxes (using the profile.setFBML API method) and canvas pages. FBML contains many tags that make it simple to include Facebook features and data in your application. Facebook-specific tags in FBML have the prefix "fb". For example can be used to output the name of a Facebook user.

FQL is a query language that allows you to access Facebook data in much the same way as SQL (Structured Query Language) is used to access data in a relational database such as MySQL. The Facebook Platform allows access to a series of FQL tables such as user, photo, album—which contains data about Facebook users—uploaded photos, and photo albums, respectively. See a full list of FQL tables.

The Facebook API is a REST-like interface for accessing Facebook data in your applications. The API is accessed by applications that make POST or GET requests to the Facebook API REST server. The API makes available many methods that allow you to easily retrieve Facebook data about users, profiles, friends, groups,

Implement a Facebook photo album using the Flex SDK Page 6 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

photos, and more. In particular, the fql.query API method allows you to issue FQL statements that return customized results.

To make using the API easier, a number of API clients have been made available. In this tutorial you will be using the Facebook API PHP Client Library to access the Facebook API.

Section 4. Installing components

This section covers the installation of the components required to develop a Facebook application with Flex. First, you will install the open source Flex SDK and set up the required environment variables to simplify compiling your applications. Next, you will create an application on Facebook and configure the Facebook application settings for your sample application. Finally, you will see how a Flex application should be structured and where you need to put the Facebook PHP Client library and Facebook ActionScript API files.

Installing the Flex SDK

This tutorial assumes you are using the Microsoft® Windows® operating system. There should be minimal differences between the procedures outlined here and those that are required to follow this tutorial if you are using Mac OS X or Linux®. To install the open source Flex SDK, you will need to download the SDK from the Adobe Web site (see Prerequisites for a link). Click on Open Source Flex SDK for the latest stable build. If you want to install the debugger version of the Adobe Flash Player and the Adobe AIR runtime, feel free to download the Adobe Flex SDK, but be aware that parts of this package are not under an open source license (see Figure 3).

Figure 3. Flex 3 SDK Downloads page

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 49 developerWorks® ibm.com/developerWorks

The latest version at the time of writing weighed in at 23MB in size. When the download is complete, open the .zip file and extract its contents to C:\flex. Before continuing, make sure that the Java Runtime Environment (JRE) Version 1.4 or higher is installed on your computer and that the java_home/bin directory is in your system's Path environment variable. This can be found by right-clicking My Computer and selecting Properties from the Context Menu. Now click on the Advanced tab and click the Environment variables button (see Figure 4).

Figure 4. Windows Environment Variables properties

Implement a Facebook photo album using the Flex SDK Page 8 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Select the Path row under the System variables section of this screen and click Edit (see Figure 5).

Figure 5. Edit Path System Variable window

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 49 developerWorks® ibm.com/developerWorks

Make sure that the path to the bin directory of your JRE installation is somewhere in the Variable value text box. Also, add a semicolon to the end of this line, and after the semicolon enter C:\flex\bin. This allows you to run the Flex compiler in any directory without having to specify the explicit path to the compiler.

Believe it or not, that's all there is to installing the Flex SDK. To verify that the installation was successful, navigate to C:\flex\samples\explorer and double-click the build batch file. This will compile a sample application that allows you to explore the many different UI components available in the Flex SDK. The compilation process may take several minutes and should look something like Figure 6. When the process is complete the DOS window will close automatically.

Figure 6. Compiling the explorer sample application

When the compilation process is complete, open the C:\flex\samples\explorer\explorer.swf file to view the application. Please note that you will need to have Adobe Flash Player 9 or later installed for the application to work. This same requirement holds for all of the applications created in this tutorial. Figure 7 shows the Explorer application in action.

Implement a Facebook photo album using the Flex SDK Page 10 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Figure 7. Explorer sample Flex application

Creating a Facebook application

To create a Facebook application you will need to have a Facebook account. If you don't have one, you can register for free. You will also need to add the "Developer" application to your Facebook profile. To do this, go to the Facebook Developer Application and click Allow to let the Developer application access your profile. On the Developer application page click the Set up New Application button. This will take you to the New Application form. On this page, ensure that the Optional Fields section is pulled down.

Figure 8. Part of the Facebook New Application form

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 49 developerWorks® ibm.com/developerWorks

In Figure 8 above you can see part of the application form. Don't be daunted by the length; there are only a few settings you need to change:

• Application Name. This is the name of your application. I have called mine fbFlexBook, but you can call yours whatever you like. While you're at it, be sure to check the check box indicating that you have read and agree to the terms of the Facebook Platform. • Callback URL. This is the URL where Facebook will look for the content of your Facebook application. This URL must point to a location on a Web server with PHP installed in order to follow this tutorial. The URL I have entered is for sample purposes only and will not work—you must replace this with your own value. Don't worry if there are no files in the location right now; you will be creating PHP files later in this tutorial that you will need to upload to this location for the application to work. • Canvas Page URL. This is the URL on Facebook where you want your application to be found. It's usually best to give it a URL similar to the application name. This must be unique so, again, you cannot use the

Implement a Facebook photo album using the Flex SDK Page 12 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

value I have supplied here. Be sure to leave the Use FBML option beneath this selected. • Can your application be added on Facebook? You must select "Yes" here or your application will not be able to add a profile box to users' profiles (including your own). • Who can add your application to their Facebook account? Be sure to select the check box next to Users here or your application will not be able to add a profile box to users' profiles (including your own). • Default FBML. Enter something like "Testing the profile box" in here. The sample application will handle the content of the profile box later. • Default Profile Box column. Select Narrow here, as your sample application is simply a list of photo albums and does not need to be wide. Only narrow profile boxes can be added to the new Facebook profile's Wall tab. Wide profile boxes can only be added to the Boxes tab. • Developer Mode. Ensure that this check box is checked so that only you can use the application. If this is not checked, anyone can add your application to their Facebook profile. You can optionally fill out some of the other fields if you wish, but this is not required for the sake of your sample application. You can always change these values later on via the Edit Settings link on the My Applications page. Click Submit to create the Facebook application, which will generate an API key and Shared Secret and bring you to the "My Applications" page for your Facebook application, which should look like Figure 9 (the API key and Shared Secret have been blurred for security purposes).

Figure 9. Facebook My Applications Page for fbFlexBook

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 49 developerWorks® ibm.com/developerWorks

That is all there is to creating a Facebook application. Right now the application doesn't do anything and will return an error if you try to navigate to it. We will return to this application when developing your sample application later in this tutorial, at which point you will be developing some neat functionality.

The Facebook PHP Client Library and ActionScript API

To follow the sample application at the end of this tutorial you need to download the latest version of the Facebook PHP Client Library. Facebook has recently undergone some major changes in terms of how its profile works. As a result, some major changes have been made to the Facebook PHP Client library, so be sure to get the latest version from Prerequisites. If you can log in to your Web server via SSH, you can issue the commands shown in Listing 1 to easily download and extract the tarball directly on the server.

Listing 1. Download and extract the Facebook PHP Client library

wget 'http://svn.facebook.com/svnroot/platform/clients/packages/facebook-platform.tar.gz'

Implement a Facebook photo album using the Flex SDK Page 14 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

tar -xzvf facebook-platform.tar.gz

Alternatively you can download the library from the link shown in Listing 1 above and extract it using an archiving utility that supports .tar.gz files, such as 7-Zip.

In the sample application your slideshow will be retrieving photos from Facebook and will need to access the Facebook API to do so. We will use the Facebook ActionScript API to make our lives easier. Be sure to download the latest source version of this library. Extract the .zip file to a convenient location since you will be copying the "com" folder into your sample application later in this tutorial.

Now that you have downloaded and configured all of the different components required for this tutorial, you'll next create a basic Flex application to get started.

Section 5. Creating your first Flex application

Before diving into creating your sample application, you will first create a Flex application with a very simple example (see Downloads for the source files). You are going to put this example and the slideshow application you build later on in a new folder called projects, which you will place in the C:\flex folder. Within this new folder you will create a new folder called firstApp, which will be the project folder for this application.

Creating the MXML interface

Create a new file called firstApp.mxml in the C:\flex\projects\firstApp folder and open it with your favorite text editor. (Notepad will do fine.) Enter the code as described in Listing 2 in the file and save it.

Listing 2. firstApp.mxml MXML interface

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 49 developerWorks® ibm.com/developerWorks

This code will create a new Flex application with a VBox component that is centered in the application window. Within the VBox component are a button and a text input field. You will now compile this application. To do so, open up the command line prompt (Start>Programs>Accessories>Command Prompt). When the window opens up, enter the command cd \flex\projects\firstApp to navigate to the project folder. Now enter the command mxmlc firstApp.mxml to compile the application. If the process worked correctly, you should see a screen similar to the one shown in Figure 10.

Figure 10. Compiling your first Flex application

To run the application (Adobe Flash Player 9 or newer required), you can simply type firstApp.swf at the command prompt and press Enter. Alternatively you can navigate to the c:\flex\projects\firstApp folder in Windows Explorer and double click on the firstApp.swf Shockwave Flash Object file. The application should be similar in appearance to Figure 11.

Figure 11. Running your first Flex application

Implement a Facebook photo album using the Flex SDK Page 16 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Congratulations! You've got your first application up and running. This application doesn't actually do anything right now, so in the next section you will modify this code and add some ActionScript to respond to a user click on the button.

Creating ActionScript

You are now going to create an ActionScript function that will update the value of the TextInput component with some text when the user clicks the "Push Me!" button. To do this, you need to modify your firstApp.mxml file (see Listing 3).

Listing 3. Adding an ActionScript event handler

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 49 developerWorks® ibm.com/developerWorks

You'll notice that you've added a click attribute to the button. This basically tells ActionScript which function is to be called when the user clicks on a button. In this case you're telling it to call onBtnPushMeClick.

The main change between this listing and Listing 2 is the block, which contains the ActionScript code for this application. You'll also notice the character data

Inside the ActionScript block you have declared a function, onBtnPushMeClick. You have set the return type to void, which basically means that the function does not return a value. Inside the function, you assign the text property of the txtPushed component (our TextInput component) to "You pushed the button!". The combination of these changes should result in the text within the TextInput field being updated when the user clicks the button.

To make sure, you will recompile the Flex application by issuing the command mxmlc firstApp.mxml in the command line window opened earlier (if you closed this window just repeat the steps from the previous section to compile the application). When it has compiled, enter the command firstApp.swf to run the application again. This time, click the button, and the value of the text box should change, as shown in Figure 12.

Figure 12. Running the updated firstApp.swf file

Implement a Facebook photo album using the Flex SDK Page 18 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

That's all there is to creating applications using the Flex SDK. Of course, this example isn't exceptionally useful, but in the next section you will develop an application that provides much more interesting functionality: a Facebook slideshow.

Section 6. Building the sample Facebook application

The sample application you are building in this tutorial is a Facebook application called fbFlexBook. The main application page (and the profile box for the application) will present a list of the user's photo albums on Facebook, each showing the name of the album and how many photos are in that album. Clicking on any of the album names will bring the visitor to a Facebook canvas page that contains a Flex-built slideshow application, which retrieves the photos in the selected album from Facebook and presents them to the user.

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 49 developerWorks® ibm.com/developerWorks

End result

By the end of this tutorial you will have created a profile box for the Facebook application made earlier in this tutorial, which displays a list of the user's Facebook photo albums. This profile box can be seen in Figure 13 below. You will also have created a Facebook canvas page that displays a slideshow of the photos in the album selected by the user (by clicking on one of the albums in the profile box).

Figure 13. Our Facebook application's profile box

This slideshow will automatically move to the next photo after five seconds via a timer you will create. You will have a button to play or pause the slideshow and buttons to move to the next, previous, first, and last photos in the album. When the slideshow changes the photo, the new photo comes into the application with a funky spinning effect. The slideshow will also display the caption for the photo at the top of the application. A screenshot of the slideshow is shown in Figure 14.

Figure 14. Our Facebook application canvas page

Implement a Facebook photo album using the Flex SDK Page 20 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Updating the Facebook profile box

Let's start by creating a PHP page that will display a list of the user's Facebook photo albums. This page will also update your Facebook profile box with the same list of photos by calling the profile.setFBML method of the Facebook API. It is worth mentioning at this point that in order for the list of photos to be updated on the profile box, the main application canvas page will need to be visited. If you want the profile box to be updated automatically you could set up a cron job on your Web server that regularly calls your PHP script.

Now create a new subfolder in the c:\flex\projects folder called fbflexbook. Inside this folder create a subfolder called release. This folder will contain all of the files that are to be uploaded to the Web server (at the location specified as the callback URL for your Facebook application). If you extracted the contents of the Facebook PHP Client Library to your local machine, copy the entire contents of the facebook-platform\ folder from that archive to the release folder. If you used SSH to download and extract the library, you can simply copy the contents of the facebook-platform\php folder to the folder where the callback URL points to.

Now create a new file with your favorite text editor called index.php and save it to

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 49 developerWorks® ibm.com/developerWorks

your release folder. This is the page that will be called when someone visits your Facebook application. Listing 4 contains the contents of index.php.

Listing 4. index.php

require_login(); // Here we use FQL to retrieve the user's albums $fql = "SELECT aid, name, size FROM album WHERE owner = $uid"; $albums = $fb->api_client->fql_query($fql); $fbml = "fbFlexBook Albums:

"; // Now we loop through the albums and add them to our FBML variable foreach($albums as $album) { $fbml .= ''.$album['name'].' ('.$album['size'].')
'; } // Here we set the profile box to show the list of albums $fb->api_client->profile_setFBML(null, $uid, $fbml, null, null, $fbml); // On the main

Implement a Facebook photo album using the Flex SDK Page 22 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

application page we will greet the user. If they have // not yet added the application to their profile a button will show // up that allows them to, and finally we will display the list of albums echo '

Hello, !

'; echo ''; echo $fbml; ?>

The first thing to do in the index.php file is include the Facebook library and assign your API key and shared secret to the variables. Be sure to replace the xxxxxxxxxxxxxxxxxxxx strings with your own API key and secret values or you will get an error. You will also need to replace the "fbflexbook" in the URL http://apps.new.facebook.com/fbflexbook/album.php... to your own application's canvas folder. Be sure to leave the album.php and the rest of the line as is, however, or the links will not point to your slideshow later.

The comments in the code explain pretty thoroughly what each part does. You are using Facebook Query Language (FQL) to retrieve information about the user's photo albums. You are then using the fql_query method of the Facebook client library to process the statement. If you are familiar with MySQL, this statement will look very familiar and reflects just how easy it is to use FQL. The API returns an array which you then loop through with a foreach statement, adding each album as a link to the $fbml variable. You then assign the contents of this variable to the main profile box using the profile_setFBML method of the API, before outputting some content to the actual page itself.

At this point you can upload index.php (and if required, the Facebook PHP client library) to the location on your Web server that the Facebook Application Callback URL setting points to. In my case this is http://www.joelennon.ie/fbflexbook/. Once you have uploaded the index.php file you should be able to use the Facebook application. To do this, log in to your Facebook account and go to the Developer application. In the "My Applications" on the right-hand side of this page, click on the more link next to your Facebook application and click the View About Page link, as highlighted in Figure 15.

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 49 developerWorks® ibm.com/developerWorks

Figure 15. Facebook Developer application

On the About page for your application, click on Go To Application in the top right of the page to navigate to your Facebook application (see Figure 16).

Figure 16. Facebook Application page

Implement a Facebook photo album using the Flex SDK Page 24 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

At this point you will be asked for permission to allow the application access to your Facebook profile, photos, and so on. Click on Allow to grant the application access (see Figure 17).

Figure 17. Allow application access to profile page

As soon as you have granted the application access to your Facebook information, you will be taken to the main page of your Facebook application, which will display a greeting, an Add to Profile button, and a list of photo albums. Please note that the links for each photo album will not work at the moment, but you will be adding this

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 49 developerWorks® ibm.com/developerWorks

functionality later in the tutorial. What you will do now, however, is add this application as a profile box on the Wall tab of your profile. To do this, click Add to Profile, as highlighted in Figure 18.

Figure 18. Our Facebook application (Add to Profile button)

Clicking on this button will pop up a box that asks you to confirm that you want to add the box to your profile and allowing you to add it to either the "Wall and Info Tab" or the "Boxes Tab". Leave the default (Wall and Info Tab) option selected and click Add to add the profile box to your profile (see Figure 19).

Figure 19. Add application to Profile pop up window

Implement a Facebook photo album using the Flex SDK Page 26 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

When you click on the Add button, you will be taken to your profile where you will see your new profile box in all its glory. It will ask you whether you want to Keep or Remove the box. Click Keep, and that's it. Your profile box has been added to the Wall tab of your Facebook profile! The end result should look something like Figure 20.

Figure 20. Our application profile box on the Facebook profile

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 49 developerWorks® ibm.com/developerWorks

So that's all that's involved in creating a Facebook application! As you can see, thanks to the Facebook PHP Client Library and FQL, it is very quick and simple to retrieve data from Facebook and add it to your application. You will be adding a degree of complexity to your Facebook application in the next sections of the tutorial, however, as you create the album page and add the Flex slideshow to it.

Creating the View Album page

The View Album page is where your Facebook application will open your Flex slideshow and display the photos from the selected Facebook photo album. You will be working on building the slideshow itself later, but for now let's set up your View Album page on Facebook.

The View Album page will use the Facebook PHP Client Library to retrieve the name of the selected photo album and the number of photos in the album. It will display these values to the user. Beneath this information you will include a Flash SWF object using the FBML tag, passing the album ID to the Flex application using the flashVars attribute. Finally, at the bottom you will have a link back to the main canvas page for the Facebook application.

Start off by creating a new file in your text editor and saving it as album.php in the same folder as the index.php file you created previously. Enter the code from Listing

Implement a Facebook photo album using the Flex SDK Page 28 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

5 into this file and save it.

Listing 5. album.php

require_login(); // Here we get the album ID from the GET variable aid $aid = $_GET['aid']; // Now we use FQL to get the name and size of the requested albums $fql = "SELECT name, size FROM album WHERE aid = $aid"; $albums = $fb->api_client->fql_query($fql); // Select our album (should only be one result) $album = $albums[0]; echo 'Viewing '.$album['name'].'
'; echo 'There are '.$album['size'].' photo' .($album['size'] > 0 ? 's' : '').' in this album.'; echo '

'; // This displays our Flex application, passing the album

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 49 developerWorks® ibm.com/developerWorks

ID variable to it // NB: You must replace the swfsrc with the URL of the file on your web server echo ''; echo '

'; echo 'Back to fbFlexBook Main Page
'; ?>

Once again, you will need to change the $api_key and $secret variables to your own values or you will get an error. Also, be sure to change the value of the swfsrc attribute of the tag to the location of the application on your own Web server. Don't worry that fbFlexBookApp.swf does not exist for the moment. You will be creating this file next. Once you have finished this, upload album.php to the same location on your Web server as index.php and navigate to your Facebook profile (see Figure 21).

Figure 21. Our Facebook application profile box

Implement a Facebook photo album using the Flex SDK Page 30 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Now click on any of the photo albums (in Figure 21 I have selected my "Boston 2006 4" album with 32 photos in it), and you should see a page that looks like the screenshot in Figure 22.

Figure 22. View Album page of our application

As you can see, the album.php page has picked up the appropriate album ID for the Facebook photo album and has retrieved the name of the selected photo album and how many photos it contains. As soon as you have uploaded the end product (the fbFlexBook.swf Flash object file) to the Web server, your album.php page will show the Flex slideshow below the text highlighted in red.

Creating the slideshow user interface

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 49 developerWorks® ibm.com/developerWorks

You will now proceed with the development of the slideshow user interface using the Flex SDK. You are going to create ActionScript classes to create Photo, Album, and FacebookREST objects from. You will then create a slideshow MXML component which will contain the majority of the UI components for the application. You will then bind this slideshow component to your FacebookREST object in the main application MXML file.

Before you begin coding, you need to set up the project folder in the correct way. In the c:\flex\projects\fbflexbook folder, create a new folder called src. This is the folder that will contain all of the Flex application's source code. Now put the source code for the Facebook ActionScript API in the project folder. When you extract the zip file this library comes in, navigate down through the resulting folder until you find the "com" folder. Copy this entire folder and paste it into your c:\flex\projects\fbflexbook\src folder.

Now you are going to create the package folders for the ActionScript classes. Navigate to the c:\flex\projects\fbflexbook\src\com folder and create a new folder called "ibm". In this folder create a new subfolder called "developerworks". You will be creating the ActionScript classes in this folder.

The first file you will create is the Photo.as ActionScript class file. Open a new file in your text editor and save it as Photo.as in the c:\flex\projects\fbflexbook\src\com\ibm\developerworks folder. The code for this class can be found below in Listing 6.

Listing 6. Photo.as

package com.ibm.developerworks { [Bindable] public class Photo { public var caption:String; public var src_big:String; public function Photo(photo:Object = null) { if(photo != null) { this.caption = photo.caption; this.src_big = photo.src_big; } } } }

Implement a Facebook photo album using the Flex SDK Page 32 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

This class has two properties, caption and src_big and a simple constructor method. The next class you need to create is the Album class. Create another new file, this time calling it Album.as and save it to the same location as the Photo.as file you created a moment ago. Listing 7 shows the content of this file.

Listing 7. Album.as

package com.ibm.developerworks { import mx.collections.ICollectionView; import mx.collections.ArrayCollection; import mx.collections.IViewCursor; [Bindable] public class Album { public var photos:ArrayCollection; public var selected:int; private var photo:Photo; public function Album(album:Object = null) { photos = new ArrayCollection(); if(album != null) { this.selected = 0; for(var i:int = 0; i < album.photos.length; i++) { photo = new Photo(album.photos[i]); photos.addItem(photo); } } } } }

The Album class has two properties, photos, which is an ArrayCollection of photo objects, and selected, which indicates the index of the photo currently selected in the slideshow. In the Album constructor method, you default the selected property to 0 and add each photo passed to the constructor (in Object) from to the ArrayCollection as a Photo object.

The final ActionScript class you need to create is the FacebookREST class. This

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 49 developerWorks® ibm.com/developerWorks

class will be responsible for using the Facebook ActionScript API to connect to Facebook and retrieve the photos for the selected album. You will bind the slideshow control to this class at a later point. This is by far the most complex part of the tutorial, so I will explain this code listing in detail.

Listing 8. FacebookREST.as

package com.ibm.developerworks { import flash.events.*; import mx.collections.ArrayCollection; import mx.collections.IViewCursor; import mx.core.Application; import mx.rpc.events.ResultEvent; import mx.utils.ArrayUtil; import com.pbking.facebook.data.photos.FacebookPhoto; import com.pbking.facebook.delegates.photos.GetPhotosDelegate; import com.pbking.facebook.FacebookSessionType; import com.pbking.facebook.Facebook; public class FacebookREST { private var fb:Facebook; private var flashVars:Object; [Bindable] public var albums:ArrayCollection; public function FacebookREST() { fb = new Facebook(); fb.addEventListener(Event.COMPLETE, onFacebookConnect); flashVars = Application.application.parameters; fb.startWidgetSession(flashVars, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); } private function onFacebookConnect(e:Event):void { if(fb.isConnected)

Implement a Facebook photo album using the Flex SDK Page 34 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

{ fb.photos.getPhotos(null, flashVars.aid, null, onPhotosFound); } } private function onPhotosFound(e:Event):void { var del:GetPhotosDelegate = e.target as GetPhotosDelegate; var photos:ArrayCollection = del is ArrayCollection ? del as ArrayCollection : new ArrayCollection(ArrayUtil.toArray(del)); var temp:ArrayCollection = new ArrayCollection(); var cursor:IViewCursor = photos.createCursor(); while(!cursor.afterLast) { temp.addItem(new Album(cursor.current)); cursor.moveNext(); } albums = temp; } } }

In Listing 8 you create a new class called FacebookREST, importing a series of in-built classes as well as relevant classes from the Facebook ActionScript API for use in the class. You create a bindable variable albums, which is an ArrayCollection that will be returned to the application to be bound to your slideshow control. The constructor method creates a new Facebook object (from the API) and adds an event listener to this object that basically tells it to call the onFacebookConnect method as soon as it has connected to the API. You then retrieve the flashVars and pass them into the startWidgetSession method of the Facebook object, along with the application's API key and shared secret (be sure to swap the xxxxxxxxxx values for your actual API key and secret values or the application will not work!).

The onFacebookConnect function, when called, checks that you are connected to the Facebook API and if you are, it uses the API to retrieve the photos for the selected album ID. Because your Facebook application passes in the flashVar aid to the Flex application, you can retrieve this from the flashVars variable and use it to

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 49 developerWorks® ibm.com/developerWorks

tell Facebook which album you want to retrieve the photos for. When the API has retrieved the photos as required, the onPhotosFound function will be called.

The onPhotosFound function gets the albums retrieved by the API as an ArrayCollection object and you then use an IViewCursor to loop through the results and create Album objects in your albums' ArrayCollection. This ArrayCollection will be used to bind to the slideshow, as you will see very shortly.

Now that you have finished creating the ActionScript classes, you will move on to the development of the slideshow component. This component will combine MXML and ActionScript to produce pretty impressive results. Listing 9 contains the complete code for this component. Create a new text file and save it in the c:\flex\projects\fbflexbook\src folder. Name the file fbFlexBook.mxml.

Listing 9. fbFlexBook.mxml

Implement a Facebook photo album using the Flex SDK Page 36 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

function childrenCreated():void { super.childrenCreated(); t = new Timer(5000, 0); t.addEventListener(TimerEvent.TIMER, onTickTock); } private function onShow():void { // Start the Timer t.start(); } private function onTickTock(event:TimerEvent):void { // When the Timer strikes, we move to the next photo album.selected = (album.selected + 1) % album.photos.length; } private function onBtnPlayPauseClick(event:MouseEvent):void { // When the Play/Pause button is clicked, we check // to see if the timer is running. If it is we stop // it and update our button's label to "Play". If it // is not running we update the button's label to // "Pause" and start the timer. if(t.running == true) { t.stop(); btnPlayPause.label = "Play"; } else { btnPlayPause.label = "Pause"; t.start(); } }

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 49 developerWorks® ibm.com/developerWorks

private function onBtnFirstClick(event:MouseEvent):void { // Navigate to the first photo in the album album.selected = 0; // Restart the timer at 0 resetTimer(); } private function onBtnNextClick(event:MouseEvent):void { // Navigate to the next photo in the album, or // if we are at the end of the album, go back // to the first photo album.selected = (album.selected + 1) % album.photos.length; resetTimer(); } private function onBtnPrevClick(event:MouseEvent):void { // Here we check if we are at the first photo in // the album and if we are we go back to the last // photo in the album, otherwise we just step // back to the previous photo if(album.selected == 0) { album.selected = album.photos.length - 1; } else { album.selected = album.selected - 1; } resetTimer();

Implement a Facebook photo album using the Flex SDK Page 38 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

} private function onBtnLastClick(event:MouseEvent):void { // Navigate to the last photo in the album album.selected = album.photos.length - 1; resetTimer(); } private function resetTimer():void { // Check if the timer is running, if it is we // simply reset it. if(t.running) { t.stop(); t.start(); } } ]]>

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 49 developerWorks® ibm.com/developerWorks

horizontalAlign="center" verticalAlign="middle">

This MXML component consists of a Flex canvas containing a script block, a binding tag, two VBox components, and an HBox component. The canvas component is pretty self explanatory, but it is worth noting that you call the onShow function when the event creationComplete occurs. This function simply starts the slideshow's timer. The script block defines a Bindable album object and a Photo object for the currently selected photo. Each time the timer strikes the event (every 5000 ms or 5 seconds in this case), the onTickTock function is called, which simply changes the photo to the next photo in the album.

The script block also contains a series of functions that handle the events generated when the user clicks on the First, Previous, Play, Pause, Next ,or Last buttons at the bottom of the slideshow. The comments for each of these functions explain their functionality in more detail.

You create a binding for the current photo which you then use in your first VBox component, which contains a Text component for the caption of the currently

Implement a Facebook photo album using the Flex SDK Page 40 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

selected photo. Note that the text of the component is set to {currPhoto.caption}, which basically means the caption property of the currPhoto binding. The next VBox contains the Image component, essentially the heart of the slideshow component. Interesting points to note about the component are the completeEffect="Rotate" and the that are applied to it. These generate the rotation effect each time the image changes and the drop shadow effect to your image. This is an example of how simple Flex makes adding dazzling effects to your applications.

The final section of the component, the HBox, contains the buttons that control the slideshow, in other words, the First, Previous, Play/Pause, Next, and Last buttons. Each button has a click event associated with it that calls the relevant ActionScript function.

You're almost there now. The final file you need to create is the fbFlexBookApp.mxml file. Save this in the same location as the fbFlexBook.mxml file you just created. Listing 10 contains the remaining code for the application.

Listing 10. fbFlexBookApp.mxml

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 41 of 49 developerWorks® ibm.com/developerWorks

{ fb = new FacebookREST(); } ]]>

This file should look familiar as it not so different from the first Flex application you created earlier in this tutorial. When the application is loaded you create and instantiate a new FacebookREST object. You create a bindable album object that you bind to the one (and only) album returned by the FacebookREST object. You then add a new fbFlexBook component (this is the custom slideshow component you created) and bind it to the album object.

Next you will compile the application into a SWF file and upload it to your Web server. You should then be able to run your Facebook application in all its glory.

Running the Facebook application

Despite this application being much more complex in structure than the first application you created, compiling it is just as easy. Open up a Command Prompt window (Start>All Programs>Accessories>Command Prompt) and type cd \flex\projects\fbflexbook\src to change to your project's src folder. Now enter the command mxmlc fbFlexBookApp.mxml, and the Flex compiler will compile the application into a SWF file. You will now copy this file to the release folder. Issue the command copy fbFlexBookApp.swf ..\release to do so. If all went as expected, your command prompt window should look like that in Figure 23.

Figure 23. Compiling the sample application

Implement a Facebook photo album using the Flex SDK Page 42 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

The final step in deploying the application is to upload the fbFlexBookApp.swf file from your release folder to your Web server, in the same location as the album.php and index.php files that you uploaded earlier.

Now if you navigate to your Facebook profile and click on one of the photo albums in the application's profile box, you should see your Flex application in action. Congratulations, you have created a Facebook slideshow application with Flex! The slideshow interface should look something like Figure 24.

Figure 24. The Facebook application in action

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 43 of 49 developerWorks® ibm.com/developerWorks

Suggested improvements to the application

Your application has some useful functionality, but it could easily be extended to provide some more exciting features. The application you have created has been done so in such a manner that makes it easy to extend the slideshow to multiple albums, so a logical next step would be to create a multi-album photo gallery that perhaps allows you to select which album to display from a thumbnail selector in the Flex application itself.

Other features that could be added include:

• A thumbnail photo selector to make moving between photos easier • Use of different funky transitions to make the slideshow more interesting • Controls that allow the user to change the size of the image, to rotate it, or to perform other manipulative actions • Nicer slideshow controls with some attractive icons that appear when the user moves over the photo itself and disappear after a predefined number of seconds

Implement a Facebook photo album using the Flex SDK Page 44 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

• User-defined controls for defining how long a pause to show between each photo • Use of the HTTPService component to search for similar photos on Flickr

Section 7. Summary

This tutorial detailed the Flex SDK and how Flex applications are developed, namely using MXML and ActionScript. You looked at Facebook applications and the technologies that are available to developers who wish to create them, such as FBML, FQL, and the Facebook API.

You used the Facebook PHP Client Library to create a Facebook profile box that returns a list of the user's photo albums. You created a slideshow for these Facebook photo albums using the open source Flex SDK, and you used the Facebook ActionScript API to communicate with Facebook directly from your Flex application.

From the examples in this tutorial you should now be able to create sophisticated and useful Facebook applications using the Flex SDK, as well as general Flex applications using MXML and ActionScript.

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 45 of 49 developerWorks® ibm.com/developerWorks

Downloads

Description Name Size Download method The first example firstApp.zip 152KB HTTP The Facebook Slideshow App fbflexbook.zip 574KB HTTP

Information about download methods

Implement a Facebook photo album using the Flex SDK Page 46 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Resources

Learn •"Integrating Flex into Ajax applications" (Brice Mason, developerWorks, July 2008): Read an article that introduces the Adobe Flex Ajax Bridge (FABridge), a code library that enables an easy and consistent method for integrating Ajax and Flex content. •"Combine the power of WebSphere sMash with Adobe Flex" (Jorge Rasillo and Mike Burr, developerWorks, August 2008): Read an article that shows how a simple application can be enhanced to support a Web 2.0 user interface written in Adobe Flex. •"Access a web service using Flex 2 in Rational Software Architect V7" (Jeff Miller, developerWorks, December 2007): See how easy it is to access Web services using Adobe Flex 2. •"Develop Web services clients with Macromedia Flex" (Leugim Bustelo and Julio Ruano, developerWorks, August 2004): Walk through several examples that map WSDL constructs to Flex declarations. •"Use Ext, and AIR to build desktop applications" (Joe Lennon, developerWorks, July 2008): Use the open source Aptana Studio IDE, the Adobe AIR plug-in for Aptana, and the open source JavaScript framework Ext to build Web applications that run seamlessly on the desktop. •"Mastering Facebook application development with PHP, Rational Application Developer, WebSphere Application Server, and DB2" (Jake Miles, developerWorks, May 2008): Develop a Facebook application using both PHP and Java programming language in this three-part tutorial series. • Visit the Adobe Flex Developer Center. • Flex.org. Visit the community-driven Flex Portal. • Simple Flex Tutorial: Read Pete Freitag's tutorial to learn how to create a simple blog reader in 23 lines of MXML code. • Visit the Facebook Developer Center. • Read An introduction to FBML by Jesse of 20bits.com. • How to Develop a Hit Facebook App: 29 Essential Tools and Tutorials: Learn how to develop a hit Facebook application. • Get the The PHP Manual. • Visit PHP.NET for PHP documentation. • For tutorials on learning to program with PHP, check out the developerWorks

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 47 of 49 developerWorks® ibm.com/developerWorks

Learning PHP series. • Visit IBM developerWorks' PHP project resources to learn more about PHP. • Find a full list of FQL tables. Get products and technologies • Get the Flex 3 SDK. • Get the Facebook PHP Client Library. • Get the Facebook ActionScript API. The latest version is V0.9.1. • Get Adobe Flash Player Version 9 or later. • Get information on installing the debugger version of Adobe Flash. • Innovate your next open source development project with IBM trial software, available for download or on DVD. • Download IBM product evaluation versions, and get your hands on application development tools and middleware products from DB2, Lotus, Rational, Tivoli, and WebSphere. Discuss • Participate in developerWorks blogs and get involved in the developerWorks community.

About the author

Joe Lennon Joe Lennon is a 23-year-old software developer from Cork, Ireland. Joe currently works as a Web application and Oracle PL/SQL developer for Core International, having graduated from University College Cork in 2007 with a degree in Business Information Systems. He lives in Cork with his girlfriend, Jill.

Trademarks

Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States, and/or other countries. Java and all Java-based trademarks and logos are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.

Implement a Facebook photo album using the Flex SDK Page 48 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both. Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.

Implement a Facebook photo album using the Flex SDK © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 49 of 49