niedziela, 22 stycznia 2012

dataProvider Flex 4.6 spark DataGrid and Flex 3.6 mx DataGrid comparasion

Well I think DataGrid is the most used control and most power full one in flex, so how it's different in spark and mx

DataProvider

The most common thing you do with datagrid is assign dataprovider to it and display data.
There is a significant difference on this method. So let's start with flex 3.x cause it's interesting one.

First difference is that the DataGrid is the class on top of the mx ListBase and there are mostly all the data operations so the function in ListBase in shortcut (not important lines were removed) looks like this.


public function set dataProvider(value:Object):void
{
if (value is Array)
{
collection = new ArrayCollection(value as Array);
}
else if (value is ICollectionView)
{
collection = ICollectionView(value);
}
else if (value is IList)
{
collection = new ListCollectionView(IList(value));
}
else if (value is XMLList)
{
collection = new XMLListCollection(value as XMLList);
}
else if (value is XML)
{
var xl:XMLList = new XMLList();
xl += value;
collection = new XMLListCollection(xl);
}
else
{
// convert it to an array containing this one item
var tmp:Array = [];
if (value != null)
tmp.push(value);
collection = new ArrayCollection(tmp);
}
// get an iterator for the displaying rows. The CollectionView's
// main iterator is left unchanged so folks can use old DataSelector
// methods if they want to
iterator = collection.createCursor();
collectionIterator = collection.createCursor(); //IViewCursor(collection);
}


It's now clear that to create own implementation of the dataProvider you need to implement ICollectionView cause it's only one without the root class on top of it and make sure you also have strong IViewCursor implementation cause it's the most important one. The IViewCursor is iterator for the list that let's you display the data.

On the other hand in spark 4.6 you have one big class that inherits from SkinnableContainerBase and is using composition to make Grid with columns and rows so the dataProvider is assigned to Grid - well it's using 3 method's to do it - that's the spirit of the flex 4 design.


//FIRST
public function set dataProvider(value:IList):void

//SECOND
private function setGridProperty(propertyName:String, value:*):Boolean

// THIRD - the most valuable and readable for simple grid.dataProvider = value;
private static function setPartProperty(part:Object, properties:Object, propertyName:String, value:*, defaults:Object):Boolean


YEAH it sucks ;) well nevermind, the person who wrote it lost the contact with reality, hope they meet the dedline.

The grid dataProvider function looks simple _dataProvider = value, so if you want to implement the custom dataProvider you need implement the IList and the most important function is

function getItemAt(index:int, prefetch:int=0):Object

cause it's using it all the time to get to the data.

Summary
Overall spark DataGrid dataprovider assign is much more straightforward and I need not much time to implement my own, if only all flex4 code will be refactored for performance - what I hope will become true in ASF during the Apache Flex incubation we could have pretty decent platform independent (with AIR captive runtime) framework for developing business applications.

Another thing is with processor time and memory when compiling the flex sdk 3.6 I got 22MB flash debugger application and with flex sdk 4.6 I got 40MB flash debugger application - hope that's only the debugging size but the 3.6 datagrid runs a little faster.
I need to try with custom itemrenderers with override data and manualy change with propertyChange event yet.

And that's all about my analysis.

Icing on the cake is my custom 8KB only datagrid early prototype, without flex but with custom item renderers (ex time is rendered with custom date) and custom dataprovider. Compiled for SDK 4.6. you can drag to see 100 generated insturments with code generated data feed.

[kml_flashembed fversion="8.0.0" movie="http://blog.vane.pl/wp-content/uploads/2012/01/testmarketwatch2.swf" targetclass="flashmovie" publishmethod="static" width="500" height="300"]

Get Adobe Flash player


[/kml_flashembed]

Now without the itemrenderer caching, sorting, css styles.
Similar one compiled in air captive runtime for IOS runs smoothly and takes only 11MB with custom compiled prototype of RPC and real data push inside ;)

Beware of further flex components comparasion and happy codding as always ;)

środa, 11 stycznia 2012

Flex Spark TextInput scroll and position coursor

Well ex. you want to browse for directory and then display results in to let end user modify it. These operations you can find easy in one place textDisplay property.

And the code:


xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
applicationComplete="windowedapplication1_applicationCompleteHandler(event)">

import mx.events.FlexEvent;

protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void
{
var s:String = "myVeryVeryVeryLongString";
$myInput.text = s;
$myInput.setFocus();
$myInput.textDisplay.selectRange($myInput.text.length,$myInput.text.length);
$myInput.textDisplay.scrollToRange($myInput.text.length, $myInput.text.length);
}

]]>




hope that helps you can find also textDisplay in spark TextArea.

środa, 5 października 2011

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

Well,

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.

Third

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.users=[]
self.messages = []
loopingCall = task.LoopingCall(self.__print_time)
loopingCall.start(.25, False)
Resource.__init__(self)

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

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

def __print_time(self):
sendMSG = None
while len(self.messages) > 0:
sendMSG=self.messages.pop();
# 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)
reactor.run()
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
package
{
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()
{
if(!stage)
addEventListener(Event.ADDED_TO_STAGE, init);
else
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);
addChild(_gui);

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

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

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
{
_log.debug(data.readUTFBytes(data.bytesAvailable));
});
var r:URLRequest = new URLRequest("http://127.0.0.1:8081");
r.data = encodeURI("msg=" + event.data);
r.method = URLRequestMethod.POST;
c.load(r);
}

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

var o:Object;
try
{
o = JSON.decode(next);
} catch(e:Error)
{
Throws.error(e);
}
if(o)
{
_log.track(o.time);
if(o.msg)
{
if(o.msg[0] && o.msg[0].msg)
{
_gui.appendText = o.msg[0].msg+"\n";
}
_log.info(o.msg);
}
//chat.text = next+ "\n" + chat.text;
}
trace("DUPA:"+data);
}

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()
{
super();
if(!stage)
addEventListener(Event.ADDED_TO_STAGE, init);
else
init();
}

protected function init(event:Event = null):void
{
if(!_txt)
{
_txt = new TextField;
_txt.type = TextFieldType.DYNAMIC;
addChild(_txt);
}
if(!_msg)
{
_msg = new TextField;
_msg.type = TextFieldType.INPUT;
_msg.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_msg.border = true;
addChild(_msg);
}
resizeHandler();
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

twistedstream

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.writeObject(eg1);
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
System.gc()
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
{
if(Capabilities.isDebugger)
{
System.gc();
System.gc();
} else
{
try
{
new LocalConnection().connect("so");
new LocalConnection().connect("so");
} catch(e:Error)
{
log.error(e.getStackTrace());
}
}
}

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

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;

[RemoteClass("pl.vane.profiler.samples.MemorySample")]
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
{

[RemoteClass("pl.vane.profiler.samples.FPSSample")]
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