Observer Pattern Actionscript 3

One of the most useful design pattern when you don’t want to work with framework like Swiz, Cairngorm, Mate or PureMVC but you’d like to work with a comfortable utility to manage events in your application or web site is Observer Pattern.

The definition from Wikipedia is:

The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.


For more information and if you want to see UML diagram, take a look at wikipedia site.

You can use this design pattern when you want to notify to all object that are interesting in a particular notification; for example if you have 100 buttons you can show or hide only even or odd ones; it’s not important where they are added, if in the same displaylist or in another one, because it’s observer pattern that substitute event handling to notify something.
If you think how you usually work with event handling you must know where is situated your component  and if it’s nested in 10 different containers you must dispatch that event trough each component… it’s totally crazy!

Observer Pattern solve this problem because it’s like an event engine where knows all object that could be interesting in a notification and it notifies to all components.
When you start to work with it, you could use everywhere in your productions, believe me!

So how Observer Pattern works:

First of all you must create an Interface (IObserver) that has an update method that will be called from Observer manager when a notification will be called:

public interface IObserver {
    function update(_notification:String):void;
}
Then you must have an Observer Manager that manage all objects that implements IObserver interface.
This manager will have 3 public methods: subscribe, unsubscribe and notify.
You call subscribe when you want to add an object that is update from Observer; unsubscribe when you remove an object from a displaylist or if you don’t need to update anymore  and notify when you want to notify something to all subscribed objects:
public class ObserverManager {
private static var instance : ObserverManager;
private var observerData : Array;
public function ObserverManager():void{
observerData = new Array();
}
public static function getInstance() : ObserverManager{
if(instance == null)
instance = new ObserverManager();
return instance;
}
public function subscribe(observer:IObserver):void{
observerData.push(observer);
}
public function unsubscribe(observer : IObserver) : void {
var totObs:int = observerData.length;
for(var i:int = 0; i < totObs; i++){
if(observer === observerData[i]){
observerData.splice(i, 1);
break;
}
}
}
              
       public function notify(_notification:String):void{
var totObs:int = observerData.length;
for(var i:int = 0; i < totObs; i++){
observerData[i].update(_notification);
}
}
}

Ok now you are ready to work with observer, so we create an object that implements IObserver and another one that add on displaylist all IObserver objects and notify to all some notifications:

custom button that implements IObserver interface:

public class ObserverButton extends Button implements IObserver

{

	public static const HIDE_BUTTON:String = "hideBtnEvt";

	public static const SHOW_BUTTON:String = "showBtnEvt";

		

	public function ObserverButton()

	{

		super();			

	}

		

	public function update(_notification:String):void

	{	

		switch(_notification){			

			case HIDE_BUTTON:

				this.alpha = .2;

				break;

				

			case SHOW_BUTTON:

				this.alpha = 1;

				break;

		}			

	}

}

subscribe some custom buttons to observer manager:			

protected var observer:ObserverManager;

protected function init():void{				

	observer = ObserverManager.getInstance();

	for(var i:int = 0; i < 100; i++){			

		var btn:ObserverButton = new ObserverButton();

		btn.label = i.toString()

		addElement(btn);




		if((i & 1) == 0)

			observer.subscribe(btn);

					

		btn.x = Math.random() * 800;

		btn.y = Math.random() * 500 + 70;

					

}

That’s it! You can see the Flex 4 sample that use Observer Pattern here (with right click you can see and download source code).
If you have any questions or suggestions feel free to leave a comment.

Working with zip files and Flash Platform

In our last Flash / AIR project we are working with tons of automations to create files, save them on computer, download files from the web and so on.

A library that I think could be interesting not only for us but also for other people that will work with zip files is FZIP from codeazur.

I saw it a couple of years ago and finally I used it, I think it’s so cool for your desktop or web projects based on Flex, Flash or AIR.
Working with FZIP is so easy, if you want to add a file into a new zip file you only write:

var zip:FZip = new FZip(); zip.addFile(f.name, f.data); //f is a File object instance

You can also set a particular position for your file with addFileAt method, remove a file, read each file and working with it without using any different language; all with Actionscript 3!

When you are ready to create your zip file you can save it with FileStream object like this:

var ba:ByteArray = new ByteArray(); zip.serialize(ba) ba.position = 0; var finalZIP:File = File.desktopDirectory.resolvePath("AIRZIPPER.zip"); var fs:FileStream = new FileStream(); fs.open(finalZIP, FileMode.WRITE); fs.writeBytes(ba); fs.close();
So easy, isn’t it?!
One of the main thing that could be interesting to know about FZIP is that library doesn’t read zip file with data descriptor like you can read on official website in Limitations paragraph:
FZip generally can’t read ZIPs that make use of Data Descriptors. Examples of such ZIPs are those created by the Mac OS X Archiver utility, SWCs, JARs, etc.
So to solve this problem I made a simple AIR application that zip your files (only files for now but soon I also work with folders and subfolders) and give a perfect zip file without any data descriptor, so you can use to work with FZIP lib.
You can download it for free from this link (I think they are on dedicated servers), I hope that you enjoy it and if you have any requests feel free to ask me via email or adding a comment to this post!
UPDATE
I’ve just received a mail from Claus of codeazur that gives me a new repository for FZIP where they solved data descriptor issue; thank you Claus!

Memento Pattern in Actionscript 3 (UNDO/REDO)

Happy new Year everybody!

I’d like to begin 2010 with a design pattern argument.

First design pattern of this year is Memento pattern, that could be very useful if you are working on an AIR desktop application or in a Flex RIA and you want to make an history of user’s actions.
In fact this pattern is used to make undo and redo in an application.

Memento pattern is tightly coupled with originator object and it’s usually composed by 3 different parts:

  • memento
  • caretaker
  • originator

Originator is object that pass data to caretaker and it saved them in a couple of arrays (undoArray and redoArray).
So caretaker is an object that stores a memento snapshot and, if originator needs, pass undo or redo data to this object.

I prepare a sample to understand better what could you use Memento pattern in your applications (“view source” option is activated).
I wrote a Memento class with a Singleton to centralize all users actions,then I create a MementoVO that is a dynamic class to help me store data from each object used by the user, you could use a simple Object instead of a dynamic class to save more memory if you prefer.
Sample is very easy but useful for Memento pattern purpose, in fact you can move windows trough the stage and our “history” class (Memento.as) saves their positions when saveAction method is called by the originator (an instance of CustomWin).

Memento class has 4 essentials methods that are:

  • undo()
  • redo()
  • saveAction(_obj:Object)
  • saveRedoAction(_obj:Object)

I start from the end, saveRedoAction, last method, is used to save the position of a window before I restore its positions, usually Redo action is used only one time, but if you want you could create an Array and work with multiple Redo.

Another important method is saveAction that is called when mouse down event was triggered and it stores in memento class own old position and object itselfs.

First two methods need to undo and redo an user action, it’s easy isn’t it?!

I think that in this year I’ll share lots of those patterns with you to share our knowledge together so feel free to add comment at this post and we could make an interesting and useful conversation, I’m totally sure!

Multitouch with Actionscript 3 and AIR 2.0

AIR 2.0 is out with a BETA version on labs since a couple of weeks ago more or less.
It introduces a lots of new features like UDP protocol, Socket server implementation, access to raw micrhophone data, multitouch and gesture support and so on.

When I see multitouch and gesture support I start to think how many devices are touchscreen based and they are growing a lots in those months, so I start to investigate about that features.
First of all I suggest to read a cool article on devnet made by Christian Cantrell, he goes in deep about this new features and give you a lots of information about Multitouch, TouchEvent and gestures.
It’s so interesting because you can see compatibility of that features with different OS also.

In this post, I’d like to share with you a little sample on how you can create an AIR 2.0 application with Flash Builder and test it with a macbook trackpad.
In fact, you can use macbook trackpad gesture because they are supported on AIR and it’s so interesting, for example, if you want to test an application for new Wacom Bamboo pen & touch and you haven’it.
Wacom Bamboo has a new AS3 SDK for Flex and Flash that allow you to work with multitouch and gesture too, it could be so interesting if you don’t have a multitouch for an expo and you want to buy a cheap solution to give a cool interaction for your possible new clients.
Bamboo has also the availability to create “minis” that are applications dedicated to Wacom Bamboo, but you can read more at Wacom developer website.

So, in this sample we load an external image and we use gesture to try our macbook trackpad:

package {


import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.events.TransformGestureEvent;
import flash.text.TextField;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;


public class MultiTouchSample {


Multitouch.inputMode = MultitouchInputMode.GESTURE;
private var sq:Sprite;


public function MultiTouchSample() {


sq = new Sprite()
addChild(sq);


this.addEventListener(TransformGestureEvent.GESTURE_ZOOM, scaleObj);
this.addEventListener(TransformGestureEvent.GESTURE_PAN, panObj);
this.addEventListener(TransformGestureEvent.GESTURE_ROTATE, rotObj);


var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, addImg);
l.load(new URLRequest("img/sample.jpg"));
}


private function addImg(e:Event):void{
sq.addChild(e.target.content);
sq.scaleY = sq.scaleX = .2;
}


private function rotObj(e:TransformGestureEvent):void{
sq.rotation += e.rotation;
}


private function panObj(e:TransformGestureEvent):void{
sq.x += e.offsetX * 2;
sq.y += e.offsetY * 2;
}


private function scaleObj(e:TransformGestureEvent):void{
sq.scaleX *= e.scaleX;
sq.scaleY *= e.scaleY;
}
}
}

You can see that is so simple work with gesture, a couple of suggestions before starting work with them:

  • remember to verify which gesture are supported on your system, more information you can read on devnet article about multitouch and gesture
  • TransformGestureEvent is event class dedicated to gesture
  • you can use TouchEvent also

Feel free to leave a comment and thank you to visit this blog.

Moving to LiveCycle Collaboration Service

We saw an year ago during San Francisco MAX a great project called COCOMO that allowed developers to take all features in Acrobat Connect (chat, webcam and audio streaming…) and to add in your Flex application with few lines of codes and with this “library” pre-built very easy to use.

This year at MAX in L.A. I followed a very interesting seminar about LiveCycle Collaboration Service (LCCS) that is the final name of the project COCOMO.
LCCS is very interesting for many reasons:

  • easy to use
  • very cheap service
  • very well documented
  • customizable and integrable with own desktop application or RIA made with Flex
  • open new opportunities for customer care solutions and other kind of applications

EASY TO USE

Yes, you can create your application with LCCS integrated with few lines of code. An example?
This is a little conference call environment:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" backgroundColor="0xFFFFFF"
minWidth="400" minHeight="600" xmlns:rtc="AfcsNameSpace">
<mx:Script>
<![CDATA[
protected function startTalk():void{
pubAudio.publish()
}
protected function stopTalk():void
{
pubAudio.stop();
}
]]>
</mx:Script>
<rtc:ConnectSessionContainer id="cSession"
roomURL="https://connectnow.acrobat.com/user/room">
<rtc:authenticator>
<rtc:AdobeHSAuthenticator userName="***********" password="************"/>
</rtc:authenticator>
<mx:VBox width="100%" height="100%" horizontalAlign="center">
<rtc:WebCamera width="320" height="240"/>
<mx:HBox width="100%" horizontalCenter="center">
<rtc:AudioPublisher id="pubAudio"/>
<rtc:AudioSubscriber/>
<mx:Button label="talk" click="startTalk()"/>
<mx:Button label="stop talk" click="stopTalk()"/>
</mx:HBox>
<mx:List dataProvider="{cSession.userManager.userCollection}"
labelField="displayName" width="100%"/>
</mx:VBox>
</rtc:ConnectSessionContainer>
</mx:Application>

That’s cool, isn’t it?
You can download the sample from this link.

CHEAP SERVICE

How much does it cost!? this is the question!
It’s cheap, LCCS is totally free you can download LCCS from Adobe site; like developer you have $15  per month to use for your test, applications and so on.
This is the LCCS “menu”1:

  • 1000 push/messages:  $0.10
  • 1GB live streaming: $0.49
  • user per hours: $0.01

No any additional cost and you don’t maintain anything because you use Adobe servers with LCCS.

VERY WELL DOCUMENTED

When you download SDK you have an AIR application that guide you to use LCCS in your Flex application, you can retrieve there API, SWC for Flex and Flash, you can manage your room and your account so you have a real console for your LCCS applications.

CUSTOMIZABLE INTERFACE AND NEW BUSINESS OPPORTUNITIES

LCCS components could be integrable with your application, so you can create an intranet dashboard with a chat or a VOIP service to communicate with others fellows or maybe you can create an interactive catalogue that help users to choose right product for own requirements.
But not only, you can create collaborative solutions with a shared whiteboard and list of users that could chat or share own ideas via VOIP.
I think that a lots of desktop applications and RIAs could become more interesting with those services and also, if you think, there are many opportunities for your business.

Finally, I think that LCCS could help all developers to make own application more fashionable and useful, but also open new doors for services that are so old.
It’s easy, it’s cheap so why don’t use LCCS?! With my company we start to propose LCCS to our customers and they are so interesting about this technology because it solves some problems in particular

Flickr mesh-up with actionscript 3, REST or SWX

Today I spend my afternoon to configure a part of a full Flash website that interact with Flickr and that retrieve data from my account without any appication authentication but only with my Flickr key.

First of all I was really impressed about how many languages you can use to bring Flickr photos and use in own desktop application or website (Real Basic, cUrl, Perl, Delphi, C…).

When you want retrieve photos from Flickr you must have a Flickr key that is totally free and you can activate one directly in the right section of Flickr site.
In the same section you can find whole documentation and lots of services expose to retrieve any kind of data from a photo, from Exif data to user or friends informations.
For AS3 we have a couple of interesting library; first one is as3flickrlib very well documented but it’s so long to start work with it because you must to find a frob ID then a token and finally you can start to work with Flickr API.
The other one is SWX, that is written by Aral Balkan and it’s too easy to mesh up any kind of popular service like Flickr, Twitter and so on.
Aral gives us availability to use SWX Service Explorer to take a look at the data and how to mesh up your application with public API, I really love it on Flash Lite too!

This is very interesting because you can retrieve all API in this library and in few line of code you can work with public services.
This is a simple example to call Flickr services with SWX, you can download source code too:

swx = new SWX();
swx.gateway = GATEWAY_PHP;
swx.encoding = "POST";
var callDetails:Object =
{
serviceClass: "Flickr",
method: "photosSearch",
args: ["", "", "#mart3"],
encoding: "POST",
timeout: 5,
resultHandler: resultPhotos,
faultHandler: faultHandler
};
swx.call(callDetails);

Another interesting way to work with Flickr API without any authentication is using REST API.
REST (Representational state transfer) is a very simple way to request data from a database, update, delete them or to create new record using HTTPHeaders and XML.
You must know that AS3 doesn’t have PUT and DELETE method but there are some libraries that create a workaround to solve this limitation and they work very well with REST (as3httpclientlib for example)
I start to approach REST a couple of months ago with Ruby on Rails and I think is amazing.

Flickr gives us REST API too, and you can see that is so simple create a Flickr gallery with REST and Actionscript 3.

We have some API that works without authentication like photos search and we use this service to retrieve data for our Flickr gallery.
First of all we take a look at service documentation on Flickr, you can see that we have a lots of opportunity to find data on Flickr; we can search photos via userID, tags, text on title or description and so on.

In Actionscript 3 we’ll use URLLoader class and prepare some url to retrieve XML data from REST.

private const FLICKR_SERVICE = "flickr.photos.search";

private const API_FLICKR:String = "c6c31464878505403f9bbbf6214ae413";

private const PATH_SEARCH_FLICKR:String = "http://api.flickr.com/services/rest/";

		

public function FlickrRest(){

			

	var varsFlickr:URLVariables = new URLVariables();

	varsFlickr.method = FLICKR_SERVICE;

	varsFlickr.api_key = API_FLICKR;

	varsFlickr.tags = "#mart3";

			

	var req:URLRequest = new URLRequest();

	req.url = PATH_SEARCH_FLICKR;

	req.method = URLRequestMethod.POST;

	req.data = varsFlickr;

			

	var urlL : URLLoader = new URLLoader();

	urlL.addEventListener(Event.COMPLETE, retrieveImages);

        urlL.load(req);

			

}

You can download source code and final sample from this link.
Finally I’d like to explain how to compose photo’s url to retrieve them on Flickr.
Flickr url is composed by some variables that you can find in REST XML or SWX result object

  1.  set FARM (ex.: http://farm”+flickrXML..photo[i].@farm+”.static.flickr.com/)
  2. set SERVER (ex.: +flickrXML..photo[i].@server+”/”)
  3. set Photo ID with underscore  (ex.: +flickrXML..photo[i].@id+”_”+”)
  4. set Secret code (ex.: flickrXML..photo[i].@secret+)
  5. last parameters is which size you want to get photos, you can use “_s.jpg” for small size, “_m.jpg” for medium, “_l.jpg” for large and so on.

I hope that could be interesting for many developers, if you have any suggestions or idea about mesh up with Flickr, feel free to drop a comment.

Flash Platform, automotive and industrial marketplace

During my last 6 months I take part in a couple of projects that are focused on Flash Platform and “unconventional devices”.
It seems strange, I know, but what I mean with the term “unconventional devices” ?

I mean that I use Flash Platform on embedded system with the purpose to create interface of industrial machine and automotive world.
Solutions based on Flex and AIR have great success for final customer, in particular because client has a great GUI with a cool user experience and he doesn’t lost any features with the hardware.
In fact we mix a couple of technologies to create those software like Python and C++.
Those tehcnologies make dirty work for us and via Socket or JSON, depends on traffic data, we make a bridge with Flex or AIR.
Performance are very cool, CPU processors move from 45% to 70%, optimization task take a great part of our time.

It was so interesting try for the first time AIR 1.5 on linux OS, we use Gentoo and Ubuntu too and I think they are very strong OS in particular development like this one.
Many people was really shocked in front of powerful of Flash Platform GUI from others developers to our clients, they can find from GPS integration until to a VOIP module made with Ribbit, from a wizard that guide user to interact with industrial machine to customization of GUI at runtime; everything in the same application that doesn’t run in a computer! Really awesome!

I saw during MAX that others companies are moving first steps trough automotive world but with Flash Lite, I think that an Intel ATOM processor has more potential and it’s so cheap for industrial market, when will be release new ARM processors (I think ARM 9…), that will be more powerful and cheap too, and Flash Player 10.1 or AIR 2.0 will have more opportunity to approach new marketplaces and also gives to many people great and easy user interface to work with.

Today Adobe releases in Adobe Labs Flash Player 10.1 and AIR 2.0 public beta, it’s a first steps to new opportunity for Flash Platform developers, many devices implements Flash Player and in future I think there will be many more.
So I’d like in a future, to find many “unconventional devices” with a Flash GUI because NOW we could make the history with those technologies.

A real workflow with Flash Catalyst and Flash Builder

Yesterday I take part of a pre-event labs at MAX called: Creating Application for the Flash Platform where Matt Boles show how to create a real workflow with Catalyst and Flash Builder.

I was interesting in this pre-event because I had some questions in my mind that I answered during this session.

First of all, I’d like to spend a couple of words about Matt Boles; guys Matt rocks! I love so much his training skills, how he explains during the session and also how he moves around the room, bring my attention for the whole duration of the session.
I think one of the best teacher that I ever seen, thank you so much Matt!

So come back on Catalyst and Flex 4; session was interesting and there are some things that I’d like to share with you:

  1. until now and probably also in the final release, if you create your project in Catalyst, then bring it to Flash Builder and start to modify it, you CAN’T go back to Catalyst…
    This is a problem because I’m sure that during a real project there will be some changes to do, so you must do that via Flash Builder Design mode or via code.
  2. Catalyst doesn’t export Flex Modules but only custom components, I talk about that with Matt and he is agree with me, after your work in Catalyst you must create in Flash Builder a Module Container and create modules for each custom components.
    So you’ll study to organize very well your assets during design process.
  3. I think that could be miss a part of a process that is a study of GUI usability, I mean, when you create a RIA or a desktop application you must study how users interact with it so if a designer starts to work on GUI but he doesn’t know how Flex works could be a big problem and you must refactoring the code to add a new functionalities or to group some components.
    Maybe could be useful start project with a meeting where designer and developer (and project manager or producer too) define informations (GUI, functionalities and so on) to create the final application and with a software like Balsamiq, define how to manage all components and custom components.
  4. I was surprise about Flash Builder design view, totally different of Flex Builder 3 one; could be useful when you want to make some little graphic changes at your project.
  5. Very cool news is data wizard of Flash Builder where in few steps you can retrieve remote data and then create VO for your application.
    Associate data to a component is really easy, just a drag ‘n’ drop in design view to a component.

This is a little resume of a day with Flash Builder and Catalyst, in a couple of hours starts the first official day at MAX with a Keynote that I think will be very interesting and with tons of news, so start to take a look at labs. I’m sure that Flash Player 10.1 become your best friend!!!

Obviously, feel free to add comment to this post and we could start an interesting conversation on how is the best way to realize a RIA or desktop app with Flash Platform.
I’m so interesting to know what do you think about that!

See ya 😉

Flash, Flex and SEO

During the flight from Philadelphia to Los Angeles I read a book that I wait for long time and finally arrive a couple of months ago but I’ve never started to read before.

The book is Search Engine Optimization for Flash by Todd Perkins, the first that talks about this argument and also about how to make your Flex RIA searchable from spiaders, so I was so exciting before start to read.

My final impression is that you don’t need to read this book if you are a developer because there aren’t new things to do…
I can resume the book in those few best practices:

  • Use SWFObject because make your SWF file more easy to read for spiders
  • Use SWFAddress or URLKit to rewrite url of your page but it’s useful only for RIA or site usability, not for SEO because HTML is the same for all pages, change only the page url.
  • Avoid to develop a full flash site if you are interested to indexing your project
  • Remember to “talk” with spiders via META tag in HTML page
  • One of most important thing is to make a relevant title of your HTML page
  • With FP 10 you don’t make anything to indexing your contents (dynamic or static text) because spider navigate trough SWF file to retrieve informations
  • Remember that you can set XMP file for your Flash project but until now, search engines don’t use those informations

I think that’s all, I hope to find more about how can create searchable content with Flash (there is a good PDF file in adobe website) but I think that there is no way.
We are only at the beginning of a big mountain and I hope that Adobe starts to make something new in next few months… maybe at MAX 2009 also, but I really don’t know.

Modules and DragManager bug in Flex 3

In my last RIA project based on Flex 3, I find a bug working with modules that I’d like to sharing in this blog.

I create a dashboard where 4 custom components, that extend Panel component, load in a ModuleLoader differents sections.
In those sections there are components based on List component and when I run my project I’ve this kind of error:

TypeError: Error #1034: Type Coercion failed: cannot convert mx.managers::DragManagerImpl@21ef6df9 to mx.managers.IDragManager.

Surfing on web I don’t find anything about this kind of problem, finally on JIRA Adobe Flex bugs, I find it!
You can find workaround on JIRA ticket, it’s so easy to solve it, you only create a new instance of DragManager in your Default Application and everything works well.
This bug is created because you have more instance of DragManager in this sample, but DragManager in Flex framework is used like a Singleton so only one instance per time.
Each module has a List component that use DragManager when you have in the same application 2 or more modules you must put in Default Application file a DragManager instance and that’s it!
I think could be useful for anybody in the same situation.