Speaking at DevSummit

November 9, 2009

Looking forward to speak at Adobe DevSummit @Chennai 24/Nov & @Hyd 1/Dec on Topic “Integration of Spring with BlazeDS and CairngormUM (Deep Dive)”

The Presentation Document : link &
Presentation

Speaking at Adobe DevSummit

DevSummit


Loading Image / Swf in MAC, AIR

July 2, 2009

A Quick tip, was stuck today to load an local image / swf inside AIR at MAC OS.
The below is the solution:

var filenotion:String =”;
if(Capabilities.os.search(“Mac”) >= 0) filenotion = “file://”;
Image.source= filenotion +imgFileURI;


Using / Creating Locale for your language

June 24, 2009

How to do :

1 ) To create resource bundles for different languages and then use the ResourceManager class provided by the Flex API to get the resources.
Just changing the locale of the resource manager will reflect changes in the entire application with the values from the new locale’s resource bundle.

How to Create Locale :

For example if I want to support two locales (en_US and fr_FR) in your application and I my parent folder is named as “Locales”, then I might have following folders. As en_US ,fr_FR

It will be like this :
Locales/en_US , Locales/fr_FR

Steps to do before make the Bundle

Part 1 : SDK

Create folder
1 D:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0\frameworks\projects\framework\bundles \fr_FR
2 D:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0\frameworks\projects\framework\bundles\fr_FR \src

Download and paste
3.http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/frameworks/projects/framework/bundles/fr_FR inside step 2

Create folder :
4 D:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0\frameworks\locale \fr_FR

Execute
5. D:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0

bin\compc -locale=fr_FR -source-path+=frameworks/projects/framework/bundles/fr_FR/src -include-resource-bundles=collections,containers,controls,core,effects,formatters,logging,SharedResources,skins,states,styles,utils,validators -output=frameworks/locale/fr_FR/framework_rb.swc

Part 2 : Project

1. Set System PATH
D:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0\bin
2. create required properties file mainBundle.properties
3. keep that file inside a folder with your locale name ‘fr_FR
4.execute from root path
mxmlc -locale=fr_FR -source-path={locale} -include-resource-bundles=mainBundle,collections,containers,controls,core,effects,skins,styles -output=src/Resources_fr_FR.swf

mxmlc -locale=en_US -source-path={locale} -include-resource-bundles=mainBundle,collections,containers,controls,core,effects,skins,styles -output=src/Resources_en_US.swf

After that place that swf file your Project

Locale/en_US :
Inside we need create the file name like “mainBundle.properties” inside that we need to create like that

welcome_title_text=Welcome,
form_first_name_text=First Name
form_second_name_text=Last Name
form_gender_text=Gender
form_gender_list_male_text=Male
form_gender_list_female_text=Female

Locale/fr_FR :
Inside we need create the file name like “mainBundle.properties” inside that we need to create like that

welcome_title_text=Bienvenue ,
form_first_name_text=Prénom
form_second_name_text=Nom de famille
form_gender_text=Sexe
form_gender_list_male_text=Mâle
form_gender_list_female_text=Femelle

Adding Locales to your Projects
Add the locale to the compiler options.
-locale=en_US,fr_FR

This link, claims to have compiled swc files for most languages : Babel


Flex with Java Collaborative using the Best Architectures of Both

June 18, 2009

This Post was my overdue subject, I wanted to help with a sample Application using Cairngorm, Spring BlazeDS Integration & Generic DAO.

This might be a heavy subject as it deals with many subjects:

The Source is available at the link: cairnspring

How to use the source effectively?
it is simple, steps below:

  1. Download, Source and Libs
  2. Unzip both and import “CairnSpring”, to your Eclipse
  3. Paste the lib files to “CairnSpring\WebContent\WEB-INF\lib” folder
  4. Import the “db.sql” into your MySQL Db, (change mysql port to 3036, else can be configured to default in “CairnSpring\WebContent\WEB-INF\config\jdbc.properties” file)
  5. In Eclipse, Window -> Preferences -> Web and XML -> XML Catalog -> Add User Specified Entries with below values
    Location : CairnSpring/WebContent/WEB-INF/config/spring-flex-1.0.xsd
    KeyType : Namespace Name
    Key : http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
  6. Start the Tomcat Server with CairnSpring instance (the server host and port can be configured in file “CairnSpring\flex_src\Server.properties”)

Flex with JAVA

April 18, 2009

The best architectures for java with flex collaboration

spring – with – hibernate
http://www.ibm.com/developerworks/java/library/j-genericdao.html

spring -with – blaze
http://coenraets.org/blog/2009/03/springblazeds-integration-test-drive-m2-update-available/

maven – with – spring – flex
http://docs.codehaus.org/display/ENUNCIATE/Architecture+Guide


AS3 Color Utility Functions

April 17, 2009

Utility for Color functions, like RGB to CMYK, RGB to HSV, HSV to RGB, ColorTransformation, int color value to RGB and Color Calculations.

package
{
import flash.geom.ColorTransform;
public class ColorUtil
{
public static function colorTransform( rgb:uint=0, amount:Number=1.0, alpha:Number=1.0 ):ColorTransform
{
amount = ( amount > 1 ) ? 1 : ( amount 1 ) ? 1 : ( alpha > 16 ) & 0xff ) * amount;
var g:Number = ( ( rgb >> 8 ) & 0xff ) * amount;
var b:Number = ( rgb & 0xff ) * amount;
var a:Number = 1-amount;
return new ColorTransform( a, a, a, alpha, r , g , b, 0 );
}
public static function subtract( col1:uint , col2:uint ):uint
{
var colA:Array = toRGB( col1 );
var colB:Array = toRGB( col2 );
var r:uint = Math.max( Math.max( colB[0]-(256-colA[0]) , colA[0]-(256-colB[0]) ) , 0 );
var g:uint = Math.max( Math.max( colB[1]-(256-colA[1]) , colA[1]-(256-colB[1]) ) , 0 );
var b:uint = Math.max( Math.max( colB[2]-(256-colA[2]) , colA[2]-(256-colB[2]) ) , 0 );
return r << 16 | g << 8 | b;
}
public static function sum( col1:uint , col2:uint ):uint
{
var c1:Array = toRGB( col1 );
var c2:Array = toRGB( col2 );
var r:uint = Math.min( c1[0]+c2[0] , 255 );
var g:uint = Math.min( c1[1]+c2[1] , 255 );
var b:uint = Math.min( c1[2]+c2[2] , 255 );
return r << 16 | g << 8 | b;
}
public static function sub( col1:uint , col2:uint ):uint
{
var c1:Array = toRGB( col1 );
var c2:Array = toRGB( col2 );
var r:uint = Math.max( c1[0]-c2[0] , 0 );
var g:uint = Math.max( c1[1]-c2[1] , 0 );
var b:uint = Math.max( c1[2]-c2[2] , 0 );
return r << 16 | g << 8 | b;
}
public static function min( col1:uint , col2:uint ):uint
{
var c1:Array = toRGB( col1 );
var c2:Array = toRGB( col2 );
var r:uint = Math.min( c1[0] , c2[0] );
var g:uint = Math.min( c1[1] , c2[1] );
var b:uint = Math.min( c1[2] , c2[2] );
return r << 16 | g << 8 | b;
}
public static function max( col1:uint , col2:uint ):uint
{
var c1:Array = toRGB( col1 );
var c2:Array = toRGB( col2 );
var r:uint = Math.max( c1[0] , c2[0] );
var g:uint = Math.max( c1[1] , c2[1] );
var b:uint = Math.max( c1[2] , c2[2] );
return r << 16 | g << 8 | b;
}
public static function rgb(r:uint, g:uint, b:uint):uint
{
return r << 16 | g <> 16 & 0xFF;
var g:uint = rgb >> 8 & 0xFF;
var b:uint = rgb & 0xFF;
return [r,g,b];
}
public static function RGBtoHSV( r:Number, g:Number, b:Number ):Array
{
r/=255; g/=255; b/=255;
var h:Number=0, s:Number=0, v:Number=0;
var x:Number, y:Number;
if(r>=g) x=r; else x=g; if(b>x) x=b;
if(r<=g) y=r; else y=g; if(b<y) y=b;
v=x;
var c:Number=x-y;
if(x==0) s=0; else s=c/x;
if(s!=0){
if(r==x){
h=(g-b)/c;
} else {
if(g==x){
h=2+(b-r)/c;
} else {
if(b==x){
h=4+(r-g)/c;
}
}
}
h=h*60;
if(h<0) h=h+360;
}
return [ h, s, v ];
}
public static function RGBtoCMYK( r:Number, g:Number, b:Number ):Array
{
var c:Number=0, m:Number=0, y:Number=0, k:Number=0, z:Number=0;
c = 255 – r;
m = 255 – g;
y = 255 – b;
if(r<g) k=r; else k=g; if(b 0)
{
c = c – k;
m = m – k;
y = y – k;
}
c = Math.round(c / 255 * 100);
m = Math.round(m / 255 * 100);
y = Math.round(y / 255 * 100);
k = Math.round(k / 255 * 100);
return [ c, m, y, k ];
}
public static function HSVtoRGB( h:Number, s:Number, v:Number ):Array
{
var r:Number=0, g:Number=0, b:Number=0;
var i:Number, x:Number, y:Number, z:Number;
if(s < 0) s=0;
if(s > 1) s=1;
if(v < 0) v=0;

if(v > 1) v=1;
h = h % 360; if (h > 0) h += 360; h /= 60
i = h > > 0;
x = v * (1 – s); y = v * (1 – s * (h – i)); z = v * (1 – s * (1 – h + i));
switch(i){
case 0 : r=v; g=z; b=x; break;
case 1 : r=y; g=v; b=x; break;
case 2 : r=x; g=v; b=z; break;
case 3 : r=x; g=y; b=v; break;
case 4 : r=z; g=x; b=v; break;
case 5 : r=v; g=x; b=y; break;
}
return [ r*255>>0, g*255>>0, b*255>>0 ];
}
}
}


SQLLite DBManager for AIR

April 2, 2009

The code file contains functions for managing SQL Lite Table and Database


Preloader for Flex Application

April 2, 2009

Save the below code as a Class file and refer the class name as

import mx.preloaders.*;
import flash.events.ProgressEvent;
public class Bar extends DownloadProgressBar
{
public function Bar()
{
super();
// Set the download label.
downloadingLabel=”Downloading…”
// Set the initialization label.
initializingLabel=”Initializing book…”
// Set the minimum display time to 2 seconds.
MINIMUM_DISPLAY_TIME=2000;
}
// Override to return true so progress bar appears
// during initialization.
override protected function showDisplayForInit(elapsedTime:int,
count:int):Boolean {
return true;
}
// Override to return true so progress bar appears during download.
override protected function showDisplayForDownloading(
elapsedTime:int, event:ProgressEvent):Boolean {
return true;
}
}


Date Util Functiions

March 18, 2009

Utility functions to find First Day of a month, Relative Date information like “Today”, “Yesterday”

public static function getFirstDayofMonth(fullyear:uint,month:uint):uint
{
var tmp:Date = new Date(fullyear,month,1);
return tmp.getDay();
}

public static function isLeapYear( fullyear:uint ):Boolean
{
var flag:Boolean = false;
if(((fullyear%4==0) && (fullyear%100!=0)) || (fullyear%400==0)) flag = true;
return flag;
}

public static function getWeekName( index:uint , type:uint=0 ):String
{
var week:Array;
if(type==0) week = ["SUNDAY","MONDAY","TUSEDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"];
else if(type==1) week = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
else week = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
return week[index];
}

public static function getMonthName( index:uint , type:uint=0 ):String
{
var month:Array;
if(type==0) month = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"];
else if(type==1) month = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];
else month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return month[index];
}

public static function getRelativeDateName( date:Date, type:uint=0 ):String
{
var d1:Date = new Date();
d1 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate());
var d2:Date = new Date(date.getFullYear(),date.getMonth(),date.getDate());
if(d11000*60*60*24*7) return “”;
if(type>8||isNaN(type)) type = 0;
var list:Array;
switch(type) {
case 0: case 3:
list = ["TODAY","YESTERDAY"]; break;
case 1: case 4:
list = ["Today","Yesterday"]; break;
case 2: case 5:
list = ["today","yesterday"]; break;
}
var diff:int = d1.getDate()-d2.getDate();
if(diff<=1) return list[diff];
return getWeekName( d2.getDay(), type );
}


Currency/Numeric Formatter

March 12, 2009

The below custom functions might be of use where you don’t want to use currency formatter or numeric Formatter of AS3

 
public function currencyFormat( number:Number ):String {
var words:Array = String( number ).split( “” ).reverse(); 
  var results:Array = new Array();
 var l:int = words.length;
  for ( var i:int = 0; i < l; i++ ) {
   results.push( words[i] );
   if ( i % 3 == 2 ) {
     results.push( “,” );
   }
   }
   return results.reverse().join( “” );
}

public function prefixZero( number:Number, figure:int ):String {
   var str:String = String( number );
   for ( var i:int = 0; i < figure; i++ ) {
     str = “0″ + str;
   }
   return str.substr( str.length – figure, str.length );
}


ByteArray to BitmapData

March 5, 2009

The Below code demonstrates the conversion of ByteArray to BitmapData. In the below case, SWF is loaded and converted into BitmapData

private function swfLoad_complete(evt:Event):void {
byteArrayToBitmapData(swf.content.loaderInfo.bytes);
}
private function byteArrayToBitmapData(ba:ByteArray):void {
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, getBitmapData);
loader.loadBytes(ba);
}
private function getBitmapData(e:Event):void {
var content:* = loader.content;
var BMPData:BitmapData = new BitmapData(content.width,content.height);
var UIMatrix:Matrix = new Matrix();
BMPData.draw(content, UIMatrix);
}


Convert Data Types: ArrayCollection, XML, Object, String

March 5, 2009

The code below demonstrates the data type conversions among basic DataTypes used most in Flex. The ‘init()’ method does to and from conversion for ArrayCollection to XML and XML to ArrayCollection

Object, String, XML, ArrayCollection

 

import mx.collections.ArrayCollection;
import mx.rpc.xml.SimpleXMLEncoder;
import mx.rpc.xml.SimpleXMLDecoder;
import mx.utils.ObjectUtil; 
  private function xmlToArrayCollection(xml:XML):ArrayCollection{                 
            var xmlDoc:XMLDocument = new XMLDocument(xml.toString());
           var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
            var resultObj:Object = decoder.decodeXML(xmlDoc);
            var ac:ArrayCollection =new ArrayCollection(Array(resultObj.root.list.source.item));
            return ac;
}
private function objectToXML(obj:Object):XML {
            var qName:QName = new QName(“root”);
            var xmlDocument:XMLDocument = new XMLDocument();
            var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
            var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
            var xml:XML = new XML(xmlDocument.toString());
            return xml;
}
private function objectToArrayCollection(obj:Object):ArrayCollection {
            var ac:ArrayCollection =  new ArrayCollection(obj as Array);
            return ac;

private function arrayCollectionToXML(ac:ArrayCollection):XML{
var xml:XML = objectToXML(ac);
return xml;
}
private function init():void{
  var arr:Array = new Array();
  arr.push({data:0,name:’deva’});
  arr.push({data:1,name:’raj’});
  var ac:ArrayCollection = new ArrayCollection(arr);
  var xml:XML = arrayCollectionToXML(ac);
var newAc:ArrayCollection = xmlToArrayCollection(xml);
trace(newAc[0][0].name);
}
private function objToStr(value:Object,indent:int =0,
                                         refs:Dictionary= null, 
                                         namespaceURIs:Array = null, 
                                         exclude:Array = null):String{
var str:String;
var refCount:int = 0;
if (value is Date)
            {
                return value.toString();
            }
            else if (value is XMLNode)
            {
                return value.toString();
            }
            else if (value is Class)
            {
                return “(” + getQualifiedClassName(value) + “)”;
            }
            else
            {
                var classInfo:Object = ObjectUtil.getClassInfo(value, exclude,
                    { includeReadOnly: true, uris: namespaceURIs });
                var properties:Array = classInfo.properties;
                str = “(” + classInfo.name + “)”;
                if (refs == null)
                    refs = new Dictionary(true);
                var id:Object = refs[value];
                if (id != null)
                {
                    str += “#” + int(id);
                    return str;
                }
                if (value != null)
                {
                    str += “#” + refCount.toString();
                    refs[value] = refCount;
                    refCount++;
                }
                var isArray:Boolean = value is Array;
                var isDict:Boolean = value is Dictionary;
                var prop:*;
                indent += 2;
                for (var j:int = 0; j < properties.length; j++)
                {
                    str = newline(str, indent);
                    prop = properties[j];
                    if (isArray)
                        str += “[";
                    else if (isDict)
                        str += "{";
                    if (isDict)
                    {
                        str += objToStr(prop, indent, refs,
                                                namespaceURIs, exclude);
                    }
                    else
                    {
                        str += prop.toString();
                    }
                    if (isArray)
                        str += "] “;
                    else if (isDict)
                        str += “} = “;
                    else
                        str += ” = “;
                    try
                    {
                        str += objToStr(value[prop], indent, refs,
                                                namespaceURIs, exclude);
                    }
                    catch(e:Error)
                    {
                        str += “?”;
                    }
                }
                indent -= 2;
                return str;
            }
}
private static function newline(str:String, n:int = 0):String
   {
       var result:String = str;
       result += “\n”;
       for (var i:int = 0; i < n; i++)
       {
           result += ” “;
       }
       return result;
   }
/* General function for Conversion (thanks, Krystian Bień)
 public function xmlToArrayCollection(xml:XML):ArrayCollection{
            var temp:String = ‘<items>’ + xml.toString() + ‘</items>’;
            xml = XML(temp);
            var xmlDoc:XMLDocument = new XMLDocument(xml.toString());
            var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
            var resultObj:Object = decoder.decodeXML(xmlDoc);
            var ac:ArrayCollection;
            ac = new ArrayCollection();
            ac.addItem(resultObj.items);
            return ac;                
        }*/


Flex Effects Explorer

February 16, 2009

I came across the efflex.org. Its so amazing.. someone took effort to make such library.. I compiled a zip with required Lib elements on this link efflex.


AS3 : Basic String function

February 11, 2009

Some Basic String functions:

public function replaceChars(str:String, Char:String, replace:String) : String
{
var result:String = “”;
for (var i:int = 0; i < str.length; i++) {
if (str.charAt(i) == Char)
{
result += replace;
}
else
{
result += str.charAt(i)
}
}
return result;
}

public function trimWhiteSpace(str:String) : String
{
var pattern:RegExp = /[\s]+/g;
return str.replace(pattern, “”);
}

public function containsAlphaNumeric(str:String) : Boolean
{
var pattern:RegExp = /[^a-zA-Z0-9]/;
return str.search(pattern) != 0;
}


P2P Video Conferencing : Stratus

January 30, 2009

The adobe labs rocks once again, Stratus. This is a superior technology for P2P communication using RTMFP-capable server. The link does have sample included, example here (w/o DB) and here (w DB) . I have included file sharing along with this.


Licensing Flex / AIR Application

January 20, 2009

I have came through the thread and this is my solution  to protect the product with a serial key uncrackable.

The solution can be used in both Online browser based / AIR products.

The MD5 class does create a Unique system ID and verifies the MD5 checksum with a foreign key to check whether the user is registered or not.

MD5.registereduser – Boolean returns true, if user is registered.
MD5.skey                      - The Serial key to be used, to register (can store in a db or xml)
MD5.setRegKey(MD5.skey);   – To unlock the product.


Preview Image Loader

November 11, 2008

Loading Image from local file system using the power of  Flash Player 10, Filereference.load()
Check the Demo the link contains the source file.


CO Binding Util

November 11, 2008

Like Chemical CoValent Bonding, Bind two Objects of Flex through this
AS3 Utility… ;)  

package
{
import flash.events.Event;
import mx.binding.utils.ChangeWatcher;
public class CovalentBindig
{
public static function Bond(obj1:Object, prop1:String, obj2:Object, prop2:String):void
{
var flag:Boolean = false;
ChangeWatcher.watch(obj1, prop1, function(event:Event):void
{
if(!flag)
{
flag = true;
obj2[prop2] = obj1[prop1];
flag = false;
}
});

ChangeWatcher.watch(obj2, prop2, function(event:Event):void
{
if(!flag)
{
flag = true;
obj1[prop1] = obj2[prop2];
flag = false;
}
});
}
}
}


Dotted Line Util

November 5, 2008

Dotted Line, Utility Class for AS3 

package {
import flash.display.Graphics;
import flash.geom.Point;
public class DotLine{
public function DotLine( target:Graphics, seg:Number=20, xx:Number=0, yy:Number=0 ):void{
this.target = target;
this.now = new Point( xx, yy );
this.seg = seg;
this.rest = 0;
this.flag = false;
}
public var target : Graphics;
public var seg : Number;
public var now :  Point;
public var rest : Number;
public var flag : Boolean;
public function dotLineTo( xx:Number, yy:Number ):void{
var s: Point = new Point( now.x, now.y );
var e: Point = new Point( xx, yy );
var d:Number = Point.distance( s, e );
now.x = e.x;
now.y = e.y;
rest = (seg * 1 < rest) ? rest – seg * Math.floor( rest / seg ) : rest;
if(d <= rest){
rest -= d;
if(flag){
target.lineTo( e.x, e.y );
flag = (rest == 0) ? false : true;
}
else{
target.moveTo( e.x, e.y );
flag = (rest == 0) ? true : false;
}
return void;
}

var m:Number = 1 / ( d / seg );
var n:Number = 1 / ( d / rest );

for( var i:Number=1-n; 0<i; i-=m ){
var a: Point = Point.interpolate( s, e, i );
if(flag){
target.lineTo( a.x, a.y );
flag = false;
}
else{
target.moveTo( a.x, a.y );
flag = true;
}
if( i – m < 0 ){
var b: Point = Point.interpolate( s, e, i – m );
var c: Point = Point.interpolate( s, e, 0 );
rest = Point.distance( e, b );
if(flag){
target.lineTo( c.x, c.y );
}
else{
target.moveTo( c.x, c.y );
}
}
}
}

}
}


Collision Detection AS3 Util

November 5, 2008

Collision Detection Utility class for AS3,

Usage: var collide:Rectangle = checkForCollision(obj1, obj2);

package {
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Matrix;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;

public class CollisionDetection{

public static function checkForCollision(firstObj: DisplayObject,secondObj: DisplayObject):Rectangle
{
var bounds1:Object = firstObj.getBounds(firstObj.root);
var bounds2:Object = secondObj.getBounds(secondObj.root);

if (((bounds1.right < bounds2.left) || (bounds2.right < bounds1.left)) || ((bounds1.bottom < bounds2.top) || (bounds2.bottom < bounds1.top)) ) {
return null;
}

var bounds:Object = {};
bounds.left = Math.max(bounds1.left,bounds2.left);
bounds.right= Math.min(bounds1.right,bounds2.right);
bounds.top = Math.max(bounds1.top,bounds2.top);
bounds.bottom = Math.min(bounds1.bottom,bounds2.bottom);

var w:Number = bounds.right-bounds.left;
var h:Number = bounds.bottom-bounds.top;

if(w < 1 || h < 1)
{
return null;
}

var bitmapData:BitmapData = new BitmapData(w,h,false);

var matrix:Matrix = firstObj.transform.concatenatedMatrix;
matrix.tx -= bounds.left;
matrix.ty -= bounds.top;
bitmapData.draw(firstObj,matrix,new ColorTransform(1,1,1,1,255,-255,-255,255));

matrix = secondObj.transform.concatenatedMatrix;
matrix.tx -= bounds.left;
matrix.ty -= bounds.top;
bitmapData.draw(secondObj,matrix,new ColorTransform(1,1,1,1,255,255,255,255),BlendMode.DIFFERENCE);

var intersection:Rectangle = bitmapData.getColorBoundsRect(0xFFFFFFFF,0xFF00FFFF);

/*try{
bitmapData.dispose();
}catch(e:Error){}*/

if (intersection.width == 0) { return null; }

intersection.x += bounds.left;
intersection.y += bounds.top;

return intersection;
}
}
}


Execute Commands on queue

November 4, 2008

The AS3 Utility Class to add commands in a queue, the usage and class is below:

/** 
* var commands : CommandsQueue = new CommandsQueue();
* commands.addCommand( this, myFunc );
* commands.addCommand( this, myFunc2, [0,2], this, Event.COMPLETE );
* commands.execute();
*/
package
{
import flash.events.Event;
import flash.events.EventDispatcher;

public class CommandsQueue extends EventDispatcher
{
protected var commands : Array;
protected var _index : Number = 0;
public var onComplete : Function;

public function CommandsQueue():void
{
commands = [];
}
public function addCommand( thisObj : Object, func : Function, params: Array = null , completeEventDispatcher : Object = null, completeEventName : String= null ) : void
{
commands.push({
thisObj : thisObj,
func : func,
completeEventDispatcher : completeEventDispatcher || thisObj,
completeEventName : completeEventName,
params : params
})
}
public function get progress():Number
{
return (commands.length>0)? _index / commands.length * 100 : 0;
}
public function cancel() : void
{
throw new Error(“commandQueue.cancel is not implemented yet”);
}
public function execute() : void
{
doNext();
}
public function get index():int
{
return _index;
}
public function get length():int
{
return commands.length;
}
protected function doNext() : void
{
var act : Object = commands[ _index ];

if( act.completeEventName ){
act.completeEventDispatcher.addEventListener(act.completeEventName, _commandComplete, false, 0, true);
act.func.apply( act.thisObj, act.params );
} else {
act.func.apply( act.thisObj, act.params );
doNextCommand();
}
}
protected function doNextCommand() : void
{
var act : Object = commands[ _index ];

if( act.completeEventName )
act.completeEventDispatcher.removeEventListener(act.completeEventName, _commandComplete);

_index ++;

if( _index == commands.length )
{
commands = []; //remove all registerd command for GC
if( onComplete != null )
onComplete();
dispatchEvent( new Event(Event.COMPLETE) );
}else{
doNext();
}
}
protected function _commandComplete( e : Event ) : void
{
doNextCommand();
}
}


AS3 GarbageCollection Utility

October 30, 2008

The below class serves as Garbage Collection utility for AS3. You can use it to prevent your applications from memory leakage.

package{
import flash.events.TimerEvent;
import flash.system.System;
import flash.utils.Timer;
public class GCUtil {
private var _timer:Timer;
public function GCUtil(interval_sec:uint = 60) {
_timer = new Timer(interval_sec*1000);
startGC(interval_sec);
}
public static function doGC():void {
System.gc();
}
public function startGC(interval_sec:uint):void {
if (interval_sec > 0) {
_timer.delay = interval_sec*1000;
if (!_timer.running) {
_timer.addEventListener(TimerEvent.TIMER, handleTimer);
_timer.start();
}
} else {
stopGC();
}
}
public function stopGC():void {
if (!_timer.running) {
_timer.removeEventListener(TimerEvent.TIMER, handleTimer);
_timer.stop();
_timer.delay = 0;
}
}
private function handleTimer(te:TimerEvent):void                       {
doGC();
}
}
}


Elearning using Flex

October 29, 2008

I am glad to announce the first Step for basic requirements of E-Learning using Flex has been achieved.
Basic Requirements met:

  • All Flash player versions starting from Flash Player version 6 to 10, should be loaded. (For support of old elearning courses).
  • Without any memory leak due to loading multiple swf files.
  • Ability to navigate to any particular lesson (SWF).
  • XML Support for loading swf files into a lesson.
  • PreLoader for showing the loading status of individual SWF files
  • Ability to detect events of SWF files (eg: totalframes, swf playing etc.,) 

See the demo of loading a number of animations. The source files include floader.mxmlForcibleLoader.as and XML


Power of FP10

October 22, 2008

Get your own mp3 from local system played from web. more


AVM1Movie Controller in Flex

October 16, 2008

Overcome restrictions on an AVM1 SWF file loaded by an AVM2 SWF file:

While trying to control AVM1Movie (Flash Player 8, 9, 10 or older) from flex, we will get the below error message: ”Property stop not found on flash.display.AVM1Movie and there is no default value. ”

To overcome this problem, ForcibleLoader class converts them into latest player versions on runtime. The below is an working example for how to control AVM1Movie from Flex.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” initialize=”init()”>
<mx:Script>
<![CDATA[
private var swfURL:String = "AVM1Movie.swf";
private var libMC:MovieClip = new MovieClip();
private function init():void{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete);
var fLoader:ForcibleLoader = new ForcibleLoader(loader);
fLoader.load(new URLRequest(swfURL));
swfContainer.addChild(loader);
}
private function swfComplete(event:Event):void{
libMC = event.currentTarget.content as MovieClip;
libMC.gotoAndStop(1);
}
]]>
</mx:Script>
<mx:UIComponent id=”swfContainer”/>
<mx:NumericStepper id=”slide” change=”{libMC.gotoAndStop(slide.value)}”/>
</mx:Application>


Loading flash library asset in Flex

October 4, 2008

The below is the code to load flash library asset (using linkage name) on Flex.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” creationComplete=”onCreationComplete()” >
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
private function onCreationComplete():void{
var swfLoader:Loader = new Loader();
swfLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSWFLoadComplete);
swfLoader.load(new URLRequest("flash.swf"));
}
private function onSWFLoadComplete(event:Event):void{
var tempClass:Class = event.target.applicationDomain.getDefinition("libraryAsset") as Class;
var movieClip:MovieClip = new tempClass() as MovieClip;
var uiComp:UIComponent = new UIComponent();
uiComp.addChild(movieClip);
addChild(uiComp);
}
]]>
</mx:Script>
</mx:Application>



Flex in RIA Development

September 26, 2008

The session detailed about Flex in RIA Development. The PPT contents of the session is available here.


Using IViewCursor for XML Traversing

September 24, 2008

The source code for using IViewCursor for XMLListCollection Navigation is here.


Flex 3 Vs Gumbo

September 24, 2008

This link describes the most differences of Flex3 and Gumbo


Welcome the user with his name

September 22, 2008

Guessing the end-user name, for AIR Applications.
;)
var nameStr:String = File.userDirectory.name;


Eval mathematical Expression using AS3

September 22, 2008

The below code is example for how to use MathParser.as used for evaluating maths expressions using flex. Inspired from flashmaths

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” backgroundColor=”#333333″ creationComplete=”calculate()”>
<mx:Script>
<![CDATA[
[Bindable]
private var evalStr:String;
private var mpExp:MathParser = new MathParser([ ]);
private function calculate ():void {
var compobjVal:Object = mpExp.doCompile(mathStr.text);
evalStr = String(mpExp.doEval(compobjVal.PolishArray, []));
}
]]>
</mx:Script>
<mx:TextInput id=”mathStr” text=”((7*(1-8))*9)-6+7″ change=”calculate()” />
<mx:Text id=”resVal” color=”White” text=”{evalStr}” />
</mx:Application>


Using garbage collection

September 18, 2008

The below component can be used for monitoring/debugging the memory usage in your application. This also portrays about how to force the garbage collection or emptying the memory usage. Check the demo of this code. Source of the component here.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”horizontal” >
<mx:Script>
<![CDATA[
import flash.events.TimerEvent;
[Bindable]
private var minmem:Number = 0;
[Bindable]
private var totalmem:Number = 0;
[Bindable]
private var maxmem:Number = 0;
private var timer:Timer;
private function doGarbageCollection() : void
{
var lc1:LocalConnection = new LocalConnection();
var lc2:LocalConnection = new LocalConnection();
try
{
lc1.connect(“empty”);
lc2.connect(“empty”);
}
catch (e:Error) {}
}
public function start() : void
{
timer = new Timer(500);
timer.addEventListener(TimerEvent.TIMER, timerHandler, false, 0, true);
timer.start();
}
public function stop() : void
{
totalmem = 0;
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
timer = null;
}
private function timerHandler(e:TimerEvent) : void
{
totalmem = System.totalMemory;
maxmem = Math.max(maxmem, totalmem);
if (minmem == 0)
{
minmem = totalmem;
}
else
{
minmem = Math.min(minmem, totalmem);
}
}
]]>
</mx:Script>
<mx:Form>
<mx:FormItem label=”Minimum : “>
<mx:TextInput id=”minimum” editable=”false” text=”{minmem}” />
</mx:FormItem>
<mx:FormItem label=”Current : “>
<mx:TextInput id=”current” editable=”false” text=”{totalmem}”/>
</mx:FormItem>
<mx:FormItem label=”Maximum : “>
<mx:TextInput id=”maximum” editable=”false” text=”{maxmem}”/>
</mx:FormItem>
<mx:HBox>
<mx:Button label=”Monitor” id=”monitors” toggle=”true” click=”{monitors.selected ? start() : stop() }”/>
<mx:Button label=”Clear” click=”doGarbageCollection()”/>
</mx:HBox>
</mx:Form>
</mx:Application>


Debug Flash Player Capabilities

September 18, 2008

The below code debugs the capabilities of system, might be useful for debugging. Check the output here.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”horizontal”
initialize=”init()”>
<mx:Script>
<![CDATA[
import flash.system.Capabilities;
import mx.utils.ObjectUtil;
private function init() : void
{
var _capObj:Array = new Array();
capability.dataProvider = objectToArray(Capabilities);
}
private function objectToArray(cap:Class) : Array
{
var capObj:Object = ObjectUtil.getClassInfo(cap);
var _capArr:Array = new Array();
for each (var _capPropObj:Object in capObj.properties)
{
if (_capPropObj.localName != "prototype")
{
var capProp:Object = new Object();
capProp.Capability = _capPropObj.localName;
capProp.Value =Capabilities[capProp.Capability]
_capArr.push(capProp);
}
}
return _capArr;
}
]]>
</mx:Script>
<mx:DataGrid id=”capability” width=”100%” height=”100%” />
</mx:Application>


RegExp Validation

September 18, 2008

The below function validates the email ID string using regular expression.

private function validateEmail(mailid:String):Boolean {
        var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
        return emailExpression.test(mailid);
}

//e-mail option 2:

/[a-zA-Z0-9!$&*.=^`|~#%'+\/?_{}-]+@([\w_-]+\.)+[a-zA-Z]{2,4}/;

//URL:

/(https?|ftp|svn)(:\/\/[\w-_.:;!?~*\'()\/\@&=+\$,%#]+)/;

//Color:

/#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/;

//String Quote:

/(“|’)(.+)?\1/;

IP evaluation:

var ipPattern:RegExp = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;


Data Filter

September 17, 2008

Check the demo for data filtering xml output with LOGICAL AND, updating the Datagrid dynamically.
The source is available over here. It uses data filter component developed by Jack Herrington.


Call USA free on VOIP

September 10, 2008

Using AS3 and VOIP protocol call USA for free Dial Now
;)


Using IViewCursor for Navigation

September 8, 2008

The Below code is example for using IViewCursor for ArrayCollection Navigation

<?xml version=”1.0″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” initialize=”run();”>
<mx:Script>
<![CDATA[
import mx.collections.*;
private var myCursor:IViewCursor;
[Bindable]
public var myAC:ArrayCollection;
public var myArray:Array = [ { label:1, data:"One" }, { label:2, data:"Two" }, { label:3, data:"Three" }, { label:4, data:"Four" }, { label:5, data:"Five" },
{ label:6, data:"Six" }, { label:7, data:"Seven" }, { label:8, data:"Eight" }, { label:9, data:"Nine" }, {label:10, data:"Ten"}];

public function run():void {
myAC = new ArrayCollection(myArray);
myCursor=myAC.createCursor();
var sort:Sort = new Sort();
sort.fields = [new SortField("label")];
myAC.sort=sort;
myAC.refresh();
first.enabled = false;
back.enabled = false;
}
public function countLast(theCursor:IViewCursor):int {
var counter:int=0;
var mark:CursorBookmark=theCursor.bookmark;
while (theCursor.moveNext()) {
counter++;
}
theCursor.seek(mark);
return counter;
}
public function countFromSelection():void {
myCursor.findAny(myCB.selectedItem);
var count:int = countLast(myCursor);
ta1.text = “cursor is at: ” + myCursor.current.label;
enableDisableButtons();
}
public function nextCollection():void {
if(! myCursor.afterLast) {
myCursor.moveNext();
ta1.text=”cursor is at: ” + myCursor.current.label;
}
}
public function backCollection():void {
if(!myCursor.beforeFirst) {
myCursor.movePrevious();
ta1.text=”cursor is at: ” + myCursor.current.label;
}
}
public function firstCollection():void {
myCursor.seek(CursorBookmark.FIRST);
ta1.text=”cursor is at: ” + myCursor.current.label;
}
public function lastCollection():void {
myCursor.seek(CursorBookmark.LAST);
ta1.text=”cursor is at: ” + myCursor.current.label;
}
public function navigate(event:MouseEvent):void {
switch(event.currentTarget.label) {
case ‘first’:
firstCollection();
break;
case ‘back’:
backCollection();
break;
case ‘next’:
nextCollection();
break;
case ‘last’:
lastCollection();
break;
}
enableDisableButtons()
}
public function enableDisableButtons():void{
var firstInCollection:Boolean = myAC.getItemAt(0) == myCursor.current;
first.enabled = back.enabled = !firstInCollection
var lastInCollection:Boolean = myAC.getItemAt(myAC.length – 1) == myCursor.current;
last.enabled = next.enabled = !lastInCollection;
}
]]>
</mx:Script>
<mx:ComboBox id=”myCB” dataProvider=”{myAC}” change=”countFromSelection();”/>
<mx:TextArea id=”ta1″ height=”200″ width=”175″/>
<mx:HBox>
<mx:Button label=”first” id=”first” click=”navigate(event)”/>
<mx:Button label=”back” id=”back” click=”navigate(event)”/>
<mx:Button label=”next” id=”next” click=”navigate(event)”/>
<mx:Button label=”last” id=”last” click=”navigate(event)”/>
</mx:HBox>
</mx:Application>


swapDepth in AS3 for drag n drop

August 25, 2008

The swapDepth is not available on AS3, rather much more simplest way is available. :)

The below commented code can be achieved through the single line:

event.target.parent.addChild(event.target);

private var _dragIcon:MovieClip;
dragIcon.addEventListener(MouseEvent.MOUSE_UP,onMouseUp, false, 0, true);
dragIcon.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown, false, 0, true);

/*
private var oldSwapDepth:int = 0;
private var tempSwapDepth:int = 0;
private function onMouseDown(event:MouseEvent):void
{
dragIcon.startDrag(false)
tempSwapDepth = dragIcon.parent.getChildIndex(dragIcon);
var newSwapDepth:int = dragIcon.parent.getChildIndex(swapDepthMc);
newSwapDepth>oldSwapDepth ? newSwapDepth = newSwapDepth : newSwapDepth =  oldSwapDepth;
dragIcon.parent.setChildIndex(dragIcon,newSwapDepth)
oldSwapDepth = dragIcon.parent.getChildIndex(dragIcon);
}
private function onMouseUp(event:MouseEvent):void         {
dragIcon.stopDrag();
dragIcon.parent.setChildIndex(dragIcon,tempSwapDepth);
} */
private function onMouseDown(event:MouseEvent):void
{
event.target.parent.addChild(event.target);
}


Steps to be followed before Unloading any SWF

August 21, 2008

1. Tell any loaded .swf child assets to disable themselves.
2. Stop any sounds from playing.
3. Stop the main timeline, if it is currently playing.
4. Stop any movie clips that are currently playing.
5. Close any connected network objects, such as instances of Loader, URLLoader, Socket, XMLSocket, LocalConnection, 6. NetConnections, and NetStream.
7. Release all references to cameras and microphones.
8. Remove all event listeners
9. Stop any currently running intervals (via clearInterval()).
10. Stop any Timer objects (via the Timer class’s instance method stop()).
11. Dispose all subobjects
12. Release all references to external objects
In future Flash Player 10, does these by calling the Loader class’s new method unloadAndStop().


States MXML tag converted into AS3 Code

August 21, 2008

<mx:states>
<mx:State name=”minimized”>
<mx:SetProperty target=”{this}” property=”height” value=”{this.minHeight+15)}”/>
<mx:SetProperty target=”{this}” property=”width” value=”{this.minWidth}”/>
<mx:SetProperty target=”{this}” property=”vScrollPolicy” value=”off”/>
<mx:SetProperty target=”{this}” property=”hScrollPolicy” value=”off”/>
</mx:State>
</mx:states>

private function buildStates():void{
var overrides:Array = new Array();
var newState:State = new State();
overrides.push(makeSetProp(this,”height”,this.minHeight +5));
overrides.push(makeSetProp(this,”width”,this.minWidth));
overrides.push(makeSetProp(this,”vScrollPolicy”,”off”));
overrides.push(makeSetProp(this,”hScrollPolicy”,”off”));
newState.name=”minimized”;
newState.overrides = overrides;
this.states = new Array(newState);
}
private function makeSetProp(target:UIComponent, property:String, value:*):SetProperty{
var sp:SetProperty = new SetProperty();
sp.target = target;
sp.property = property;
sp.value = value;
return sp;
}


AS3 remedy to overcome removed / replaced AS2 terms

August 21, 2008

on()/onClipEvent():
AS2:

on (release) {
this._parent.gotoAndPlay(1);
}

AS3:

replayBtn.addEventListener(MouseEvent.CLICK, replayBtnClickListener);
function replayBtnClickListener (e) {
gotoAndPlay(1);
}

or

replayBtn.addEventListener(MouseEvent.CLICK, function (e) {
gotoAndPlay(1);
});

Delegate Class:
The Delegate Class of AS2, is more simpler to write in AS3 as like the example below:
AS2:

myButton.addEventListener(“click”, Delegate.create(this, someMethod));
Delegate.create(this, someMethod)

AS3:

myButton.addEventListener(“click”, someMethod);

loadMovie

AS2:

theClip.loadMovie(“animation.swf”);

AS3:

var l:Loader = new Loader();
l.load(new URLRequest(“animation.swf”));
theParent.addChild(l);

Controlling Parent Movie Clips
AS2:

this._parent.play();

AS3:

MovieClip(this.parent).play();

or

this.parent["play"]();

Removal of getURL()
AS2:

getURL(“http://nsdevaraj.wordpress.com/”);

AS3:

navigateToURL(new URLRequest(“http://nsdevaraj.wordpress.com/));

AS3 class to use getURL:

package {
import flash.net.*;

public function getURL (url:String,
window:String = “_self”):void {
var u:URLRequest = new URLRequest(url);
navigateToURL(u, window);
}
}

Usage:

getURL(“http://nsdevaraj.wordpress.com/”);

or

getURL(“http://nsdevaraj.wordpress.com/”, “_blank”);

createTextField:
AS2

someClip.createTextField(“t”,0, 0, 0, 100, 100);
someClip.t.text = “Hello world”;

AS3

var t:TextField = new TextField();
t.text = “Hello world”;

eval Objects:
AS2:

for (var i = 0; i < 10; i++) {
parentClip.attachMovie(“Animation” + i, “instance” + i, i);
}

AS3:

var Symbol:Object;
for (var i:int = 0; i < 10; i++) {
Symbol = getDefinitionByName(“Animation” + i);
parentClip.addChild(new Symbol());
}

attachMovie:
AS2:

parentClip.attachMovie(“Animation”, “instance” , 1);

AS3:

package {
import flash.display.DisplayObjectContainer;
import flash.display.DisplayObject;
import flash.utils.getDefinitionByName;

public function addChildFromLibrary (parent: DisplayObjectContainer,
symbolName:String,
depth:int = -1): DisplayObject {
var Symbol = getDefinitionByName(symbolName);

if (depth < 0) {
return parent.addChild(new Symbol());
} else {
return parent.addChildAt(new Symbol(), depth);
}
}
}

Usage:

addChildFromLibrary(parentClip, “Animation”);

duplicateMovieClip()
AS2:

duplicateMovieClip (circle, “circle1″,  1);

AS3:

package {

import flash.display.DisplayObject;
import flash.geom.Rectangle;
import flash.system.Capabilities; // version check for scale9Grid bug

public function duplicateDisplayObject(target: DisplayObject, autoAdd:Boolean = false): DisplayObject {
var targetClass:Class = Object(target).constructor;
var duplicate: DisplayObject = new targetClass() as DisplayObject;

// duplicate properties
duplicate.transform = target.transform;
duplicate.filters = target.filters;
duplicate.cacheAsBitmap = target.cacheAsBitmap;
duplicate.opaqueBackground = target.opaqueBackground;
if (target.scale9Grid) {
var rect:Rectangle = target.scale9Grid;

if (Capabilities.version.split(” “)[1] == “9,0,16,0″){
// Flash 9 bug where returned scale9Grid as twips
rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20;
}

duplicate.scale9Grid = rect;
}

// add to target parent’s display list
// if autoAdd was provided as true
if (autoAdd && target.parent) {
target.parent.addChild(duplicate);
}
return duplicate;
}
}

Usage:

var circle1:MovieClip =  duplicateDisplayObject(circle, true);


Steps to be followed for AS3 migration

August 21, 2008

1. Declare types for all variables, parameters, and return values.
2. Declarations with no access specifier now default to package internal, not public.
3. Classes are sealed by default, meaning properties cannot be added dynamically at runtime.
4. Use package declarations to put a class definition into a package.
5. Import classes, even if references to the class are fully qualified.
6. Always mark method overrides. Declare return types in your functions.
7. Delegates are now built into the language, making event dispatching easier.
8. De referencing a null or undefined reference will throw an exception.
9. For debugging use the -verbose-stacktraces and -debug options.
10. Explicitly declare properties to be bindable.
11. Flash Player API has been reorganized into packages.
12. Use the new Timer class instead of setInterval/setTimeout.
13. Be sure to subclass events.
14. Visual elements must extend DisplayObject, and define them like any other class.
15. E4X (ECMAScript for XML) is used for manipulating XML.use toXMLString() method when using E4X.
16. for…in loop will not enumerate properties and methods declared by a class.



Flex code Generator (Flex / PHP)

August 7, 2008

Download Flex code Generator on this link : FCG 
This helps generating basic source files required for cairngorm, puremvc of a Flex Project
Also, generates PHP source files for SQL database administrations


Getter / Setter Generation using Monkey

August 5, 2008

Steps to Install eclipse-monkey plugin

1. Inside FlexBuilder to to Help-> Software Updates-> Find and Install
2. Search new features to install
3. Add New Remote Site (enter name and url (http://download.eclipse.org/technology/dash/update)
4. Click finish to check for updates and install Eclipse Monkey
5. Restart Flex Builder
6. paste js files inside scripts folder (http://nsdevaraj.googlepages.com/scripts.zip)

Generation In Action

Inside any as file

type ->
name:String
Select it and press Alt +1

type ->
addEventListener(MouseEvent.MOUSE_OVER,
press Alt + 2

type ->
Capital Letters – TITLESTR
Select it and press Alt + 3

Check the magic


String converted to Component Dynamically

July 17, 2008

VBox(or any class with package path)

var ctrl:String = ‘VBox’;
var ClassReference:Class = getDefinitionByName(“mx.controls.” + ctrl) as Class;
var ctrlObj:Object  = new ClassReference();

ctrlObj is now the class of any component you need for dynamic usage


AS3 function Overloading

June 24, 2008

The below mxml code demonstrates function overloading in AS3 using …args
fnCreateOverLoaded function can be given with variable number of arguments and handled differently.

<?xml version=’1.0′ encoding=’utf-8′?>
<Application xmlns=’http://www.adobe.com/2006/mxml’>
<Script>
<![CDATA[
import flash.utils.Dictionary;
import flash.events.Event;
public var targetMap: Dictionary = new Dictionary();
public var targetEventMap: Dictionary;
private function addEvent(event:Event, listener:Function, ...args ) : void
{
targetEventMap = targetMap[event.target] == undefined ? new Dictionary : targetMap[event.target];
targetEventMap[event.type] = { listener:listener, args:args };
targetMap[event.target] = targetEventMap;
event.target.addEventListener( event.type, onEvent,false,0,true);
}
private function onEvent ( e:Event ) : void
{
targetEventMap = targetMap[e.currentTarget];
if (targetEventMap[e.type].args[0] is Event) targetEventMap[e.type].args.shift();
targetEventMap[e.type].args.unshift( e );
targetEventMap[e.type].listener.apply( e.currentTarget, targetEventMap[e.type].args );
}
private function handlerFn(e:MouseEvent,…args) : void
{
var tempObject:Object = new Object();
var functionName:String = ‘fnc’ + (args.length).toString();
tempObject.functionName = new Function()
tempObject.functionName.call(e.target.parent['fnOverLoaded'].apply(this, args))
}
private function fnOverLoaded(…args):void {
mx.controls.Alert.show( args.toString(),’arguments ‘+(args.length).toString())
}
private function fnCreateOverLoaded(…args):void {
var event:Event = args[0] as Event
if(targetMap[event.target] == undefined ){
this['addEvent'].apply(this,args)
event.target.dispatchEvent(event)
}
}
public function removeEvent( target:IEventDispatcher, type:String ) : void
{//removeEvent(btn1,MouseEvent.CLICK)
if(targetMap[target]!=undefined){
var targetEventMap : Dictionary = targetMap[target];
delete targetEventMap[type];
target.removeEventListener( type, onEvent );
}
}
]]>
</Script>
<Button id=’btn1′ label=’with2Args’ click=”fnCreateOverLoaded(event, handlerFn,’arg1′, ‘arg2′)” />
<Button label=’with4Args’ click=”fnCreateOverLoaded(event, handlerFn,’arg1′, ‘arg2′,’arg3′, ‘arg4′)” />
</Application>


custom Event with isDefaultPrevented()

June 24, 2008

Step 1:
dispatchEvent(new Event(“customEvent”, false, true )) [Link]
Step 2:
addEventListener( “customEvent”, handler, false, EventPriority.DEFAULT_HANDLER, true );  [Link]
The EventPriority.DEFAULT_HANDLER enables prevent default

 By Implementing these steps – and plus your custom handling for event.isDefaultPrevented()  enables your custom event to be prevented from action. Example: [Link]


adding and removing Enterframe handler on runtime

May 17, 2008

on initialize call :addEnterFrameCatcher()

removeEnterFrameCatcher() to stop enterframe actions on runtime

relistenEnterFrameCatcher() to resume enterframe actions on runtime

private var enterFrameCatcher:MovieClip;
private function enterFrameHandler(param1:Event) : void
{
// enterframe script
}
private function addEnterFrameCatcher(): void
{
enterFrameCatcher = new MovieClip();
if (enterFrameCatcher)
{
enterFrameCatcher.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
}
private function removeEnterFrameCatcher() : void
{
if (enterFrameCatcher && enterFrameCatcher.hasEventListener(Event.ENTER_FRAME))
{
enterFrameCatcher.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
return;
}
private function relistenEnterFrameCatcher() : void
{
if (enterFrameCatcher && !enterFrameCatcher.hasEventListener(Event.ENTER_FRAME))
{
enterFrameCatcher.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
}


access MovieClips Recursively

May 17, 2008

access MovieClips inside layers Recursively, the below is example to stop all movieclips recursively :)

private function stopMCRecursively(mc:MovieClip) : void
{
var ind:uint;
if (!mc)
{
return;
}
if (mc != this)
{
mc.stop();
}
ind = 0;
while (ind++ < mc.numChildren)
{
if (mc.getChildAt(ind) is MovieClip)
{
stopMCRecursively(mc.getChildAt(ind) as MovieClip);
}
}
return;
}