FlexBook

20070306_FlexBook1.jpg
20070306_FlexBook2.jpg

This is the most amazing example of a Flex component I saw. I missed the ‘Making Components’ at the 360Flex conference in favor of the E4X talk. But thankfully the E4X talk finished early and left me 15 minutes seeing the end of the Making Components talk…and I was blown away. Ely Greenfield presented how he created the FlexBook component and presented some of the important concepts behind it. I know Flex is powerful but I didn’t realize you can achieve what Ely did, so maybe this is just the start. So check out these two examples to get a fell what your browser can do for you:

http://demo.quietlyscheming.com/book/app.html
http://demo.quietlyscheming.com/book/Anatomy.html

Ely also showed some Apollo application that implements paged browsing…Like Firefox on steroids!!.

Posted by Daniel Wanja Wed, 07 Mar 2007 05:09:49 GMT


Mapping Rails Errors to Flex Fields.

20070306_signup_errors.jpg

We extended the com.wheelerstreet.utils.ValidatorForm to add support for Rails Errors. Saving a form is a two step process. First, client side validation, the Signup button only gets enabled if the form is valid from a client side point of view. Step 2, server side validation, the user press the signup button and invokes the Rails UserController#create method

class UsersController < ApplicationController
  def create
    @user = User.new(params[:user])
    respond_to do |format|
      if @user.save
        self.current_user = @user
        format.xml  { head :created }
      else
        format.xml  { render :xml => @user.errors.to_xml(:dasherize => false) }       end
    end
  end
end

If saving the user fails then Rails return the xml version of the errors:

@user.errors.to_xml(:dasherize => false)

Now we need a generic way to deal with these errors. We created the Flex RailsErrors class to manage the returned xml. And we created the RailsValidationForm that extends the com.wheelerstreet.utils.ValidatorForm. The RailsValidationForm class can be bound to a RailsErrors instance. So the result handler of the Flex Cairngorm Flex SignupCommand we just set the errors on the model locatorL

	var errors:RailsErrors = new RailsErrors(data.result as XML);
	MySpyderModelLocator.getInstance().signupErrors = errors;

The signup.mxml page contains the following signup form

<mx:Canvas 
		xmlns:mx="http://www.adobe.com/2006/mxml" 
		xmlns:rails="org.onrails.rails.*"
>

 <mx:Panel x="162" y="64" title="Signup - Your Account Details.">		 	
     <!-- Instance of org.onrails.rails.RailsValidationForm  -->
	 <rails:RailsValidationForm 
			id="submitForm" 
			defaultButton="{signupButton}" 
			validators="{validators}" 
			fieldMap="{{Email:email, Password:password}}"
		    railsErrors="{MySpyderModelLocator.getInstance().signupErrors}"					
	 			x="98" y="89">
	 		 <mx:FormItem label="email">
	 		 		 <mx:TextInput id="email" />
	 		 </mx:FormItem>
	 		 <mx:FormItem label="Password">
	 		 		 <mx:TextInput id="password" displayAsPassword="true" />
	 		 </mx:FormItem>
	 		 <mx:FormItem label="Confirmation">
	 		 		 <mx:TextInput id="passwordConfirmation" displayAsPassword="true" />
	 		 </mx:FormItem>
	 		 <mx:Button id="signupButton" label="Signup &gt;&gt;" click="signup()" enabled="{MySpyderModelLocator.getInstance().signupButtonEnabled}"/>
	 </rails:RailsValidationForm>
 </mx:Panel>
 <rails:RailsErrorBox x="487" y="64" width="301" height="178"
 	errorMessage="errors prohibited this new account to be created"
 	errors="{MySpyderModelLocator.getInstance().signupErrors}"  
 	visible="{MySpyderModelLocator.getInstance().signupErrors &amp;&amp; MySpyderModelLocator.getInstance().signupErrors.hasErrors()}"
 />
</mx:Canvas>

The RailsErrorBox just displays the text of all error messages and is only visible if there are any Rails errors.

Now all the magic happens in the org.onrails.rails.RailsValidationForm railsErrors setter.

public function set railsErrors(errors:RailsErrors):void {
	_railsErrors = errors;
	if (_railsErrors==null || !_railsErrors.hasErrors()) {
		resetErrors();
	} else {
        for each (var field:String in _railsErrors.fields) {
        	if (_fieldMap[field]) 
        		_fieldMap[field].errorString = field + ' ' + _railsErrors.getFieldErrors(field).join(', ');
        }				
	}
}

The key is to associate the Rails error message with the field is simply to set the errorString on the field.

I just created this code this morning at breakfast so it’s really a work in progress. For instance it doesn’t support Rails attributes that are more than one word. But this goes hand in hand with the ActiveResourceClient and can be useful I hope to others trying to integrate Rails and Flex. So we will create a Google project and post the RailsErrors and RailsValidationForm.

Posted by Daniel Wanja Tue, 06 Mar 2007 18:36:30 GMT


360Flex - Day two

All right, here we go again.

08:30am Flex Data Services by Jason Williams FDS is a J2EE Application that provides data synchronization between a client and a server. Provides Messaging, RPC Services and Data Management. All these services use service adapters on the server to get the job done. All the other services are build on top of Messaging. Jason goes through the various ways to configure these services, way to much data to blog about. Jason will post his slides online. I will point to them as soon as I gound out.

10:00am Flex Builder Secrets by David Zuckerman Change in plan, I won’t attend the Modules presentation as I played with Module last week and it works pretty well. So Let’s see if there are some good FlexBuilder secrets out there. If not that will give me some time to play with handling Rails Errors from Flex. I’ll blog about that shortly. David will briefly show some editing features, the will dive into hacking FlexBuilder, hacking the property inspector and use the APIs exposed by FlexBuilder. David is part of the FlexBuilder development team and is currently working on ‘Find all references’ and Refactoring support.

apple-shirt-t Open Type
apple Turns an identifier into a ‘navigate to’ link
ctrl-o Outline view

David mentions’ that everything he shows now is at our risks and can damage the installation. He shows or the color syntax settings can be modified. There are defined in the Colors.xml file inside of a .jar file that is part of an eclipse plugin. Note sure that I want to mess with that stuff. Graphical Property Inspector. You can create your own customer common property inspector. This inspector is defined by by an xml file. David nows describe how to extend FlexBuilder using java. I guess that these notes won’t be to useful, so hopefully he will provide his slides.

01:00pm MXML vs. AS3 by Ted Patrick His goal is that we understand MXML as a medium to write applications. Apparently I am the trouble maker for the bad sound with the mikes that the presenters experienced since the beginning of the conference..as my EDVO card may interferer with their microphones. So I will start taking notes offline and post them here after the talks are over. MXML gets translated to AS3, so it’s the same. MXML Tags are instances of AS3 classes. 100% compatible, 100% the same. To see how the translation work use the compiler flag -keep-generated-actionscript. Best way to understand inner workings and what’s going behind the scenes.

02:30pm E4X by Danny Patterson Danny co-authored the ActionScript 3 with Design Patterns book. He described the new XML related classes and showed examples for each of them: . XML, XMLList, QName, Namespace.

Filtering:

catalog.product.(price < 50).name,

or using a variable

var findPrice =50;
catalog.product.(price < findPrice).name

Chained Filter:

catalog.product..(name.toString().length >0).(price < 50).name

Namespaces

	//xmlns
	var envelop = <soap:envelop xmlns:soap="{uri}" />
	envelop.body = <soap:body xmlns:soap="{uri} />
	//Namespace
	var soap:Namespace = new Namespace(uri);
	envelop.soap::body = new XML();
	//Default namespace
	default xml namespace = soap;
	envelop.body = new XML()

04:00pm Flex and Flash Together by Jesse Warden Jesse goes fast through lots of material. Call Flash from Flex directly But he shows how to load a swf file using the SWFLoader into flex, cast the loader.content to the interface you would to use, then then Flex can call the methods you want on the Flash movie.. You can do that today with the Actionscript 3 plugin for Flash 8. addFrameScript addFrameScript(39, stop)…show a way to load dynamically code inside you application by using Embed…he uses this to build a nice Flash components that can be used straight from Flex. He makes a compelling case of using Flex and Flash together.

Posted by Daniel Wanja Tue, 06 Mar 2007 15:54:41 GMT


360Flex - Day one.

08:00am sitting at the Denny’s down of the Ebay conference center where the 360Flex Conference is starting. There seems to be a already a large coverage in the blog community of the 360flex conference…so I’ll be rather brief and just provide what strikes me at each of the presentation I will attend. I will update this blog entry as the conference moves on.

I am currently making up my mind as to which talk to attend here after is a first pass at my list.

08:10 All right I am at the conference. Pretty well organized the facilities and the conference room is pretty impressive…and they have Starbucks coffee. The room is mostly already full.

Day 1

08:30am Keynote: The Magic of Flex by Mark Anders
1st Flex specific conference. Mark asks how many are Flash developers in the audience. It’s the minority, about 30 hands raised. Flex is the way to create Flash stuff in a developer friendly way. MXML Mark shows some SVG components and demonstrates how MXML ties in with Actionscript classes. Databinding He demonstrates databinding to change the gradients of an svg components without coding using. His Microsoft ghost is chasing him…his Mac froze and is now rebooting. He blames it on Powerpoint that runs Rosetta. Composition New controls can be build by composing other controls. Mark show several components that different people created such as the fisheye component and an cool RSSReader that smokes. States allowing to build liquid interface declaratively. He demonstrate in FlexBuilder how to create a little Flickr Browser that has two states, the search state that just shows the search box and the result state that also displays the results. It’s Flash! Flex is powerful thanks to the underlying Flash engine. He demonstrates some Flex application that use the full power of Flash: Picnik and Buzzword from Virtual Ubiquity. ActionScript 3 He now starts the new version of the Flash IDE and show a “Ring of Fire” rendering application and compares the AS3 and AS3 application…the crowd claps as it shows off fast AS3 is. An Exciting Future He invites Mike Downey on stage to show Apollo. Mike will show the new things you can do with Flex using Apollo to build cross-operating system applications that can do things like accessing the local files, run online/offlie, full drag-and-drop between the Desktop and the application, clipboard access and more…Mike shows Buzzword as an Apollo application. He shows gTimer, an Apollo time tracking application written by Grant Skinner. He goes on to show Maptacular which overlays a Flex app with Google Maps. The last app shown is Scout, written by Christian Cantrell that is an Html inspector ala Firebug. Flex 3 Mark is now back on stage and is talking about what they are working on with Flex 3. Designer/developer workflow. Make it easier to integrate Flex with existing services and enabling richer data display and manipulation (live data). Building Apollo applications from FlexBuilder and embed Html (real browser) in a Flex application. Increase developer productivity. Timeline: First half 2007 will see the release of public labs release of Apollo and Flex 3 (“Moxie”). In the second half the first version of Apollo and Flex 3 will be release. That’s it!

08:55am Apollo APIs by Christian Cantrell He writes Apollo application as Apollo is being developed. Everything he talks about is subject to change. He is writing real-world usage, cool Apollo applications to provide feed back to the Apollo development team. Apollo is based on the Flash Player, and provides Flash, Flex, Javascript and Apollo APIs. NativeWindow allows to use native OS windows with Flash, Flesh or HTML content, supporting full transparency. He is doing all his work from FlexBuilder and will not show some demo applications. HTMLEditor, allows to edit html that shows a system chrome. Lookup application that demonstrate an Apollo window which is a Apollo look and feel chrome that provides it’s own close, maximize buttons and window scrollbars. PixelPerfect that is a pure Actionscript based application that demonstrates a custom chrome which is a transparent ruler application that allows to pixel measure your Desktop. ScreenPlay an application that has no chrome and allows to draw on the desktop and highlight anything on the Desktop. File System APIs File extends FileReference. File objects are pointers to files and directories. File APIs can be Synchronous and Asynchronous. Threading is not accessible to the developers. URL Schemes file:, app-resource, app-storage:. Two more demos. FileBrowser, that supports full drag and drop file operations. FileComponentTest that allows to view folders in Tree, List or Grid view and is written in 47 lines of MXML code. HTMLControl is a display object than can display HTML, it’s an embedded browser (without chrome) build using Khtml (WebKit). Has loadString function to load content, adds to the URLRequest class. Script Bridging allows scripting between Actionscript and Javascript. References to object can be passed between the two environments. I.e. an Actionscript event can be attached to a Dom object. The Flex HTML Components Allows to add an HTMControl to a Flex container. Some more demos. Scout, the html inspector. He now use the dom tree to select an item on the google home page, then edit it and the changes are directly rendered. Assassin, an application to watch items on Amazon. He want’s to know when Halo 3 is available or when the rating changes. Shell provides access to shell or runtime facilities. I.e. when all the windows applications close then developers can decide if the application closes. Or find out which window has the focus, or close the application. Network Detection Event.NETWORK_CHANGE event to listen if the application goes online/offline. He mentions an application for Doctors that need to be offline when they do house calls but still need to have access to the application. Apollo will provide a framework around this. The important fact is not wether the application is online or not, but wether the application can access the external services is need. He now shows the OCD application that uses the ServiceDetector class to listens to the ServiceEvent.SERVICE_AVAILABLE and ServiceEvent.SERVICE_UNAVAILABLE events. InvokeEvent tell every time the application is invoked. Provides control to the application what to do when the run is clicked again, some application just will do nothing or bring the application in front, another may open a new tab, another may create a new window. He demos now InvokeTest and PixelPerfect to demonstrate this. A question from the audience was if you can grab pixels from the desktop. Christian mentions that they are no APIs for that and he wasn’t sure why, maybe a security constraint. Application Update API to make updating your applications easier. The runtime allows to update the application and restart it from within the application. There is still some code left to be provided (when to update, data migrations). They currently provide a bar minimum framework for this and may build some higher level framework on top of it. Managing Multiple Displays currently doesn’t work in the latest build. Screen class. Screen.screens returns an array of Screen objects. Screen.mainScreen returns the primary screen. Screen.visibleBounds allows to properly align the screens. URLRequest changes support for arbitrary methods: GET, POST, HEAD, PUT, etc. Allows more HTTP header flexibility. Security A question from the audience is what about security. The answer is yes, but Christian is not providing details on the model, he just mentions that they are looking into. But he mentions that Apollo allows to write “bad” apps like in other frameworks. They will be more information on that closer to the launch of Apollo.
Icons Apollo handle platform independent icon conversion. The minimum is 128×128. Installation You need to install the Apollo runtime to deploy an application. So an application cannot be deployed without the run time. Future Apollo APIs Menus, Drag&Drop, File extension registration, System notifications. That’s it!. Q&A Q:When will it be available? A: Pretty soon. (Someone in the room mentions before the 16th).

02:05pm Flex loves Flash? Embed and Beyond by Grant Skinner He will show us know where we are and let us make the call if Flex loves Flash. The workflow is not well integrated at the tool level for now. Embed metatag [Embed(source=…)], compiler directive “@Embed”, style directive upSkin:Embed(source=…). The Flex compiler doesn’t do a great job bringing in SVG it also drops annimations and as sizing issues. From a workflow point of view the issue is than when importing images into Flex the images cannot be resized and transformed if needed without going back to the original editing tool and re-exporting it. Grant now goes into the details of embed fonts. Flash bitmaps font cannot be embedded. Raw binary data can also be embedded by using mimeType=‘application/octect-stream’. Grant now goes on prepping why using Flash with Flex is a good thing by exploring 6 challenges. Challenge 1 – Prepping and managing assets isn’t fun in Flex. Embed(source=“mySWF.swf”, symbol=“SymbolName”) to access Flash symbol that are in an Flash library. This allow to centralize all your assets into one Flash file. He now shows an Flash command that allows to generate a Flex class (SimpleAssetLibrary) to provide access to Flex for all the embedded Flash assets. Challenge 2 Flex doesn’t have a lot of love for designers or their tools. But…Flash 9 has really good support to import Photoshop images. And preserves layers, folder names, vector assets, text and allows to map these assets in different ways. So Flash is a really good intermediary between Flex and Photoshop. Challenge 3 Flex ain’t so good with fonts. Flash can help out by embedding all the fonts into Flash then using them from Flex. This does allow to use Flash bitmap fonts. It’s not quite straight forward yet as the Flash Font symbol needs to be referred to by using the system generated class name (i.e. Arial_12pt_st). To find out this font names you can iterate over the embedded font returned by Font.enumeratedFonts(false). Challenge 4 Flex hates Flash ActionScript. It can be done…but I may not quote Grant correctly here. But a swf file can be embedded as an octet-stream, the loaded using a loader and access to the class can then be done using the ApplicationDomain. If we go beyond embed we can get better results by exporting your FlashCS3 application into a .swc file. And Flex can then import and use that .swc file. Challenge 5 Flex is stuck up. Flex doesn’t love the Flash display symbols. Make it a child of UIComponent or wrap it in a class that extends IUIComponent. He wrote a DisplayObjectWrapper that is a generic solution for this issue. A better approach would we that Flash components developers support the IUIComponent or extend something that does (FlashSymbol, name still to be determined). Challenge 6 Run-time loading of Flash content. Load Swf into Loader. ApplicationDomain.getReference to get access to the symbol, then wrap into a DisplayObject. It’s tricky to work with Icons and other aspects as an AssetClass needs to be extended. Flash v3 components will work in Flex. See his blog and talk page for more info.

03:30pm Introduction to Apollo by Mike Chambers. After a brief introduction of what Apollo is, Mike shows some demo applications. Ascension – a sound visualizer that can load your iTunes library and visualize the playing music, load the album art from Amazon and images from Flickr regarding the album and artist. The Apollo run-time target size is between 5 and 10 Mb. Mike provides an overview of the APIs. He demonstrates now using FlexBuilder how to get started with an Apollo application. All applications start with two files, the main.mxml file that is a Flex application with the mx:ApolloApplication as root component file and an .xml application descriptor file providing additional information on how to build the Apollo application such a system icons to use, the main contain (main.mxml).

04:00pm Flex Apps Faster with WebORB – Well it seems that I had some issues with MarsEdit the soft I use writing these entries I lost all the coverage of the WebORB presentation and the last bit of the Apollo presentation. Mark presented the benefits of WebORB over traditional approaches using HttpServices or WebServices by demonstrating some applications which take around 6 seconds to perform 50 remote calls and the sames calls using WebORB take less than 1 seconds. Mark goes on showing the benefits of using WebORB Data Management services that allow to generate much of the plumbing required to interact between Flex and .Net, PHP, and later on Rub y On Rails.

Posted by Daniel Wanja Mon, 05 Mar 2007 16:07:00 GMT


XML Filtering Predicate

I need to filter some XML data based on several conditions. I found the following article “”http://www.darronschall.com/weblog/archives/000214.cfm">E4X: Predicate Filtering with Regular Expressions" from Darron that provides a nice overview of filtering using e4x. I haven’t found any more detailed information on using predicates so I checked out the ECMAScript for XML
(E4X) Specification 2nd edition
. See page 52 for details. But in short the filter can be an expression and use && and ||, the logical and and or.

filtered = list.item.( /^4567.*/.test( number ) || /^D.*/.test( name ) ); 

Here is the full test case:

package tests.actionscript
{

import flexunit.framework.*;

public class TestXml extends TestCase
{

public function testXMLFiltering():void {
 var list:XML =  <list>  
  <item>
     <name>Kamesh</name>
     <number>12345</number>
 </item>
 <item>
     <name>Daniel</name>
     <number>12345</number>
 </item>
 <item>
     <name>Robin</name>
     <number>12345</number>
 </item>
 <item>
     <name>George</name>
     <number>4567</number>
 </item>
 <item>
     <name>Adam</name>
     <number>4567</number>
 </item>
 <item>
     <name>Dean</name>
     <number>4567</number>
     <policy>yes</policy>
 </item>
 </list>

var filtered:XMLList = list.item.( /^D.*/.test( name ) ); Assert.assertEquals(2, new XMLListCollection(filtered).length);
filtered = list.item.( /^4567.*/.test( number ) ); 
Assert.assertEquals(3, new XMLListCollection(filtered).length);

filtered = list.item.( /^4567.*/.test( number ) && /^D.*/.test( name ) ); 
Assert.assertEquals(1, new XMLListCollection(filtered).length);

filtered = list.item.( /^4567.*/.test( number ) || /^D.*/.test( name ) ); 
Assert.assertEquals(4, new XMLListCollection(filtered).length);

}

} // class

} // package

Posted by Daniel Wanja Tue, 27 Feb 2007 22:31:00 GMT


Flex introspection API: describeType(value:*):XML

I am playing with the mx.automation framework provided by Flex. For that I need to associate each control with it’s automation implementation. More on that on a subsequent blog entry. But it some case I need to find the super class of a class

Let’s take the following three classes:

class A {}
class B extends A {}
class Tab extends Button {}

Now we can create the following function:

import flash.utils.describeType;
private function superClass(clazz:Class):String {
    return describeType(clazz).factory.extendsClass[0].@type;
}

Let run the following code

trace("A super class:"+superClass(A));
trace("B super class:"+superClass(B));
trace("Tab super class:"+superClass(Tab));

And we get the following output:

A super class:Object
B super class:com.nouvelles_solutions::A
Tab super class:mx.controls::Button

Let me know if there is an easier way.

The build in describeType function takes a class as parameter and return an XML definition of a class. For example describeType(B) returns the following:

<type name="com.nouvelles_solutions::B" base="Class" isDynamic="true" isFinal="true" isStatic="true">
  <extendsClass type="Class"/>
  <extendsClass type="Object"/>
  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
  <factory type="com.nouvelles_solutions::B">
    <extendsClass type="com.nouvelles_solutions::A"/>
    <extendsClass type="Object"/>
    <method name="a" declaredBy="com.nouvelles_solutions::B" returnType="void">
      <parameter index="1" type="String" optional="false"/>
    </method>
  </factory>
</type>

Pretty cool.

Posted by Daniel Wanja Sat, 24 Feb 2007 04:11:00 GMT


Cairngorm Generators

I looked into Cairngorm a while ago (version 0.95 I believe, pre-ModelLocator area) and didn’t like the fact that you couldn’t use Flex bindings at that time. I recently gave it a second look I liked what I saw. Using Cairngorm is at first very verbose but it provides you with a clear way of organizing your code, which is very beneficial on larger projects. Cairngorm is well documented and there are several nice examples available. Also checkout http://www.cairngormdocs.org/. So yesterday introduced Cairgorm on two Flex projects I am working on.

The first project is a larger Flex 1.5 project (65 actionscript classes, 75 Data transfer object, >100 Mxml views) that I need to migrate to Flex 2.0. I though “great time to start with Cairngorm”. So the first step was to look at all the user gestures for all the screens and create a list of events, map these events to commands, create 3 delegates and services to handle all the remote calls. On paper that was pretty fast to do, but I didn’t want to create all the Cairngorm supporting class by hand. Handily I found the following generator that is a PHP application:

Cairngen


It targets currently only Cairngorm 2.0 and not the newer Cairngorm 2.1. So after generate the supporting classes I had to manually do some changes. But thanks for this tool.

The second project is a smaller Flex application backed by a Ruby on Rails server. And I found the following Ruby on Rails Cairngorm generators at http://code.google.com/p/cairngorm-rails-generator/

Simply copy the generators to your “/vendor/generators” folder, the generators folder will then contain the following generators:

cairngorm
command
delegate
event
vo
worbservice

Note there are several places in Rails you can set generators, but that did the trick for me. The I created a “src” folder in my Rails root folder and issues the following commands:

Then you can use these different generator commands to build the structure you require, the events, commands, delegates and more.

   ./script/generate cairngorm org/onrails/myspyder   
   ./script/generate delegate  org/onrails/myspyder server
   ./script/generate command   org/onrails/myspyder show_page_watch server
   ./script/generate event     org/onrails/myspyder show_page_watch 

I issued the generate script for each of the commands that application needs to support. The main controller now looks as follows (still very early in the development phase)

package org.onrails.myspyder.control
{
	import com.adobe.cairngorm.control.FrontController;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	import org.onrails.myspyder.control.*;
	import org.onrails.myspyder.command.*;
	
	public class MySpyderController extends FrontController
	{
		public function MySpyderController()
		{
			initialiseCommands();
		}
		
		public function initialiseCommands() : void
		{
			// Application Tabs
			addCommand( ShowAccountEvent.EVENT_SHOW_ACCOUNT, ShowAccountCommand );
			addCommand( ShowPagesEvent.EVENT_SHOW_PAGES, ShowPagesCommand );
			addCommand( ShowSettingsEvent.EVENT_SHOW_SETTINGS, ShowSettingsCommand );			
			
			// Page List
			addCommand( ReloadPagesEvent.EVENT_RELOAD_PAGES, ReloadPagesCommand );
			addCommand( AddPageEvent.EVENT_ADD_PAGE, AddPageCommand );
			addCommand( ReloadPageEvent.EVENT_RELOAD_PAGE, ReloadPageCommand );
			addCommand( RemovePageEvent.EVENT_REMOVE_PAGE, RemovePageCommand );
			addCommand( SavePageEvent.EVENT_SAVE_PAGE, SavePageCommand );

			// Page Details
			addCommand( ShowPageWatchEvent.EVENT_SHOW_PAGE_WATCH, ShowPageWatchCommand );
			addCommand( ShowPageWatchResultEvent.EVENT_SHOW_PAGE_WATCH_RESULT, ShowPageWatchResultCommand );
			
			// Html Section
			addCommand( ShowOriginalPageEvent.EVENT_SHOW_ORIGINAL_PAGE, ShowOriginalPageCommand );
			addCommand( ShowPageSectionEvent.EVENT_SHOW_PAGE_SECTION, ShowPageSectionCommand );
			addCommand( SelectPageSectionEvent.EVENT_SELECT_PAGE_SECTION, SelectPageSectionCommand );
			
		}	
						
	}
	
}

Let me know your experience with Flex and Cairngorm.

Posted by Daniel Wanja Wed, 21 Feb 2007 19:40:00 GMT


RESTFul Rails from Flex.

As part of the “MySpyder” project I am currently working on we want a Flex front-end to access a RESTFul Ruby on Rails service. You can read more on RESTFul and ActiveResource on David’s blog, on the “release notes” of Rails 1.2, PeepCode as an excellent screencast (not free) on the subject, and many other places.


In short using the RESTFul approach allows to expose and manipulate a Rails model via a predefined set of standard Http requests. For example we have an ActiveRecord named Watch which can be manipulated via the following requests:

command url
index # GET /watches.xml
show # GET /watches/1.xml
new # GET /watches/new
create # POST /watches.xml
update # PUT /watches/1.xml
delete # DELETE /watches/1.xml

This allows for standard CRUD operations. Note rest supports also custom operations and CRUD operations on nested resources (such as a has_many relationship). We won’t address them in the article, but I will certainly need them later in the project.


The Rails application can determined what format to return based on the content type or the extension of the url. We are only interested in xml for the moment.


Some of the advantages of a RESTFul Rails application are that it provides a standard way to organize your controllers, as you will see just in a moment because the controllers are standard most of the code can easily be generated, and because the URL to access the application are standard we can now provide some standard utility class to access a RESTFul server. Rails provides an ActiveResource client class, and I haven’t found one yet for Flex. So I started to write one which I will show here after. Now please contact me or add some comments to this blog if you find anything similar or if you want to help me out writing this class. Another cool feature of writing RESTFul Rails controllers is that you get an API for your application nearly for free. This is the main reason we went down that direction.


Assuming we have an ActiveRecord named Watch we can now generate a RESTFul Ruby on Rails controller issuing the following command

./script/generate scaffold_resource watch

Our server now supports RESTFul http requests.


Now wouldn’t it be nice if we could access the server data from Flex in the following manner:

import mx.rpc.AsyncToken;
import org.onrails.ActiveResourceClient;

var watches:ActiveResourceClient = new ActiveResourceClient();
watches.defineResource("http://localhost:3000", "watches", resultHandler, faultHandler);

// Note that all the calls are performed in parallel and asynchronously.
watches.list()
watches.show(8)

// create
var data:XML = <watch>
<url>www.picnik.com</url>
<xpath></xpath>
<frequency>10080</frequency>
</watch>
watches.create(data)

// update
data = <watch>
<id>8</id>
<frequency>10080</frequency>
</watch>
data.frequency = 1440;
watches.update(data)

// delete
watches.deleteItem(8)

Now we can. I started to write the ActiveResourceClient actionscript class to allow this. It’s attached at the end of the article. Now, this is a first try I’ve created this morning. So please be critical and let’s improve it together, or even better if you have one or know one that’s way better please point me where I can get it.


To use the ActiveResourceClient just put the ActiveResourceClient.mxml file into the org.onrails folder in your Flex project. Note that you can provide a default result handler and fault handler or set one handler for each specific call, i.e. the watches.create returns an AsyncToken where a dedicated handler can be specified just to handle the result of the creation.


Download: ActiveResourceClient.mxml (renamed file to ActiveResourceClient.mxml)


Enjoy,
Daniel Wanja.

Posted by Daniel Wanja Sat, 10 Feb 2007 05:13:00 GMT


Certified Flex 2.0 Developer.

Last week I passed Adobe's Flex 2 Developer Exam. Now what's that got to with Rails. Like you may have seen in my previous post I like both technologies, Flex and Ruby on Rails, and I see the strength of both coming together and allowing to build some really cool applications. Now WebORB for Ruby on Rails will play a big element in tying both together. WebORB is not the only way to build a Flex app on top of a Ruby on Rails server, but it provides an efficient mechanism to transfer data between the UI and the server. Beginning of 2005 with Lee we wrote Flex::OnRails, a now "deprecated" (as in don't even try to use it) framework, that was build on top of AMF4R. At that time combining Flex and Rails was an odd match, due to the pure enterprise nature of Flex with it's very high price sticker. Now that Flex is free, I can see many projects benefiting from integrating both. It is true that many web sites don't need a Rich User interfaces that go beyond what can be achieve with javascript. There are many javascript based websites that are incredible. See http://www.fluxiom.com/ or http://wufoo.com/ as two refined examples. However with Flex it's often faster to build an application than with html and javascript, the applications often perform better, are easier to skin for a developer, the code is more readable and can support very large projects. Don't take me wrong, I love the Prototype library and Scriptaculous is really cool, and I will do many more "pure" Ruby on Rails projects, but at least now there is a serious alternative that I will consider in many scenarios.

Now before you ask why did I even bother doing a certification, let me answer it. The first reason is that it forces me to read and study material that I would never have the patience to read otherwise as there is always too many cool things to try out. Now everyone has it's own style of learning. I started Rails by reading all the rdoc that was available and I also love to read the source code. The second reasons is marketing, and this worked really well for me in the past and opened several doors. Personally, I wouldn't value a developer by it's certification but rather by the projects he worked on, the code he writes and it's personality.

I haven't found much information out there on the Flex certification which is pretty new . The Exam Preparation Guide by Adobe provides an overview and there is a more detailed version on the net which is not the official one. I found lot's of information in Adobe's online documentation and in the Flex 2, Training from the source book.

So be ready to hear a little more on Flex and Rails on this blog.

Posted by Daniel Wanja Wed, 07 Feb 2007 07:03:00 GMT


Sneak Peek: Digital Seed: - an eLearning Application build Ruby on Rails and Flex.

Last year Sean and Greg asked us to join one of their venture as Ruby on Rails developers. Dolores joined as designer. Like Sean describes it "Digital Seed is a Flash and Ruby on Rails application that has been designed to allow learning and training companies to more easily deliver their “soft skills” training (leadership, management, communications, etc.) in a multimedia-rich online learning environment.". This is a really fun project to work on. Sean put up a 10 minute screencast.

20070206-digital-seed.png

Posted by Daniel Wanja Wed, 07 Feb 2007 00:51:00 GMT