Notes on Rocky Mountain Flash Camp (10/12/10)

These are some notes on the recently held Flash Camp in Denver that I attended. I’ve included links to slides where I have them and the recordings that were made of each session (apparently the first 3 sessions had some audio issues).

First off was RJ Owenof Effective UI on the Flex 4 Component Lifecycle (slides,recording) who covered the classic elastic racetrack (for some reason I always want to say electric racetrack), the birth, life and death of components and where the “skin” aspects of Flex 4 come into play. He also covered some performance considerations (such as constructors are not JIT compiled and therefore not optimized so should be as small as possible).

Next up Paul Trani of Adobe covered a Flash CS5 deep dive (recording) going through some of the things you can do with the tool. It was an entertaining session with more of a designer emphasis.

Kevin Hoyt, also of Adobe went next on the Flash Player for Flex Developers (recording). Unfortunately, Kevin’s blog seems to be unavailable while I’m writing this but you should find him at probably after Adobe MAX is finished. This talk was one I’d seen Kevin give before going through a simple app to gather weather data written purely in Flash starting with the stage and using Sprite as the base object for the display components. The end result was a Flash program of ~ 3k compared to a Flex program (using framework libs) of ~100k. This time I remembered to ask him if there were any lightweight Flash frameworks I could look at rather than re-inventing everything myself. His suggestions were AS3CoreLib and MinimalComps.

James Ward (Adobe) talked about Mobile Flash and Flex Development (recording). His session covered the “Tour de Flex” mobile app for Android he’s currently working on using Flex Hero beta. It’s not generally available yet but you can find his code on github.

David Hassoun of RealEyes Media talked about Video on the Flash Platform (recording) which demoed some of the features of the Open Source Media Framework (OSMF)

Jun Heider also of RealEyes Media covered “cool things you can do with Flash Player P2P” (slides and source,recording). I had vaguely heard of Adobe Stratus (now Cirrus) but that was about it so it was interesting to see some examples of how it could be used.

Last but not least was Juan Bonfante of Roundarch talking on Advanced skinning and layout with Flex 4 (code,recording).

RMAUG did a great job putting on this camp and if you’re in the Denver area on November 9th, you should check out their “Mini MAX” event (details on the website).


Use the Force Luke!

The “Force” in this case being (or SFDC). If you haven’t heard of it, is a cloud platform, Software as a Service (SaaS) offering for sales related activities. It also has modules for customer relationship management (CRM) as well as more general computing services.

You can sign up for a free developer account and find plenty of documentation to get you started here. SFDC allows you to create or modify database tables by creating custom objects or fields, query the data using a SQL like language  – SOQL (Salesforce Object Query Language) , write business logic in a Java like language called Apex and display code using Visualforce pages which is javascript with custom tags.

One thing to keep in mind when you start working with SFDC are the governor limits. Because you’re working in a shared environment, Salesforce doesn’t want you hogging all the resources so there are limits set to make sure things don’t get out of hand. When developing using Flex, you’re using a wrapper for the web services api so the “WSDL method” column in the link above is what you’re interested in. Basically, what this means is you should try and limit the number of queries you do (<100) and the amount of data you return for them (<10,000 rows).

One annoying factor  is that SFDC counts the number of rows it has to look at to perform a query to determine if you hit the limit so if you issue a query like “select count() from Opportunity” and you have more than 10,000 opportunity records, you’re going to get a system exception. Not only that, you can’t catch that type of exception so you’ll need to use a limit clause  if you think you’re going to get near that level.

Salesforce Flex APIs

There are two APIs for Flex provided by Salesforce. The older Flex toolkit SFDC page, Adobe Page which is basically a wrapper for the web services interface as a library swc file and a newer Flash builder interface SFDC page, Adobe page which is still currently in Beta and involves a custom version of the Flash builder tool. It seems to be suited more to Air apps working outside of SFDC as it contains data synchronization capabilities. For the rest of this post, I’m going to concentrate on the older API as it’s the one I’ve actually used for a deployed app. You can find documentation for the classes it provides here.

Internal or External

You can design your Flex app to run either within SFDC or as an external app (either hosted on your own webserver or as an Air application). If you’re going to run externally, your users will need to login to SFDC via your app to allow you to access the data.  When logging in externally, users must append a security token to the end of their password (from setup on the top of the page, My Personal Information on the left, Reset My Security Token) unless the ip address they are logging in on has been entered as a member of a trusted network (from setup, Security Controls, Network Access).

Regardless of how you connect to SFDC, the method of the Connection class you use is the same, login() the data you provide is what changes. For an external app, you’ll provide serverURL. username and password in your LoginRequest object, for an internal app, server_url and session_id.

Unless you have specific reasons not to, it makes sense to let SFDC host your Flex app and have your users access it in the same place they’re using for their other activities related to that data.

During development, I would hard code a login to run your app externally so you can use it with your debug player to get trace data etc and then convert it to use the internal SFDC data before you build it for deployment.

Deploying a Flex Application to Salesforce

Once you have a swf for your application, you can load it onto SFDC as a static resource. To do this, select setup, Develop, Static Resources, new, provide a name for your app and browse to the swf file on your machine.

Now you have the swf, you’ll need a wrapper page to access it. Select setup, Develop,Pages, new and you can enter your visualsource code to display the swf. If you’re going to be doing a lot of SFDC development, they provide an eclipse based IDE which is worth getting to know.

If you look at the getting started code through the “Flex toolkit” link above, you’ll see the use of an <apex:flash> tag. This works but causes a security warning pop up when running on IE which might cause problems for some of your users. The way around this is to use  swf wrapper code more like the example below.

You’ll need to use flashvars to import the session id and server url to your app (along with any other startup data you might want. I’ve had issues sometimes using the !API.Session_ID parameter so you’ll see a reference to !mySessionID in the code below which comes from the custom Apex class SessionUtil provided as the page controller which we’ll discuss later.

Here’s an example visualsource page for a Flex app:

<apex:page controller="SessionUtil" sidebar="false" showHeader="false">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  id="FlexAPP" width="1200" height="820"
  <param name="movie" value="{!$Resource.FlexAppName}" />
  <param name="quality" value="high" />
  <param name="bgcolor" value="#869ca7" />
  <param name="allowScriptAccess" value="sameDomain" />
  <param name="flashvars" value="uid={!$User.Id}&sid={!mySessionID}&surl={!$API.Partner_Server_URL_150}
  &name={!$User.FirstName} {!$User.LastName}" />
  <embed src="{!$Resource.FlexAppName}" quality="high" bgcolor="#869ca7"
    width="1200" height="820" name="Name of my App" align="middle"
    &name={!$User.FirstName} {!$User.LastName}"

The FlexAppName after $Resource is the name you gave the Static Resource for your swf file. You can get data from the user record for the user logged in using $User everything else is either boilerplate stuff or pretty obvious.

The Apex class SessionUtil needs to be added using Apex Classes under the Develop menu. Here’s the most basic version of it:

public class SessionUtil
    public String mySessionID {get; private set;}

    public SessionUtil() {

You can expand on this to use SOQL queries to grab more data if you need it to initialize your app. This solution is based on the one provided by Wintermute (love that username!) I just didn’t want to work off a standard controller.

Once you have your page setup you can access it directly by <salesforce url>/apex/pagename or you can configure it to appear wherever Salesforce lets you reference a visualforce page (dashboard, custom links etc).

Tips for Developing using the Salesforce API

The API pages linked to above are a great place to start. Both the Adobe pages have videos going over what they provide and  Adobe evangelist James Ward has a number of great posts on both APIs.

Although the old API has been around for a while, it works perfectly well with Flex 4 – that’s what I built my app with.

The API documentation is pretty light and doesn’t go into a whole lot of detail – the thing to remember is it’s basically the web services API so you can usually find more detail looking at that documentation. Look for the “see also” link to Apex Developer Doc in the top description of the API class documents or go directly to the Web services API document.

The interface is asynchronous – you’ll declare a success and failure handler for each request. Usually you can reuse your fail handler and you should at least check for  “INVALID_SESSION_ID” so you can warn the user their session has timed out. Different Requests give rise to different result objects – QueryResult, SaveResult, UpsertResult so make sure your result handler is using the correct one for your request. All results are provided as an array.

A lack of a fault event does not necessarily mean your insert/update/upsert was successful. You need to check your result object for an id. Here’s an example upsert handler:

//upsert  handler
 private function handleUpsert(result:Object):void {
     if (!(result[0] as UpsertResult).id) {
     //failed to update/add
     trace('error on change: ' + (result[0] as UpsertResult).errors.getItemAt(0).message);"Unable to update SalesForce: "+(result[0] as UpsertResult).errors.getItemAt(0).message,"Error");

Salesforce has field level security so one reason you’ll see an error is if your user does not have permission to write to that object or field.

Keep your SFDC interaction encapsulated in it’s own class and define data objects to carry the information you work on for the rest of your app. I used an XML file to generate the data I wanted within my Salesforce class initially, it gave me the chance to work on the display side while I was still figuring out my SFDC queries and generate data conditions to test for without having to alter data in SFDC. I could then switch that out for the real code without having to change anything else as the interface stayed the same.

Don’t forget to test logged in as your target users. As a developer, you’ll probably have a profile that allows you full access to everything, your users will likely be more restricted so you need to make sure they can access everything your app is going to need.

Learning Flex 4 – States

States are easier to work with in Flex 4 than they were with 3. While Flex 3 had the advantage that everything to do with your states was in one place, it made things more complicated by the additional syntax you had to deal with to add/remove items etc. With Flex 4, you can just add your state name to a property to specify a value specific to that state and specify if components should be included in/excluded from a state. The only downside to this is that your state specific code gets scattered but Flash Builder has an option to show you components by state so that helps there.

Starting from the beginning, you first need to declare what states you are going to have. This is done using the <s:states> tag. Within this, specify one or more <s:State> tags with the name property set to the name for your state. The first State is used as the default. In addition to the name, you may also specify a stateGroups property. This allows you to group states so you can refer to the group rather than all the individual states. This could be useful in the case where for most of the time, you want to do the same thing for several states but for specific components/properties you need a finer distinction.

Here’s an example (I like to use all caps for my state names to help them stand out a little more):

<s:State name="LOADING"/>
<s:State name="EMPLOYEE_VIEW" stateGroups="VIEW" />
<s:State name="MANAGER_VIEW" stateGroups="VIEW"/>
<s:State name="MANAGER_SELECT" />

The grouping is a bit artificial in this case but this app starts in the LOADING state while it’s gathering data from the back end. Then, if you’re a manager, the state becomes MANAGER_SELECT where you can select an employee to view data on, finally you get a MANAGER_VIEW of the data or the EMPLOYEE_VIEW if you logged in as an employee. You can see how there might be several components common to the MANAGER_VIEW and the EMPLOYEE_VIEW which you could use the VIEW stateGroup for but some components (maybe a change pay rate button for instance) would be specific to the MANAGER_VIEW.

You can include components in a state by using the property includeIn or exclude them using excludeFrom.  You can specify more than one state by using commas to separate them in the string (or specify a stateGroup). By adding the state to a group container, you can affect all the components within that group.

You can change properties (including event handlers) by suffixing the property name with the state name you want it to apply to eg – label.LOADING="retrieving data..."

If you don’t specify a state, the component/property is considered to be the same for all states. You can change the state by setting the currentState property (by setting it to the empty string, you return to the default or first state).

Custom components can declare their own states and you can use the currentState property of the instance of the custom component to change the state for that particular object.

When the state changes, the enterState event is fired by the State object being entered and by components entering that state. The exitState event is sent by the State and components being left. The object the currentState is being changed on fires currentStateChanging when it’s about to change and currentStateChange when it’s done.

You can use states within a custom item renderer to react to view states such as hovered, selected and change the presentation for these cases. This article has the details. Saturn Boy has also written a blog post looking at states with skinning.

Learning Flex 4 – Spark Components and Skinning Basics

One of the key changes to Flex moving to version 4 is the introduction of the Spark component set.

The components in Flex 3 (Button, TextInput etc) were known under the code name Halo and they’re still available in Flex 4. These components are distinguished by the mx namespace prefix you are used to. The new Spark components have an s prefix and require the addition of a new namespace definition – xmlns:s="library://" (The mx namespace definition also changes to  xmlns:mx="library://").

There are Spark equivalents of most but not all mx or Halo components (DataGrid, AdvancedDataGrid and Tree are some of the currently missing).

The key difference in the component sets is their construction. Halo components contain everything required for that object including styling, behavior and layout. Spark components on the other hand, separate out the behavior of a component from the display aspects. The information corresponding to component display is kept in a separate skin class.

The upshot of this change is that the look and feel of an application can be separated from it’s behavior and more readily changed. With the introduction of the Catalyst tool in CS5, designers can deal with the display skins while developers deal with the underlying behavior.

You can specify the skin a component should use with:

  • CSS: S|Button {skinClass: ClassReference ("com.example.skins.MyButtonSkin");}
  • MXML: <s:Button skinClass="com.example.MyButtonSkin"/>
  • ActionScript: myButton.setStyle("skinClass",Class(MyButtonSkin);

The skin class is generally written in MXML and defines the states (with transitions) the skin reacts to, graphical elements and any component parts the skin is constructed from. The skin may also specify the HostComponent in a metadata tag. The HostComponent is the component class that will use the skin. This is useful for the skin to be able to gain a reference to properties of the component instance.

A skin class must declare state properties that are specified for it’s host component. For example, a Spark Button has states up, over, down and disabled so the skin must declare what it looks like for each of these states. The component will then set the relevant state at runtime.

Skin parts are sub components used to define a larger component – for example, a scrollbar has increment and decrement button parts together with a track and thumb part whereas a button just has a label.

The graphical elements of a skin are defined using a new graphics tag library cald FXG which includes graphics and text primitives including tags for creating basic shapes, fills, gradients and bitmaps. FXG is also used by Catalyst and other tools to transfer graphical data. The specification for FXG can be found here.

A great way to begin working with Skins is to modify the Adobe supplied skin class for a component. Flash Builder 4 has a workflow for creating skin classes that allows you to work from a supplied class. With FlashDevelop, you’ll have to go off and find the class for yourself and copy it in to your project under the name you want. You’ll find the skin class source files under your SDK install in the frameworks\projects\spark\src\spark\skins\spark directory.

For further detail on skinning Spark components, take a look at these Adobe articles.

Posted in Flex. 4 Comments »

Where do we go from here?

My previous post completes what was hopefully a good introduction to Flex 3 so what next? Well don’t worry, there’s plenty more stuff out there to learn.

To start with, Flex 4 is in beta now and due to be released some time this year. It’s not a complete redo so there’s plenty that carries over from 3. Many of the changes revolve around the new Spark component set and the way they’ve separated out appearance (with skinning), states (with the new states design) and behavior. This supports the Catalyst tool as I’ve covered briefly in prior posts.

You can download the SDK for Flex 4 Beta2 from here and use it with FlashDevelop (although it only understands the MX namespace right now so it’s MXML autocomplete isn’t very helpful).

There’s a good article on the differences between Flex 3 & 4 here to get you started and that’s certainly something I plan to post more on in the future.

Another avenue for exploration is frameworks – if you’re going to be writing Flex professionally as part of a team or larger apps on your own, you’re probably going to need to know about them. One of the oldest and most well known is Adobe Cairngorm. It’s sometimes criticized as heavy and requiring a lot of boilerplate code but because it’s well known, it’s probably worth at least knowing how it works. A newer contender is the Swiz framework. I’ve seen a couple of presentations on this and plan to get to know it a lot better.

There are plenty of ActionScript libraries you can use, I’ve already written about Google maps and the FLAR toolkit manager but I plan to start looking more into data visualization using Axiis in the future.

All in all, I’d say there’s plenty to keep me busy here!

Learning Flex – Lesson 26, The Basics of Memory Management and Performance

There are two basic ways to handle memory allocation. The first (used by C,C++) is to make the developer deal with it – you are responsible for allocating memory required and freeing it when you’re done. This allows the developer the freedom to decide when time consuming memory operations are done but the responsibility to keep track of everything or run into memory leaks (when unused memory isn’t released) or null pointer issues and the like when it’s released too soon.

The alternative chosen by Flash (and Java) is to use the runtime for garbage collection – i.e. let it decide how to allocate and free memory. The downside to this is that garbage collection can be time consuming and it’s nondeterministic – the runtime decides when it’s going to happen, not the developer.

There are several different algorithms for  garbage collection. The Flash player uses a version comprised of “reference counting” and “mark-and-sweep”. (For a discussion of various garbage collection strategies see this article).

For reference counting, the runtime keeps track of all the active references to an object. Each object keeps a reference internally to its children and each child has a reference to its parent. There are also references created explicitly by the developer as a way to access the object in question. If the reference count is zero, nothing can access that object any more so it can be removed and it’s memory reclaimed.

The second phase, mark-and-sweep is more costly and required to discover circular references – i.e. objects that reference each other but have no outside references. To perform the mark, the player starts at the root of the application and traverses through its references marking each as it goes. When it’s reached the leaf nodes of all those references, any objects not marked can be “swept” away and deallocated. Due to its cost, this operation is performed iteratively over several frames and is only run occasionally.

What does all this mean to a Flash/Flex developer? Well you should be sure to remove all references to an object when you no longer need it. Often this will be done for you with variables going out of scope etc but you should be proactive in removing longer lived references you no longer require.

Event Listener Leaks

Objects that want to be informed of an event can register as a listener using the addEventListener() method. This results in the creation of a reference to the object doing the listening. Therefore if an object is listening for events, it may not be available for garbage collection.

There is a method called removeEventListener() that can be called to remove the reference when it’s no longer required which would allow the listener object to be removed when it has no other references. Unfortunately, it’s not always easy to know when to call this.

An alternative when calling addEventListener() optional parameters may be added, the last of which is a Boolean indicating a weak reference (the default is false). What this means is that if set true, the reference created for the listener is considered weak and not counted as a reference for garbage collection. A listener with only weak references remaining would be eligible for garbage collection. Here’s a post with more on weak references and here’s an opinion on when they shouldn’t be used.

Flash/Flex Performance tuning

FlexBuilder (and now FlashBuilder) professional comes with a profiler tool that allows you to investigate the memory usage of your application and time operations to look for areas in need of tuning.

There are no free alternatives that I’m aware of but you can use flash.utils.getTimer() to time operations and System.totalMemory to keep track of memory use in your application. Grant Skinner also has a performance test harness you might find useful.

A great resource with lots of links to more detailed information on memory management and performance is this page on Jun Heider’s blog.

Learning Flex – Lesson 25, Debugging, Logging and Error Handling


Perhaps the simplest form of debugging is adding a trace() statement to your code to print out when a function is entered or the value of a variable at a particular point.

In addition to the global trace() method, the <mx:TraceTarget/> tag allows you to see communication with a remote server. This can be particularly useful in determining what (if anything) your server is returning for your requests.

TraceTarget actually sets up the Flex logging API. The appearance of the server communication is down to the fact that the internal Flex components mx.rpc.*, mx.messaging.* and* all use this API. We’ll come back to logging later.

A more interactive strategy for finding errors is to use a debugger. If you’re fortunate enough to have access to Flex Builder, you have a built-in graphical debugger that will allow you to set breakpoints, inspect variables etc.  If not, the Flex SDK comes with a command line debugger – fdb. This can be found in the bin directory and started by typing fdb and then run location of swf or just fdb location of swf directly. You can use help or tutorial at the fdb prompt to get information on the commands available. Basically you can set breakpoints (even conditional ones which the Flex Builder version doesn’t support), step through code and print or change the values of variables. It’s not quite as easy to use as the Flex Builder version but it will get the job done. There are also some 3rd party free tools available such as Demonster Debugger which can give you some of the features of a graphical debugger along with memory usage and frame rates but unfortunately, don’t support breakpoints.

Here’s Adobe’s info on the command line debugger and here’s a great chapter from the book Programming Flex 3 that OReilly have kindly put on their website that covers the command line debugger, the Flex Builder debugger and the logging framework.


The aforementioned OReilly chapter covers this topic really well. You can define different levels of logging (debug, warn etc) and filter on which you want to be logged. You can also determine what happens to your log data so for instance, you could arrange to log particularly worrying errors back to your server or perhaps to a local file that support staff could request users email them if problems occur.

Error Handling

Like most modern languages, ActionScript3 has the concept of exceptions and the associated try, catch, throw and finally commands.

Runtime exceptions occur during the operation of the application, often due to unexpected input or problems communicating with remote systems. In these situations, you can place the potentially troublesome code within a try-catch block like so:

some dangerous code
do something about the error

Within the catch block, you can access properties and methods of the Error object: message; name; getStackTrace() – for debugger versions of the Flash player, returns the call stack for the error as a String and toString() which returns “Error” by default or the value contained in message if defined.

There are a number of error classes defined both by ECMAScript and ActionScript, more details on which can be found here.

You may define multiple catch blocks to deal with specific error classes. The rules are that the first catch block to satisfy the error will be executed and only one catch block may be run. For this reason, you should never use the base class Error before other catch blocks as it will always take the error.

The throw statement allows you to raise an exception which will bypass the normal operation of your application. You would normally do this if you have discovered a condition that prevents the normal flow of execution. You may either throw an existing error type or create your own by extending the Error class.

The finally statement should be placed after all catch blocks and is used to define code that should be executed regardless of whether an exception was raised or not (generally this is used for something like freeing resources requested in the try block).

Flash player 10.1 introduces the concept of a global error handler so you can trap errors that have otherwise not been processed. This allows you to have a catch-all point where you can at least log something and potentially inform the user before gracefully exiting.

According to the release notes (pdf), the current beta 2 of 10.1 has this functionality disabled but here’s a blog post from Christian Cantrell on how to do it using Air and here’s some more detail about the UncaughtErrorEvent.