Flex code annotations

Today I was talking with a friend of mine that said to me that the only way to find something related to code annotations in Flex is a book he has… that’s definitely not true, the Flex documentation contain a lot of info on this topic and the web is full of resources.

In this short post I want to summarize the building blocks of code annotation in Flex.

In computing, the programmer often adds annotations to source code in the form of comments. These do not affect the working of the program but give explanations (for other programmers, or potential readers of the code principally, but also as a reminder for the author),  hints or plans for improvement, etc.
Further Annotations can also be added by a compiler or programmer in the form of metadata, which is then made available in later stages of building or executing a program. For example, a compiler may use metadata to make decisions about what warnings to issue, or a linker can use metadata to connect multiple object files into a single executable.

In computer programming, a Java annotation is a way of adding metadata to Java source code that can also be available to the programmer at run-time.
Java annotations can be added to program elements such as classes, methods, fields, parameters, local variables, and packages.
Unlike tags added to Java documentation and processed with tools such as XDoclet, Java annotations are completely accessible to the programmer while the software is running using reflection.

Class annotations, also known as metadata in Flex, are extremely valuable as they allow developers to provide additional information about classes, properties and methods which may not be appropriate to convey through implementation details such as Marker interfaces or some other means.

You can create your own custom metadata following the same format. The example which follows defines a custom metadata attribute utilized for annotating a class with version information. The name of the annotation is “Version”, which contains three properties; major, minor and revision.

package{

[Version(major="1", minor="2", revision="123")]
public class Model {

}
}

Accessing custom annotations in Flex is accomplished via the flash.utils reflection APIs; describeType, getQualifiedClassName and getDefinitionByName.

ArrayElementType metadata tag can be easily associated to code annotations in fact when you define an Array variable in ActionScript, you specify Array as the data type of the variable but you cannot specify the data type of the elements of the Array.
To allow the Flex MXML compiler to perform type checking on Array elements, you can use the [ArrayElementType] metadata tag to specify the allowed data type of the Array elements, as the following example shows:

public class myComponent extends VBox {
[ArrayElementType("String")]
public var users:Array;

[ArrayElementType("Number")]
public var orders:Array;

}

In a more complex environment you can use java beans in Flex as the datatype of the ArrayElementType tag specifyng the fully qualified name of the class or get inspiration from this article http://www.flexpasta.com/index.php/2008/05/19/blazeds-with-annotations-for-remote-objects/ that is strictly related to Flex and Blaze DS (i.e. java based enterprise applications).

This tag only works for Arrays – there is no way to set the type of elements in ArrayCollection, to have typed array collection, you can take existing ArrayCollection.as rename it to YourArrayCollection.as and modify source property and add ArrayElementType tag with your prefered type, (I have not tried it but it should work) or even better extend the ArrayCollection in order to create your custom collection with the support for the ArrayElementType metatag.

In order to check the generated code add the -keep parameters to the flex builder compiler.

Introduction to MVP for Flex

In these days I spent a lot of time to get a deeper knowledge about the Model View Presenter design pattern and at the end of the day I have to say “it rocks!”.
The Model View Presenter design pattern is a variation of the Model View Control that in a similar way separate the concerns of an application’s data, presentation and user input into specialized components.
The original implementation of the MVP is born in the 1979, its name was Thing Model View Editor and during these years there were a lot of different implementations between them the Taligent’s one (1996) was for sure the more sophisticated and the more powerful.

During the preparation of material on presentation layer patterns in 2006 Martin Fowler decided that the treatment given to the MVP pattern must be divided under the names Supervising Controller and Passive View.
In the first one the View delegate user events to the Controller which in turn interacts with the business logic of the application and the uses data binding techniques and the Observer Pattern to update itself when changes occur in the model.

Supervising Controller decomposes presentation functionality into two parts: a controller (often called presenter) and view. The domain data that needs to be displayed is separate, and following rough MVC terminology I’ll refer to it as a model, although it need not be a Domain Model.
In the second one the Controller is always the one that handle user input and that interact with the business logic but it’s also the responsible of the update of the view. In this way the view maintain no links with the Model and relies only on the controller for the all the presentation logic.
This pattern is yet another variation on model-view-controller and model-view-presenter. As with these the UI is split between a view that handles display and a controller that responds to user gestures. The significant change with Passive View is that the view is made completely passive and is no longer responsible for updating itself from the model. As a result, there is no dependencies in either direction between the view and the model.

These patterns are anther evolution of the MV* family, but came back again to the MVP and let’s try to see the building blocks of its implementation (I really want to point your attention on the building blocks words because in the future I want to show a Taligent like implementation of MVP in Flex) and on the wiring between the presenter and view.
In the sample implementation we’ll discover in this post we’ll take in exam a simple form used to recover the details of some customers stored in a simple XML file.
The View is responsible for visual representation of the UI and it contains a presenter in private field. View is implementing interface whose members are approximated and technology striped UI elements of the view. When some event occurs on view is just forwarding it to presenter and it is presenter responsibility to handle the event. Presenter is manipulating view by talking to interface representation of the view. Presenter should never reference directly view members (UI controls). Presenter for his logic operations is using Model which can be persisted state or representation of the object which provides necessary functionality.

In the application sample you find here there are a lot of actors: an MXML file that contains an instance of the UserView component that extends tha VBox class, the IUserView interface that defines the method the view needs to update its state, the UserViewPresenter class that is the responsible of the search operation and of the update of the view

The MXML fine that holds the application is self explanatory, it only defines the custom component view

<contactDetail:UserView x="10" y="10" />

The interface IUserView (implemented by the UserView.mxml file) define the methods we need in order to update the view and get the search criteria from the view to complete the operation

function set userName(value:String):void;
function set lastName(value:String):void;
function set city(value:String):void;
function set errorMessage(value:String):void;
function get searchCriteria():String;

The UserView custom component contains the MXML tag needed to define the UI (sorry for not using code behind but the focus of the post is different) and the call to the recoverData() method defined in the presenter

<mx:Label text="Contact Details Manager" width="100%" fontWeight="bold"/>
<mx:Label id="_errorMessage"  width="100%" color="#FF0006"/>
<mx:Form width="100%" height="50%">
<mx:FormItem label="Name" width="100%">
<mx:TextInput id="_userName" editable="false" width="100%"/>
</mx:FormItem>
<mx:FormItem label="Surname" width="100%">
<mx:TextInput id="_lastName" editable="false" width="100%"/>
</mx:FormItem>
<mx:FormItem label="City" width="100%">
<mx:TextInput id="_city" editable="false" width="100%"/>
</mx:FormItem>
</mx:Form>
<mx:HBox width="100%">
<mx:Label text="Insert a code to search" />
<mx:TextInput width="120" id="_searchCriteria" restrict="0-9" />
<mx:Button label="search" click="_presenter.recoverData()" />
</mx:HBox>

It also contains the methods defined in the IUserView and a private method that is registered as a listener for the creationComplete event that initialize the presenter

private function init():void{
_presenter = new UserViewPresenter(this);
}
public function set userName(value:String):void{
_userName.text = value;
}
public function set lastName(value:String):void{
_lastName.text = value;
}
public function set city(value:String):void{
_city.text = value;
}
public function get searchCriteria():String{
return _searchCriteria.text;
}
public function set errorMessage(value:String):void{
_errorMessage.text = value;
_errorMessage.visible = value != "";
}

As we already said the presenter is the one that handle with the business logic (in this Mickey Mouse sample we have simulated this with the XML data) and that update the view trough the interface without accessing directly the user interface elements.
In order to complete these tasks the presenter stores as a private member the view and perform the update accordingly to the result on the research on the XML file performed in the recoverData public method

public function recoverData():void{
if(_view.searchCriteria == ""){
_view.errorMessage = "Insert a code please!";
}else{
var data:XMLList = _xdata.customer.(@code == _view.searchCriteria);
if(data.length() == 0){
_view.errorMessage = "No user found!";
_view.userName = "";
_view.lastName = "";
_view.city = "";
}else{
_view.userName = data.firstName.text();
_view.lastName = data.lastName.text();
_view.city = data.city.text();
_view.errorMessage = "";
}
}

As you can see the MVP pattern it’s simple and powerful because it’s easy configurable in order to perform unit testing and because the presenter depends only on the view interface and not on the UI implementations. I really want to make a deeper post on the MVP in the next days discovering the the implementation of the Taligent’s one with Flex.

Make ILOG elixir charts accessible

During the last 360|Flex at San Jose I have had the opportunity to talk about Flex and Accessibility. One of the samples I worked on is the exposure of the information stored inside the Organization Chart  to the screen reader.

The experience was amazing for me because the ILOG elixir charts source code is well written and arranged in a good way, that’s the reason why the process to make the information accessible to the screen reader was so easy and quick.

At the end of this entry you can find the slides and the link to the ILOG elixir accessible demo (source view enabled) and here you can find a preview of the new accessibility Flex documentation.

In the  Organization Chart component I did a lot of changes…

Basically what I did is to make the component aware of TAB navigation, this means that when it get the focus it forces the player to navigate through the TAB the items rendered inside it

override public function setFocus():void{

super.setFocus();

// Diable the other component in order to keep here the focus
// -> better implementation is required!
this.dispatchEvent(new HandleTabEnabled(false, this));

// Get the first item selected in the chart
var ir:IListItemRenderer = _container.getChildAt(2) as IListItemRenderer;
var data:Object = getWrappedData(ir.data);

// Force the selection of the first item
dispatchChangeEvent(data, ir, new MouseEvent(MouseEvent.CLICK));

// Update the information stored for the screen reader
if((this.getItemRenderer(data) as AccessibleChartRenderer)){

if(Accessibility.active){

this.accessibilityProperties.name = (this.getItemRenderer(data)
as AccessibleChartRenderer).accessibilityProperties.name;
this.accessibilityProperties.description =
(this.getItemRenderer(data) as
AccessibleChartRenderer).accessibilityProperties.description;
flash.accessibility.Accessibility.updateProperties();

}

}

The method disable the other component in order to keep here the focus, get the first item selected in the chart and update the information stored for the screen reader.

In order to handle the TAB enabling I created a custom event with which I set enabled or disabled the tabEnabled property on all the componensts but not on the one that get the focus

// Code needs to be optimized for a real production
private function onHandlingTab(e:HandleTabEnabled):void{

for(var i:int = 0; i < this.parentApplication.numChildren; i++){

if(this.parentApplication.getChildAt(i) is IFocusManagerComponent){

(this.parentApplication.getChildAt(i) as UIComponent).tabEnabled
= e.isEnabled;

}

}

}

Another small change I did is in the keyEventHandler method that now is able to get the TAB key pressure and move to the next item updating the information stored inside MSAA

// Move down the focus
moveFocus("down");

// Update the screen reader informations
if(this.getItemRenderer(actualItemData) as AccessibleChartRenderer){

if(Accessibility.active){

this.accessibilityProperties.name = (this.getItemRenderer(actualItemData) as
AccessibleChartRenderer).accessibilityProperties.name;
this.accessibilityProperties.description = (this.getItemRenderer(actualItemData) as
AccessibleChartRenderer).accessibilityProperties.description;

Accessibility.updateProperties();

}

}

break;

For future implementations I added to the ItemRendererCache class the capability to define the tabIndex property of each component rendered inside the all ILOG elixir framework.
A greater testing and research may bring us to more advanced solutions for the accessibility enhancement of these components (i.e. focus handling).

Here you can find the demo and here the slides, a good question I received during the conference was about the possibility to ask to impaired user to disable the screen reader and put into the Flash Player the captions, the audio content, etc. I’m pretty sure that is a good point to discuss also if it’s not a standard way…