» Publishers, Monetize your RSS feeds with FeedShow: More infos (Show/Hide Ads)
This week I’m in San Francisco at Dreamforce – Salesforce.com’s yearly conference. It’s amazing to walk around the expo hall and see how much Flex is being used in enterprise products and services. Like last year I’ve been recording some videos of some of the great enterprise Flex apps here. Also Greg Wilson has been tweeting a few pics of some of these apps including right90 and PivotLink with more to come.
Many of the Flex applications that people have built on top of Salesforce.com / Force.com today use the existing Flex Toolkit for Force.com. The new Flash Builder for Force.com tool today only supports desktop applications with Adobe AIR – but will also support web applications in the future. But you can still use the existing Toolkit within Flash Builder for Force.com. All you need to do is configure your project to use the Flex 3.4 SDK and add the force-flex.swc file to the project’s libs folder. That’s it!
If you aren’t at Dreamforce and want to learn about the new Flash Builder for Force.com then check out the recording from a webinar I co-presented a few weeks ago.

Here are some upcoming Flex presentations I’ll be giving:
- Thursday November 12 in Dallas – Java and Flex
- Friday November 13 in Plano, TX – Flex and the Cloud @ TexFlex09
- Monday November 16 at Flex Camp Wall Street (New York) – Flex Stuff I’m Excited About
- Monday November 16 at the Web 2.0 Expo (New York) – Connecting RIA’s to Services
- Tuesday November 17 at the Web 2.0 Expo (New York) – Best and Worst Practices Building Rich Internet Applications (RIAs) from Adobe and Microsoft (with Josh Holmes)
- Thursday November 19 at Dreamforce (San Francisco) – Building Force.com Apps with Adobe Flex/AIR
I hope to see you somewhere along the way!
The web’s success has been partially due to the sandbox it provides users. Users do not generally have to entirely trust every website they visit because malicious web sites should be sandboxed from doing the user harm. One way that web sites are sandboxed is through a same-origin policy. By default any code that runs inside a web browser can only access data from the domain in which the code originated from. So if code (JavaScript, Flash, etc) loads from the foo.com domain then it can’t access data on the bar.com domain. The code may be able to make requests to bar.com but the code from foo.com shouldn’t be able to read or access the results of those requests.
Since Rich Internet Applications built with Flex, Silverlight, etc usually try to do more on the client side, for example mash-up data from multiple sites, the same-origin policy presents a problem.
In most cases Flash Player sticks with the typical browser sandbox concepts. But there are a few places where it goes outside this boundary such as with microphone and webcam access. Another area is by allowing opt-in to cross-domain communication bypassing the browser’s regular same-origin policy. Other plugins such as Silverlight and JavaFX also do this. This cross-domain capability is powerful but also very dangerous. The primary reason it’s dangerous is that a malicious application can potentially make requests on behalf of the user and access data from domains that the application didn’t originate from. To protect against these types of attacks Flash Player and other plugins have implemented a cross-domain policy system. This policy system is one of the most misunderstood aspects of web security.
To illustrate the problem I’ve create a few demos. Let’s say that I’m building an application for www.jamesward.com that will fetch some data from the www.firststepsinflex.com site.
Here’s that application on www.jamesward.com – open it in a new window.
The application correctly pulled the data from the www.firststepsinflex.com site but in order to allow the request I blindly put a crossdomain.xml policy file on www.firststepsinflex.com that looks like this:
<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <site-control permitted-cross-domain-policies="master-only"/> <allow-access-from domain="*"/> </cross-domain-policy>
What this policy file does is instruct Flash Player to allow requests from any website to get around the same-origin policy and make requests to www.firststepsinflex.com – on behalf of the user. Sounds harmless, right? At this point it is, as long as all of the data on www.firststepsinflex.com is publicly available data. But let’s suppose that not all of the data should be publicly available. Perhaps I’m protecting access to some data though cookie authentication or HTTP basic authentication. In this case I am (for the purpose of the demo).
See the protected data by opening up http://www.firststepsinflex.com/private/bankaccounts.html using “username” and “password” (without quotes) for the user name and password.
Now imagine that someone starts posting Twitter links (obfuscated through a URL shortener) phishing for people to open a malicious application (open it in a new window – I promise it doesn’t do anything bad).
So let’s recap… There is a protected resource that only you should be able to see in your browser. Other applications should NOT be able to see that data. But a malicious application was able to load that same data and do whatever it wants with it. Scary.
Here’s how it works… The malicious application requests the protected page. It was able to make the request because you were authenticated already. And the malicious application can now read the data contained in the page and do whatever it wants with it (probably send it back to a server somewhere).
OK. Now do you understand why crossdomain.xml policy files are dangerous? Imagine if Facebook, MySpace, or YouTube had a misconfigured policy file on their servers! Well they have – but they’ve since been fixed. Imagine if your bank or a corporate intranet had a misconfigured policy file. There are some very serious ramifications to these types of attacks.
There are also some great uses of crossdomain policy files. For instance, api.flickr.com has an open crossdomain.xml policy file. This allows applications loaded from anywhere to access Flickr data and it’s safe because api.flickr.com doesn’t use cookies or basic auth – they use web service tokens, which are not automatically transmitted by the browser and are only known to the application that performed the authentication.
I often hear from Flex / Flash developers that when they run into security sandbox issues the first thing they try is to open things up with a global (i.e. “*”) policy file. I hope this article discourages that practice. Developers should understand why the security error is happening and consider alternatives before blindly opening up their website to the possible attacks. One alternative is to leverage a server proxy. A server proxy can be configured so that an application doesn’t violate the same-origin policy. For instance, if an application on foo.com needs data from bar.com then a proxy can be configured such that requests to foo.com/bar are forwarded on the server to the bar.com site. This helps avoid attacks because users’ cookies (or basic auth tokens) will not be sent to bar.com since all requests are actually being made to the foo.com site. But be careful not to expose intranet servers through proxies. Here is a sample Apache config for setting up a forward proxy:
ProxyRemote /bar/* http://bar.com/ ProxyPass /bar http://bar.com ProxyPassReverse /bar http://bar.com
BlazeDS also includes a proxy service.
If you really need to use a crossdomain policy file then be very careful! NEVER put a crossdomain policy file on a site that uses cookie or basic auth and NEVER put a crossdomain policy file on an intranet site – unless you really know what you are doing. To learn how to safely use crossdomain policy files here are some great resources:
I hope this helps create better understanding of web security. Please let me know if you have any questions.
Here’s a special episode of Drunk on Software from Adobe MAX 2009. Enjoy!!
Here is the video of my session from MAX 2009 – Introduction to BlazeDS and LCDS. In this session I walk through the basics of connecting Flex applications to BlazeDS and LCDS. Let me know what you think!
We’ve recently posted three great episodes of Drunk on Software – the video podcast for those who like booze and bits. So grab your favorite adult beverage (if you are of legal age), sit back, and enjoy getting Drunk on Software!
Episode 17: Half of the Java Posse
Today Ubuntu released Karmic Koala 9.10 Desktop Edition. Like Snow Leopard and Windows 7, I find this release underwhelming. It seems that all three major operating systems are running out of room for innovation and the focus has now shifted to core improvements. But the lack of anything really new and exciting in all three recently released operating systems (Snow Leopard, Windows 7, and Ubuntu 9.10) indicates that the OS space has become a commodity market. All OS innovation seems to have shifted to mobile devices while the only significant remaining differentiator between the operating systems is the applications that run natively on them.
Applications are now the key to OS adoption. I love using iPhoto and iMovie on my wife’s MacBook Pro. They are fantastic apps for a novice photo and video editor (like me). Outlook and Office on Windows continue to be significantly better for office productivity, email, calendaring, and contact management than any other available options for me. Everyone I work with passes around PowerPoint presentations and Word documents. Without 100% compatibility the Mac and Linux alternatives to Office make it unusable for me. Adobe uses Exchange so Outlook is the only real option for email, calendaring, and contact management. Outlook may not be sexy or simple but it just works. There are also some great plugins for Outlook that really improve my productivity. For instance, Adobe’s travel agency has an Outlook plugin that automatically syncs my travel information to my calendar. I frequently hear my co-workers who use Mac Mail / Entourage complain about calendar mishaps and other issues, which makes me thankful that I have never had any issues with Outlook in the past seven years that I’ve been using it.
Ubuntu Linux is my primary desktop OS and since I need Office for my day-to-day work I use VMWare Workstation and boot the same Windows 7 install that I also can dual-boot into for presentations. This provides me with the ability to use the OS I’m most familiar with (Linux) most of the time but to also use Windows for Office when needed. It’s just too bad that I can’t run Snow Leopard in VMWare since that would certainly alleviate some marital tension because my wife hates it when I use her laptop to produce new episodes of Drunk on Software.
As I said before I’m underwhelmed by Ubuntu 9.10. It’s not a bad release. Most stuff works. But looking back at my review of Ubuntu 9.04 it seems that not much has really changed:
- Battery Life – Still great!
- Suspend – Still works great except that I still can’t see my F3507g Mobile Broadband card after I resume (open bug) unless I toggle my wireless kill switch.
- 3G Mobile Broadband – Now consistently works much better! And works out-of-the-box (unlike on Windows).
- Email – I would love to switch to Evolution from Outlook but MAPI is still not working for me. Whenever I try Evolution crashes.
- Display – The Intel drivers are working great except that setting the Display Preferences in Gnome’s Preferences still doesn’t work. Using xrandr from the command line works fine though – even when plugging into a projector.
- Boot Performance – Improved by a few seconds. From BIOS to logged in in under ten seconds!
- Office Productivity – OpenOffice is unusable for me. It’s UI is clunky and it’s compatibility with Office is still not perfect.
- Screen Sharing – Still no Adobe Acrobat Connect presenter plugin for Linux.
- Flex Builder for Linux – The alpha is about to expire. Please vote for the feature request.
- Accelerometer – Still doesn’t work out-of-the-box.
Overall I really appreciate any steps that Linux takes towards being a more viable Windows / Mac alternative. And who am I to complain? I don’t have to pay for Linux and have never really contributed to making it better. So overall I am happy with Ubuntu 9.10 and there are only a few things that I wish were better. The good news is that improvement of Linux on the Desktop is accelerating while desktop OS innovation seems to have stagnated due to the OS market being commoditized. As long as the applications that run on Linux continue to improve then the future of Desktop Linux seems bright. Maybe what we need is more cross-platform applications using Adobe AIR? :)
Here are a few upcoming Flex and Java presentations I’ll be giving:
- Thursday October 29 in Zurich – RIAs with Java, Spring, Hibernate, BlazeDS, and Flex
- Thursday November 12 in Dallas – Java and Flex
- Friday November 13 in Plano, TX – Flex and the Cloud @ TexFlex09
I hope to see you there!
The two major trends transforming software right now are Rich Internet Applications (RIAs) and Cloud Computing / Software as a Service (SaaS or PaaS). These trends are driven by two needs:
- Full client capabilities, which allow software to perform optimally and increase usability
- Easy deployment, which allows developers to focus on business needs instead of building infrastructure
The combination of RIA and Cloud is the future of software because it provides full client capabilities and easy deployment. The chart below illustrates this in comparison to the other major software architectures (main-frame, client / server, and web).

In line with these trends Adobe and Salesforce.com announced today that they are working together to unite Rich Internet Applications and The Cloud. At the core of this announcement is a developer preview of the Adobe Flash Builder for Force.com tool. This tool enables developers to easily build intuitive user interfaces with Flex which connect to the Force.com cloud platform and Salesforce.com CRM data. These applications can be deployed either in the browser or on the desktop using Adobe AIR. When utilizing Adobe AIR, the applications can still function when users are disconnected. Later, when users reconnect, the changes are synchronized with Force.com using the LiveCycle Data Services synchronization engine.
Being able to connect Flex applications to Salesforce.com / Force.com has been possible (and easy) since I co-created what was originally called the Flex Toolkit for Apex. So while it has been possible to build Rich Cloud Applications for a few years, today’s announcement is significant for a few reasons:
- Adobe and Salesforce are now officially partnered together around Rich Cloud Applications
- Much better, officially supported developer tooling
- Much better offline data synchronization
It’s really exciting to see how the vision of Rich Cloud Applications is becoming reality!
If you’d like to learn more or try out the new tooling check out these resources:
- Get the developer preview and watch video demos
- Get inspired and see how it works
- Watch a video walk-through
Another great way to learn more is to sign up for a Webinar / Tech Talk that I will be co-presenting.
Let me know what you think about this exciting new partnership and developer tooling.
Back in August at the Flex Jam in Orlando one of the projects we worked on was Text to Speech in Flex. We didn’t finish the project at the Jam so I wanted to post the final version here. Check it out:
(source code)
I used the iSpeech.org API to convert the text to speech. It was pretty easy to build this demo but a production version would need to use a proxy so that the username and password can’t be discovered.
Let me know what you think.
UPDATE: Periodically this demo might stop working because I’ve run out of credits at ispeech.org. If it doesn’t work for you please post a comment here and let me know.
I recently tried to upgrade to Eclipse 3.5 on my Ubuntu Linux desktop. Unfortunately this caused some problems with the Flex Builder 3 for Linux alpha 4. According to the stack traces in Eclipse the main problems seemed to stem from the com.adobe.flexbuilder.project.compiler.internal.ProblemManager class. So I decided to re-write that class from scratch to see if I could make the problems go away. My new implementation of ProblemManager seems to have fixed the issues that I was seeing. I’ve only tested this on Linux so I’m not sure if it will fix any problems on Mac or Windows. Here are the instructions for fixing the problems with Flex Builder 3 on Eclipse 3.5 on Linux:
- Make sure you have installed Eclipse 3.5 and the Flex Builder 4 for Linux alpha 4
- Download the ProblemManager patch
- Unzip the ProblemManager patch file
- Locate where Flex Builder is installed – in my case: ~/flex_stuff/Adobe_Flex_Builder_Linux
- Update the com/adobe/flexbuilder/project/compiler/internal/ProblemManager.class file in <Flex Builder Install Location>/eclipse/plugins/com.adobe.flexbuilder.project_3.0.204732/zornproject.jar with the file extracted from the patch
- Start Eclipse 3.5
- Smile!
UPDATE: Instructions for Windows were posted on InsideRIA by Mike Slinn. Thanks Mike!
So far this works for me. But I’m sure there are some problems I haven’t discovered with it yet. So please let me know if you have any problems. Also if someone wants to check this on Windows or Mac let me know if it works there. If not then feel free to update the ProblemManager.java class so that it does work.
DISCLAIMER: This patch is totally unsupported by Adobe. Use at your own risk.
As a companion to our book, First Steps in Flex, Bruce Eckel and I have recorded some screencasts which walk through the code samples in the book. Let us know what you think about these first few. The rest will be posted sometime in the next few months.
One of the things I love most about programming is running into walls and then finding creative ways to get over (or through) them. The most recent wall I ran into with Flex was that I wanted to be able to find classes at runtime that either implement a given interface or have specific metadata on them. Flash Player doesn’t provide an API to do this directly so I went searching for a workaround. Christophe Herreman tipped me off to a few great utilities for doing this:
- getDefinitionNames by Denis Kolyako
- as3-commons-reflect
A Flex application (using the Flex framework or AS3 only) can use getDefinitionNames to query any loaded SWF file (Application, Module, etc) for its class definitions. The getDefinitionNames utility just parses through the loaded bytecode and finds the class definitions. Then the as3-commons-reflect library can help determine which of those classes implement a given interface or have specific metadata on them. Here is an example:
Here is how it works:
var a:Array = getDefinitionNames(systemManager.loaderInfo); allClasses.dataProvider = a; ifooClasses.dataProvider = new ArrayCollection(); metafooClasses.dataProvider = new ArrayCollection(); for each (var cn:String in a) { var t:Type = Type.forName(cn); for each (var md:MetaData in t.metaData) { if (md.name == "MetaFoo") { metafooClasses.dataProvider.addItem(cn); break; } } if (ClassUtils.getImplementedInterfaceNames(t.clazz).indexOf("IFoo") >= 0) { ifooClasses.dataProvider.addItem(cn); } }
Pretty cool! There are a number of fun uses for this kind of thing… Modular IOC containers, client-side plugins, etc.
Getting over this wall was pretty easy thanks to Denis and Christophe. The Flex / AS3 community rocks!
Some believe that the “Internet” in “rich Internet application” (RIA) means that RIAs must only run in the browser. However my definition of RIA is not constrained to only web-based applications. RIAs can run anywhere: web, desktop, mobile devices, TVs, or even inside PDFs. Ideally we should have some level of code and library reusability between these environments. However to think that we can reuse the entire application is a pipe dream. Client capabilities and end user needs vary too greatly between these mediums.
I wanted to build an application in Flex that shows how applications can have a high degree of reuse between the web, the desktop, and in a PDF. I decided to build a Mortgage Calculator to illustrate this. Here is the web widget:
From within the web widget you can install the desktop widget or email yourself a PDF containing the widget. Since this application is a small, self contained application (i.e. a widget) the functionality between the different mediums is very similar. In this case I was able to reuse about 99% of the code between the different versions. However, sometimes achieving that level of reuse is not possible due to the differences in client capabilities and the end user needs. This is the case with the Flex and Adobe AIR based Oracle CRM Gadgets, which are for different use cases than the primary Siebel UI.
There are beginning to be more instances where RIA widgets are being reused across different mediums. But this is only one piece of software development. In other instances the capabilities and functionality of web, desktop, and mobile applications vary so greatly that there is little reuse. Either way it’s important to architect our back ends such that they are agnostic to the front end. This is one of the ways RIA and mobile app development have changed the way we build software. It’s a good thing and we should embrace it.
This month I’ll be presenting about Flex and Java at the Chicago and Ann Arbor Java User Groups:
Also on September 22 I’ll be doing a Flex Jam in Ann Arbor (all day coding and exploration).
I hope to see some of you at one of these events!
Combining the power of the cloud and the client allows developers to have the best of both worlds – easy deployment and full client capabilities. Salesforce.com’s cloud platform, called Force.com, and the Flash Platform are two proven and reliable choices for building these types of Rich Cloud Applications. Last week I co-hosted a webinar called “Developing Rich User Interfaces on Force.com Using Adobe Flex” in which Ryan Marples (from Salesforce.com) and I walked through the two platforms and how to use them together to build great software. If you didn’t have the chance to join the webinar then please go watch the recording and let us know what you think.
In the webinar we didn’t have a chance to walk through all of the details of building Rich Cloud Applications with Force.com and Flex so here is a tutorial and the source code for the highly desired car insurance demo.
Overview
With Rich Cloud Applications the back-end and front-end are distinctly different pieces. The first step when building these types of applications is to identify the domain model that will be used on the back-end for longterm persistence. Force.com will take care of all the details around scalability, reliability, disaster recovery, constraints, security, etc. All we need to do is describe the model in Force.com. In this case the model is for a piece of the insurance demo I frequently do. Here is a screenshot:

The information we need to store for this demo is the coordinates of all four cars and the coordinates of the crash indicator. In the next section we will describe that data model on Force.com.
Since the front-end will be built with Flex you will need either Flex Builder (60 day trial available) or the open source Flex SDK. This tutorial will assume you are using Flex Builder. Flex contains many out-of-the-box components but the car dragging UI used in the insurance demo is not one of them. The section about building the front-end will walk through some of the Flex code used to create that UI. If you want to learn more about creating custom components in Flex there is great documentation on the Adobe Developer Connection. Also if you want to see the components that are available in Flex then check out Tour de Flex.
Once the Flex application has been built, this tutorial will walk through the steps to put it up on the Force.com cloud.
Setting up the Back-end
To begin setting up the back-end on Force.com you will need a developer account. Once logged in you can go into the Setup mode by clicking on the “Setup” link at the top of the page. Setup mode is where you will configure the back-end data model on Force.com and deploy the Flex application after it’s built. On the left side of the Setup page you will see a section titled App Setup and underneath that a link titled “Create”. Click that link and then click the “Objects” link which will now appear in the list. This is where custom objects on Force.com are created and configured.
Add a new custom object titled “AccidentReport”. Then on that object create a few custom fields:
- Date_of_Accident – The type is Date. This field will store the date the accident happened.
- IncidentX – The type is Number. This field will store the X coordinate of the crash indicator.
- IncidentY – The type is Number. This field will store the Y coordinate of the crash indicator.
Next create another custom object titled “IncidentCar”. On that object create these custom fields:
- StartX – The type is Number. This field will store the X coordinate of the starting car’s position.
- StartY – The type is Number. This field will store the Y coordinate of the starting car’s position.
- EndX – The type is Number. This field will store the X coordinate of the ending car’s position.
- EndY – The type is Number. This field will store the Y coordinate of the ending car’s position.
- AccidentReport – This is a Master-Detail Relationship where the relationship is to the AccidentReport.
The data model has now been configured on Force.com and is ready for use. You may want to add a few fake records (an AccidentReport with two cars) manually to test the data model.
Building the Flex Client
Now that the Force.com back-end is configured we can begin building the Flex client. The client can run in three ways:
- Embedded in a Force.com page
- On your own server
- As a desktop application using Adobe AIR
In this tutorial we will use option 1. The details for deploying the application will be covered in the next section.
In order to connect to Force.com we need to download the Force.com Toolkit for Adobe AIR and Flex.
Start by creating a new Flex Project in Flex Builder. Then copy the force-flex.swc file from the Toolkit into the project’s libs folder. In your application start with something simple like:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:salesforce="http://www.salesforce.com/"> <mx:Script> import com.salesforce.AsyncResponder; import com.salesforce.objects.LoginRequest; import com.salesforce.results.LoginResult; import com.salesforce.results.QueryResult; </mx:Script> <mx:applicationComplete> var lr:LoginRequest = new LoginRequest(); lr.username = "YOUR USER NAME"; lr.password = "YOUR PASSWORD"; lr.callback = new AsyncResponder( function(result:LoginResult):void { conn.query("Select Id, IncidentX__c, IncidentY__c, Date_of_Accident__c from AccidentReport__c", new AsyncResponder(function(result:QueryResult):void { dg.dataProvider = result.records; })); }); conn.login(lr); </mx:applicationComplete> <salesforce:Connection id="conn"/> <mx:DataGrid id="dg"/> </mx:Application>
Give it a try by running the application. This simply logs in, fetches the AccidentReports and displays them in a DataGrid. Make sure that you have some sample data on Force.com before you run this. Otherwise you will get an error. That is a simple read-only view of some data on the Force.com cloud! However the full Car Incident application requires quite a bit more code. You can download the code and then copy and paste the files into your project.
Let’s walk through the application requirements:
- Retrieve a list of AccidentReports
- Allow the user to select an AccidentReport
- Retrieve the IncidentCars for the selected AccidentReport
- Allow the user to create a new AccidentReport
- Allow the user to position the crash indicator and cars in the AccidentReport
- Save the changes to Force.com
When we started building our back-end we modeled the data in Force.com. Now we need a client-side model of the data. The two value objects for this purpose are AccidentReport.as and Car.as. Those two value objects contains public properties corresponding to the values we need to hold once we get data back from Force.com. They also have a constructor that can map the data format from Force.com to the value object’s properties. For instance the Car value object’s constructor does the following:
public function Car(o:Object=null) { if (o != null) { id = o.Id; startX = o.StartX__c; startY = o.StartY__c; endX = o.EndX__c; endY = o.EndY__c; } }
This simply sets the properties on an instance of Car to the data values retrieved from Force.com. Later on you will see where those values come from and how we create new Car value objects.
Now that the client-side data model has been created we need a central place that will hold our value objects. The easiest way to do this is to create a Singleton called Model. You can find it in the Model.as class. The model contains properties which store information about the current state of the Flex application. In this case the state properties our application needs are:
- statusMessage:String – Holds messages related to server communication
- loggedIn:Boolean – Specifies whether or not the user is logged in
- accidentReports:ArrayCollection – Stores all of the AccidentReports that get fetched from the server
- selectedAccidentReport:AccidentReport – The AccidentReport selected by the user (if any)
Next we will setup a Controller that manages the communication to Force.com and updates the Model. You can find the source code in the Controller.as class. This class contains an instance of the Connection object from the Toolkit, which will actually do the communication to Force.com’s SOAP API. It also contains a reference to the Singleton Model. The controller exposes several public methods that support the requirements listed above. These are:
- login(sessionId:String, serverUrl:String):void – A method that logs into Force.com based on the sessionId and serverUrl provided by the Force.com page. Flex applications running outside of Force.com (on your own website or as a desktop application) will not have a sessionId so they will need to set the username and password instead.
- getAccidentReports():void – Does a query for the AccidentReports owned by the authenticated user.
- createAccidentReport():void – Creates a new AccidentReport.
- getAccidentReport(accidentReport:AccidentReport):void – Fetches the IncidentCars for a given AccidentReport.
- saveAccidentReport(accidentReport:AccidentReport):void – Updates an AccidentReport and its associated IncidentCars.
All network requests in Flex happen asynchronously. This means that all requests to Force.com also happen asynchronously; so while the methods listed above can make the request, other private functions are used to actually handle the server response and then update the Model. For instance when the response from the query in getAccidentReports returns, the model is updated in the following way:
private function getAccidentReportsResult(qr:QueryResult):void { model.accidentReports = new ArrayCollection(); // store AccidentReports for each (var o:Object in qr.records) { model.accidentReports.addItem(new AccidentReport(o)); } }
Notice that the records returned from the server are typed as Objects. In the for loop we use the mapping in AccidentReport’s constructor to convert the Object to a typed AccidentReport.
Now that the Model and Controller are setup the next task is to build the UI. The UI is built with a number of components:
- CarShape.as – A class that draws a single car.
- DraggableCars.as – Has two CarShapes and draws a curved line between them. Also has a Car value object which is used to position the CarShapes. When the user drags a CarShape the underlying Car is updated.
- Accident.mxml – Has an AccidentReport value object, two DraggableCars, and a crash indicator. The cars stored on the AccidentReport are passed to the DraggableCars. When the crash indicator is moved the AccidentReport value object is updated.
- AccidentReportView.mxml – Contains the Controller, a DataGrid that displays the list of all AccidentReports, an Accident that is displayed when the user selects an item in the DataGrid, and buttons that allow the user to create, save, or close an AccidentReport.
- CarIncident.mxml – The main application that contains an AccidentReportView and does the login when the application loads.
Describing how the custom UI components work is beyond the scope of this article. However it’s important to describe how the Model, View, and Controller interact. In the AccidentReportView the Accident uses data binding to setup an observer on the model. When the observer observes a change it lets the view know so that it can refresh its view of the model. The instance of the Accident uses data binding for two things:
<cars:Accident id="accident" accidentReport="{Model.getInstance().selectedAccidentReport}" visible="{Model.getInstance().selectedAccidentReport != null}"/>First the accidentReport value object of the Accident is set to data bind to the Model’s selectedAccidentReport. When that value changes the data binding observer will notify the Accident about the change. Second, the Accident is only visible when the Model’s selectedAccidentReport is not null.
The AccidentReportView also interacts with the controller by calling its public methods. Here’s an example:
<mx:Button label="Save"> <mx:click> controller.saveAccidentReport(accident.accidentReport); accidentReportDataGrid.selectedItem = null; Model.getInstance().selectedAccidentReport = null; </mx:click> </mx:Button>
When the user clicks the save button, the event handler calls the Controller’s saveAccidentReport method passing it the currently selected AccidentReport. Since the components internally have made changes to the AccidentReport those changes are then propagated to Force.com by calling the Connection’s update method. The save button’s event handler also deselects the currently selected item in the DataGrid and sets the selectedAccidentReport on the Model to null.
Now that you have a fully functional Rich Cloud Application built with Force.com and Flex the next step is to make that application available on the cloud.
Deploying the Flex Client
When in the development phase it may be convenient to hard code your username and password into the application like we did in the simple example above. However, you should never do that in a production application. If you are deploying on a Force.com page then you can use the session_id. Here is an example:
conn.serverUrl = parameters.server_url; var lr:LoginRequest = new LoginRequest(); lr.session_id = parameters.session_id; lr.server_url = parameters.server_url; lr.callback = new AsyncResponder(loginResult, loginFault); conn.login(lr);
The parameters are available on the main Application and are passed into the application using the apex:flash VisualForce tag, which we will setup later.
Once your application is set up to use the session_id then you will need to create a release build of the Flex project. To do that follow the Export -> Flex -> Release Build wizard. This will create a smaller SWF file (the application) that will later be uploaded to Force.com.
To deploy the application go into the Force.com Setup mode, click on Develop under App Setup, and then click on Static Resources. Create a new resource called “CarIncident” and upload the application’s SWF file found in the bin-release folder under the project. Then under Develop, click Pages and add a new Page called “AccidentReport”. Put the following code in the page:
<apex:page > <apex:pageBlock > <apex:flash src="{!$Resource.CarIncident}" width="500" height="500" flashvars="session_id={!$Api.Session_ID}&server_url={!$Api.Partner_Server_URL_150}"/> </apex:pageBlock> </apex:page>
Save the page and then you should be able to access it by going to:
https://na1.salesforce.com/apex/AccidentReport
If my instructions are accurate then hopefully you will now see the CarIncident application on the cloud pulling data from Force.com like this screenshot:

This is just a basic walk through of how to build Rich Cloud Applications with Force.com and Flex. There are tons of additional features and configuration changes you can make on both the back-end and front-end. But hopefully this helps you get started building Rich Cloud Applications with Force.com and Flex. Let me know how it goes!
MAX 2009 is coming fast! It’s going to be another great event with tons of great speakers and after party fun. Here are my sessions this year:
- Introduction to BlazeDS and LiveCycle Data Services
- Designing for Augmented Reality
- Building Flex and Adobe AIR Service Clients 2009
- Flex and Adobe AIR Boot Camp
Also Drunk on Software will be there filming some episodes.
So this is certainly a MAX you don’t want to miss! I hope to see you there!
Also check out the very cool MAX Widget (there are some funny facts about me in there):
![]()
It was really fun to be able to sit down and record an episode with Ben and Dion. They are great guys who are at the center of the tech industry. Let me know what you think of the episode.
I’ll be in Florida next week for a few great Flex and Java events:
- Tuesday August 25 – Flex Jam in Winter Park, FL – This is a bring your own laptop, self-paced learning event. Anyone, at any level of Flex knowledge is welcome.
- Wednesday August 26 – Flex and Java at the GatorJUG
- Thursday August 27 – Flex and Java at the Orlando JUG
If you live in Florida then I hope to see you at these events!
I get a lot of emails containing great questions about topics like Flex, rich Internet applications, and bull riding. These emails are usually the highest priority emails for me to respond to – because that’s what a cowboy does. But I was just thinking that when people ask me questions over email other people with similar questions don’t get the benefit of seeing my response. Since I’ve been trying to use Stack Overflow more and more for technical Q&A I thought it would be worth an experiment to see if I can move some of those questions from email to Stack Overflow. So here’s how it works:
- Go Ask a Question
- Tag the Question with “riacowboy” (and other relevant tags)
- Wait for me to get on my horse and respond
And please let me know what you think about this. Thanks!







