Data structures


We use often data structures for whatever application we build, but since ActionScript itself offers them as base classes (Array, ArrayCollection,Vector, Dictionary) you probably never stop to think about them. I was forced when working on casual games, since speed is a must in this context, even going against the best practices. Sometimes, and specially in heavy process context (100 enemies coming around) is not possible to just use an array because processing get out of control. If you add some artificial intelligence to your enemies, should find the best path and should avoid some bullets, you get the picture. Anyway I’m not saying that applications or heavy sites don’t need also code optimizations, but as ActionScript developers probably casual games is the field where this situation is more evident.

To see the running sample click here

Table of contents
How to install the example
Array
Linked List
Binary Search Tree
Binary Heap
Hash Table
Graph
Summary


Files to run the example locally

This example was built using Flash Builder, amfphp and a mysql database, so in order to run it you should have some available server. Anyway there’s no need to run your own version, you can download the flex project to just read the source and check the running example here. Anyway if you want to run your own version follow this steps

  1. Download the source code from here , source include sql to generate the database and the php file to create the service.
  2. Import the project into Flex.
  3. You will find a rar file inside the main folder of the project with the SQL to generate the database table, the database is named “structures” but you can use any name as far as you change the PHP accordingly.
  4. You will find services.php file inside the main folder of the project that need to be copied to amfphp/services … if you dont know what amfphp is, probably you need to read first the Remoting tutorial
  5. Data structures are heavily based on dpdk opensource package. A copy is included in the lib folder of the project, but you can update with the latest source from http://www.dpdk.nl/opensource/source-code.

My example is just to feature the algorithms, his structure is probably a little messy, with sorting in the main mxml file while data structures manipulation lives each one in his own component.

Array

Probably the most widely used in ActionScript and the base structure for other more sophisticated data structures. Array is a simple list of elements that can be accessed by index.

Array

Complexity
Insertion/deletion average: O(n)
Indexing: Θ(1)
Insertion/deletion at end: Θ(1)
Insertion/deletion in middle: Θ(n)
Wasted space (average): Θ(n)
Family: Bit array, Circular buffer, Heightmap, Lookup table, Sparse matrix

We will no give much more details since you should be familiar with it, but we want to mention that array is the base element for may of the other classes, and is widely used for general purpose data storing. Just is important to note that in AS3 there are some methods that comes very handy to manipulate arrays, like Array.every, forEach, map, some, reverse, that even being available since AS3, are not often used.

Linked List
Each record of a linked list is often called an element or node.
The field of each node that contains the address of the next node is usually called the next link or next pointer. The remaining fields are known as the data, information, value, cargo, or payload fields. The head of a list is its first node, and the tail is the last node (or a pointer thereto). If the last node contains a link to the first node, then we call it a circular linked list.

Double linked list

Double linked list

Insertion/deletion average: O(n)

They can be used to implement several other common abstract data structures, including stacks, queues, associative arrays, and symbolic expressions, though it is not uncommon to implement the other data structures directly without using a list as the basis of implementation. It’s principal advantage when inserting/deleting data is that you don’t need to reorder the entire list, you just change the reference of the adjacent nodes. In AS3 object access is faster than array access, so it competes very well in terms of performance when iterating over the list.

Binary Search Tree
Also named as sorted binary Tree, this is a tree of nodes following this principles:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.

Binary Tree

Binary Tree

The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient. So retrieving data (specially when there’s a large list) is very fast. The BST as the hash table is very fast to search, but the approach is different: the BST uses a recursive approach to split up large amounts of data into smaller sets.

Binary Heap

A binary heap is a heap data structure created using a binary tree . It can be seen as a binary tree with two additional constraints:
The shape property: the tree is a complete binary tree ; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right.
The heap property: each node is greater than or equal to each of its children according to a comparison predicate defined for the data structure.

Binary Heap

Binary Heap

If the tree is ordered from greater to smallest is called max-heaps, while the opposite is called min-heaps, that are often used to implement priority queues. It is possible to modify the heap structure to allow extraction of both the smallest and largest element in O(log n) time

Hash Table

A hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys. The hash function is used to transform the key into the index (the hash) of an array (slot or bucket) In the simplest case each key map to a single value (i.e names and telephone numbers) but value could be anything. That means that a good hash function is a must to have a good look-up average. A perfect hashing function will not repeat any hash for different inputs, but this is almost impossible. To allocate collisions (two keys mapping to the same location) there are many strategies, that vary from have a rule to find an different bucket using a progression (open addressing) or use dynamic arrays to store many entries in the same slot, so the look-up should scan the list to find the value, and of course the key itself should be stored.

Hash Table

Hash Table

ActionScript have his own implementation of the Hash table named Dictionary, but you can build your own, and in fact in our example we use a custom class for this purpose.
Hash table are very fast to look-up data as far as you don’t expect a lot of collisions, in which case probably a tree fits better.

Graph

A graph data structure consists of a finite (and possibly mutable) set of ordered pairs, called edges or arcs, of certain entities called nodes or vertices. As in mathematics, an edge (x,y) is said to point or go from x to y. The nodes may be part of the graph structure, or may be external entities represented by integer indices or references.

Graph

Graph

Graph are very used in path finding, where some character should find the best path between two points. In fact there are many algorithms to do this, being one of the most used the named A* algorithm
Related to this (how to move and interact with he world) , Artificial Intelligence also use graph structures, and also soft-body dynamics.

Summary

As noted in the beginning of this quick walk trough principals sorting algorithms and data structures, there are a lot of chances that you never face to the need of selecting in a fine grain fashion which kind of algorithm or structure you need, since many times the language you use have built-in mechanism or classes that priories the choice. Anyway, when you should face some complexity, in example when building games, where performance is a priority, having this concepts clear is a plus.

I want to emphasize here that the classes we have used to showcase the whole thing are from the open source library you can find here the package http://www.dpdk.nl/opensource/source-code and here an explanation http://www.dpdk.nl/opensource/the-collections-package, thanks to them to give the real power to this example

Posted in General | Leave a comment

Free Flash ebooks from O’Reilly

We find an interesting offer by O’Reilly for all the Flash community. In fact is not a book, but three books targeting different aspects of Flash platform.

Flash Player 11

Flash Player 11

This book will detail the various enhancements, new functionalities, and general improvements
available in this new version of Adobe Flash Player. Each item is explained
in detail, and when possible, a series of screen captures and a full code example is
provided, enabling you to both grasp the new feature in a visual way, and integrate the
feature into your own code quickly, based upon example.

 

Air 3 by O'Reilly

Air 3 cover

AIR (Adobe IntegratedRuntime) evolves from a simple runtime for local content to a tool which not only showcases why it is so relevant in this new
ecosystem, but also why it is (in many cases) the ideal technology platform for advanced
interaction on a multitude of devices. Since version 3, features regarding mobile world become a key for the success of the Flash platform, that push the limits of performance even in low profiles.

 

Starling 2d framework for flash

Starling 2d framework for flash

Starling is an ActionScript 3 2D framework developed on top of the Stage3D APIs
(available on desktop in Flash Player 11 and Adobe AIR 3). Starling is mainly designed
for game development, but could be used for many other use cases. Starling makes it
possible to write fast GPU-accelerated applications without having to touch the lowlevel
Stage3D APIs.

 

Enjoy this lecture as we did !!

Posted in Uncategorized | Leave a comment

Robotlegs demo application

RobotLegs is one of the more recents frameworks based on Dependency Injection like Parsley or Swiz, but with a strong emphasis in a Model-View-Controller arquitecture, that is suggested as the pattern of choice (but is not mandatory) RobotLegs use the SwiftSuspenders library to perform injector in the three allowable ways: constructor injection, parameter (method/setter) injection and property (field) injection.

Injection mappings are supplied to Robotlegs in three places. The MediatorMap, the CommandMap, and through the Injector directly. Both the MediatorMap and the CommandMap are making use of the Injector as well, but they are doing additional work required by these tiers. As the names imply, MediatorMap is used for mapping Mediators, CommandMap is used for mapping Commands, and anything else that needs to be injected (including but not limited to Models) is mapped directly with the Injector.

You can download the demo application from here

Context
At the heart of any Robotlegs implementation lies the Context. The Context, or Contexts as the case may be, provides the mechanism by which any given implementation’s tiers will communicate. An application is by no means limited to a single Context, but for many use cases one Context is sufficient. The Context has three functions within an application: provide initialization, provide de-initialization, and provide the central event bus for communication. In this sense is similar to the ParsleyConfig mxml file or the Swiz Beans mxml, where the main configuration is provided.
Here’s the startup method of the Context in our example:

override public function startup():void
{
	// Controller
	commandMap.mapEvent(LoginEvent.LOGIN_REQUESTED, AuthenticateCommand);
	// Model
	injector.mapSingleton(UserProxy);
	injector.mapSingleton(QuizProxy);
	// Services
	injector.mapSingletonOf(IAuthService, DummyAuthService);
	// View
	mediatorMap.mapView(QuizRobotLegs, ApplicationMediator);
	mediatorMap.mapView(LoginForm, LoginFormMediator);
	mediatorMap.mapView(QuizView, QuizViewMediator);
	mediatorMap.mapView(ResultsView, ResultsViewMediator);
	// Startup complete
	super.startup();
}

Controller and Commands

The Controller tier is represented by the Command class. Commands are stateless, short-lived objects used to perform a single unit of work within an application. Commands are appropriate for communication between application tiers and are able to send system events that will either launch other Commands or be received by a Mediator to perform work on a View Component in response to the event. Commands are an excellent place to encapsulate the business logic of your application.

View and Mediators

The View tier is represented by the Mediator class. Classes that extend Mediator are used to handle framework interaction with View Components. A Mediator will listen for framework events, add event listeners to the View Components, and send framework events in response to events received from the View Components they are responsible for. This allows the developer to put application specific logic on the Mediator, and avoid coupling View components to specific applications.
Probably the most important view in our example is the QuizView, that iterates over the questions listening to user selections (onRegister fires automatically when the framework instantiates and bind the Mediator):

override public function onRegister():void
{
	quizView.addEventListener(QuizEvent.USER_SELECTION, onAnswer);
	quizView.qModel = quizModel;
}
protected function onAnswer(evt:QuizEvent):void
{
	userModel.addResult(evt);
	if (quizView.qModel.hasNext())
	{
		quizView.qModel.moveNext(evt);
	}
	else
	{
		dispatch(new QuizEvent(QuizEvent.FINISH));
	}
}

Model, Service and the Actor

Conceptually there are many similarities between the service and model tiers in the MVCS architecture. Because of this similarity, models and services are extended from the same base Actor class. A class that extends the Actor base can serve many functions within your application architecture. We are going to utilize extensions of Actor for defining both the models and the services an application will need .

Model
Model classes for use in the model tier encapsulate and provide an API for data. Models send event notifications when work has been performed on the data model. Models are generally highly portable entities. We follow the same lines as in PureMVC (probably just because do this example after the other) and use Proxies and ValueObjects for our model. In the heart of our Quiz, there’s a simple QuestionVO holding the basic neccesary needs as a collection of public properties:

public var question:String;
public var answerA : String;
public var answerB : String;
public var answerC : String;
public var answerD : String;
public var correct:int;
public var selected:int;
public var time:String;

Service

A Service for use in the service tier communicates with “the outside world” from within an application. Web services, file access, or any action that takes place outside of the scope of your application is appropriate for a service class. Service classes dispatch system events in response to external events. A service should be highly portable, encapsulating interaction with an external service. We use a dummy AuthService to simulate the user login

Framework Events

Robotlegs uses native flash events for communication between framework actors. Custom events are typically utilized for this purpose, it is however possible to use existing Flash events for this same purpose. Robotlegs does not support Event bubbling, as it does not depend on the Flash display list as an event bus. Utilizing custom events allows developers to add properties to the Event that can be used as strongly typed payloads for system events between framework actors. In our example we use the typed LoginEvent and QuizEvent for communication

Highlights

- We have used a very similar structure as in PureMVC, but with injection avaibility, code becomes more compact, bur naming convention is very similar (Mediators i.e)

- As in Parsley and Swiss, to allow Dependency Injection variables need to be public, I have expend some time when my injection fails until find that my injected variables are private (probably you as me, use always private variables by default)

- The best practices document is a very concise guide to build the basics in good shape and short time.

- You can use normal addEventListener and dispatchEvent to normal event handling but if you want to use RobotLegs event bus, you should use eventMap.mapListener and dispatch.

- Pay attention to different methods to instantiate classes: mapValue, mapSingleton, mapSingletonOf are different ways to provide a class or an instance of a class as a singleton value

- Remember that the framework use lazy instantiation, that means instances are not created until they’re needed, so will not exist magically if you don’t inject somewhere.

- There’s an interesting example where RobotLegs use Signals isntead of normal Flash Events. Signals are light-weight, strongly-typed AS3 messaging tools writed by Robert Penner. We’re not using in our example right now, but will use in a future example so take a look at Joel Hooks bloog

Foru further reading you can check http://www.robotlegs.org/

Posted in Flex | 3 Comments

PureMVC demo application

PureMVC is probably one of the oldest ActionScript and Flex frameworks. It was born using ActionScript, but quickly was ported to other languages like Ruby, Python, C++, PHP or Java. His name expose clearly his matrix: it follows Model-View-Controller pattern, one of the most naturally when working with Flash and Flex.

You can download the demo application from here

PureMVC have 3 core singleton clases or actors: Model, View and Controller, plus another singleton, the Façade, that simplifies development by providing a single interface for communication with the Core actors.

Is important to note that PureMVC has his own Notification system that don’t rely on Flash Events system, and is based on a model/subscriber mechanism without the need of strong typing, since it carries and object ready to be used and aditionally a string identifier, anyway nothing prevents you to use Event mechanism and in fact we use in our example.

Model and proxies

 

The Model simply caches named references to Proxies. Proxy code manipulates the data model, communicating with remote services if need be to persist or retrieve it. This results in portable Model tier code. Generally speaking, the Proxy pattern is used to provide a placeholder for an object in order to control access to it. In a PureMVC-based application, the Proxy class is used specifically to manage a portion of the application’s data model. Data manipulation is done using Value Object, basically a class with a collection of public properties. Proxies can also retrieve data from Webservices of databases in asynchronous patterns. Here’s an excerpt of our QuizProxy that gets data from an XML file:

public class QuizProxy extends Proxy implements IProxy {
    public static const NAME:String = "QuizProxy"; (...)
    public function QuizProxy() {
    super(NAME);
    var ldr:URLLoader = new URLLoader();
    ldr.dataFormat = URLLoaderDataFormat.TEXT;
    ldr.addEventListener(Event.COMPLETE, onLoadXML);
    ldr.load(new URLRequest("com/flashdb/quiz/model/questions.xml"));
}

In the constructor, we load all the quiz question that will be used trough the application an will be accessed by the view.
The proxy, as any other piece in PureMVC, is registered to the Facade (in the StartupCommand in our application):

facade.registerProxy( new QuizProxy());

The proxy never manipulates Mediators, it just send notifications. The Model maintains its integrity through the use of Proxies, which house Domain Logic, and expose an API for manipulation of Data Objects

Controller and Commands

Commands are executed by the Controller as a result of Notifications being sent. Commands should never be instantiated and executed by any other actor than the Controller. To interact with the system, commands send notifications to be responded by others commands or mediators and manipulate directly proxies and mediators. Commands house the Business Logic of our application. Commands interact with Mediators and Proxies, but should be insulated from boundary implementations.
Commands could be chained, so you can use a MacroCommand (a chain of commands) in your application. A typical example is the StartupCommand:

public class StartupCommand extends MacroCommand {
    // Initialize the MacroCommand by adding its subcommands.
    override protected function initializeMacroCommand() : void {
        addSubCommand( ModelPrepCommand );
        addSubCommand( ViewPrepCommand );
    }
} 

The StartupCommand calls two other commands when Model and View should be setup before entering the application. In our example the StartupCommand just register the proxies and the Application and Login mediators (since the others view are created by deferred instantiation)

View and Mediators

A Mediator class is used to mediate the user’s interaction with one or more of the application’s View Components (such as Flex DataGrids or Flash MovieClips) and the rest of the PureMVC application.
To the PureMVC-based application, a View Component is any UI component, regardless of what framework it is provided by or how many sub-components it may contain. A View Component should encapsulate as much of its own state and operation as possible, exposing a simple API of events, methods and properties. The responsibilities for the Mediator are primarily handling Events dispatched from the View Component and relevant Notifications sent from the rest of the system.

The base mediator accepts an argument in the constructor that represents the concrete view component. You need to explicitly cast this object based on your concrete implementation, and for this implicit getter/setter comes in handy. Another important concern of Mediators is to register a list of interests, that’s the notifications the mediator is interest in handling, and of course the handler for it. Here’s is an example of the ApplicationMediator from our example:

public function ApplicationMediator( viewComponent:Object ) {
    super( NAME, viewComponent );
}  
//implicit getter to avoid casting
private function get application():QuizPureMVC {
    return viewComponent as QuizPureMVC;
}
 (...)
override public function listNotificationInterests():Array{
    return [ ApplicationFacade.AUTHENTICATED_SUCCESS, ApplicationFacade.SEND_ANSWER, ApplicationFacade.SHOW_RESULTS ];
}
override public function handleNotification( note:INotification ):void{
    switch ( note.getName() ){
        case ApplicationFacade.AUTHENTICATED_SUCCESS:
            application.currentState = "quizz";
            break;
        case ApplicationFacade.SEND_ANSWER:
            userModel.addResult(note.getBody() as QuizEvent);
            break;  
        case ApplicationFacade.SHOW_RESULTS:
            application.currentState = "results";
     }
}

Facade

The Facade brokers your requests to the Model, View and Controller, so that your code does not need import those classes and you do not need to work with them individually. The Façade class automatically instantiates the Core MVC Singletons in its constructor.

The Façade provides an implementation that should be considered abstract, in that you never instantiate it directly. Instead, you subclass the framework Façade and add or override some of its methods to make it useful in your application. Once the application’s View hierarchy has been built, the PureMVC apparatus is started and the Model and View regions are prepared for use.

Highligths

- Since PureMVC was writed as language agnostic, his first implementation was ActionScript, so still the main documents (like best practices) features ActionScript examples, so is easy to read for Flex developers

- Since examples on StartupCommands usually calls a couple of composite commands (ModelPrepComand and ViewPrepComand), we don’t need such a preparation, but probably medium to big applications do.

- It’s very important to give views an implicit getter for the reference to the view, this way you access to the advantages of strong typing instead of work with a generic object. Also you avoid to possible receive compile errors or warnings.

- Proxies are usually paired with Value Objects to store pieces of data.

- Asynchronous access to external services is routed trough proxies, since in our case is just an XML file

- Is very important to take into account instantiation process: you can’t register a Mediator on a view not on DisplayList (say hide inside a ViewStack or TabNavigator) For this you should use Deferred Instantiation, a common problem that arise when trying to use Mediators. Take a look at ApplicationMediator in our example, it receives notifications for creationComplete callbacks upon components and register the proper Mediator as needed.

- Since proxies are useful, the lack of an exposed Model singleton that stores itself reference to data (as in others frameworks) makes confuse at beginning the use of proxies

- The ApplicationFacade, ApplicationMediator and StartupCommand are central pieces to chain the whole framework

- Using Events and Notifications is sometimes confuse, since both could be used for similar purposes. In our example application we use both.

For further reading you can check http://www.puremvc.org

Posted in Flex | 1 Comment

Mate demo application

Mate is a is a tag-based, event-driven lightweight Flex framework that could be used mixed with others like Cairgorm. It uses injection to pass reference to the views declared in a central EventMap, where you also declare event handling. You have a lot of helper classes, like Mocks or different tags for invoke methods, but mate doesn’t impose a rigid structure.

Mate

Let’s take a very quick tour trough Mate fundamentals.

You can download the demo application as fxp file (Flash Builder Project) from here

You can see the running application here (select framework you’re working on for multiple choice)

Event map
Central to Mate is the Event Map. In the Event Map (or multiple event maps), you define what needs to happen when certain events are dispatched. Each event type you want to listen to will have its own Event Handlers block in the event map. Usually you declare it in the main application and use for handling events and inject dependencies. Here’s an example from our test application

<EventHandlers type=”{QuizzEvent.USER_SELECTION}” debug=”true” start=”showStart(event)” end=”showStart(event)”>
<MethodInvoker generator=”{User}” method=”addResult” arguments=”{[event]}” />
<MethodInvoker generator=”{QuizzModel}” method=”moveNext” />
</EventHandlers>
<!– Services ->
<services:Services id=”services”/>
<!– Injectors –>
<Injectors target=”{LoginForm}”>
<PropertyInjector targetKey=”user” source=”{User}”/>
</Injectors>

Event Handlers
An Event Handlers block defined in the Event Map will run whenever an event of the type specified in the EventHandlers’ “type” argument is dispatched. In order to handle events, the bubbling phase should be set to true and should be dispatched from an object that has Application as his root. You can see an example of event handler in the previous code

MethodInvoker, WebServiceInvoker, HTTPServiceInvoker, RemoteObjectInvoker
Easy to understand by its names, all this tags are used to invoke methods or services usually inside an EventHandler.
methodInvoker is one of the most used, it will create an object of the class specified in the “generator” attribute. It will then call the function specified in the “method” attribute on the newly created object.
The others invokers depends on external services, so declare an resultEvent and a faultEvent to manage results. Here’s an example of a MethodInvoker

<MethodInvoker
generator=”ClassNameToInstantiate”
method=”methodToExecute”
arguments=”{['argument1', 'argument2']}”/>

There are others handy tags like DataCopier (to copy data into some storage), StopHandlers (to prevent handlers to run at certain point) or MessageHandlers (for Flex Messaging system) between others.

Multiple choice using Mate

Being the second example of this story, I begin coping the files from the Swiz project directly to my new one, keeping some of the classes that probably will survive without much change among all the others frameworks, like Events classes or Models for quiz and User (in the case of the user basically a Data Transfer Object)

Steps were as follows

  • Add the compiled framework code to your project (Mate.swc).
  • Create a file that will be the EventMap, to declare injectors and event handlers
  • Include the event map in your main Application file.
  • Create one or more custom event.
  • Create one or more views
  • Dispatch that event from the different views as needed.
  • Add EventHandlers in your event map that listen for the event type you dispatched.
  • Execute some actions inside the EventHandlers block (ie: call the server, store data, etc).

Add as many event handlers as you need

Highligths

- The event map centralize the functionality and probably you will go back and forth to it as far as you add views
- A bunch of events is needed for different actions, create as much as you need
- If you use states for the main application be careful: move the EventMap tag to the first view, if not each time you move to another view it will be redeclared.
- Avoid any relationship between view and models (in the business folder), use injection instead trough the EventMap
- Use a Services.mxml to declare your external services.
- You can use Mocks for your service at development stage, just use a MockRemoteObject tag inside services and create your Mock class (inside mock.quiz.services package)
- For the clock we have used just a custom class that dispatch events and is injected into the view
- For the final result we collect all the info from the User, where we store progress.

Summarizing: Mate is an extremely easy framework with a centralized management, just avoid it if you don’t like mxml tags but prefer pure AS classes

For further reading on the topic: http://mate.asfusion.com/

Posted in Flex | Leave a comment

Tour de Flex 4.5

Looking in how to create a pop-up in a mobile application I return to a classic demo for those working in Flex, “Tour de Flex”, that recently was relaunched with new examples targeting Flex 4.5 version.

Tour de Flex

There are many things that are a novelty, at least for me that have miss a couple of Tour de Flex versions.  We can do a short list of new elements:

- Flex 4.5 Spark components, featuring datagrid (a key piece in Spark family), formatters, collators, OSMF player, string tools
- Flex Mobile samples, show how to access key pieces of Mobiles devices like accelerometer, Camera, Microphone, Geolocation,  Gestures.
- Flex Mobile workflows and components: transitions, navigation, multi-DPI, rotation.
- Cloud APIS featuring AOL, Flickr, Google, Twitter, YouTube among others

Also Tour de Flex include samples inluded in older versions: Flex 3 and Flex 4 samples, Data Visualization, Flex Data Access, AIR, etc. In summary, Tour de Flex is a quick and simple way of accessing samples for your daily work on Flex. You can download it from http://www.adobe.com/devnet/flex/tourdeflex.html

Posted in Uncategorized | Leave a comment

Cairgorm demo application

Cairngorm was my first framework when I begin with RIA development. Probably his difficult name and the tight support of Adobe help in his early adoption. Cairngorm was borrowed from J2EE and has been in use now for a decade (since 2002) His rules are easy to follow, but probably was overkilling for many of the small applications at that time. As far as RIA becomes more complex, his benefits arise.

But before talking about the Cairngorm arquitecture, is important to note that the last version of Cairngorm, formally Cairngorm 3 becomes a collection of good practices, some libraries and a agnostic use of IoC (Inversion of control) even on top of other frameworks like Parsley or Swiz, If you don’t have previous experience with the framework probably you become confuse in how to design your application. Since all the practices encouraged by the last version are well proven and useful, I based this review on Cairngorm 2, since practices there are more prescriptive and easy to follow. Once you have the taste, then you’re free of moving to version 3 and expand your howizon.

You can download the demo application from here
You can see the running application here (select framework you’re working on for multiple choice)

Basics

Cairngorm encourages separation of concerns

  • Model holds data objects and the state of the data
  • Controller process business logic
  • Views render data and announce gestures with events
  • Views communicate with Controller using events
  • Views watch Model with data bindings
  • Views are graphical user interfaces or visual portions of the Flex application.
  • Views usually are composites of UI controls or other views.
  • Views can contain child views
  • Even <mx:Application /> is a view

Classes holding the basics

We can summarize the important classes holding functionality like this:

- ModelLocator is a Singleton holding global data for global access. It does not persist data to a permanent data store by itself and does not contain business logic

In our example application the ModelLocator is the QuizModel and have array of questions but also a reference to the current user and the view state, all of them bindable and used trough the views. Here’s the list of elements on our model

public class QuizModel
{
    private static var modelLocator : QuizModel;
    public var questions:ArrayCollection;
    [Bindable]
    public var currentQuestion:Question;
    [Bindable]
    public var title:String;
    [Bindable]
    public var total:int;
    [Bindable]
    public var currentUser:User;
    [Bindable]
    public var viewState:String;

- Services is a repository of Remote Data Services around the Application (HTTPService, Webservices, Remote Object or any external service you use) A singleton named ServiceLocator create a registry to centralize the external resources used, and support simple lookup of services by name

In our example application we simulate a remote object and the LoginDelegate just return an hardcoded success, but implement a real service is trivial (in fact the code is commented)

public class LoginDelegate
{
    private var responder : IResponder;
    private var service : Object;

    public function LoginDelegate( responder : IResponder )
   {
        //Currently just a Mockup, if this is a real service you want to uncoment next line
        //this.service = ServiceLocator.getInstance().getRemoteObject( "LoginService" );
        this.responder = responder;
   }

- Commands are non visual components that process business logic and respond to business events. Each Command class represents a specific business feature with
associated business logic and processing. All commands have the same entry point, the execute method. Usually command names represent business logic, and modify the data in ModelLocator

In our example we use just two commands, LoginCommand and NextQuestionCommand, but in a more complex application you can have a long list

- Events are custom events that triggers commands to start the business logic. They use the Event Delegation Pattern where responses and reactions in a component are delegated to one or more different components. The delegation is achieved by dispatching events. Custom events are used to package data and to trigger commands in the business layer

Is advisable to use different class of events for different business logic, but sometimes the list can become very long. I.e you can use a LoginEvent with success and fail, or you can use a type of LoginEvent with a value of “success” and “fail”.

- Controller route business events to commands for processing, is a kind of registry of event-to-command. FrontController pattern provides a solution that allows the View
and Control layers to connect using event delegation

Our controller maps just two commands, but again, could be a long list

public function initialiseCommands() : void
  {
    addCommand( LoginRequest.LOGIN_REQUESTED, LoginCommand );
    addCommand( QuizEvent.USER_SELECTION, NextQuestionCommand );
  }

- Views are used to render data stored in the Model layer and announce user gestures. Views are never aware of the FrontController, Commands, or Delegates, or the Services repository

In the example we use three views: LoginForm, QuizView and Result, each one in a state of the main Application

Highligths

- Cairngorm is easy to follow with clear rules in how to build your application. My last Cairngorm app was from some years ago, but takes me only 15 minutes to recall the basics reading the documentation.

- The Quiz application need a lot of changes to be adapted. In example from Swiz to Parsley classes remains almost the same, here many aditional classes were created

- Caingorm don’t use metatags as other frameworks do, his core resides in pure ActionScript classes

- Extensively binding is comfortable with Cairngorm and the Singleton Model holds almost all the data you want to show

- Naming convention is very important. In a medium size CRUD application probably you will end with 30-50 commands to manage your database, so if you are no clear in your names, chaos is a chance

- The same is valid for events and even Value Objects … if you need to see the source code to remember a member functionality, probably it has a bad name.

- Cairngorm is better suited for medium to large application. For simple ones probably is overkilling and not neccesary.

- Adobe continue to support Cairngorm as the best practice for Flex development … but IoC have become so popular (and useful) that the version 3 advice to use it even trough other frameworks on top of Cairngorm

For further reading you can check http://sourceforge.net/adobe/cairngorm/home/

Posted in Flex | Tagged , , | Leave a comment

Pass parameters to Spark Skins

Sometimes we face the case where we should skin multiple components in a similar way, but with a small difference. Yesterday I should skin 6 spark Panels with different header color. Spark panels doesn’t support headerColors style as his Halo counterpart, so instead of writing different styles or set just a property, I should write 6 different skins with just a small difference: the header color. So I was wondering if it’s possible to pass some parameter like

<s:Panel skinClass=”{skins.mySkin(someparameter)}” …

And find some clue in s StackOverflow post, http://stackoverflow.com/questions/2574425/possible-to-pass-parameters-to-a-skin

Since the correct way seems to subclass the component to have your custom parameter, there’s another simple way just using some existing parameter as a selector for a color. So I just added a name on each of my Panels (I use the id as the identifier, so an unused property like the name looks fine to me) So my panels are

Code:
   <s:Panel skinClass="skin.mySkinClass" name="panel1"> ....
   <s:Panel skinClass="skin.mySkinClass" name="panel2"> ....
   <s:Panel skinClass="skin.mySkinClass" name="panel3"> ....

So in my Skin class I add a small switch in the <fx:Script block (don’t check Remove ActionScript Styling Code when creating the MXML skin)

First I declare 2 bindable variables

Code:
                [Bindable]
		private var headerColor1:Number;
		[Bindable]
		private var headerColor2:Number;

Then I use a switch in the updateDisplayList method

override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
       (...)
      switch(hostComponent.name){
          case "myPanel1":
                headerColor1 = 0x006633;
                headerColor2 = 0x006633;
                break;
          case "myPanel2":
                headerColor1 = 0x0033cc;
                headerColor2 = 0x000099;
                break;
         case "myPanel3":
                headerColor1 = 0x990000;
                headerColor2 = 0x990000;
                break;
   }
}

Finally I use in the fill for the header bar

Code:
<!-- layer 0: title bar fill -->
                <!--- @private -->
                <s:Rect id="tbFill" left="0" right="0" top="0" bottom="0" alpha="0.4">
                    <s:fill>
                        <s:LinearGradient rotation="90">
                            <s:GradientEntry color="{headerColor1}" />
                            <s:GradientEntry color="{headerColor2}" />
                        </s:LinearGradient>
                    </s:fill>
                </s:Rect>

With a similar approach, you can reuse a skin when they’re very similar.

Posted in Flex | Leave a comment

Parsley demo application

short story: Parsley gives me the more long stack errors I have seen, I.e I have received 183 lines in the stack for a fail in instantiating the User… so if you come from Java you’re at home :)

Parsley
Parsley is an Application Framework for Flex and Flash Applications built upon an IOC Container and Messaging Framework that can be used to create highly decoupled architectures. It allows you to configure objects to be managed by the container with Metadata, MXML, XML or ActionScript and is easily extensible.

By its own it doesn’t impose any special architecture, but as usually, MVC pattern fits better when building application. Anyway Parsley is very flexible and extensively, so it can manage complex situation, modular application and many flavors of object creation strategies, decoupling and dependency injection. Probably Parsley is a better candidate for modular and scalable applications, but also easy to configure for small goals as our example features. It haves extensive documentation on his web (see link at the end of this article) with detailed explanation on advanced topics

Let’s do a quick review of fundamentals

You can download the demo application from here
You can see the running application here (select framework you’re working on for multiple choice)

Library and setup
In order for Parsley to run in Flex applications you need to include a couple of swc

* parsley-flex3-${version}.swc (or -flex4- when using Flex 4)
* spicelib-flex-${version}.swc

Defining dependencies

As in previous frameworks we have seen, Parsley use the [Inject] metatag to define dependencies along your project. You can use on properties

[Inject]
public var loginService:LoginService;

Or declaring multiple dependencies at once

[Inject]
public function init (loginService:LoginService, cartService:CartService = null) : void

If you don’t provide the second parameter it will fail silently. If you have several injections of the same interface, you can use injection by id

[Inject(id="mainLoginService")]
public var loginService:LoginService;

This is one of the more common tasks when setting your application, and is also a central point (in tandem with messaging) to have a decoupled arquitecture

Messaging

With Parsley 2 you can configure the sending as well as the receiving side with metadata tags. The sending part may simply contain a [ManagedEvents] tag at the class declaration, listing which of the events this class dispatches should be managed:

[Event(name="loginSuccess",type="com.bookstore.events.LoginEvent")]
[Event(name="loginFailed",type="com.bookstore.events.LoginEvent")]
[Event(name="stateChange",type="flash.events.Event")]
[ManagedEvents("loginSuccess,loginFailure")]

public class LoginServiceImpl extends EventDispatcher implements LoginService {

[...]

    private function handleLoginResult (user:User) : void {
           dispatchEvent(new LoginEvent("loginSuccess", user));
    }
}

Here we instruct the framework to dispatch any loginSuccess or loginFailure event to all registered handlers. Now to handle this message we need to use the MessageHandler metatag on the receiving side:

[MessageHandler]
public function login (event:LoginEvent) : void

If you use several messages types of the same event class (I usually do to avoid finishing with hundred of event classes ) you can select by event type

[MessageHandler(selector="loginSuccess)]
public function login (event:LoginEvent) : void

Putting all together

Parsley resume

Parsley foundation

Parsley have a lot of more configurations options but Dependency Injection and Messaging are by far the most used. Initializing the framework and declaring the main elements that will be used. You can use MXML, XML or pure ActionScript to create a configuration file, in our example we use the MXML option like this:

<?xml version="1.0" encoding="utf-8"?>
<Objects
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns="http://www.spicefactory.org/parsley"
xmlns:events="events.*" xmlns:model="model.*"
xmlns:services="services.*" xmlns:utils="utils.*">

   <fx:Declarations>
      <model:QuizModel/>
      <model:User/>
      <services:LoginService/>
      <utils:Clock />
   </fx:Declarations>
</Objects>

The QuizModel and the User are the key elements of our simple application. The LoginService is used (in our case is just a Mockup) to validate the user, and a helper class is used to manage time. This configuration file is running in our main application using  the ContextBuilder command like this:

<fx:Declarations>
<sf:ContextBuilder config=”{QuizParsleyConfig}”/>
</fx:Declarations>

In this way we initialize the framework to instantiate our key elements that will be injected in the views. Our configuration file is very simple as the application itself, but a lot of elements could be instantiated here.

Highlights

- Define clearly which are the central elements of your architecture, this will be injected into the views over and over.

- Don’t forget to add the Configure MXML tag in your views, if not events and injection will fail silently (guess why I expend one hour with my first view …)

- Messaging is very straightforward and probably your choice for simple tasks like event handling. Just declare a type of event in the [ManagedEvents] metatag and use [MessageHandler] metatag to subscribe to them. Note that if you reuse the same Event class with different types (I use a lot), should use selectors to subscribe to different types. In theory, using different Event classes allow to better encapsulation

- You can use normal Event dispatching trough Flex EventDispatching mechanism or use Parsley messaging mechanism. I have used the last because I want to be sure my MessageHandler will not be ignored and also I don’t need to extend EventDispatcher in non visual classes. In case of using messaging mechanism, you should use the metatag [MessageDispatcher] to allow the framework initialize a function as dispatcher

- Since I have used just Messages to walk the screens of my simple application, in more complex context you probably will use Commands. Remember: Parsley is an ambitious and extensible architecture, complex situation have his own set of tools

- Thinking about my patterns, Parsley is a great candidate to follow a “Cairgorm like” structure, with Mediators and Commands. In fact the inversion of control was introduced in Cairgorm 3, so differences become less obvious

- No Mockups for services or data is provided by the framework, anyway it’s easy to create your own

For further reading: http://www.spicefactory.org/parsley/

Posted in Flex | Tagged , , | 5 Comments

BlackBerry Playbook Tablet with Flash

Blackberry announced some time ago support for flash in his new tablet “Playbook”. This supply in part the low quantity of native applications opening a wide range of options from the flash world. Also as we stated in previous posts, Flex 4.5 will be shortly deploy to the new tablet, since Adobe announced an update to support Blackberry and IPhone.

For those thinking that Flash is a secondary feature on the new Playbook, take a look at the last commercial they did for his new tablet

Posted in Uncategorized | Leave a comment