49
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 Web application 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

Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Implement a Facebook photo album using the FlexSDKSkill Level: Intermediate

Joe Lennon ([email protected])Software DeveloperCore International

18 Nov 2008

Adobe® has released the free, open source Flex SDK framework to enabledevelopers to create Rich Internet Applications (RIAs). The Flex framework providesyou with a method of creating cross-browser, cross-platform Web applications that isquick and simple. Flex applications run in the Flash player, which is installed on themajority of Internet-connected computers, but Flex also provides you with anobject-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'sFacebook photo albums. The Facebook application will contain a profile box listing allof the user's photo albums, each a link to a Flex slideshow of that album. The Flexapplication will use the Facebook REST API to fetch the photos of the selectedFacebook album and dynamically generate the slideshow.

Section 1. Before you start

This tutorial is for Web developers who are looking to create interactive Facebookapplications using the free Adobe Flex SDK. Although not required, a basicknowledge of PHP, HTML, and Web application development would be of greatbenefit to readers. No prior experience with Flex development or Facebookdevelopment 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

Page 2: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

using the Adobe Flex SDK and the Facebook development platform. You'll first beintroduced to the concepts of Adobe Flex, in particular MXML and ActionScript. Thenwe'll look at Facebook applications and the tools available to developers, such asFBML (Facebook Markup Language), FQL (Facebook Query Language), and theREST API. Next, we'll set up the development environment by installing the FlexSDK, and I'll explain the structure of a Flex application and show you how to create aFacebook application. We then create a basic Flex application, which lays thefoundation 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 developingFlex applications, in particular, the free Adobe Flex SDK. We can then look at thetechnologies used to create a Flex application: MXML and ActionScript.

What is Flex?

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

developerWorks® ibm.com/developerWorks

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

Page 3: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

What is the Flex SDK?

The Flex SDK is an open source framework that can be used to develop Flashapplications using a standards-based language that should be easy to learn fordevelopers of all disciplines. The Flex SDK is available in two forms: the opensource Flex 3 SDK and the Adobe Flex 3 SDK. Both are available free of charge, butdiffer in terms of the license. The open source Flex 3 SDK contains everything youneed to develop Flex applications and is entirely licensed under Version 1.1 of theMozilla Public License (MPL). The Adobe Flex 3 SDK contains everything in theopen source Flex 3 SDK, as well as additional components such as the Adobe AIRruntime and the debugger version of the Adobe Flash Player. These additionalcomponents are licensed under the Adobe Flex SDK license.

This tutorial only covers the open source Flex 3 SDK. Whichever version you chooseto download should not impact your ability to follow along with the sampleapplications. 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 tolayout a Flex application and to add rich components to it, much like Swing in theJava language. MXML is also used to create data sources and to bind the userinterface components to these sources. One of the greatest advantages of MXML isthat it allows the developer to create animations, states, transitions, and styles verysimply, resulting in reduced UI development time and greater productivity on thedevelopment of the application functionality itself. A very useful feature of MXML isits extensible nature, allowing developers to easily create reusable components.

ActionScript is a scripting language based on ECMAScript, with syntax similar to thatof JavaScript, which should make it relatively simple for Web developers to learn.ActionScript was traditionally used to control Flash animations, but nowadays isused in the creation of full-blown procedural and object-oriented applications. Interms of Flex, ActionScript allows you to provide an application with interactivity, andyou 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 aCDATA section within <mx:Script> tags. Alternatively, ActionScript code can bestored in an external file, with the extension .as. MXML and ActionScript code iscompiled into Flash bytecode, resulting in a .swf file. This file can then be included inHTML files or AIR applications and deployed to the Web or to the desktop.

ibm.com/developerWorks developerWorks®

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

Page 4: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Section 3. Introduction to Facebook applications

Now let's examine the concept of a Facebook application and the tools that allowyou 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 thiswriting, Facebook has over 36 million users and, according to Alexa, is the fifth-mostvisited Web site on the Internet. Facebook allows users to create a profile ofthemselves with personal information, photos, and so on. It also allows users tocommunicate with each other using the "Wall", present on every Facebook user'sprofile.

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

Profile boxes and canvas pages

As mentioned, in this tutorial you will create a sample application that resides on aFacebook 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'sprofile and are generally the starting point for a Facebook application. An example ofa profile box is the Friends box, highlighted in Figure 1 below.

Figure 1. Facebook profile box

developerWorks® ibm.com/developerWorks

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

Page 5: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

Figure 2. Facebook canvas page

ibm.com/developerWorks developerWorks®

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

Page 6: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

FBML, FQL, and the Facebook API

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

FBML is basically a modified version of HTML, with some new Facebook-only tagsadded and some tags modified or removed as required. FBML can be used on bothprofile boxes (using the profile.setFBML API method) and canvas pages. FBMLcontains many tags that make it simple to include Facebook features and data inyour application. Facebook-specific tags in FBML have the prefix "fb". For example<fb:name> 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 sameway as SQL (Structured Query Language) is used to access data in a relationaldatabase such as MySQL. The Facebook Platform allows access to a series of FQLtables such as user, photo, album—which contains data about Facebookusers—uploaded photos, and photo albums, respectively. See a full list of FQLtables.

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

developerWorks® ibm.com/developerWorks

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

Page 7: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

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

Section 4. Installing components

This section covers the installation of the components required to develop aFacebook application with Flex. First, you will install the open source Flex SDK andset up the required environment variables to simplify compiling your applications.Next, you will create an application on Facebook and configure the Facebookapplication settings for your sample application. Finally, you will see how a Flexapplication should be structured and where you need to put the Facebook PHPClient 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 andthose that are required to follow this tutorial if you are using Mac OS X or Linux®. Toinstall the open source Flex SDK, you will need to download the SDK from theAdobe Web site (see Prerequisites for a link). Click on Open Source Flex SDK forthe latest stable build. If you want to install the debugger version of the Adobe FlashPlayer and the Adobe AIR runtime, feel free to download the Adobe Flex SDK, butbe aware that parts of this package are not under an open source license (seeFigure 3).

Figure 3. Flex 3 SDK Downloads page

ibm.com/developerWorks developerWorks®

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

Page 8: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

Figure 4. Windows Environment Variables properties

developerWorks® ibm.com/developerWorks

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

Page 9: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

ibm.com/developerWorks developerWorks®

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

Page 10: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Make sure that the path to the bin directory of your JRE installation is somewhere inthe Variable value text box. Also, add a semicolon to the end of this line, and afterthe semicolon enter C:\flex\bin. This allows you to run the Flex compiler in anydirectory 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 theinstallation was successful, navigate to C:\flex\samples\explorer and double-click thebuild batch file. This will compile a sample application that allows you to explorethe many different UI components available in the Flex SDK. The compilationprocess may take several minutes and should look something like Figure 6. Whenthe process is complete the DOS window will close automatically.

Figure 6. Compiling the explorer sample application

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

developerWorks® ibm.com/developerWorks

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

Page 11: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Figure 7. Explorer sample Flex application

Creating a Facebook application

To create a Facebook application you will need to have a Facebook account. If youdon'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 DeveloperApplication and click Allow to let the Developer application access your profile. Onthe Developer application page click the Set up New Application button. This willtake you to the New Application form. On this page, ensure that the Optional Fieldssection is pulled down.

Figure 8. Part of the Facebook New Application form

ibm.com/developerWorks developerWorks®

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

Page 12: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

• Application Name. This is the name of your application. I have calledmine fbFlexBook, but you can call yours whatever you like. While you'reat it, be sure to check the check box indicating that you have read andagree to the terms of the Facebook Platform.

• Callback URL. This is the URL where Facebook will look for the contentof your Facebook application. This URL must point to a location on a Webserver with PHP installed in order to follow this tutorial. The URL I haveentered is for sample purposes only and will not work—you must replacethis with your own value. Don't worry if there are no files in the locationright now; you will be creating PHP files later in this tutorial that you willneed to upload to this location for the application to work.

• Canvas Page URL. This is the URL on Facebook where you want yourapplication to be found. It's usually best to give it a URL similar to theapplication name. This must be unique so, again, you cannot use the

developerWorks® ibm.com/developerWorks

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

Page 13: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

value I have supplied here. Be sure to leave the Use FBML optionbeneath 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 toselect the check box next to Users here or your application will not beable to add a profile box to users' profiles (including your own).

• Default FBML. Enter something like "Testing the profile box" in here. Thesample application will handle the content of the profile box later.

• Default Profile Box column. Select Narrow here, as your sampleapplication 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'sWall tab. Wide profile boxes can only be added to the Boxes tab.

• Developer Mode. Ensure that this check box is checked so that only youcan use the application. If this is not checked, anyone can add yourapplication to their Facebook profile.

You can optionally fill out some of the other fields if you wish, but this is not requiredfor the sake of your sample application. You can always change these values lateron via the Edit Settings link on the My Applications page. Click Submit to create theFacebook application, which will generate an API key and Shared Secret and bringyou to the "My Applications" page for your Facebook application, which should looklike Figure 9 (the API key and Shared Secret have been blurred for securitypurposes).

Figure 9. Facebook My Applications Page for fbFlexBook

ibm.com/developerWorks developerWorks®

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

Page 14: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

That is all there is to creating a Facebook application. Right now the applicationdoesn't do anything and will return an error if you try to navigate to it. We will returnto this application when developing your sample application later in this tutorial, atwhich 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 thelatest version of the Facebook PHP Client Library. Facebook has recentlyundergone some major changes in terms of how its profile works. As a result, somemajor changes have been made to the Facebook PHP Client library, so be sure toget the latest version from Prerequisites. If you can log in to your Web server viaSSH, you can issue the commands shown in Listing 1 to easily download andextract 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'

developerWorks® ibm.com/developerWorks

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

Page 15: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

tar -xzvffacebook-platform.tar.gz

Alternatively you can download the library from the link shown in Listing 1 above andextract 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 Facebookand will need to access the Facebook API to do so. We will use the FacebookActionScript API to make our lives easier. Be sure to download the latest sourceversion of this library. Extract the .zip file to a convenient location since you will becopying the "com" folder into your sample application later in this tutorial.

Now that you have downloaded and configured all of the different componentsrequired 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 Flexapplication with a very simple example (see Downloads for the source files). You aregoing to put this example and the slideshow application you build later on in a newfolder called projects, which you will place in the C:\flex folder. Within this new folderyou will create a new folder called firstApp, which will be the project folder for thisapplication.

Creating the MXML interface

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

Listing 2. firstApp.mxml MXML interface

<?xmlversion="1.0"encoding="utf-8"?><mx:Applicationxmlns:mx="http://www.adobe.com/2006/mxml"layout="absolute">

<mx:VBoxverticalCenter="0"horizontalCenter="0"><mx:Buttonlabel="Push Me!"id="btnPushMe" />

ibm.com/developerWorks developerWorks®

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

Page 16: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

<mx:TextInputid="txtPushed" />

</mx:VBox></mx:Application>

This code will create a new Flex application with a VBox component that is centeredin the application window. Within the VBox component are a button and a text inputfield. You will now compile this application. To do so, open up the command lineprompt (Start>Programs>Accessories>Command Prompt). When the windowopens up, enter the command cd \flex\projects\firstApp to navigate to the projectfolder. Now enter the command mxmlc firstApp.mxml to compile the application. Ifthe process worked correctly, you should see a screen similar to the one shown inFigure 10.

Figure 10. Compiling your first Flex application

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

Figure 11. Running your first Flex application

developerWorks® ibm.com/developerWorks

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

Page 17: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Congratulations! You've got your first application up and running. This applicationdoesn't actually do anything right now, so in the next section you will modify thiscode 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 theTextInput component with some text when the user clicks the "Push Me!" button. Todo this, you need to modify your firstApp.mxml file (see Listing 3).

Listing 3. Adding an ActionScript event handler

<?xmlversion="1.0"encoding="utf-8"?><mx:Applicationxmlns:mx="http://www.adobe.com/2006/mxml"layout="absolute">

ibm.com/developerWorks developerWorks®

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

Page 18: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

<mx:Script><![CDATA[private

functiononBtnPushMeClick():void{txtPushed.text ="You pushed thebutton!";

}]]>

</mx:Script><mx:VBox

verticalCenter="0"horizontalCenter="0"><mx:Buttonlabel="Push Me!"id="btnPushMe"click="onBtnPushMeClick()"/><mx:TextInputid="txtPushed" />

</mx:VBox></mx:Application>

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

The main change between this listing and Listing 2 is the <mx:Script> block,which contains the ActionScript code for this application. You'll also notice thecharacter data <![CDATA[ sequence within this tag. These two features must bepresent when you are including ActionScript within an MXML file.

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

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

Figure 12. Running the updated firstApp.swf file

developerWorks® ibm.com/developerWorks

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

Page 19: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

That's all there is to creating applications using the Flex SDK. Of course, thisexample isn't exceptionally useful, but in the next section you will develop anapplication 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 applicationcalled fbFlexBook. The main application page (and the profile box for theapplication) will present a list of the user's photo albums on Facebook, each showingthe name of the album and how many photos are in that album. Clicking on any ofthe album names will bring the visitor to a Facebook canvas page that contains aFlex-built slideshow application, which retrieves the photos in the selected albumfrom Facebook and presents them to the user.

ibm.com/developerWorks developerWorks®

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

Page 20: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

End result

By the end of this tutorial you will have created a profile box for the Facebookapplication made earlier in this tutorial, which displays a list of the user's Facebookphoto albums. This profile box can be seen in Figure 13 below. You will also havecreated a Facebook canvas page that displays a slideshow of the photos in thealbum 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 atimer you will create. You will have a button to play or pause the slideshow andbuttons to move to the next, previous, first, and last photos in the album. When theslideshow changes the photo, the new photo comes into the application with a funkyspinning effect. The slideshow will also display the caption for the photo at the top ofthe application. A screenshot of the slideshow is shown in Figure 14.

Figure 14. Our Facebook application canvas page

developerWorks® ibm.com/developerWorks

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

Page 21: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Updating the Facebook profile box

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

Now create a new subfolder in the c:\flex\projects folder called fbflexbook. Inside thisfolder create a subfolder called release. This folder will contain all of the files that areto be uploaded to the Web server (at the location specified as the callback URL foryour Facebook application). If you extracted the contents of the Facebook PHPClient Library to your local machine, copy the entire contents of thefacebook-platform\php folder from that archive to the release folder. If you used SSHto download and extract the library, you can simply copy the contents of thefacebook-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

ibm.com/developerWorks developerWorks®

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

Page 22: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

Listing 4. index.php

<?phprequire_once'facebook.php';// Replace$api_key and$secret with thevalues for yourown Facebook// application$api_key ='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';$secret ='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';$fb = newFacebook($api_key,$secret);// In order toget the user idthey have to login to ourapplication$uid =$fb->require_login();

// Here we useFQL to retrievethe user's albums$fql = "SELECTaid, name, sizeFROM album WHEREowner = $uid";$albums =$fb->api_client->fql_query($fql);

$fbml ="<strong>fbFlexBookAlbums:</strong><br/><br />";// Now we loopthrough thealbums and addthem to our FBMLvariableforeach($albumsas $album) {

$fbml .= '<ahref="http://apps.new.facebook.com/fbflexbook/album.php?aid='.$album['aid'].'">'.$album['name'].'</a>('.$album['size'].')<br />';}// Here we setthe profile boxto show the listof albums$fb->api_client->profile_setFBML(null,$uid, $fbml,null, null,$fbml);

// On the main

developerWorks® ibm.com/developerWorks

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

Page 23: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

application pagewe will greet theuser. If theyhave// not yet addedthe applicationto their profilea button willshow// up that allowsthem to, andfinally we willdisplay the listof albumsecho '<p>Hello,<fb:nameuid="'.$uid.'"useyou="false"/>!</p>';echo'<fb:add-section-buttonsection="profile"/>';echo $fbml;?>

The first thing to do in the index.php file is include the Facebook library and assignyour API key and shared secret to the variables. Be sure to replace thexxxxxxxxxxxxxxxxxxxx strings with your own API key and secret values or you willget an error. You will also need to replace the "fbflexbook" in the URLhttp://apps.new.facebook.com/fbflexbook/album.php... to your own application'scanvas 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 areusing Facebook Query Language (FQL) to retrieve information about the user'sphoto albums. You are then using the fql_query method of the Facebook clientlibrary to process the statement. If you are familiar with MySQL, this statement willlook very familiar and reflects just how easy it is to use FQL. The API returns anarray which you then loop through with a foreach statement, adding each album asa link to the $fbml variable. You then assign the contents of this variable to the mainprofile box using the profile_setFBML method of the API, before outputting somecontent to the actual page itself.

At this point you can upload index.php (and if required, the Facebook PHP clientlibrary) to the location on your Web server that the Facebook Application CallbackURL setting points to. In my case this ishttp://www.joelennon.ie/fbflexbook/. Once you have uploaded theindex.php file you should be able to use the Facebook application. To do this, log into your Facebook account and go to the Developer application. In the "MyApplications" on the right-hand side of this page, click on the more link next to yourFacebook application and click the View About Page link, as highlighted in Figure15.

ibm.com/developerWorks developerWorks®

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

Page 24: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Figure 15. Facebook Developer application

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

Figure 16. Facebook Application page

developerWorks® ibm.com/developerWorks

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

Page 25: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

At this point you will be asked for permission to allow the application access to yourFacebook 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 agreeting, an Add to Profile button, and a list of photo albums. Please note that thelinks for each photo album will not work at the moment, but you will be adding this

ibm.com/developerWorks developerWorks®

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

Page 26: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

functionality later in the tutorial. What you will do now, however, is add thisapplication as a profile box on the Wall tab of your profile. To do this, click Add toProfile, 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 toadd the box to your profile and allowing you to add it to either the "Wall and InfoTab" or the "Boxes Tab". Leave the default (Wall and Info Tab) option selected andclick Add to add the profile box to your profile (see Figure 19).

Figure 19. Add application to Profile pop up window

developerWorks® ibm.com/developerWorks

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

Page 27: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

Figure 20. Our application profile box on the Facebook profile

ibm.com/developerWorks developerWorks®

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

Page 28: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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 toretrieve data from Facebook and add it to your application. You will be adding adegree 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 Flexslideshow and display the photos from the selected Facebook photo album. You willbe working on building the slideshow itself later, but for now let's set up your ViewAlbum page on Facebook.

The View Album page will use the Facebook PHP Client Library to retrieve the nameof the selected photo album and the number of photos in the album. It will displaythese values to the user. Beneath this information you will include a Flash SWFobject using the <fb:swf> FBML tag, passing the album ID to the Flex applicationusing the flashVars attribute. Finally, at the bottom you will have a link back to themain canvas page for the Facebook application.

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

developerWorks® ibm.com/developerWorks

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

Page 29: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

5 into this file and save it.

Listing 5. album.php

<?phprequire_once'facebook.php';// Replace$api_key and$secret with thevalues for yourown Facebookapplication$api_key ='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';$secret ='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';$fb = newFacebook($api_key,$secret);// In order toget the user idthey have to login to ourapplication$uid =$fb->require_login();

// Here we getthe album ID fromthe GET variableaid$aid =$_GET['aid'];

// Now we use FQLto get the nameand size of therequested albums$fql = "SELECTname, size FROMalbum WHERE aid =$aid";$albums =$fb->api_client->fql_query($fql);// Select ouralbum (shouldonly be oneresult)$album =$albums[0];echo 'Viewing<strong>'.$album['name'].'</strong><br/>';echo 'There are<strong>'.$album['size'].'</strong>photo'.($album['size']> 0 ? 's' : '').'in this album.';echo '<br /><br/>';// This displaysour Flexapplication,passing the album

ibm.com/developerWorks developerWorks®

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

Page 30: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

ID variable to it// NB: You mustreplace theswfsrc with theURL of the fileon your webserverecho '<fb:swfswfsrc="http://www.joelennon.ie/fbflexbook/fbFlexBookApp.swf"'

.'width="720"height="565"flashvars="aid='.$aid.'"/>';echo '<br /><br/>';echo '<ahref="index.php">Backto fbFlexBookMain Page</a><br/>';?>

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

Figure 21. Our Facebook application profile box

developerWorks® ibm.com/developerWorks

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

Page 31: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Now click on any of the photo albums (in Figure 21 I have selected my "Boston 20064" album with 32 photos in it), and you should see a page that looks like thescreenshot 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 theFacebook photo album and has retrieved the name of the selected photo album andhow many photos it contains. As soon as you have uploaded the end product (thefbFlexBook.swf Flash object file) to the Web server, your album.php page will showthe Flex slideshow below the text highlighted in red.

Creating the slideshow user interface

ibm.com/developerWorks developerWorks®

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

Page 32: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

Before you begin coding, you need to set up the project folder in the correct way. Inthe c:\flex\projects\fbflexbook folder, create a new folder called src. This is the folderthat will contain all of the Flex application's source code. Now put the source codefor the Facebook ActionScript API in the project folder. When you extract the zip filethis library comes in, navigate down through the resulting folder until you find the"com" folder. Copy this entire folder and paste it into yourc:\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 foldercalled "ibm". In this folder create a new subfolder called "developerworks". You willbe creating the ActionScript classes in this folder.

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

Listing 6. Photo.as

packagecom.ibm.developerworks{

[Bindable]public class

Photo {public

varcaption:String;

publicvarsrc_big:String;

publicfunctionPhoto(photo:Object= null) {if(photo != null){this.caption =photo.caption;this.src_big =photo.src_big;

}}

}}

developerWorks® ibm.com/developerWorks

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

Page 33: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

Listing 7. Album.as

packagecom.ibm.developerworks{

importmx.collections.ICollectionView;

importmx.collections.ArrayCollection;

importmx.collections.IViewCursor;

[Bindable]public class

Album {public

varphotos:ArrayCollection;

publicvar selected:int;

privatevar photo:Photo;

publicfunctionAlbum(album:Object= null) {photos = newArrayCollection();if(album != null){this.selected =0;

for(var i:int =0; i <album.photos.length;i++) {photo = newPhoto(album.photos[i]);photos.addItem(photo);

}}

}}

}

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

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

ibm.com/developerWorks developerWorks®

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

Page 34: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

Listing 8. FacebookREST.as

packagecom.ibm.developerworks{

importflash.events.*;

importmx.collections.ArrayCollection;

importmx.collections.IViewCursor;

importmx.core.Application;

importmx.rpc.events.ResultEvent;

importmx.utils.ArrayUtil;

importcom.pbking.facebook.data.photos.FacebookPhoto;

importcom.pbking.facebook.delegates.photos.GetPhotosDelegate;

importcom.pbking.facebook.FacebookSessionType;

importcom.pbking.facebook.Facebook;

public classFacebookREST {

privatevar fb:Facebook;

privatevarflashVars:Object;

[Bindable]public

varalbums:ArrayCollection;

publicfunctionFacebookREST() {

fb =new Facebook();fb.addEventListener(Event.COMPLETE,onFacebookConnect);flashVars =Application.application.parameters;fb.startWidgetSession(flashVars,"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

}

privatefunctiononFacebookConnect(e:Event):void{if(fb.isConnected)

developerWorks® ibm.com/developerWorks

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

Page 35: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

{fb.photos.getPhotos(null,flashVars.aid,null,onPhotosFound);

}}

privatefunctiononPhotosFound(e:Event):void{

vardel:GetPhotosDelegate= e.target asGetPhotosDelegate;

varphotos:ArrayCollection= del isArrayCollection

?del asArrayCollection: newArrayCollection(ArrayUtil.toArray(del));

vartemp:ArrayCollection= newArrayCollection();

varcursor:IViewCursor=photos.createCursor();while(!cursor.afterLast){temp.addItem(newAlbum(cursor.current));cursor.moveNext();

}albums = temp;

}}

}

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

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

ibm.com/developerWorks developerWorks®

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

Page 36: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

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

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

Listing 9. fbFlexBook.mxml

<?xmlversion="1.0"encoding="utf-8"?><mx:Canvasxmlns:mx="http://www.adobe.com/2006/mxml"xmlns="*"

width="100%"height="100%"horizontalScrollPolicy="off"verticalScrollPolicy="off"implements="mx.managers.IFocusManagerComponent"creationComplete="focusManager.setFocus(this);onShow()">

<mx:Script><![CDATA[import

com.ibm.developerworks.Photo;import

com.ibm.developerworks.Album;

importmx.events.FlexEvent;

importmx.resources.*;

importflash.utils.Timer;

[Bindable]public

var album:Album;

[Bindable]public

varcurrPhoto:Photo;

privatevar t:Timer;

overrideprotected

developerWorks® ibm.com/developerWorks

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

Page 37: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

functionchildrenCreated():void{super.childrenCreated();

t =new Timer(5000,0);t.addEventListener(TimerEvent.TIMER,onTickTock);

}

privatefunctiononShow():void {

//Start the Timert.start();

}

privatefunctiononTickTock(event:TimerEvent):void{

//When the Timerstrikes, we moveto the next photoalbum.selected =(album.selected +1) %album.photos.length;

}

privatefunctiononBtnPlayPauseClick(event:MouseEvent):void{

//When thePlay/Pause buttonis clicked, wecheck

// tosee if the timeris running. If itis we stop

// itand update ourbutton's label to"Play". If it

// isnot running weupdate thebutton's label to

//"Pause" and startthe timer.if(t.running ==true) {t.stop();btnPlayPause.label= "Play";

}else {btnPlayPause.label= "Pause";t.start();

}}

ibm.com/developerWorks developerWorks®

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

Page 38: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

privatefunctiononBtnFirstClick(event:MouseEvent):void{

//Navigate to thefirst photo inthe albumalbum.selected =0;

//Restart the timerat 0resetTimer();

}

privatefunctiononBtnNextClick(event:MouseEvent):void{

//Navigate to thenext photo in thealbum, or

// ifwe are at the endof the album, goback

// tothe first photoalbum.selected =(album.selected +1) %album.photos.length;resetTimer();

}

privatefunctiononBtnPrevClick(event:MouseEvent):void{

//Here we check ifwe are at thefirst photo in

//the album and ifwe are we go backto the last

//photo in thealbum, otherwisewe just step

//back to theprevious photoif(album.selected== 0) {album.selected =album.photos.length- 1;

}else {album.selected =album.selected -1;

}resetTimer();

developerWorks® ibm.com/developerWorks

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

Page 39: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

}

privatefunctiononBtnLastClick(event:MouseEvent):void{

//Navigate to thelast photo in thealbumalbum.selected =album.photos.length- 1;resetTimer();

}

privatefunctionresetTimer():void{

//Check if thetimer is running,if it is we

//simply reset it.if(t.running) {t.stop();t.start();

}}]]>

</mx:Script>

<mx:Bindingsource="album.photos.getItemAt(album.selected)as Photo"destination="currPhoto"/>

<mx:VBoxwidth="640"height="35"top="0"horizontalCenter="0"horizontalAlign="center"verticalAlign="middle">

<mx:Texttext="{currPhoto.caption}"textAlign="center"fontSize="14"color="#ffffff"fontFamily="Arial,Helvetica,sans-serif" />

</mx:VBox>

<mx:VBoxwidth="640"height="480"top="35"horizontalCenter="0"horizontalAlign="center"verticalAlign="middle">

<mx:Imagesource="{currPhoto.src_big}"width="100%"height="100%"completeEffect="Rotate"

ibm.com/developerWorks developerWorks®

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

Page 40: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

horizontalAlign="center"verticalAlign="middle"><mx:filters><mx:DropShadowFilter/></mx:filters></mx:Image>

</mx:VBox>

<mx:HBoxwidth="640"height="50"top="515"horizontalCenter="0"horizontalAlign="center"verticalAlign="middle"><mx:Buttonid="btnFirst"label="<<"click="onBtnFirstClick(event)"/><mx:Buttonid="btnPrev"label="<"click="onBtnPrevClick(event)"/><mx:Buttonid="btnPlayPause"label="Pause"click="onBtnPlayPauseClick(event)"/><mx:Buttonid="btnNext"label=">"click="onBtnNextClick(event)"/><mx:Buttonid="btnLast"label=">>"click="onBtnLastClick(event)"/>

</mx:HBox></mx:Canvas>

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

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

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

developerWorks® ibm.com/developerWorks

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

Page 41: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

selected photo. Note that the text of the component is set to{currPhoto.caption}, which basically means the caption property of thecurrPhoto binding. The next VBox contains the Image component, essentially theheart of the slideshow component. Interesting points to note about the componentare the completeEffect="Rotate" and the <mx:DropShadowFilter /> that areapplied to it. These generate the rotation effect each time the image changes andthe drop shadow effect to your image. This is an example of how simple Flex makesadding dazzling effects to your applications.

The final section of the component, the HBox, contains the buttons that control theslideshow, 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 ActionScriptfunction.

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

Listing 10. fbFlexBookApp.mxml

<?xmlversion="1.0"encoding="utf-8"?><mx:Applicationxmlns:mx="http://www.adobe.com/2006/mxml"xmlns="*"paddingBottom="0"paddingTop="0"paddingLeft="0"paddingRight="0"layout="vertical"pageTitle="fbFlexBookApp"creationComplete="startShow()"backgroundGradientColors="[#6699cc,#003366]">

<mx:Script><![CDATA[

importcom.ibm.developerworks.Album;importcom.ibm.developerworks.FacebookREST;

importmx.collections.ArrayCollection;importmx.rpc.events.*;

[Bindable]private varalbum:Album;

[Bindable]private varfb:FacebookREST;

private functionstartShow():void

ibm.com/developerWorks developerWorks®

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

Page 42: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

{fb = newFacebookREST();

}]]>

</mx:Script>

<mx:Bindingsource="fb.albums.getItemAt(0)as Album"destination="album"/>

<fbFlexBookid="fbFlex"album="{album}"/></mx:Application>

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

Next you will compile the application into a SWF file and upload it to your Webserver. 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 firstapplication you created, compiling it is just as easy. Open up a Command Promptwindow (Start>All Programs>Accessories>Command Prompt) and type cd\flex\projects\fbflexbook\src to change to your project's src folder. Nowenter the command mxmlc fbFlexBookApp.mxml, and the Flex compiler willcompile the application into a SWF file. You will now copy this file to the releasefolder. Issue the command copy fbFlexBookApp.swf ..\release to do so. Ifall went as expected, your command prompt window should look like that in Figure23.

Figure 23. Compiling the sample application

developerWorks® ibm.com/developerWorks

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

Page 43: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

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

Figure 24. The Facebook application in action

ibm.com/developerWorks developerWorks®

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

Page 44: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Suggested improvements to the application

Your application has some useful functionality, but it could easily be extended toprovide some more exciting features. The application you have created has beendone so in such a manner that makes it easy to extend the slideshow to multiplealbums, so a logical next step would be to create a multi-album photo gallery thatperhaps allows you to select which album to display from a thumbnail selector in theFlex 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, orto perform other manipulative actions

• Nicer slideshow controls with some attractive icons that appear when theuser moves over the photo itself and disappear after a predefined numberof seconds

developerWorks® ibm.com/developerWorks

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

Page 45: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

• User-defined controls for defining how long a pause to show betweeneach 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, namelyusing MXML and ActionScript. You looked at Facebook applications and thetechnologies that are available to developers who wish to create them, such asFBML, FQL, and the Facebook API.

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

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

ibm.com/developerWorks developerWorks®

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

Page 46: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

developerWorks® ibm.com/developerWorks

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

Page 47: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

Resources

Learn

• "Integrating Flex into Ajax applications" (Brice Mason, developerWorks, July2008): Read an article that introduces the Adobe Flex Ajax Bridge (FABridge), acode library that enables an easy and consistent method for integrating Ajaxand Flex content.

• "Combine the power of WebSphere sMash with Adobe Flex" (Jorge Rasillo andMike Burr, developerWorks, August 2008): Read an article that shows how asimple application can be enhanced to support a Web 2.0 user interface writtenin Adobe Flex.

• "Access a web service using Flex 2 in Rational Software Architect V7" (JeffMiller, developerWorks, December 2007): See how easy it is to access Webservices using Adobe Flex 2.

• "Develop Web services clients with Macromedia Flex" (Leugim Bustelo andJulio Ruano, developerWorks, August 2004): Walk through several examplesthat map WSDL constructs to Flex declarations.

• "Use Ext, Aptana and AIR to build desktop applications" (Joe Lennon,developerWorks, July 2008): Use the open source Aptana Studio IDE, theAdobe AIR plug-in for Aptana, and the open source JavaScript framework Ext tobuild Web applications that run seamlessly on the desktop.

• "Mastering Facebook application development with PHP, Rational ApplicationDeveloper, WebSphere Application Server, and DB2" (Jake Miles,developerWorks, May 2008): Develop a Facebook application using both PHPand 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 simpleblog 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: Learnhow 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

ibm.com/developerWorks developerWorks®

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

Page 48: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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 applicationdevelopment tools and middleware products from DB2, Lotus, Rational, Tivoli,and WebSphere.

Discuss

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

About the author

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

Trademarks

Adobe, the Adobe logo, PostScript, and the PostScript logo are either registeredtrademarks 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.

developerWorks® ibm.com/developerWorks

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

Page 49: Implement a Facebook photo album using the Flex …...Introduction to Facebook applications Now let's examine the concept of a Facebook application and the tools that allow you to

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

ibm.com/developerWorks developerWorks®

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