Posts Tagged ‘Tip’

Code Tip: parse variables response from backend into as3

August 6, 2011 4 comments

Just a quick code bit I wanted to share, for those interested. Example below assumes that a response from backend is in this format:


Here is how I parse it. If someone knows a better & faster way; please let me know.

function onResponseComplete(e:Event):void

var nameValuePairs:Array = unescape(‘&’);
var id:String;
var status:String;
var message:String;
var i:int = 0;
var length:int = nameValuePairs.length;
var nameValuePair:String;
var variable:String;
var value:String;

for (i = 0; i < length; ++i)

nameValuePair = nameValuePairs[i] as String;
variable = nameValuePair.substring(0, nameValuePair.indexOf(‘=’));
value = nameValuePair.substring(nameValuePair.indexOf(‘=’) + 1, nameValuePair.length);

if (variable == ‘id’) id = value;
if (variable == ‘status’) id = value;
if (variable == ‘message’) id = value;



Categories: ActionScript, Flash Tags: , ,

Code Tip: Copying image files along with an AIR application

March 20, 2010 6 comments

*** UPDATE ***
In my post below; I am mentioning 1 out of 2 possible ways of embedding image (or any other format for that matter) into an AS3 project but here is link to a detailed post by Renaun Erickson mentioning both the techniques.

I have been developing an Adobe AIR application for the last 2-3 weeks and so far, it has only been a simple yet big (in terms of content) interactive presentation running on the desktop. Just recently, I was asked to see if there is any way some images could be copied to user’s desktop when the application is being installed or is being run so that the user can select those images to set as wallpaper.

As always, I started my journey with googling but soon realized that there is no direct way of copying images from development environment to a user’s desktop via AIR application. The solution I figured out was as follows and please, if someone knows a better way around this; let me know.

As a note; my main development IDE was Flash CS4 Professional and I used FlashDevelop as code-editor.

I first embedded the images I wanted to carry with my application using the [Embed] metadata tag; which is a part of Flex SDK. Attached a Class to it obviously and then instantiated in code.

private var Wallpaper :Class;
private var wallpaper :Bitmap = new Wallpaper ();

Then it was about creating a folder on user’s desktop. It uses File class of AIR API.

var directory :File = File.desktopDirectory.resolvePath ( 'Wallpapers' );
directory.createDirectory ();

Then it was about writing a JPG file.

this.file = File.desktopDirectory.resolvePath ( 'Wallpapers/Wallpaper.jpg' );

The above code doesn’t write the file instantly as you can see we haven’t yet connected our embedded image to this file in anyway but instead it creates a placeholder, a blank image file which has nothing but 0 bytes yet.

The FileStream class of AIR API is the one providing the necessary methods of opening/reading/writing bytes on a file but since it only allows ByteArray to be written on to a File instance, I had to first convert my embedded image data into ByteArray data. as3corelib comes in handy again. JPGEncoder class of this package provides us with encode method which converts BitmapData to ByteArray.

var imageByteArray:ByteArray = this.jpgEncoder.encode ( this.wallpaper.bitmapData );

And finally, it was about opening the File instance and feeding this imageByteArray data to it using our FileStream instance.

this.outputProgressed.addOnce ( this.onProgress_CopyFiles );
this.fileStream.openAsync ( this.file, FileMode.WRITE );
this.fileStream.writeBytes ( imageByteArray );

I used openAsync instead of open because I wanted the other code to run at the same time while the images were being copied in the background. Plus, since I used Robert Penner’s AS3Signals as my main event mechanism throughout this application, I used the lovely addOnce method to make sure the listener object gets removed once the event is fired.

P.S. Robert Penner has compiled a list of examples of AS3Signals for those who are interested in giving it a try.

Things I learnt recently

March 9, 2010 8 comments

For the last few months, I have been experimenting and playing a lot with different techniques and code frameworks just to improve my Flash/ActionScript skills overall.

Stuff like SWC compilation, creating code-snippets are not something new and people have already mastered these arts but as I feel very new in Flash world and as I feel there is a lot for me to learn, I thought I should share some the things I recently discovered.

SWC compilation

I have been using (and still use) Flash Professional IDE as my main development IDE for project compilation for the last three years or so but recently I had a little chat with one of my seniors (Philip Bulley, the guy who got me going in Flash) about the different ways of compiling a SWF file. I had my arguments (typically because I was in my comfort zone using Flash IDE) but he convinced me as always to adopt to ActionScript-only projects so I can just use Flash IDE for assets creation.

Reasons like fast compilation, adding wrapper on top of classes whenever need be (since in Flash, if you have a movieclip structure in place and later on you feel there is a need to change/alter it, it is very difficult) and a pure Object-Oriented feel (instantiation of assets, removal when done) were good enough for me to give it a thought. I am looking forward to feature projects which will certainly be based on ActionScript-only approach using FlashDevelop.

FlashDevelop’s code snippets and code generation

Everyone knows about the usefulness of code snippets and if these snippets are quickly accessible, what else do you want. In my classes, most of the public functions (after implementing an Interface) are same and I use to write them and indent them and comment them again and again. Too be honest, after exploration of code snippets in FlashDevelop, I feel like I have been so stupid. Trust me, whichever your ActionScript Editor is, create and store your little gems, and use them as needed as all of the editors come with this feature of storing snippets.


Oh Robert Penner, I owe you for that one; you are the man :). AS3Signals is simply fantastic. With different tests showing the speed of this event mechanism and a presentation and a video tutorial showing how easy it is to use Signals, there is no reason ActionScript Developers should give it a try. Lot can be (and has been) said about as3signals, but I will keep it for you to explore. Oh and btw, an enhancement to as3signals is going on as well which, to be very honest, is going over my head. :)

formatString function

I just didn’t know how handy could … rest really be before I got into this situation (i.e. formatString function). Check this little function I created out of curiousity. Little things matter a lot sometimes.

Casalib ActionScript Library

I downloaded CASALib quite a while ago and the utility functions (the ones I have used so far) are very handy in everyday projects. Everytime I google for some helper class, I find it under casalib library, right under my nose.

Look at Inactivity class of time package for instance, wouldn’t you want to decrease stage’s framerate when the user is idle for some time (i.e. the mouse is not moving at all), I would, on all projects actually. Essentially, it is a matter of adding timers and checking if the last mouse position is equal to the new position, but who would do that if someone has already done that and with additional functionality. So, kudos to Casalib for a great package of useful classes.

FlashPlayer 10 3D

I am done with it. I am done playing with FlashPlayer 10’s 3D capabilities. Oh! why did I develop two projects using it, I should’ve used Papervision3D.

Anyways, I will give any external 3D library a try on my next 3D-based project.

That’s it. There is obviously a lot that I need to learn and master and I will Insha Allah.

Code Tip: Merge/Combine two objects into one

December 23, 2009 Leave a comment

Ever wanted to combine properties of one object with another object resulting finally into one single object. Here is a little utility function which would help you do this:

private function combineVars ( defaultVars:Object, additionalVars:Object ):Object
var combinedObject :Object = {};
for ( var property:String in defaultVars )
combinedObject[ property ] = defaultVars[ property ];
for ( var property:String in additionalVars )
combinedObject[ property ] = additionalVars[ property ];
return combinedObject;

Code Tip: Array containing random but unique numbers

December 9, 2009 1 comment

I am just sharing here a good utility function I found over the internet to get an array of random but unique numbers starting from zero.

Here it is:

function getUniqueRandom ( range:int ):Array
var numberList :Array = [];
var randomList :Array = [];
var i :int;

for ( i = 0; i <= range; i ++ )
numberList[ i ] = i;

var length :int = numberList.length;

for ( i = length - 1; i >= 0; i -- )
var picked = Math.floor ( Math.random () * i );
randomList[ i ] = numberList[ picked ];
numberList[ picked ] = numberList[ i ];

return randomList;

var myArray :Array = this.getUniqueRandom ( 10 );
trace ( myArray ) // results: 5,1,4,7,10,2,3,9,6,8,0

Code Tip: Percentage to Value – Value to Percentage

November 19, 2009 1 comment

While on a project just recently, I was in need of calculating a percentage of a certain value which is in a specified range and then to convert back this percentage to equivalent value of another range.

For example, if I have a range of integers from 0 to 50 and I need to find an equivalent percentage of the value of 25 within this range, the resulting percentage would be 50%. And now if I take this 50% and find an equivalent value within another range of 50 to 100, the resulting value would be 75.

Tried to find a utility class for this type of basic percentage-to-value conversion over the internet but couldn’t find so I wrote my own. Here it is:

package com.tahirahmed.utils

* Number Utilities
* …
* @author Tahir Ahmed –
* @version 1.0
public class NumUtils

public function NumUtils ( )

* Determines an equivalent percentage of a value within a given range
* @param value the value to which the equivalent percentage needs to be calculated
* @param min the lower value of the range
* @param max the upper value of the range
* @return percentage the resulting percentage of the given value within the specified range
* @example
* NumUtils.getPercentage ( 5, 0, 10 ); // returns 50

public static function getPercentage ( value:Number, min:Number, max:Number ):Number
var percentage :Number = ((( value – min ) / ( max – min )) * 100 );

return percentage;

* Determines an equivalent value of a percentage within a given range
* @param percentage the percentage to which the equivalent value needs to be calculated
* @param min the lower value of the range
* @param max the upper value of the range
* @return value the resulting value of the given percentage within the specified range
* @example
* NumUtils.getValue ( 50, 0, 10 ); // returns 5

public static function getValue ( percentage:Number, min:Number, max:Number ):Number
var value :Number = ((( max – min ) / 100 ) * percentage ) + min;

return value;

Download it from here.

Code Tip: Removing Children from a MovieClip

November 4, 2009 Leave a comment

I used to remove children of a movieclip like this:

for ( var i:int = 0; i < myMovie.numChildren; i ++ )
myMovie.removeChildAt ( i );

But it becomes problematic if myMovie has children placed all over the container without having any control over the depth at all. Since the approach mentioned above uses depth as its primary source of identification, it is difficult to get all the objects present within if the developer loses control over depth of each child element (ok I admit, I did that :) and I complicated it for myself). So there was a point I was thinking that ok I made a mistake, just clear up my container movieclip.

Then I recently found out that removing all children from a movieclip can also be done through a while loop like this:

while ( myMovie.numChildren )
myMovie.removeChildAt ( 0 );

Boom. We are done. End of story.


Get every new post delivered to your Inbox.