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 , , | 4 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

Flex SDK 4.5 mobile roadmap

I was certainly very excited about the new SDK regarding to mobile development. Lately many clients ask about mobile support for their applications and slowly all projects become multi target (web, local, tablet, mobile) This imply a difficult migration, running around some CSS magic or even writing versions in Objective C to target IOS platform.

File->Create new me

 

So is possible to develop once and deploy to any target? Well, not really, but with a good design, we’re almost there. The new SDK can target Android devices in his debut, and promise to support IOS devices (via cross-compiling to Objective C) and Blackberry Playbook in the near future (update in June … or probably is a fact when you read this)

 

Wizard to create new Mobile Project

Wizard to create new Mobile Project

Wizzard to create Mobile Project

The process is straightforward: you need to create a Flex Mobile Project or an ActionScript Mobile Project from the File menu and a wizard will help you target the correct device. As stated, currently only Android devices are available, but the concrete model doesn’t matter since you can change device target at any point (always inside Android family with version 2.2 Froyo at least) About UI there are a couple of mechanism that helps in adequate to the different screens and resolution:

- You should constrain or your containers, say a List, to keep a certain distance from borders instead of give a fixed size, this ensures an adaptable layout
- There’s a multi DPI mechanism to adapt to different screen density trough rescaling (typically 160, 240 and 320) so your UI remain the same. For bitmaps you can use the MultiDPIBitmapSource tag to provide different graphics for each

There are a few foundation components to navigate applications: View based application (default) and tabbed based application. The first one use a stack of screen to push and pop different applications screens, creating and destroying them on the fly so memory consumption doesn’t growth. Since screens are destroyed on demand, data persists because the application could be interrupted at any moment (because a call i.e) and you should be able to restore at the same point, or go back to a previous screen. Data is injected as the data property at any view. Tabbed applications works similarly, but instead of scrolling from screen to screen, you just tab between them.

Here’s a sample code of the Twitter Trends demo, showing the initial application template

<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" firstView="views.TwitterTrendsHomeView"
persistNavigatorState="true">
  <s:actionContent>
    <s:Button id="refreshBtn" click="Object(navigator.activeView).refresh()">
    <s:icon>
      <s:MultiDPIBitmapSource source160dpi="@Embed('assets/refresh160.png')"
      source240dpi="@Embed('assets/refresh240.png')"
      source320dpi="@Embed('assets/refresh320.png')"/>
    </s:icon>
  </s:Button>
 </s:actionContent>
</s:ViewNavigatorApplication>

Another important thing to remark is that mobile aware components were updated to perform smooth on mobile devices, and in this sense should be considered “light” components, while web components are more resource intensive consumers, so are not a good choice for mobile apps. Articles emphasize in simple skins and programmatic itemrenderers (based on ActionScript, not on MXML) to gain a better performance.

Finally some thoughts about architecture. If you want to develop once and deploy to multiple target you can do … partially. All the business and services domain can be the same, but view will change between different targets. So suppose you want to have your web application available for mobiles, you can follow some MVP or MVC pattern (Model-View-Presenter or Model-View-Controller) so View related code keeps on each project, while data, business and services access can be shared. Almost all of the traditional Flex frameworks emphasize this structure, and if you follow some of them probably will not be difficult to adapt to this structure (if not, read flex frameworks)

To start on this topic, Adobe have many articles and examples, you can begin reading about the topics commented here but more in deep reading a mobile reference or check a list of examples as a basement for your own. We’re planning our own example very soon, so stay tuned.

Posted in Flex | 2 Comments

Flex SDK 4.5 is out!

Finally Flex SDK 4.5 leaves the beta state and was officially released with all the CS5.5 package. Changes are not major like in the transition between Flex 3 and Flash Builder 4, but it adds important features. First of all, the Datagrid component was moved to Spark namespace, probably one of the most used components when dealing with data. Other components like Image or XXX was moved as well, having more elements to choice in the goal of having a Spark only application. Anyway that’s not posible since a lot of elements are still in the Halo namespace whitout his Spark counterpart (Viewstack or the Charting elements) so coexistence will be still the rule.

Flash Builder 4.5

Another exciting feature is the Mobile templates (for Android and IOs), that allows to create projects with a mobile profile, so you can target different devices around there. This opens a wide field to Flex developpers, building at the same time for web and mobile. Anyway you probably can’t reuse the same, since many components are very intensive in resource consuming and not the best for a restricted environment like the mobile platform. Will be true the phrase “one development, many targets”? Only partially, but we will write about this when testing the mobile profiles.

Another thing to note, specially for those moving Flex 3 applications to Flash Builder 4, and now to 4.5 is that some deprecated tags are not anymore supported (in example verticalAxisRenderer for charting) so instead of getting a warning, you get a compile error that prevents you to further go. For those wondering to move to Flash Builder 4.5 standalone application adding SDK 4.1 as a compile options, take into account that you can’t switch to design mode so are constrained to code-only view if you set SDK 4.1 for compile options.

code

There’s a special version for PHP developers that integrates with Zend server. Also Flash Builder adds the feature of code snippets, where you can add your favorite code to insert with just a couple of keys. In adition with code completition and autogeneration of handlers, the code editor is much more powerful and profesional

So welcome Flash Builder 4.5 and stay tunned, we will be doing some test around the new version, specially for mobile profiles

Posted in Flex | Leave a comment