Archive for July, 2008

Moock on ActionScript 4

July 29, 2008

Thease feature  will probably be present in ActionScript 4 .

  • Generic Functions: This functionality will add Java-style method overloading to ActionScript. A function must be defined with the keyword generic, but then mutliple methods (with different method signatures) can be used.
  • Iterators and Generators: Increased support for iterating over a series of values using a class defined iterator. Both of these items are very Python-like.
  • Proper Tail Calls: A function can properly call another function as its last operation – this adds increased support for recursion patterns.
  • New Number Types: byte, double, decimal (and the current generic ‘Number’ type would be removed)
  • Numeric Suffixes: As in Java, numeric literals will have suffixes to denote their specific numeric type.
  • Vector Type: As in Java, there will be a mono-typed array called Vector. Length can optionally be pre-defined at creation.
  • Record Type: Describes the details of an object – easier to create than a class. I believe it is dynamic – in that it has required values, but additional properties can be defined per instance.
  • Array Type: A type that describes what will be contained within an array. For example – you could say that you will have a 7-element array made up of Strings.
  • Union Types: A property (or argument) could be one of a list of types (as opposed to now where a property has to be of one type – or no type). This would give you the ability to have an argument that could be a String or XML – but nothing else.

Copying objects with Flash.utils.ByteArray

July 17, 2008

I have been exploring the ways to copy an Array object to a new Array with less of the effort. Reason being the following statements in ActionScript

var arrayA:Array = new Array(”Jack”,”Steve”,”Mark”,”Ted”);
var arrayB:Array = arrayA;

The above statements appears to create a copy of arrayA, however in the actual it creates a new reference to the arrayA object. The problem is that if you execute any operation on arrayB object now it will impact the arrayA eventually. For example:

arrayB.pop();
trace(arrayA);

The statement is supposed to trace “Jack,Steve,Mark,Ted” whereas it will trace “Jack,Steve,Mark”.

To overcome this problem we use the following methodology

var arrayA:Array = new Array(”Jack”,”Steve”,”Mark”,”Ted”);
var arrayB:Array = new Array();
for(var i:int = 0; i < arrayA.length; i++) {
arrayB[i] = arrayA[i];

}
arrayB.pop();
trace(arrayA);

Now it will trace the desired result i.e. “Jack,Steve,Mark,Ted” and if you trace arrayB then it will trace “jack,Steve,Mark”

This methodology is very good when you are dealing with single array objects but when it comes to Nested Arrays it is really a tedious job as you have to look for every inner object of an array if it is an Array type and then again create a new array and copy it’s element. To overcome this we can use now the ByteArray class of Flash.utils package

You can review the following code used to copy an array. There is a disadvantages of using the ByteArray and that is you will loose on some speed. The ByteArray.Read method is slower than copying an Array. You can see a benchmark here

——————————–
Copying a 100000 elements array
——————————–
Copy with loops starts at :: 802504163
Copy with loop ends at :: 802504210
Time elapsed :: 47 milliseconds
Copy with ByteArray Starts at :: 802504257
Copy with Byte Array :: 802504382
Time elapsed :: 125 milliseconds

There is certainly a significant amount of processing time which ByteArray take however it is eventually helping us out when it comes to copying nested objects.

Download the fla from here.

Here is the code for the same.

——————————————————–

——————————————————–

import flash.utils.ByteArray;

var tDate:Date = new Date();
var iStartTime:uint;
var iTime:uint;
var byteArray:ByteArray = new ByteArray();

trace(”——————————–”);
trace(”Copying a 100000 elements array “);
trace(”——————————–”);
//———- Create and Populate Array ———
var arrayA:Array = new Array();
for (var i:uint; i<=100000; i++) {
arrayA.push(Math.random()*i);
if (i == 100000) {
copyArray();
}
}

//———– Copy Array using Loops ——–

function copyArray():void {
tDate = new Date();
iStartTime = tDate.time;
trace(”Copy with loops starts at :: ” + iStartTime);
var arrayB:Array = new Array();
var arr_len:uint = arrayA.length -1;
for (var i:int = 0; i <= arr_len; i++) {
arrayB[i] = arrayA[i];
if (i == arr_len) {
tDate = new Date();
iTime = tDate.time;
trace(”Copy with loop ends at :: ” + iTime);
trace(”Time elapsed :: ” + (iTime – iStartTime) + ” milliseconds”);
copyWithByteArray();
}
}
}
//——- Function copy with Byte Array ———
function copyWithByteArray():void {
tDate = new Date();
iTime = tDate.time;
trace(”Copy with ByteArray Starts at :: ” + iTime);
byteArray.writeObject(arrayA);
byteArray.position = 0;
var arrayB:Array = byteArray.readObject() as Array;
tDate = new Date();
var iByteArrTime:uint = tDate.time;
trace(”Copy with Byte Array :: ” + iByteArrTime);
trace(”Time elapsed :: ” + (iByteArrTime – iTime) + ” milliseconds”);
}

Check the Internet connectivity is present or not.

July 15, 2008

There are two ways to achive the same.

Method : 1)

                        private var monitor:URLMonitor;

                        public function checkConnectionStatus():void

                        {

                                var checkUrl:URLRequest = new URLRequest(“http://www.google.com“);

                                monitor = new URLMonitor(checkUrl);

monitor.addEventListener(StatusEvent.STATUS,updateConnectionStatus);

                                monitor.start();

                        }

                        public function updateConnectionStatus(event:StatusEvent):void

                        {

                                monitor.stop();

                               if(event.code == “Service.available”)

                                {

                                        Alert.show( “Online”);

                                }

                                else if(event.code == “Service.unavailable”)

                                {

                                        Alert.show(“Offline”);

                                }

                        }

Method 2) :

                       When you login to the application  , If
internet connection goes out or comes back , the below event will be
fired, you can catch this event an call    back the method described

in MEthod 1)

Application.application.addEventListener(Event.NETWORK_CHANGE,handleNetwork

Resizing button component on the fly

July 9, 2008

We have encountered a situation where the the UI button label was changing frequently in Flash CS3. So basis on that we have to resize our button component as the label changes. There is no inbuilt AutoResize feature in button component so what we have done is, get the size of the label and then set the width of the button. Following is the code we have implemented in this case. Put a UI button on stage and name it “_btn”. You can download the source files from here.

import flash.events.Event;
//———-
var t_arr:Array = ["This is string 1","Hello","Hello to String 3","Hello to String 4","Hello to String 5","This is a long string NOW "];
//——— Set the button textfield properties ———-
_btn.textField.autoSize = TextFieldAutoSize.LEFT; // We need to set the autosize to LEFT?RIGHT or CENTER instead of NONE
_btn.textField.multiline = false; // Make sure the multiline is false in this case to get proper dimensions
_btn.label = t_arr[0];
_btn.textField.addEventListener(Event.RENDER,resizeBtn); // Add an event listener to textfield on render event
_btn.addEventListener(MouseEvent.CLICK,clickHandler);
//——– Resize the button ———–
function resizeBtn(evt:Event):void{
// trace(evt.target.width+” “+evt.target.parent.width);
_btn.width = evt.target.width+5;
_btn.validateNow();

}
//———— Handle button click ———
function clickHandler(evt:MouseEvent):void{
_btn.label = t_arr[Math.floor(6*Math.random())];
}

Loading library assets from flash9 swf to Flex

July 9, 2008

This is a prototype to load external flash9 swf file into flex and using the library items from the swf. In given example we have two library symbols with linkage ids (”mc1″, “mc2″).

Just make sure when you create a movieclip from these definitions, you firstly add these to a UIComponent and then that component to stage or any container, otherwise there will be a conversion error you will be getting

You can download sources from here

Following is the code for the same.

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” creationComplete=”init()” layout=”absolute”>

<mx:Script>

<![CDATA[

import mx.core.UIComponent;

//-------- Declare Variables --------

private var swfLoader:Loader;

private var fileURL:URLRequest;

//----- Initialize Function ------------

private function init():void{

//    Security.allowDomain("*");

swfLoader = new Loader();

_fileURL = new URLRequest("sample.swf");

configureListeners(swfLoader.contentLoaderInfo);

try{

swfLoader.load(_fileURL);

}

catch(e:IOErrorEvent){

trace(e.toString());

}

}

private function configureListeners(dispatcher:IEventDispatcher):void {

dispatcher.addEventListener(Event.COMPLETE, onSWFLoaded);

dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);

dispatcher.addEventListener(Event.INIT, initHandler);

dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);

dispatcher.addEventListener(Event.OPEN, openHandler);

dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);

dispatcher.addEventListener(Event.UNLOAD, unLoadHandler);

}

private function completeHandler(event:Event):void {

trace("completeHandler: " + event);

}

private function httpStatusHandler(event:HTTPStatusEvent):void {

trace("httpStatusHandler: " + event);

}

private function initHandler(event:Event):void {

trace("initHandler: " + event);

}

private function ioErrorHandler(event:IOErrorEvent):void {

trace("ioErrorHandler: " + event);

}

private function openHandler(event:Event):void {

trace("openHandler: " + event);

}

private function progressHandler(event:ProgressEvent):void {

trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);

}

private function unLoadHandler(event:Event):void {

trace("unLoadHandler: " + event);

}

//-----

private function onSWFLoaded(event:Event):void{

var mClip:Class = event.target.applicationDomain.getDefinition("mc1") as Class;

var mClip1:Class = event.target.applicationDomain.getDefinition("mc2") as Class;

var mClipInstance:MovieClip = new mClip() as MovieClip;

var mClipInstance1:MovieClip = new mClip1() as MovieClip;

//trace(mClipInstance.totalFrames);

var uiComp:UIComponent = new UIComponent();

uiComp.addChild(mClipInstance);

uiComp.addChild(mClipInstance1);

addChild(uiComp);

uiComp.x = 100;

uiComp.y = 100;

uiComp.getChildAt(0).x = 150;

}

]]>

</mx:Script>

</mx:Application>