środa, 5 października 2011

Go IOC and DI rewrite your flex code now - sleep well, be happy, drink beer


The most important thing when rewriting the old code is to decide which framework chose Yes framework or maybe only some utility classes ex smartypants ioc is better . I will say go with IOC 100% to separate your view from the logic part. You can loose some time when you've got some not organized code, or you are using the oldie framework but it will benefit in the future.

First Separate your business logic.

Badly written project have some business logic mixed up with the view logic. Services with specific calculations. When you will try to rewrite your application try to group your business methods in one part and the view logic in the other part. It's easy in the Robotlegs Mediator so you can see what methods have it's view.someFancyComponent reference and what have not. Put the minimum in the view components logic and separate other things to some Helper classes that you can refactor later. If  your project is quite big and getting larger you will see you have some helpers that methods are the same but maybe some little part is different. Try to use it as params. Once you clear your view logic out from business logic  you can separate the business itself to services logic and equations logic. Do equations in separate classes call it some strategy. ex. MyBudgetImportantStrategy if you are using DI you can insert it and decouple with interface and you can use unit tests in the future. The equations logic merely changes when it's done right.  And you are ready for webworkers dude. You can then put your all equations to the worker. The update will be 1-2days not 1-2weeks, months when you wrote your code wrong and keep doing it.

Second be elastic with gui.

Well the gui part is the most important thing in the flex. It have changes. Well it is changing all the time. Maybe you remember some css issues when migrating from flex 2 to flex 3 and you will remember rewrite to the flex 4 and then you will remember if your boss told you compile it to mobile. The simple part is IOC. When you have IOC framework with your business logic highly separated from the gui. The gui logic is the bottleneck. If you screw this up and you need to refresh the look of your big enterprise application you are in hell now. You need to keep your mediators smart and simple, decouple the state and change layout logic from the interaction logic. The layout logic it the shit when you need to reorganize your components view the all the old layout is often the shit see the flex 3 and flex 4 states, flex 3 and flex 4 css. But the button clicks as it clicks it is the main functionality for it, combobox often is only combobox and list is a list. But it may be in the different state of your layout now. When you put your view components first think what is your functionality for this control. And try to put the functionality components separate from your layout component's don't mix them up or they will mix you up when refreshing the look.


Think, read and ask, there are many people out there that have the same problems and there are many authorities in the world of flash/flex that write some good shit about every problem you have. But don't chose the first solution of your problem the person who wrote it 3 years ago is not the same programmer now, maybe someone did it better so you can use it . Try to read more, yes it's time consuming but when you rewriting you don't want to rewrite it again and again. Maybe sometimes it's better to mix some solutions up to build something better.  Use event's as much as you can you can. Man if you have some performance problems why then not use signals or do some own simple notifications where you send often. The event's are for you to keep your life easier not to kill you. Do the commands. The command is the shit cause it only have one functionality. You can separate it and use it in your logic.

Prototype only when your time is very limited but try to separate the 4 logical parts

- layout, - interaction,- services, - equations

cause  flashplayer is crossplatform only from the basis and you interact with phones, tablets other then on desktop or even game console. Your layout and functionality may be different for other screens and equations could be moved to the server when low performance. And on there is still more freedom on the desktop.

Happy codding ;)

niedziela, 4 września 2011

Extra large modular robotlegs application code organize ?

Well when doing some extra large project I was always concerned how to force myself to code right. Not share some dependences across modules not reference to the application, how to manage large codebase and what framework I need to use. Well I chose Robotlegs cause it's simple and will be the best way to success and Joel Hooks wrote nice modular extension to it so we can make everything modular.  It's amazing that that technology works smoothly without any problems. But let's get back to the point.

Well if you have something like 1-10 modules you can keep everything in the same project I think. But what if your plan is to have 20-30 modules ? And by the way you have external people working on your project you not really want to share all your code. How to keep things consistent.  I'll share my concept with you cause it's simple. LIBRARIES, yes each module should have separate project library so you won't use one module  codebase in another module codebase what's modular application essential.  Next you need at least one common module for your framework classes that are shared across all modules. Let's say it will be the Components, validators, renderers and some other visual related stuff I will name it CORE. I also managed to separate communication module that sends and receives the data from the services. And for this point I wanted to have all my communication classes in another module - let's say the API. So you can use the API and give the api and the CORE to the external developer and he will do some shit for you. And you give him only SWC with some documentation not the all codebase.

Some conclusions:

- Unless you are moving something to the  CORE library or API library your project build time will be something like 1-2 seconds. That's something. You are not frustrating while flashbuilder is building your project or freezes sometimes without memory.

- You don't have to worry that you used some classes across modules and you don't know what dependences are - you have it all in CORE. Your modules should be equal in size, and the size won't be 10-40kB it will be all the classes you have in the library so 100-200kB so you will save some time while loading big application and showing it to client.

- If you managed to separate your SERVICE to the external module and that's with all flash domain policy really hard shit, if you use some remote classes that you send or receive it's really messy but then you can use it in some third party related project's.

-You can then give the API and CORE  and see what other people will build with it.

sobota, 2 lipca 2011

Simple http push server for flash using python twisted

I was preety busy at work. Sorry for not posting. I will try to post once a month from now.
The networing profiler project was stopped due to my work but I will try to finish it's simple and post the sources. To the point.

In my workplace we are pushing some data to the clients, and more websites are pushing realtime data so it made me think. How hard it's to write simple http push server for actionscript using python ?

Well it seems not so hard cause we got great library for it twisted. So let's get started on server side:

We will be using twisted web server and Site object,JSON to send data, simplejson library to convert our objects to JSON

So we start by creating simple class Test with GET and POST handlers and in get we add server.NOT_DONE_YET to never stop sending GET request once connected. In __init__ method we declare array for users and array for messages to pass. Next we add LoopingCall task to throtle messages for our clients every 250ms, and define method __print_time that we will be using to create messages. Well __print_time is simple method that we pass time and messages when there are any in our messages array.
We simply loop in our users array and add aditional message to send.

Things to improve:
1. detect when user disconnect
2. add user id when connected
3. replace json with amf protocol
from twisted.internet import reactor, task
from twisted.web.server import Site
from twisted.web import server
from twisted.web.resource import Resource

import simplejson as json
import time

class Test(Resource):
isLeaf = True
def __init__(self):
self.json_encoder = json.JSONEncoder()
self.messages = []
loopingCall = task.LoopingCall(self.__print_time)
loopingCall.start(.25, False)

def render_GET(self, request):
request.write(self.json_encoder.encode({"time":time.ctime(), "type":"CONNECT"}))
print "client connected"
print "number clients:", len(self.users);
return server.NOT_DONE_YET

def render_POST(self, request):
if request.args["msg"]:
print request.args

def __print_time(self):
sendMSG = None
while len(self.messages) > 0:
# keep alive connection
for p in self.users:
p.write(self.json_encoder.encode({"time":time.time(), "msg":[sendMSG]}))

print "server start"
resource = Test()
factory = Site(resource)
reactor.listenTCP(8081, factory)
print "server stop"

Next what about client, some time ago I started simple library for my inhouse projects.
I created simple HTTPConnection class where I use URLStream for handling connection and some self created Observer for listening events instead of eventDispatcher.
Well I will not describe my classes here but only show the main class for the server class in python.
The main method is init where we create gui, HTTPConnection named consumer and some logger. We add event for progress where we simply try to parse json using as3corelib and if we have some messages we try to display it in our gui. when we press ENTER in our upper TextField we are simply sending post to the same url.

Things to improve:
1. detect when disconnected and try to reconnect
2. parse messages only when we need
import clazz.GUI;

import com.adobe.serialization.json.JSON;

import flash.display.Sprite;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;

import pl.vane.framework.errors.Throws;
import pl.vane.framework.logging.ILog;
import pl.vane.framework.logging.Log;
import pl.vane.framework.net.HTTPConnection;
import pl.vane.framework.net.IConnection;

public class Main extends Sprite
public function Main()
addEventListener(Event.ADDED_TO_STAGE, init);

private var _gui:GUI;

private var _consumer:IConnection;

private var _log:ILog;

protected function init(event:Event = null):void
_gui = new GUI;
_gui.addEventListener(DataEvent.DATA, dataSendHandler);

_consumer = new HTTPConnection;
_consumer.observer.addListener(Event.COMPLETE, connectionCompleteHandler);
_consumer.observer.addListener(ProgressEvent.PROGRESS, connectionProgressHandler);
_consumer.load(new URLRequest(""));

_log = Log.getLogger(this);
_gui.appendText = "start\n";

protected function dataSendHandler(event:DataEvent):void
// TODO Auto-generated method stub
var c:IConnection = new HTTPConnection(true)
c.observer.addListener(Event.COMPLETE, function complete(data:ByteArray):void
var r:URLRequest = new URLRequest("");
r.data = encodeURI("msg=" + event.data);
r.method = URLRequestMethod.POST;

protected function connectionProgressHandler(data:ByteArray):void
// TODO Auto Generated method stub
var next:String = data.readUTFBytes(data.bytesAvailable);

var o:Object;
o = JSON.decode(next);
} catch(e:Error)
if(o.msg[0] && o.msg[0].msg)
_gui.appendText = o.msg[0].msg+"\n";
//chat.text = next+ "\n" + chat.text;

protected function connectionCompleteHandler(data:ByteArray):void
// TODO Auto Generated method stub
_log.debug("data" + data.readUTFBytes(data.bytesAvailable));

And the gui class for display the messages:
package clazz
import flash.display.Sprite;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.ui.Keyboard;

[Event(name="data", type="flash.events.DataEvent")]

public class GUI extends Sprite
private var _txt:TextField;
private var _msg:TextField;

public function GUI()
addEventListener(Event.ADDED_TO_STAGE, init);

protected function init(event:Event = null):void
_txt = new TextField;
_txt.type = TextFieldType.DYNAMIC;
_msg = new TextField;
_msg.type = TextFieldType.INPUT;
_msg.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_msg.border = true;
stage.addEventListener(Event.RESIZE, resizeHandler);

protected function keyDownHandler(event:KeyboardEvent):void
if(event.keyCode == Keyboard.ENTER)
dispatchEvent(new DataEvent(DataEvent.DATA, false, false, _msg.text));
_msg.text = "";


public function set appendText(value:String):void
_txt.text = value+_txt.text;

protected function resizeHandler(event:Event = null):void
_txt.x = 0;
_txt.y = 50;
_txt.width = stage.stageWidth;
_txt.height = stage.stageHeight - 50;

_msg.x = 0;
_msg.y = 0;
_msg.width = stage.stageWidth;
_msg.height = 50;

And that's it. The exported swf size is wow 12KB, not much :)
Any questions please post in comments.
Sources are below, i will try to post my HTTPConnection class sources with others on github as soon as I will have some more time.
Just run twisted_stream.py in server folder and Main.swf in client/bin-release


Have fun :)

niedziela, 10 kwietnia 2011

Register class between swf files

Well I got a problem with registerClassAlias and that was all because I didn't read the manual, the whole thing is working now. Thanks to the awesome project flashlcs - Unlimited 2 way local runtime data messaging for the Flash Platform. that I visited one more time this week. And they are mentioning to read the manual page on their main page.
So from the AS3 manual page correct version of registerClassAlias is:

package {
import flash.display.Sprite;
import flash.net.registerClassAlias;
import flash.utils.ByteArray;

public class RegisterClassAliasExample extends Sprite {
public function RegisterClassAliasExample() {
registerClassAlias("com.example.eg", ExampleClass);
var eg1:ExampleClass = new ExampleClass();
var ba:ByteArray = new ByteArray();
ba.position = 0;
var eg2:* = ba.readObject();
trace(eg2 is ExampleClass); // true

class ExampleClass {}

But you need to remember when you define the ExampleClass with constructor to not leave the constructor arguments not set otherwise you will get the null pointer exception when reading the object back ex.

// correct
class ExampleClass
function ExampleClass(someVar:Object = null, someVar2:String=null)

// incorrect
// will throw Exception when ba.readObject();
class ExampleClass
function ExampleClass(someVar, someVar2)

so now I can write and read my objects between my AIR socket server and AS project. I also have some kind of protocol to send large portions of data working.

Also When You are using debugger version of the flashplayer you can force to run GC yourself just by calling
and to invoke it manually Grant Skinner on his blog gave you a tip some time ago. So when I detect that user have no debugger version of flashplayer I simply invoke LocalConnection trick. The example method is:

public function runGC():void
} else
new LocalConnection().connect("so");
new LocalConnection().connect("so");
} catch(e:Error)

Well that's it for now. Next I will try to have some fun with the

niedziela, 20 marca 2011

AIR based flash profiler - preview - 1 - socket protocol and memory samples

Well, since the only decent flash memory profiler available I know is in FlashBuilder (or FlexBuilder whatever) and I loved Clement Wong post about flex profiler I started to write one this weekend.

Well since AIR 2.0 have inside socket server I don't now need the java code until will I face some performance issues. To make profiler, first I needed the socket server and socket client to implement. The common known issue is the Socket class flush() in flashplayer. Since I have to send large portions of data I need some protocol to create, why ?
Well socket is pure communication layer without any more then bytearray support and like Steven Sacks wrote you need to handle socket connection by yourself.
So I created protocol, it's simple and stupid based on states.
each state has it's value and name and the names and values are as this:
package pl.vane.profiler.business.socket.states
public class SocketStateName
public static const START:String = "START";
public static const COMPLETE:String = "COMPLETE";
public static const DATA:String = "DATA";
public static const CLOSE:String = "CLOSE";
public static const ERROR_DATA:String = "ERROR_DATA";

public static const CONNECTED:String = "CONNECTED";
public static const DISCONNECTED:String = "DISCONNECTED";

package pl.vane.profiler.business.socket.states
public class SocketStateValue
public static const START:int = 1;
public static const COMPLETE:int = 2;
public static const DATA:int = 3;
public static const CLOSE:int = 4;
public static const ERROR_DATA:int = -1;

public static const CONNECTED:int = 101;
public static const DISCONNECTED:int = 102;

I am sending the values trough the socket from client to server and from server to client to determine communication layer.

So the basic usage is Start socket server in air application and listen for client
Both client and server has DISCONNECTED state at start.
When client connects server sends the START value as byte
And the client need to reply with the START also.
So now both client and server are connected so the handshake is made - pretty clear and nice.
Then the communication starts so I can send the DATA
So when I start sending the data I also send the size of it as uint
Also to prevent client from sending more data I change the client state to wait for COMPLETE message from server.
Since I don't know if it's all the data or only a part of it I check it and after all the data is received I inform client that everything goes fine. The only part I miss now Is the error handling layer to finish the both Server and Client side protocol. But I will try to implement it later. I wanted to make something visual fast ;)
So what to send from the client to server to measure. Well I started from analyze the good old Mr.doob stats class and then I created my own. I'm sending from client to server samples with memory and FPS so I can write some memory chart on server side. I will also plan to save memory samples to the array or since I have the SQLite engine in AIR I could save them there and then visualise the memory on some charts. It's pretty awesome when I think about it.
My VO's that I'm sending look like this:
package pl.vane.profiler.samples
import pl.vane.profiler.memory.MemoryUtils;

public class MemorySample

public var freeMemory:Number;
public var privateMemory:Number;
public var totalMemory:Number;
public var fps:FPSSample;

function MemorySample(freeMemory:Number = NaN, privateMemory:Number = NaN, totalMemory:Number = NaN):void
this.freeMemory = freeMemory;
this.privateMemory = privateMemory;
this.totalMemory = totalMemory;

public function toString():String
return "free:"+MemoryUtils.bytesToMegabyte(freeMemory)+
", private:"+MemoryUtils.bytesToMegabyte(privateMemory)+
", total:"+MemoryUtils.bytesToMegabyte(totalMemory);

package pl.vane.profiler.samples

public class FPSSample
public var frameRate:int;
public var stageFrameRate:int;
public function FPSSample(framerate:int, stageFrameRate:int)
this.frameRate = framerate;
this.stageFrameRate = stageFrameRate;

public function toString():String
return "framerate:"+frameRate+", stageFramerate:"+stageFrameRate;

Well when the data was send, there was my BIG BIG surprise that my server side AIR application doesn't recognize the classes but treat them like objects. So I can readObject from server side but I cannot cast that object as my library Class. Well I tried registerClassAlias and [RemoteClass] tag but nothing happend so I get stuck with objects. Well that sucks, but not as much to leave the project, and maybe I'm missing some tiny rule I didn't put to my code. Well nevermind.
So now what to do ? I will try implement flash.sampler.* api now and try to describeType all the application that I want to profile. Well it can take some time since I have permanent work from Monday to Friday.
But hopefully it will be more posts and more data to analyze. I'm also looking for some Ideas worth implementing in the profiler. Feel free to write some in comments.
I plan write about sampler api and how to get data you want.
Will try also publish the profiler as soon as it will be finished or will have some decent features like flashbuilder profiler.
Happy Codding.

screen of my profiler project, that is lame now ;) The top flash instance is simple flash client and the bottom is server that has client and server chart.
profiler preview

piątek, 25 lutego 2011

Why and when flex 4 sucks, and why you should extremly consider when want switch.

Everybody are so amused about flex 4 and it's features so I started to digg around what's best about it ? And what I discovered - flex 4 is just no mature to put it into big enterprise project cause it's slow.

The compiler is slower then my grandmother going to the pharmacy for new medicine. That big company should be ashamed creating such a thing. The Flash Builder well - it sucks when compared to it's older friend flex builder or just to editing java in pure eclipse - just consider ctrl+1 tips, and did you ever tried edit 2k mxml file in it ? Compile really big project ? I got all the errors that could appear in it I think, it's pain in the ass.

Fortunetly there are some alternatives like Hell Fire Compiler created by Edwin Wong, the ex Adobe guy that was responsible, as far as I found, for flex 2 and 3 compiler code. More on his blog. You can also consider to edit you big flex projects in IntelliJ IDEA that is just faster.

Well what's new in flex 4 revised:
1. Layouts that you can rotate ?
Well mighty flex developers did you ever considered using flash component kit for flex
So you can create pure flash components that you can put into your old You say it's for flex 2.0.1 so you don't know that flex 3 is flex 2.0.1 path only for me. Try to also use some features you get like [Style] metadata tag that is extremly usefull if you know how to use it. Or just ProgrammaticSkin extended by Sprite not by Shape
2. So the states are better ? Why you even consider using states when effects in flex are extremly slow and painfull. Well everybody knows that every tweening engine outhere is faster then flex effects. Besides State is only simple design pattern easy to implement. When using decent framework, I prefer Robotlegs you just don't need states.
3. Text - the only thing that you need to consider why to use Flex 4 I think is text - but I'm not sure about it since I didn't ever created text application. Only I know that they putted TLF to the text components and named it flex 4 text components.
TLF - as you know is extremly slow cause it's written in actionscript.
But there are some cons against text:
- are extremly slow for dynamic text
- are extremly slow in appending text
The pros are;
- are already written and the source is available so you can use them fast
- are good for staticaly text apps like shown first Times Reader app

Something about co products:
Flash Catalyst and load fxg. Well I never used it cause I know how to cut graphics for flex I know about scale9 and how to create amazing skins using only code. But the flex is very young technology so they needed create something dumb to let create little simple applications easier and I respect that. Tell me what you cannot create in degrafa that you can create in flex 4 please.

So when the technology is young you create dumb tools to create everything "easier" and "better". And when you are software company it's obvious you need to create new tools to sell it and generate profit from technology you give for free. That's what software companies do. Consulting, tools and training.

So what's missing in flex 4:
1. decent modules - well as far I remember the guy who mainly wrote modules code for flex did not work there anymore so I don't know they understand the code behind
2. better charts - the charts in flex are extreamly good - the renderers object pool do it's job when it's going about performance but the code could be optymised for real time data performance, well not redrawing all chart everytime but give ability to append data that will be advantage in financial apps.
3. Loosly coupled AdvancedDataGrid component written from scratch based on Composite pattern that could be far faster then now. The only component that we can consider when creating real time data applications now that can do something like AdvancedDataGrid is buggy opensource TreeGrid component from flexlib

I want only add that the only api that appear in AIR is very similar to some language from company that was recently aquired by Orlace. And the new invention in the company is that one that has has been aquired from third party companies Amicima, Virtual Ubiquity.

There is not much invention in flex 4, but there is one bright star I watch.

It's Flex HERO that should run in mobile devices and desktop ones. I hope the new flashplayer api and flex will follow the true power of old flash that is develop one time then - look nice and run smooth everywhere and the same.

There was always lot's of invention and creativity in flashplayer that you can use to create amazing apps that you wonder you can ever create and maintain in other languages in such little time like apps:

1. Audiotool now previously hobnox sound creating app that is outstanding,
2. dragonfly previoulsy now homestyler from autodesk design your house app,
3. adobe rome that is like flashscs3 in the browser
4. or many more AIR desktop apps or web based applications that I forgot and all are in adobe air marketplace or presented on flex.org.

But the flex framework should follow the enterprise way to be extremly fast and bug free components library. The developement studio should be decend not amature and I hope it will live long and survive the new HTML5, CSS3, JS thrust.

Welcome back after more then a year. If you don't agree please write your opinions.
Have fun with code :)