Archive for the ‘Flex’ tag
Route Framework: Routes
Summary
Before we start, I want to point out, that this article covers low-level API of Route Framework. In most case you don’t want to worry about low-level, unless you building your own framework on top or with Route Framework
Center of Route Framework are IRoute and it’s implementor Route hence the name of the framework. Route sort of inspired by Agent Oriented1 approach minus concurrency and proactivity and EventHandlers from Mate Framework2. Generally it consists of three types of instances: ISensor, IPattern and IAction.
Simply put:
- Sensor get’s messages from Environment, which uses some way to send and receive messages, whether it’s
flash.events.Eventor some custom solution. - After sensor received message, it parses it if needed and passes it’s to
IRoute.perceive( percept:Object );method. In future we’ll call “sensed” message – percept. IRoutewill match percept againstIPattern- If successful Route will then execute it’s
IAction
.
This allows IRoute to be very agile Inversion of Control3 container. Each part of a framwork is simple enough system that can be easily modified.
Percept
Plainly speaking percept can be anything: Object, String, Event or any kind of instance. Whatever Sensor retrieves from Application and passes to Route considered to be Percept. Percept will then be matched against Patterns and passed along to Actions assigned to current Route.
Sensor
In lamen terms Sensor is an Event Listener or an instance of Observer. It simply receives messages from Application/Environment. Of course Sensors can be internal too. For example there could be a Sensor that listens to internal messages of other Routes, but that’s more rare case.
Pattern
Plainly put, Patterns used by Route to see if Actions will be executed. For example Handle Route:
route( Handle, { event: SampleEvent.BIND_PLEASE, generator: SampleEvent } ).
<route:Handle event="{SampleEvent.BIND_PLEASE}" generator="{SampleEvent}"/>
Uses two patterns, to filter by Event.type and actual Class of Event.
Actions
Actions are variation on Command Design Pattern5. Predefined actions in package eu.kiichigo.route.actions cover basic Application manipulation such as: Apply/Bind/Copy data, run closure or method on class, invoke RPC operation and such. You can extend Action, AsyncAction or Actions classes in order to create custom functionality.
There is two major things you can do with actions: assign predicates and group actions
Conclusion
This covers basic logic of Route, once again, this is low-level API which most programmers should not concern themselves with.
Footnotes
[1] PDF: Shoham, “Agent-oriented Programming”.
[2] Mate Framework.
[3] Martin Fowler about IoC.
[4] Command Pattern at Wikipedia.
Route Framework: Guards and Execution Control
Most instances of IAction also implement IGuarded interface, that allows programmer to control when certain actions will be executed. It acts a lot like guards from declarative languages, such as Prolog, Erlang or Scala. Essentially speaking: if IGuard.when evaluates into true IAction will be executed successfully, otherwise it won’t.
Predicate for guard ( value of IGuard.when ) can be in a form of: Boolean, function ():Boolean or function ( percept:Object ):Boolean. Here is small example with fluent dsl:
var router:IRouter = new Router().
route( Handle, { event: LoginEvent.LOGIN } ).
run( Run, { closure: Alert.show, arguments: ["Logging in "] } ).
when( check ).
end;
protected function check( percept:LoginEvent ):Boolean
{
if( percept.username == null || percept.username.length == 0 ||
percept.password == null || percept.password.length == 0 )
return false;
return true;
}
Action Run will be executed only if incoming LoginEvent has defined username and password. Of course, you will prefer sophisticated validation than simple length check.
Following example shows how to use multiple IGuarded.when predicates with some Functional Programming mojo:
var router:IRouter = new Router().
route( Handle, { event: LoginEvent.LOGIN } ).
run( Run, { closure: Alert.show, arguments: ["Logging in "] } ).
when( check( "username" ) ).
when( check( "password" ) ).
end;
/**
* Checks if <code>String</code> that's evaluated via <code>percept[property]</code> is not empty and is not <code>null</code>.
*
* @param property <code>String</code> name of property on <code>percept</code> argument.
* @param percept <code>percept</code> received by <code>IRoute</code> for testing.
*
* @returns <code>Boolean</code>. <code>true</code> if string is not <code>null</code> and contains at least 1 symbol, <code>false</code>otherwise</code>.
*/
protected function checkString( property:String, percept:LoginEvent ):Boolean
{
var string:String = percept[property];
if( string == null || string.length == 0 )
return false;
return true;
}
/**
* Higher order function. Simplistic Curry function.
*/
protected function check( property:String ):Function
{
return function( percept:LoginEvent ):Boolean
{
return checkString( property, percept );
}
}
I’ve used Higher Order Function, to construct actual predicates. If you have some experience working with Functional Programming, you will find this methods more elegant and logical.
MXML syntax also allows us to use Data Bindings in this example:
<route:Router id="router">
<route:Handle event="{ LoginEvent.LOGIN }">
<route:Run closure="{ Alert.show }" arguments="{ ['Logging in'] }"
when="{ router.percept.username != null && router.percept.username.length > 0 &&
router.percept.password != null && router.percept.password.length > 0 }" />
</route:Handle>
</route:Router>
No additional functions are requited.
This is rather simple, yet very powerful mechanism of controlling execution cycle of application, without need to create special actions that will check data before execution that can be achieved by simple injection of a guard.
Futher Reading
Route Framework: Sensors and Routing
In Model View Controller or Delegate Model architectures special place is reserved to messaging system. When it comes to ActionScript, we usually utilise one of three solutions:
flash.events.Event/flash.events.IEventDispatcher.
custom Observer implementation.
AS3 Signals by Robert Penner.
Usually Application Framework comes tightly coupled with some or another messaging library. It might work in many cases, but sometimes it might be a serious bottleneck*. Route Framework can switch messaging systems easily by subclassing just 2 classes: Sensor, that will receive messages, and Route to wrap sensor and pattern in it.
Let’s consider following example with custom Observer Implementation:
IMessage.as
package observer
{
public interface IMessage
{
/**
* IMessage name, can be used for additional filtering.
*/
function get name():String;
/**
* @private
*/
function set name( value:String ):void;
/**
* Any data that can be sent with IMessage
*/
function get data():Object;
/**
* @private
*/
function set data( value:Object ):void;
}
}
IObserver.as
package observer
{
public interface IObserver
{
/**
* Invoked automatically by instance of IObservable. Should contain any update logic.
*
* @param message IMessage sent by IObservable
*/
function update( message:IMessage ):void;
}
}
IObservable.as
package observer
{
public interface IObservable
{
/**
* Adds an instance of IObserver to notify queue.
*
* @param observer IObserver to be added.
*/
function add( observer:IObserver ):void;
/**
* Use this methods, to notify all instances of IObserver added to current IObservable.
*
* @param message IMessage to be sent.
*/
function notify( message:IMessage ):void;
}
}
You can check actual implementation of this interfaces in sources, but implementation does not really matter in this case.
In order to teach Route to accept Messages all we need is to subclass Sensor and Route as follows:
package observer
{
import eu.kiichigo.route.pattern.*;
import eu.kiichigo.route.pattern.match.type;
import eu.kiichigo.route.routes.*;
/**
* Version of IRoute to work with custom Observer pattern implementation.
* Fluent style:
*
* route( Receive, { from: "idOfObserver" } );
*
* MXML Syntax:
*
*
*
*
* @author David "nirth" Sergey
*
*/
public class Receive extends Route implements IRoute
{
public function Receive()
{
super();
// Setup pattern to filter out messages of correct type.
var p:IPattern = new Pattern;
p.matcher = type;
p.store( "type", IMessage );
// Inject pattern.
pattern = p;
// Inject Sensor.
sensor = new ObserverSensor;
}
// Receive.from is simple proxy get-set accesor
/**
* @copy ObserverSensor#from
*/
public function get from():Object
{
return ( sensor as ObserverSensor ).from;
}
/**
* @private
*/
public function set from( value:Object ):void
{
( sensor as ObserverSensor ).from = value;
}
}
}
import eu.kiichigo.route.sensors.Sensor;
import observer.IMessage;
import observer.IObserver;
import observer.Messenger;
class ObserverSensor extends Sensor implements IObserver
{
/**
* @copy observer.IObserver#update
*/
public function update( message:IMessage ):void
{
send( message );
}
/**
* @private
*/
protected var _from:Object;
/**
* Indicates an instance of IObservable that this ISensor is listening too.
*/
public function get from():Object
{
return _from;
}
/**
* @private
*/
public function set from( value:Object ):void
{
//ToDo: Handle removal from old Messenger here.
_from = value;
Messenger.get( value ).add( this );
}
}
Now our class has nice readable class name and accessor name, and it’s actually reads as: “Receive from accessorId” as in example:
const router:IRouter = new Router().
route( Receive, { from: "leftButtons" } ).
action( Run, { closure: Alert.show, arguments: ["Received message from leftButtons"] } ).
route( Receive, { from: "rightButtons" } ).
action( Run, { closure: Alert.show, arguments: ["Received message from rightButtons"] } ).
end;
Alternatively you can use MXML Syntax too:
<route:Router>
<observer:Receive from="leftButtons">
<route:Run closure="{ Alert.show }" arguments="{ ['Received message from leftButtons'] }" />
</observer:Receive>
<observer:Receive from="rightButtons">
<route:Run closure="{ Alert.show }" arguments="{ ['Received message from rightButtons'] }" />
</observer:Receive>
</route:Router>
* Another framework that handles decoupling of messaging from mvc logic very nicely is Parsley framework.
RESTful (Prototyping) Framework
That was a long long time since I wrote something about Flex, But looks like I found some time for both Game and RIA industries.
I want to share some of my RESTful client library ideas and concepts. I’m trying to build something very laconic, light and still powerful to connect to various REST Services.
Please note, current version is PREVIEW, which means far before ALPHA, I’m just trying around some stuff, can be not pretty.
So, here is how I want this stuff to work:
Let’s say we have imaginary Social Network, with following REST Operations:
- http://api.socnet.com/users/search
- http://api.socnet.com/users/show
- http://api.socnet.com/users/friends/list
- http://api.socnet.com/photos/new_ones
I can build (IMO) pretty Service structure right in MXML:
<kii:Service id="main" endPoint="http://api.socnet.com/"> <kii:Service id="users" endPoint="users"> <kii:Service id="friends" endPoint="friends"/> </kii:Service> <kii:Service id="photos" endPoint="photos"/> </kii:Service>
And then access it simly like this:
users.post('show', {some_param: someParam});
fiends.get('list');
photos.get('new_ones', {limit: 25});
Later on I can extend Service classes to include concrete methods like Users.list() and Users.update(); but framework is ready to use and might be much more useful than HTTPService right out of box. Again I’m not sure whether I will be using this framework for prototypes only or for release projects too.
You can get source code and binaries from Google Code
AIR on Rails
After reading Multiple File Upload with Flash and Ruby on Rails and Merb on AIR – Drag and Drop Multiple File Upload I’ve decided to create my own version of it:

Upload source(zip)
Upload Installer
Icons by P.J. Onori
Scion got Site of the Day Award :D
I can’t say that I did big part for this site, but I’m proud of this anyways.
And yes, I will remember working on this site forever
.
SOAP WebServices with Flex
For this tutorial you will need:
Adobe Flex Builder
Microsoft Visual Web Developer Express
Also need to know what is WSDL, SOAP (you can read about them at http://www.wikipedia.org).
Part I: Creating of the Web Service in Visual Web Developer Express
To be honest I love this programm, this programm designed especialy for lazy guys like me, we dont need to install, setup, download different parts and plugins, register or do other actions to test your projects. This programm will do everything for you
. This is just the right thing we need for my newbie level of WebService developing.
We will create service which should give us rates for the Adobi, Applo and Mecrosoft shares (we will generate them of course). For this purpose we will create OrangeStocks class, which will be WebService itself, and StockData class, which should “collect” data about rates.
Read the rest of this entry »