11 December 2007

Array.shuffle() in AS3

Here's an AS3 class called ExtendedArray that unsurprisingly extends the functionality of the Array class. One important thing to note is that it is a dynamic class. This allows you to add properties and methods to the base class at runtime.

Another thing to note is looping through the optionalArgs (or "rest" arguments as they're known) and using super.push() to populate the Array in the constructor. Simply using super(optionalArgs) would create an array within the Array i.e. a 2d array.

The shuffle function is just a slightly different version of the AS2 shuffle functions you can find on the web. Using the asterisk (*) as a datatype means that any type can be handled by the shuffle function.


package com.utils
{
dynamic public class ExtendedArray extends Array
{
public function ExtendedArray(... optionalArgs){
for each (var value:* in optionalArgs){
super.push(value);
}
}

public function shuffle(startIndex:int = 0, endIndex:int = 0):Array{
if(endIndex == 0) endIndex = this.length-1;
for (var i:int = endIndex; i>startIndex; i--) {
var randomNumber:int = Math.floor(Math.random()*endIndex)+startIndex;
var tmp:* = this[i];
this[i] = this[randomNumber];
this[randomNumber] = tmp;
}
return this;
}
}
}

You could add many more functions to this to increase the functionality of the base Array class.

07 November 2007

Google AdWords and Math.random

A colleague just came across a problem with a Flash banner when uploading it to Google AdWords.

The banner contained an effect where many movie clips were randomly generated and positioned. Yet when uploaded to Google AdWords, an error occurred stating that random numbers could not be used.

The problem is with Math.random, Google AdWords doesn't allow it. We called the AdWords help desk and they confirmed that Math.random cannot be used, but were unable to give a reason why.

Is this a security hole in Flash? LiveDocs say Math.random is "calculated in an undisclosed manner", so does it use the client hardware to generate that number? I'm now intrigued, if anyone can shed some light on this please comment.

07 August 2007

Two Flavours of AS3?

Actionscript 3 was first introduced with Flex 2 in the summer of 2006. At this time Macromedia (the inventors of Flex and Flash) were being acquired by Adobe. Previous to the acquisition all Macromedia class packages were prefixed with "mx" e.g. "mx.controls.Button".

Flex 2 kept the Macromedia "mx" naming convention and it seems Flex 3 (due for release later in 2007) will do the same. However Flash CS3, has been "Adobefied" and class packages relating to Flash CS3 are prefixed with "fl" e.g. "fl.controls.Button" - makes sense though.

These class libraries share a lot in common, though it appears that the Flex libraries are more extensive than Flash CS3. It'll be interesting to find the boundaries between Flash and Flex Actionsctipt as we use it more.

Flex is component based and is used to build rich user interfaces quickly and easily - it's kind of a "Flash for Web Developers". Flash is more graphical and suited to visual presentations and games. Under the hood, they are essentially the same, Flex and Flash are programmed in AS3 and except for the MXML interpreter in Flex, the AS3 compiler (I currently believe - I may be wrong) is the same.

This raises some important questions:
  • Can the Flex 2 compiler be used to compile AS3 for Flash?
  • Will we have 2 flavours of AS3?
  • Why buy 2 products that build swf's?

Ultimately I think the answer is that Adobe can have two $500 applications for sale rather than one. It is quite confusing (well it confuses me)! Should we now be called "Actionscript Developers" not "Flash" or "Flex" developers?

This may be a good thing. For example, Java developers have many different routes to choose from and a Java developer who knows his/her beans (so to speak) get high-end salaries / contracting rates. It could also root Actionscript 3 as a "proper" programming language for RIA's (Rich Internet Applications).

Another possibility is that Adobe merge the Flash timeline, library and drawing tools into the Flex Builder. Although that's probably never going to happen!

Compare the AS3 References

30 July 2007

Edit and Compile AS3/Flex for FREE!

Having exhausted my supply of free trials of Flash CS3 and Flex Builder, I managed to work out how to attach the latest Flex 3 compiler to FlashDevelop. Editing AS3 in Flash Develop is as good as the Flex Builder's text editor in Eclipse. It does all the imports and the predictive typing drills into classes perfectly (including your own). MXML is not that good but can still be compiled by the Flex 3 compiler. In Flash develop you can choose between an AS3 project and an Flex (MXML) project, either of them can be compiled.

Setting it up

These instructions are for the Flex 3 beta version (Moxie), the links to the Flex download will probably change once Flex 3 is fully released.

For this you will need to download:

  1. Install the latest version of FlashDevelop
  2. Unzip the SDK to C:\Program Files\FlashDevelop\Flex3SDK
  3. Launch FlashDevelop
  4. Go to Tools -> Program Settings -> Plugins -> AS3Context -> Settings.
  5. Set "Flex2SDK Location" to "C:\Program Files\FlashDevelop\Flex3SDK"


To test do the following:
  1. Go to Project -> New Project
  2. Select "ActionScript 3 - Default Project"
  3. Set the Name as "Test" and select your Location and click OK
  4. Project -> Test Movie
  5. You should see a new blank screen named Test.swf


As it' a .NET application it works only on a Windows PC. However, there are reports on the FlashDevelop messageboard that it also works fine on Intel based Macs.

16 July 2007

A Decent, FREE, AS3 Editor!

I used to use SEPY a lot, but it just didn't cut the mustard for AS3. Having used the Flex 2 Builder I wanted something that'd do all the imports and have good predictive typing to help me through my first AS3 projects until I get used to the class structures.

After a lot of searching around, I found this:
http://www.flashdevelop.org/

09 July 2007

MySpace technical woes.

I, as many, have a page on MySpace (www.myspace.com/lapsusmentismusic). There's always been little niggles with MySpace, occasional "an error has occurred" messages, which I put down to shoddy Fusebox programming.

These days it seems the errors are occuring so frequently that the MySpace application is frustrating and almost impossible to use, without getting one of these errors. A large part of their problem lies in the success of MySpace and the huge amounts of traffic it generates. The architecture to support massive traffic volumes just wasn't there.

I found this interesting article that explains their technical woes and is a lesson to us all: http://www.doughughes.net/index.cfm?event=viewEntry&entryId=116

13 June 2007

Adobe UK Licencing Problems

A friend of mine is have a real nightmare upgrading to CS3. He purchaced a 24 month MVLP licence in January 2006 which entitles him to free upgrades within that period. Adobe seem to have forgotten this and after 7 weeks of frustration with Adobe, Paul still has no CS3!

Paul is self-employed and this delay has the potential to affect his business.

Click here to read his blog

I've had a similiar experience trying to change my Flex Builder 2 licence from PC to Mac, as my poor 3 year old PC couldn't cope with it! After multiple phone calls and hours on the phone and not getting through, I sent an email to customer support who said "as this is a licencing issue, please call our customer support line". Thanks for that useful message Adobe! Just what I wanted.

I tried to call a few more times, but decided it'd be easier using the Windows version of Flex Builder via Parallels on my Mac!

Here's another interesting article about Adobe pricing:http://web.mac.com/libine/iWeb/Site/Article.html

11 June 2007

Ways of connecting to Flex with Coldfusion

This is a brief outline of the ways it can be done. There are many more in-depth examples on the web:

Set up you data sources in Coldfusion
Do as normal, but if you're using a MySQL version over 4, you must download the JDBC drivers. Follow this Adobe technote here

Design your CFC's
There are many ways in which you can connect to Flex. Flex Remoting or using Coldfusion / Flex connectivity (for this make sure you have all the latest CF updates for Flex 2 here).

Your CFC's must be designed to do the tasks required in an efficient way so that Flex uses the minimum of service calls.

Setting up Coldfusion for Flex Remoting
There are a few ways to set up remoting in Coldfusion, the simplest way is to set all CFC functions that need connecting to Flex i.e. to act as web services, to access="remote".

A more complex, but efficient way is to create a lightweight gateway CFC as an interface to the underlying CFC architecture. For example, consider CFC's called "MyService.cfc" and "MyGateway.cfc".

MyService.cfc contains all the logic you need doing: database queries etc. function access="public". Load this CFC into the application scope onApplicationStart, this way it is only intantiated one throught the whole application.

MyGateway.cfc is the remoting interface and contains no logic, it mearly calls the functions in MyService.cfc (now application.MyService). These function should be set to access="remote".

When you call CFC's from Flex (or Flash), a new instance of the CFC is created in memory on the Coldfusion server. If you call the full, bloated MyService.cfc each time you make a request you'll be using more memory than necessary, therefore the lightweight MyGateway.cfc is the one that is instantiated multiple times by Flex.

In Flex you need to use the HTTPService class/tag. Enter the URL for the CFC you want to call. Coldfusion will return a WDDX formatted XML response, which Flex components can parse and use natively.

This architecture is used and explained more on:
ASFusion.com

Using Coldfusion / Flex connectivity
Provided you've done all the updates. Create your myService.cfc as above containing all the logic. However, this time you won't need your MyGateway.cfc as you'll create equivalent classes in Flex which match MyService.cfc i.e. create MyService.as with all the same functions and arguments.

You can then instantiate MyService.as in Flex and use it just like any other object. This allows you to access all the backend power of Coldfusion via normal Actionscript function calls - pretty powerful!

My tuppence worth
Great and powerful CF/Flex connectivity may be, I'd personally use remoting for my Flex applications as this will make your Flex application platform independent.

05 June 2007

Resolution to the Flash 3 mintue load! (And Acrobat Reader 8 and Firefox problems)

After a lot of trawling around and a lot of dead ends, the problem was actually font based.

I noticed that csrss.exe was at 100% when I tried to load Flash CS3, Acrobat Reader 8 and get into Google News. The only Microsoft resolution (http://support.microsoft.com/kb/555021) suggests recreating your user profile - don't!

I couldn't find any other posts that had a solution to my problem, but I considered it could be font based as Flash CS3 freezes when "Initializing fonts".

In my system.ini file I noticed a list of .FON commands:

[386enh]
woafont=dosapp.FON
EGA80WOA.FON=EGA80WOA.FON
EGA40WOA.FON=EGA40WOA.FON
CGA80WOA.FON=CGA80WOA.FON
CGA40WOA.FON=CGA40WOA.FON


I removed these and now everything works fine!

I discovered that this is what Windows uses to emulate fonts in EGA and CGA monitors (it's 2007 for godssake!). So far, I've had no ill effects from removing them from my system.ini file.

24 May 2007

Convert Lines to Fills - smoothing shapes in Flash

This is a quirk of Flash, which has caught me out a few times. If you're drawing a rounded rectangle with an internal fill colour and a stroke (outline) of 3 pixels, for example, then you get a rather jagged apperance between the fill colour and the stroke.

If you zoom into the shape, all looks fine and smooth, but zooming back to 100% the problem appears again.

To solve this, you must select the stroke (outline) of the shape - double click it to make sure all of it is selected. Then choose Modify > Shape > Convert Lines to Fills.

This solves the problem and your shape now looks smooth.

17 May 2007

Extensible ServiceLoader

As part of the solution to the problem below, I've created a new ServiceLoader class that can be used for any remoting applications. Here's the class:


import mx.remoting.*;
import mx.rpc.*;

class com.utils.ServiceLoader {

private var __servicePath:String;

function ServiceLoader(servicePath:String){
__servicePath = servicePath;
}

private function __openService(remoteName:String):Service {
trace(remoteName);
return new Service(__servicePath, null, remoteName);
}


public function callService(serviceName:String, methodName:String, scope:Object, success:String, error:String, args:Array):Void{
var pc:PendingCall = __openService(serviceName)[methodName].apply(this,args);
pc.responder = new RelayResponder(scope, success, error);
}
}

Here's an example call of this class:

var service:Object = new ServiceLoader("http://localhost:8300/flashservices/gateway/");

service.callService("serviceName", "serviceMethodName", this, "successHandler", "errorHandler" [,optional argument Array]);


So the ServiceLoader class calls whatever service you need and returns the result to handlers in a specified scope ("this" i.e. the calling class, in above the example).

Accessing class function using a string

Here's a piece of dodgy looking code - but it works!?

I've got a class called "ServiceLoader" which contains many service calls, I also have buttons which correspond to these service calls. I've named the buttons as the ServiceLoader function names e.g. "getRecord" button corresponds to the "getRecord" function in my ServiceLoader class.

So I can grab the button name, which is a String and then call a function within the ServiceLoader class using associative array syntax:

var func:String = activeButton._name;
ServiceLoaderInstance[func](arg1,arg2);

I'm not sure how "correct" this is, but it works. Any thoughts?

09 May 2007

Adobe Flash CS3 - 3 minute load!?

I've just downloaded Flash CS3. It promises much, but at 1.2GB, the install seems a little on the large side. Along with Flash comes Adobe Bridge, Device Central (whatever that is), ExtendScript Toolkit (eh?), and the video encoder. I'm sure all of these apps will be quite useful, once I've got to know what they do.

To my annoyance, Flash CS3 seems to have been Adobefied in the same way as Acrobat Reader 8. Every time I try and open a pdf, no matter how big or small, Acrobat Reader grinds to a halt for about 5 minutes or crashes completely.

I have a 3GHz dual core machine with 2GB of RAM and it takes 3 minutes for Flash CS3 to start!

I'll put this down as a trial version quirk and hope the final version isn't as slow. But I'm not holding my breath, after 3 minutes I'd be clinically brain dead!

07 May 2007

Flex Coldfusion Integration - don't follow Adobe!

So... I've had a bit of free time at work to brush up on Flex, specifically Flex and Coldfusion integration.

I've been doing Flash remoting with Coldfusion Flash forms, which were really Flex 1.5. for the last 18 months. I followed the CFC structures as described on www.asfusion.com and ray.camdenfamily.com: store your CFC's in the Application scope and access them with a lightweight proxy CFC that handles the remoting. This structure improves performance, as the proxy CFC is instantiated on each request and it acts as an interface to the bulky CFC's that do all the complicated stuff. From Flex's point of view, this proxy CFC acts just like any other web service on any platform.

So I've been confused by Adobe's instructions for Flex / Coldfusion integration. They suggest you create Actionscript equivalents of your CFC's and essentially map the properties and methods of the CFC into Actionscript. This has the benefit of accessing CFC's as if they were native classes and there'd be no problem with handling data types - essentially extending Flex with Coldfusion.

However, my new job is in Calgary, Canada, where PHP reigns and Coldfusion is a rarity, hardly anyone uses it. So why would I create a Flex app which is so intertwined with Coldfusion? Even if I was in a Coldfusion centric environment, I still wouldn't build this way as I may need to port the Flex application to another Platform. I could quickly convert the CFC's to PHP classes and have no need to change the Flex application at all.

The reason I rant, is that I've been following Flex tutorials which have been confusing and going against what I thought was "right". I think I'll just stick with tips from AS Fusion and Ray Camden from now on!

09 April 2007

Declaring global array variables in classes

When declaring a global array public/private variable in a class, make sure you only call new Array() in the constructor like so:

class myClass{

private var __myArray:Array;

function myClass(){
__myArray = new Array();
}

}

NOT like this:

class myClass{

private var __myArray:Array = new Array();

function myClass(){}

}

If you declare array vars as above,__myArray in subsequent instantiations of myClass will contain the data from the first instantiation of myClass. Seem like a bug to me, but at least I now know not to declare variables like this again!

08 March 2007

Flash wmode / Firefox: key.isDown() always returns false

If you set wmode when you embed your Flash movie, key presses will not work in Firefox. This is because, in Firefox, Key.isDown() always returns false.

If using wmode, use Key.getCode() instead of Key.isDown()

This post helped me solve the problem:
http://www.johanvanmol.org/content/view/47/41/

13 February 2007

Dreamweaver 8 / IE 7 FTP bug

My computer at work melted recently (literally) and after IT rebuilt it I found all my FTP details for sites in Dreamweaver 8 would go missing every time I reopened it.

This is a bug with the IE 7 "release candidate", which does weird things to registry entries. Here's the Adobe technote:

http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=3491671c