flexongrails

A Gentle Introduction to Flex

The main goal of this chapter is to summarize Flex to Java or Grails developers who might not be familiar with the technology. It pretty much represents everything I wish I knew about Flex before I started to learn the language. 

The chapter is broken down as follows:
  • A brief intro to the advantages of building for the Flash player, specially within an enterprise environment.
  • Some of the traditional challenges of Flash tools for developers and how Flex solves them.
  • The technologies that make up what we know as Flex.
  • Cool Open Source technologies built around ActionScript and Flash/Flex.
  • Tips and Resources for Learning Flex. 
Flex in a Nutshell

Adobe Flex is a complete development framework for building Rich Internet Applications. Flex enables developers to build RIAs that run in browsers via the Flash Player runtime or on the desktop via the Adobe Integrated Runtime ( AIR). Leveraging the MXML and ActionScript programming languages, Flex allows developers to quickly transition their knowledge in JavaScript and HTML development into the world of RIA development. 

Why Should I Developing for the Flash Player? 

Reason 1: Market Penetration

One of the main selling points for Adobe Flex is that everything compiles and deploys onto the Flash Player ( or sister technlogy Adobe Air ) Runtimes. The Flash Player is one of the most popularly deployed platforms in the world. Comparable technologies like Microsoft's Silverlight simply lack the installed market share owned by Flex. 

The Adobe website boasts that the Flash Player is available to 99% of Internet-enabled computers worldwide.


Moreover, because the widespread use of Flash to stream videos on websites like YouTube, most of the installations of Flash Player are up-to-date. A June 2009 survey revealed that after only eight months of being released, 87% of Flash Players have been updated to Flash Player 10. 98.8% of the world supports Flash Player 9. 




In the enterprise, the numbers are similar. According to results from Forrester Research, in December 2008, 97.9% of enterprise clients were able to view Flash Player content. This breaks down to 60.8% on Flash Player 9 and 36.0% of users on Flash Player 10, only two months after Flash Player 10's release. ( http://www.adobe.com/products/player_census/flashplayer/enterprise_penetration.html ) 

In contrast, a document by Forrester Research ( http://www.forrester.com/Research/Document/Excerpt/0,7211,47196,00.html ) suggests that 60% of the enterprise browser market is still on Internet Explorer 6. ( http://news.cnet.com/8301-17939_109-10231713-2.html ).

Reason 2: Do Everything You Always Wanted to do WIth HTML But Couldn't.

There are several advantages for developing for the Flash Player compared to traditional HTML / JavaScript / CSS web-browser based development. These include:
  • Support for Streaming Videos and Audio. Flash is the king of video on the web. Adobe recently released the open source Strobe media framework, which aims to allow developers to quickly build custom media players based on the interfaces and communication protocols available via the Open Screen Initiative.

  • Better Font Handling - Flash always had the advantage of allowing fonts to easily be added to a swf file. Flash Player 10 introduces a Text Layout Framework that further simplifies typographical magic like kerning and ligatures, enables international character support and adds the ability to link text boxes on screen. In fact, tools like SIFr use Flash's ability to embed Fonts to allow this to happen in HTML pages.
  • Web Camera Support - currently not possible with JavaScript and HTML. 
  • Better File Uploading Capabilities - Flash Player 10 also rewrites the File uploading mechanism. For example, you can choose an image on your local hard drive and manipulate it ( resize, crop, etc ) before actually sending it onto the server. 
  • Easier to Skin than HTML - Flash development introduces a few innovations to help make skinning easier. Here are a few of the things you can do easily on the Flash Player that is difficult in HTML:
    • Rounded Corners - most components have a CornerRadius attribute.
    • Flexible image borders - Flex provides an innovative way of defining image borders called Scale-9. It let's you split an image into 9 sections and define how each of these areas resize individually. 
    • Vector-based skins with Illustrator and Photoshop support via the FXG file Format. 
    • Flash Catalyst - Adobe also introduces a special tool to take a Photoshop or Illustrator mockup and convert it quickly into a Flash / Flex skin. 
  • Basic 3D Effects - Flash Player 10 introduces 3d effects - 

FP 10 3D Effects Demo



  • Desktop Integration - The Air Runtime enables applications written using the same framework to be added to the desktop.
  • Cross-browser, cross-platform support - Flash runs the same regardless of browser and Air abstracts much of the system requirements of desktop applications, Flex enables us to build applications without spending time worrying about cross-browser and platform compatibility issues. 
  • Multiple communication formats - Under the hood, the Flash player has a support for common http-based formats like AJAX and XML web services. But it also comes with a powerful mix of previously-proprietary communication protocols like AMF and RTMP that enable peer-to-peer and publish-subscribe mechanisms that are difficult to do in traditional HTML. One of the best examples of this use is Morgan Stanley's Matrix sales and trading platform, which uses the diverse publishing technologies to deliver peer-to-peer communication and push quotes.
So we have a platform that is more readily available on enterprise and user machines than comparable technologies like Silverlight or Java, is up-to-date and supports many more features than traditional JavaScript/HTML development. This makes developing the Flash Player an ideal deployment solution for companies and developers looking to build applications that are highly visual and feature rich without worrying about compatibility issues.

Why Flex?

Flash and its Ungodly Love for the Animation Metaphor

As a Java developer who has worked extensively with widget toolkits like SAP Web Dynpro and Java Swing, I was a bit apprehensive about learning Flash. It always had the reputation to be animation-centered and extremely different than the type of developing I was used to. Fortunately, after learning about Flex and it's goals, I can say that it is much easier for developers with other framework experience to pick up easily. Let's look at some challenges of learning Flash application development and how Flex tries to overcome it.

Flash CS4 Professional, or Flash Authoring, is the latest incarnation of the tool traditionally used to build RIAs for the Flash Player. It started life as a vector based web animation tool that slowly acquired scripting, web services and video streaming support. When you start up the Flash application, you are greeted with a screen like this:



You can set it into a development perspective, which looks like this:


The baffling thing about Flash Authoring, from a web application developer's perspective, is that it centers around the idea of a stage, movie clips and a timeline. The tool is built with a primary goal of helping you build animations and rich graphical transitions. It is the perfect tool to build banners and animated games. Yes, there is scripting support. Yes, there are higher level components. The problem is that you don't see them right away and using them always feels like they have been thrown into the tool with a bit of duct-tape and Krazy Glue.

Once you start working with Flash, you start encountering areas that make it difficult to integrate within a traditional J2EE-like development environment. These include:
  • A binary file storage format ( .FLA ) incompatible with most text-based source control systems like git or subversion.
  • No command line tools for building SWF files, making it difficult to automate builds. SWF files need to be build manually prior to deployment.
  • Lackluster debugger.
  • Lack of built-in tools to integrate with web services and service oriented architectures in the IDE.
Flex: Flash Development for the Java ( PHP / Ruby ) Programmer

Luckily, Macromedia realized that using Flash Authoring was going to be a big barrier for the oh-so-sexy and wealthy enterprise application market. After much soul-searching, they introduced the Flex platform. Flex was originally conceptualized as an enterprise development platform on the server side and it has a price tag of $10,000 (ouch) per server. It introduced a java-based SDK, a server side remoting technology later known as BlazeDS and an IDE.

The following table compares the difference between traditional Flash Authoring and Flex / Flash Builder.

 Feature Flash Authoring  Flex ( and Flash Builder )
 File Formats  Binary FLA  XML and Text-based
 Main Metaphor      Movie Stage  Data-Driven UI Components
 Compilation  Only via GUI  Command-line and GUI via Open Source Flex SDK
 Web Service Support                     Not in tool  Supports Coldfusion, BlazeDS, PHP, LCDS and Web Services
 IDE  Based on FutureSplash Animator  Based on Eclipse
 Debugger          Available   Eclipse-based step debugger 

In the next section, we will discuss in more detail the distinct technologies that make up the Flex stack.

Breaking Down Flex: The Different Technologies That Make Up Flex.

It's easiest to think of Flex as a diverse set of languages, components, tools and runtimes that come together to build RIAs based on the Flash Player runtime. The following diagram shows all of the components that make up the Flex ecosystem. 


Languages

As with any framework, there are programming languages used to define application execution logic. In Flex, these are MXML, ActionScript, FXG and CSS.

The difference between these formats and the previous .FLA format defined by the Flash Authoring tool is that they are entirely text-based. This enables code written for the Flex framework to be easily checked into a source control system, or generated with tools like the GraniteDS GAS3 toolkit - which builds ActionScript files from Grails domain model declarations. 

MXML and ActionScript

The two big bads in defining components in the Flex framework are ActionScript and MXML. These two languages are used to define and lay out components within your Flex applications. ActionScript 3.0. is a scripting language compliant with the third edition of ECMAscript. MXML is a XML-based declarative language. In traditional web development terms, ActionScript is like JavaScript where MXML is like HTML.

Code written in MXML is compiled into ActionScript, which makes everything available within ActionScript also available as MXML tags, and vice versa. Think of it as the same functionality spoken in two different dialects of code. This makes it very convenient for staffing development teams, as you can easily transition developers with HTML knowledge into building MXML components and developers familiar with JavaScrit into ActionScript. 

The following code snipplets, from Adobe's MXML vs. ActionScript article, give us a brief idea of both how ActionScript and MXML look like, and how the same function might look in the two different languages:

Code Listing in MXML:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundColor="#FFFFFF"
backgroundAlpha="0">
<mx:Image source="assets/animals03.jpg" />
<mx:Label text="Photographed by Elsie Weil" />
</mx:Application>

Code Listing in ActionScript:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" backgroundColor="#FFFFFF" backgroundAlpha="0" initialize="addControls()">

    <mx:Script>
<![CDATA[
import mx.controls.Image;
import mx.controls.Label;

private function addControls():void {
createImage();
createPhotographer();
}

private function createImage():void {
var photo:Image = new Image();
photo.source = "assets/animals03.jpg";
this.addChild(photo);
}

private function createPhotographer():void {
var photographer:Label = new Label();
photographer.text = "Photographed by Elsie Weil";
this.addChild(photographer);
}

]]>
    </mx:Script>
</mx:Application>

They would both render out this component: 



Interesting Aside: Nobody really seems to know what MXML stands for. In early news articles about Flex in 2004, it was referred to an acronym for Maximum eXperience Markup Language, which to me, sounds like a bunch of middle-aged ad executives dreaming of radical marketing campaigns where programmers chugged Mountain Dew, jumped out of a plane and coded Flex at the same time. Others have suggested that it in fact stands for Magic eXtensive Markup Language. The sad truth, however, is that mxml is probably a remnant of the days where Macromedia used to put the mx: prefix in front of everything. MXML was simply mx:xml ~.                           

FXG

As of Flex 4, Adobe also introduces a new format for vector graphics called Flash XML Graphics ( FXG ). 

The goal of FXG is to help separate the presentation of components from their actual model implementation. It separates the work done by a designer from the work done by a programmer. Each component defines Skins and Skin parts, which are defined separately in the FXG format. Think of it as a structural style sheet. With CSS, you can define the image source of an icon, but you're still forced to have one icon. With FXG, you can define multiple icons, their positioning within the button and custom transition states for these icons. 

One of the other advantages about FXG is that it readily integrates with Flash Catalyst, Adobe Illustrator and Adobe Photoshop. There is also a script that exports to FXG from Adobe Fireworks. This technology makes taking a design comp from a designer and converting into a clickable, working FXG skin that can then be integrated into Flex a very simple and straightforward process. To learn more about this process, check out the Flash Catalyst videos from Adobe Flash Camp. 

Here is an example of a hello world application from Mike Chamber's Blog:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="libray:adobe/flex/halo" xmlns="http://ns.adobe.com/mxml/2009">
    <mx:Canvas top="0" bottom="0" left="0" right="0">
        <Group verticalCenter="0" horizontalCenter="0">
            <TextGraphic fontFamily="Verdana" fontWeight="bold">
                <content>Hello World</content>
            </TextGraphic>
        </Group>
    </mx:Canvas>
</mx:Application>

The code in blue is the FXG markup. It generates a text field in the middle of the screen that says hello world in verdana, bold.

Again, the nicety of FXG is not that you have a vector graphic format that you can edit by hand. Rather, FXG is supported by all the Adobe graphics packages such as Photoshop, Illustrator and Fireworks, which are already being used in the production of visual comps and design prototypes. FXG makes checking in graphic files friendlier to source control systems and enables the interchange between Adobe products easy. You can edit the FXG file for a button using Illustrator, import it into Flex and then edit it again in Illustrator when a change is needed.

CSS

Flex 4 has complete support for Cascading Style Sheets. I could write until my wrists go limp about this feature, but you could probably learn more about this feature by watching the following video: http://labs.adobe.com/technologies/flash/videos/flashcamp/lafferty/

Components

The Flex framework also introduces a set of Visual Components that enable developers to quickly build easily customizable User Interfaces. Compared to the set of components provided by HTML, Flex provides higher level components such as Tab Navigation, Trees, Date Selectors, Sliders, Accordion Controls and Flexible Data Grids normally available only through widget toolkits like YUI, Dijit or JQuery plugins

One of the strengths of Flex Visual Components is that they offer a deeper integration into the platform compared to conventional JavaScript widgets. For my day job, I use a lot of JQuery plugins. I love JQuery. If I could marry JQuery and have hideously deformed half-JavaScript half-Chinese babies, I would. However, compared to Flex, binding data to JQuery components feels cumbersome and tacked-on. 

Flex provides a robust event model and has built in syntax for passing data between it's ActionScript and MXML counterparts. For example, in JavaScript you would have to change the underlying HTML code in JavaScript to react to data changes. In Flex, you can use the Bindable keyword to associate your data driven components to variable and the framework handles these changes for you. This makes the development process much easier. 

For example, to bind the variable myString to a label, I would simply declare it as [Bindable], which let's the framework attach an event listener to it, 

 [Bindable] private var:String myString

then, in my MXML code, I would simply bind this variable via the square brackets notation:

 <mx:Text label="{myString}"/>

Flex components are fully skinnable, comply with a robust event model and are highly customizable. Moreover, Flex components are also built with accessibility in mind. You can (and really should) read more about that here.

Halo vs. Sparx?

Flex provides two sets of components, which can cause some confusion. There is one set located in the Halo libraries, with the namespace mx.controls.*. And another set called Sparx components, which have a package namespace of  sparx.components.*. If you only look at the components available under the sparx namespace, you might miss many other high level components not yet ported. 
These changes come because of the Skinnable interface introduces in Flex 4. Flex 4 components, under the sparx namespace, have a different component lifecycle that enables their display and positioning to be easily customizable. However, this also means that new components had to be written to adapt to the new interfaces. Adobe provides a helpful list of the differences between Flex 3 components and Flex 4 components here.

Flex SDK

At the core of Flex is the open source Adobe Flex SDK. This Java-based tool transforms code and projects written in MXML and ActionScript into the Flash movies we love and cherish. 

There are several advantages introduced by the Flex SDK:
  • Open Source - means that we can write code that leverage the Flex SDK without having to buy the Flash Builder tools. 
  • Command line interface - previously, SWF files could only be built using the Flash Authoring tool. With the Flex SDK, 
  • Java-based - 
Compiled Code

Runtimes

Tools

Server Side Flex.

Flex, ActionScript and the Open Source Libraries That Loves Them.

This last section is about the open source technologies and possibilities available when choosing Flex. A common misconception is that since Adobe is the master and corporate sponsor of Flex and it's surrounding ideas, there is little developing happening in the open source space. In fact, the reverse is true. Given that Flash is the technology of choice for many cutting-edge media and design companies, there are significantly more choice in rich media development compared to JavaScript frameworks like jQuery. The open source community around Flex make it, in my opinion, one of the more compelling choices for Rich Internet Application development. With the following projects, I've tried to provide links to project home pages or showcases. Please take the time to play with the demos.

Data Visualization

Degrafa

Axiis
( http://www.axiis.org/)


Birdeye
(http://birdeye.googlecode.com/)



( http://birdeye.googlecode.com/svn/branches/ng/examples/demo/BirdEyeExplorer.html )

Physics
http://box2dflash.sourceforge.net/

3D
Papervision3D and Away3D


Run C/C++ libraries via Adobe Alchemy

Alchemy is a project that uses LLVM (http://llvm.org/) to enable C/C++ libraries to be compiled into the ActionScript interpreter. What this means is that you can take the functionality provided by a C/C++ library and have this executed inside a Flash Player movie. This is great for

Doom, Heretic and Hexen on Flash via Alchemy - ( http://www.newgrounds.com/portal/view/470460 )

Augmented Reality with FLARToolKit 

The FLARToolKit is an open source project that ports the augmented reality ARToolkit ( http://www.hitl.washington.edu/artoolkit/ ) into Actionscript. Augmented reality uses the Flash Player's ability to access a computer's webcam to add objects onto a screen where none existed before. Check out these projects,

GE SmartGrid

GE SmartGrid uses FLARToolkit to show you alternative energy systems ( http://ge.ecomagination.com/smartgrid/ ) 

 

Living Sasquatch

Living Sasquatch - let's you build and control a Sasquatch ( http://www.livingsasquatch.com ) 

Data Frameworks.

BlazeDS, GraniteDS. 
RubyAMF, ZendAMF

ActionScript Data Frameworks

Gaia Sprouts

Swiz, Mate, Cairngorm, Paisley, PureMVC

Learning Flex - Websites and Resources

Websites

As you can see, there are many parts to developing in Flex and ActionScript. Teaching Flex and ActionScript is beyond the scope of this book. The following section contains useful links and tutorials to get you familiar with the Flex platform. We will cover the necessary ActionScript and MXML code needed in this book in the appropriate sections. Here are some of my favorite resources:
  • Adobe Tour De Flex Component Explorer - The Tour de Flex is a wonderful tool put together by Adobe that contains samples to both core flex and examples of third-party library and service integrations. It combines all the code samples into a comprehensive and easy to navigate application and is available as an Adobe AIR application. (http://www.adobe.com/devnet/flex/tourdeflex/)

  • Learn Flex in A Week - This is a free video training program offered by Adobe that covers all the basics of Flex. Unfortunately, the series only covers Flex 3, but I'm sure this will be updated once Flex 4 becomes available. ( http://www.adobe.com/devnet/flex/videotraining/ )

  • Lynda.com Video Training for Flash Catalyst 4 - Lynda.com offers a free online training course on Flash Catalyst

  • Gotoandlearn.com series on Flex 3 and 4 - Lee Brimelow is an evangelist at Adobe that has an excellent of video tutorials he offers on his website gotoandlearn.com. ( http://www.gotoandlearn.com ). Recent videos include a complete tutorial on Flash Builder 4 and Flash Catalyst 4.

  • Adobe Labs Video and Training Tutorials - This is a comprehensive selection of videos and tutorials about features of Flash and Flex 4 hosted by Adobe Labs. ( http://labs.adobe.com/technologies/flash/videos/ ). The FlashCamp demonstrations are really interesting, as they involve members of the Flash community.

  • Flex and RIA on Parleys.com
    • Enterprise RIA with Flex and Java - A presentation presented by Marc Meewis on Javapolis '07 that nicely presents the concept of RIAs and they relate to the Flex ecosystem.
    • The Future of Rich Internet Applications - A presentation by Matt Chodin, Chet Haase and James Ward ( all Adobe ) from Devoox '08, This talk is fantastic in understanding the Adobe vision for Flex and RIAs and covers briefly the vision for the Spring Integration project.

  • London Flash Platform User Group Presentations - The London Flash Platform user group is a monthly meeting presenting various topics from the Open Source Flex community. Videos are made available online and available at http://www.lfpug.com/category/presentations/ .

  • Adobe Flex Online Documentation. - User Guides, API references and good refences. ( http://www.adobe.com/support/documentation/en/flex/ )

Book Recommendations

Be aware that any book that you buy on Flex 3 will become outdated with the release of Flex 4 at the beginning of 2010.

  • First Steps in Flex - written by Bruce Eckert, the author or Thinking in Java and Thinking in C, this is an excellent reference for beginner Flex developers. ( to learn with this book, click here to buy )
  • O'Reilly Getting Started With Flex - this is a good smaller reference guide to Flex. ( Download free in pdf format here )

  • Charles E. Brown's Essential Guide to Flex - This book is a wonderfully written, easy to follow complete reference to Flex. ( Buy this book for  Flex 3 ) ( Buy this book for Flex 4 )

  • AdvancEd Flex - These books cover more advanced topics in Flex development. They are very good for understading architectural patterns and advanced integration. ( Buy this book for Flex 3 ) ( Buy this book for Flex 4 )

  • Developing Flex Components - Mike Jones is one of those guys that has been building Flash components for a long time and understands the intricacies of Flex component development. This book covers both Flex 3 and the new component models in Flex 4 and looks very promising. ( Buy this book here )
Summary

In this chapter, we looked at the applications and technologies that make up the core of Flex technology, as well as some really wonderful open source projects available to Flex developers. Hopefully, this chapter showed you that Flex is not only a visual display technology, but rather a robust infrastructure with it's own scripting language and open source community.