Archive for the ‘Actionscript’ Category

Introducing Quizmash

Back in the mists of time I was studying for my Adobe Flash certification, and struggled to find many example questions on the web.

There were a couple of sites that had a few, but they were always limited to the questions the person who made them had written. I thought it would be cool if someone built a site allow anyone to post questions on a subject, so that the pool of available questions would grow over time.

Flash forward a couple of years and behold, Quizmash! It lets users not only post questions, but subjects too, so if you have some knowledge on any subject, technical or trivial, post it here, and hopefully someone will find it useful in their hunt for example questions.

It’s only got a couple of example questions in there to start with, and there’s plenty of features to add, and no doubt bugs to squash, so right now I’m looking for any of you flash geniuses out there to come up with some questions about Actionscript 3, or indeed any other technical subject you can think of to get the ball rolling.

Ok, get mashing!

4 Comments


More PureMVC bits and bobs

Thanks to everyone who came to the Sydney APUG, and listened to me blather on about PureMVC again. I’ve uploaded a zip of my flashdevelop template files here.

Special thanks to Chris and the Rocketboots crew… except Robin. ;P

2 Comments


WebDU 2009 slides and sourcecode

I’ve uploaded the slides and source for my WebDU presso on PureMVC here. Thanks to all who came and listened.

6 Comments


Building a RESTful webservice client in flash, and fighting all the way.

I’ve recently finished struggling with writing a client for a RESTful webservice in flash, and let me tell you it’s been a long painful process, one which i thought i’d like to share. First a (hopefully not too inaccurate) primer on what REST is all about.

RESTful web services use the full http specification in order to send an recieve data. That is, instead of just using POST and GET like most web applications, they also make use of PUT and DELETE, amongst others. Unlike SOAP webservices in which the body of the http message contains contextual information about a request or response, they use HTTP response codes and headers to convey this information in a much more simple lightweight way. I thoughroughly reccommend RESTful webservices by O’Reilly if you want to learn all about them.

They’re becoming increasingly popular, and so I decided I was going to build one for a current job. After scraping the rust off my php skills I managed to get a fully restful webservice together, and feeling pretty pleased with myself I turned to the easy part. Building a client for said webservice in flash.

Well that turned out not to be the easy part.

Problem 1 – No PUT or DELETE

First up I dicovered that the URLLoader class does not support any http methods other than GET and POST. I suspect that this has something to do with the way flash routes requests through the browser, however REST webbservices can accommodate this limitation (as it’s apparently quite common) by using something called overloaded POST, where the request is always sent as a POST with the real request method embedded as a url variable or in the message header. And here we hit problem two.

Problem 2 – No empty POSTs

When sending a POST request from flash, if there is no body in the request, then it is always sent as a GET. Ouch! Although it is sloppy, I figured I could get around this by putting junk vars in the body to stop this. Now because this webservice is out on the public web, it uses HTTP basic authentication as a security layer. To do this an encoded username/password string is sent in the headers of the request. If the correct key is not sent, the browser issues a 401 Unauthorised http code, to challenge the client and inform it what kind of authentication method is being used. You’ll see this in use when your browser pops up a login dialog for some web pages. Flash 9 and above does not allow some blacklisted headers to be sent to the server. Including, you guessed it…

Problem 3 – No authentication headers allowed

Thats right folks. Flash player 9 does no allow the Authentication:Basic header to be sent. 9.0.115 Allows it but only if the flash cross domain policy file on the server explicitly says so. Even if the swf is on the same server. Now in this case I could modify the cross domain file as it was my own webservice, but what about the thousands of webservices that I don’t control? Anyway I couldnt be sure on which domain the client would sit, so I decided to hack my webservice to look for an alternative custom header if Authentication:Basic wasn’t present. This was a horrible way to work around this, and I had no idea what I would do if I needed to talk to a third party webservice that used basic authentication. The next step was to recieve the response from the server to see if the login was correct, and…..

Problem 4 – No support for http status codes

The http spec defines a whole raft of http status codes for use in communicating the status of a request. 200-ok means success, and i’m sure you’re familiar with 404-not found. The problem is even though the URLLoader class has a status event, with a status code property, it doesnt actually work. First up is the fact that in some browsers all codes other than success are returned to the flash player as a 0, which isn’t actually a status code. Then there’s the fact that if anything other than 200 is recieved, flash fires the status event and stop the data from being recieved. This is even if the status code is not an error, but something such as a 201-created which is a subtype of the 200 success code.

So where next?

Well after banging my head against flashes broken HTTP support, i came across a potential solution in as3httpclientlib. An open source library that uses the AS3 socket classes to emulate the entire http specification. This is an awesome library and an absolute joy to use, in no time I had built my client and all was well with the world. Until I uploaded it.

Problem 5 -Socket policy files

This is a dark realm to be dealing with indeed. The current flash player does not allow socket connections to any server, unless a socket policy file is available, even if the client is in the same domain. Ok I thought i’ll just drop one next to my cross domain file. unfortunately its not that simple. The policy file needs to be served by a socket policy server running on port 843 of the same domain, or via the same socket the request was made to in response to a specific socket call. So basically I was screwed. I didnt have enough access to the server to set this up, and even if I could you need to be a sysadmin wiz to do so. I really dont think Adobe could have made this any more dfficult, and though there are articles on how to do thisĀ  on their site, they seem not be written for the people most likely to need them, flash developers. This means that the beautiful as3httpclient is esentially only useful for AIR development.

Picking myself up.

In the midst of all this a freind of mine had suggested just giving up and writing an rpc style proxy on the client side to talk to. I told him I refused to be beaten (though I later was, curse my foolish pride) but this planted the seed for my solution. What i have basically written is an extension to as3httpclientlib, that altough behaves the same from the users view, actually interprets full HTTP requests into text based POST meta data, that is sent to a php proxy file. This proxy then make the real request to the server, encodes the response in a similar meta format, then returns this to the flash player via URLloader behind the scenes. This is then deserialised into what appears to be a seamless as3httpclientlib response, et voila.

This is all in early alpha of course, but it seems to be working for me so far. The beauty of it being that this should enable flash to talk to ANY restful webservice, without all the pain you can see i’ve been through. Please have a play with it and let me know what you think. And so i humbly present to you, the snappily titled as3httpproxyclientlib. Its up on google code, under the same MIT licence as its parent library. It requires you have the parent library in your classpath, but otherwise, short of uploading the proxy file to a server of your choosing, and passing this url to the client instance, should behave in the same way. It does require you have CURLlib installed on your php server, but i believe thats pretty common, and I’m open to people contributing proxies in other languages and for other server configurations. In fact any contributions at all are welcomed as i’m no php developer and it’s probably leaves huge room for improvement.

Let me know how you get on, and don’t let flash get you down.

2 Comments


Design pattern wanted.

Calling all design pattern gurus. I’ve got a challenge for all you object orientated persons. I’m currently working on an actionscript component framework, that includes modal behaviour. That is if a component is modal, when it is enabled, all other components are disabled. Think of an alert box that doesn’t allow you to progress through an application until you’ve chosen an option and you’ll see what i’m trying to achieve.

I’ve actually got this all working fine. My only reservation is that the solution i’ve come up with seems a bit clunky. Anyway on with the show. I’ll detail all the steps in the creation, with pseudo-code examples.

The basis for all this is the component class, which all my other components will inherit from. It has enable, and disable public functions.

class com.lookmum.view.Component{
//enable function
public function enable(){
//enable component code here
}

//disable function
public function disable(){
//disable component code here
}
}

Next comes the creation of the modal manager class. This is a singleton which all components will register with when they become enabled, and unregister from when disabling. It also includes methods to enable and disable all active components. Here’s the relevent parts of the class shown with pseudo-code

class com.lookmum.util.ModalManager
{
// the list of all enabled components
private var componentList : Array
//the list of all components that this class has disabled, stored ready for re-enabling
private var disabledList : Array
public function registerComponent (com : Component) : Void
{
//add a component to the active list
}
public function unregisterComponent (com : Component) : Void
{
//remove a component from the active list
}
public function disableModal () : Void
{
//disable all active components and add them to the disabled list
this.disabledList.push ([])
var currentLayer : Number = this.disabledList.length - 1
<![CDATA[for (var i = 0; i < this.componentList.length; i ++)]]-->
{
if (this.componentList [i].enabled)
{
this.componentList [i].disable ()
this.disabledList [currentLayer].push (this.componentList [i])
}
}
}
public function enableModal (forceAll : Boolean) : Void
{
//enable the last disabled batch of components and put them back into the enabled list
var currentLayer : Number = this.disabledList.length - 1
var currentLayerLength : Number = this.disabledList [this.disabledList.length - 1].length
<!--[CDATA[for (var i = 0; i < currentLayerLength; i ++)]]-->
{
this.disabledList [currentLayer][i].enable ()
}
this.disabledList.pop ()
}
}

We then revise the component class to register itself with the singleton on enable, and unregister on disable.

import com.lookmum.util.ModalManager
class com.lookmum.view.Component{
private var modalManager:ModalManager
//constructor function
public function Component(){
//get a reference to the modal manager singleton
this.modalManager = ModalManager.getInstance()
}
//enable function
public function enable(){
//register the component with the modal manager
this.modalManager.registerComponent(this)
//enable component code here
}
//disable function
public function disable(){
//unregister the component from the modal manager
this.modalManager.unregisterComponent(this)
//disable component code here
}
}

Our immediate problem is that the enable functions affect registration with the singleton, so we need to test wether it is the singleton doing the enabling, and not to register/unregister if it is. The quickest thing to do is to pass an argument to the enable functions telling the component that the function is being called by the manager.

//the modified enable modal function in modal manager
public function enableModal (forceAll : Boolean) : Void
{
//enable the last disabled batch of components and put them back into the enabled list
var currentLayer : Number = this.disabledList.length - 1
var currentLayerLength : Number = this.disabledList [this.disabledList.length - 1].length
<!--[CDATA[for (var i = 0; i < currentLayerLength; i ++)]]>
{
this.disabledList [currentLayer][i].enable (true)
}
this.disabledList.pop ()
}

and…

//the modified enable function
public function enable(modal:Boolean){
if(modal){
//register the component with the modal manager
this.modalManager.registerComponent(this)
}
//enable component code here
}

The main problem with this approach is that we are making what should be internal behaviour public. There’s no way to enforce that the boolean value will only be passed by the manager.

Another approach would be to have a pair of enable functions, enable() and modalEnable(). One for general use which performs the registration, and one for use by the manager. However this still makes public something that should happen behind the scenes. There’s nothing to stop another developer accidentally using modalEnable() instead of enable()

The solution I came up with was to have this second enable function, but make it a private member. I then create a function delegate within the normal enable function and pass it to the modal manager with the component registration.

//the modified enable function
public function enable(){
//register the component with the modal manager and pass a function delegate as a scond parameter
this.modalManager.registerComponent(this,mx.utils.Delegate.create(this,this.modalEnable())
}
doEnable()
} 	private function doEnable(){
//enable component code here
}

We then give the manager event dispatching behaviours and let it add and remove the listeners itself.

public function disableModal () : Void
{
this.disabledList.push ([])
var currentLayer : Number = this.disabledList.length - 1
var dispatchList:Array = new Array()
for (var i = 0; i < this.componentList.length; i ++)
{
if (this.componentList [i][0].enabled)
{
dispatchList.push(this.componentList [i][1])
this.disabledList [currentLayer].push (this.componentList [i])
}
}
for (var i:Number = 0; i
this.addEventListener(DISABLE,dispatchList[i])
}
this.dispatchEvent(new Event(DISABLE,this))
for (var i:Number = 0; i
this.removeEventListener(DISABLE,dispatchList[i])
}
}

What i really want is some way to make a method of a class A only available to instances of another class B, bearing in mind that these two classes are unrelated, and i want any errors to be compile time, which means doing fancy things with arguments.caller isn’t quite what i want.

Any ideas anyone, or am i just being a pedant?

5 Comments


Actionscript: The rules #2 – Observer pattern for all events

All classes that generate events should do so via the observer pattern.

This one might prove a little more contravertial than the last, but i’m going to stick my neck out and say that all classes should use the observer pattern for events, rather than myEvent=function() callbacks, or object listeners.

For those who don’t want to read up about the observer pattern check out the EventDispatcher class which is basically an implementation of this. or better still grant skinners GDispatcher which has a few extra tricks up its sleeve. The first benefit of this method is that you can have multiple objects listening to the same event. This is all covered in the chapter on the observer pattern in Colin Moocks Essential ActionScript 2. If you want to start using these classes i suggest you read the tutorials on EventDispatcher and Delegate over at actionscript.org.

I also tend to use Dynamic flash’s Delegate class rather than macromedias own for scoping the listener object, as this also has a few added extras, such as passing the delegate itself to a listening function, as well as the event object, which makes removal of anonymous delegates an easy task.

This may sound like overkill for a lot of simple class structures, and you will have to remember to remove your event listeners, but it does mean consistency. If you’re using EventDispatcher in one class, and myEvent=function() style callbacks in another, then it’s easier to make mistakes. And harder to pick up code that you havent looked at in a while, because you have to figure out which method you used.

When using EventDispatcher it’s always useful to include static constant variable strings (try saying that 10 times quickly) for all the events a class will dispatch. This not only lets you keep track of which events a class broadcasts easily, but also provides compile time checking to make sure you are subscribing to events that actually exist. For example:

import com.gskinner.event.GDispatcher
class com.lookmum.Broadcaster{
public static var MYEVENT:String = 'myEvent'
public var addEventListener:Function
public var removeEventListener:Function
public var dispatchEvent:Function
public function Broadcaster(){
GDispatcher.initialize(this)
}
public function myFunction(){
this.dispatchEvent({type:MYEVENT,target:this})
}
}

and…

import com.lookmum.Broadcaster
import com.dynamicflash.utils.Delegate
class com.lookmum.Observer{
private var broadcaster:Broadcaster
public function Observer(){
this.broadcaster = new Broadcaster
this.broadcaster.addEventListener(Broadcaster.MYEVENT, Delegate.create(this, this.eventHandler))
}
public function myFunction(){
this.broadcaster.myFunction()
}
private function eventHandler(){
trace('event handled')
}
}

Two added benefits are that this makes it easy to document events because you can attach javadoc comments to the string constants and they stand out from other class members so events are easy to find rather than function callbacks which apart from their names look just like empty functions.

This is all very similar to the way events are used in AS3 and so if you can get used to using this methodology now, then the transition should be that much easier. In fact another useful methodology that AS3 uses is the use of a proper Event class, as the event object rather than using a standard object, which makes it easier to keep track of what properties your event object will hold.

1 Comment


Actionscript: The rules #1 – Refactor over reuse

Lately i’ve been trying to formalise a lot of the processes i use for coding actionscript so I started to write them down. I then was going to post them to my blog, however this quickly grew into a very large post, so i’ve decided to break them up into a series. Also this should make discussion of each of these points easier, and allow me to add more as i think of them (also it means i shouldnt be stuck for content for a while ;) ).

This isn’t a definitive list of best practices, and i’m sure people will disagree with me on some of the points but i think it helps to write this stuff down and discuss it. And with the introduction over it’s time to dive into the first rule.

“When creating classes don’t create them to be reused. Reusability should come from refactoring old classes”

This is an important but tricky skill to master, the ability to go back to some code you’ve already written and rework it. It can be a major headache the first time you want to reuse something, but if you can generalise a little more the code you’re useing every time you look at it, eventually you’ll end up with a solid code base. This goes hand in hand with not writing for reusability as raised by qlod, but rather letting reusablility come out of refactoring by itself.

Heres a simple example. Lets say we write a class for a specific task:

class myClass{
private var a:Number = 1
public function doSomethingWithNumbers():String{
//multiply by 2
a*=2.toString()
//then return the new value
return a
}
}

Later we want another class that does something similar. We could subclass our original like so:

class mySubClass extends myClass{
public function doSomethingWithNumbers():String{
//multiply by 2
a*=2
//then add 1
a+=1
//then return the new value
return a.toString()
}
}

However another approach is to move the common functionality to a super class, then have both classes extend this. First We create the super class:

class mySuperClass{
private var a:Number = 1
public function doSomethingWithNumbers():String{
return doSomethingSpecificWithNumbers().toString()
}
public function doSomethingSpecificWithNumbers():Number{
return a
}
}

Then we create our two sub classes:

class myFirstSubClass{
public function doSomethingSpecificWithNumbers():Number{
//multiply by 2
a*=2
//then return the new value
return a
}
}

And:

class mySecondSubClass{
public function doSomethingSpecificWithNumbers():Number{
//multiply by 2
a*=2
//then add 1
a+=1
//then return the new value
return a
}
}

So we now have two sub classes that do exactly what we wanted, and we also have a more generalised superclass, that should we want to create a third class in the future, is easy to extend for whatever we need it for.

I realise this may be an overly simplified example, but hopefully you’ll see the benefits of what i’m getting at here. Most importantly we’ve acheived reuse without having to waste time guessing what functionality we will need in the future while writing the first class. This means we’ve avoided writing any code that we don’t actually use, and anything that helps us to do less work can only be a good thing right?

2 Comments


Extending Actionscript implicit getter & setters.

Here’s something i only just noticed. If you overwrite either a getter or setter in a subclass of a class with both, but don’t provide a hook for the other one, then the property will become either read or write only. For example:

MyClass{
var _i:Number
public function get i ():Number{
return _i
}
public function set i(num:Number):Void{
this._i=num
}
}

Will produce the following expected behaviour:

var myClass = new MyClass()
myClass.i=10
trace(myClass.i) //traces 10

In the subclass we overwrite the setter with some new behaviour:

mySubClass extends MyClass{
public function set i(num:Number):Void{
this._i=num*2
}
}

Will produce the following not so expected behaviour:

var myClass = new MySubClass()
myClass.i=10
trace(myClass.i) //traces undefined

Which means the property i has become write only. To keep the property read and write you need to copy the getter into the sub class:

mySubClass extends MyClass{
public function get i ():Number{
return _i
}
public function set i(num:Number):Void{
this._i=num*2
}
}

And you then get the following:

var myClass = new MyClass()
myClass.i=10
trace(myClass.i) //traces 20

I know it makes a kind of sense, but it does mean you have to be careful you’re not changing the signature of your subclasses, as they dont behave exactly as you might expect.

3 Comments


Flash decimal to fraction utility class

I recently had to do some work where i had to return a fraction from a decimal number. I did some hunting around on the net and found some great information at layer51 and ericlin. From the info i got there i made a utility class that handles decimal to fraction conversion. You can download the source here, or just copy and paste from below.

The documentation is in the code comments, but if there’s demand for it, i’ll create a bit of html documentation. The class itself is pretty straightforward, so hopefully you should see how to use it. Any useful additions to this class would be appreciated.

Enjoy!

/**
* Utility class for getting fractions from decimals as an array of values or a string
*
* @author Phil Douglas
* @version 1.0
*
* website : http://www.lookmumimontheinternet.com
* email : phil@lookmumimontheinternet.com
*
* based on information from:
*
* http://proto.layer51.com/d.aspx?f=289
* http://ericlin2.tripod.com/mis/ration.html
*
*/
class com.lookmum.util.Fraction
{
// class variable, limits the amount of iterations in finding the fraction to prevent infinite loops
public static var iterationLimit : Number = 10000
private static var it : Number = 0
// class variable, the accuracy to which to find the fraction (used for infinately recurring decimals e.g. 1/3)
public static var accuracy : Number = 0.00001
private function Fraction ()
{
//class is static utility class so no need to instantiate
}
private static function resetIt () : Void
{
it = 0
}
private static function addIt () : Boolean
{
it ++
if (it == iterationLimit)
{
trace ('error : too many iterations')
return true
}
}
/**
* Static class method, returns a fraction from a decimal as a string
*
* @usage com.lookmum.util.Fraction.getFractionString(0.5) // returns "1/2"
* com.lookmum.util.Fraction.getFractionString(1.5) // returns "1 1/2"
* com.lookmum.util.Fraction.getFractionString(1) // returns "1"
* @param num the decimal to find the corresponding fraction for
*
* @return a string of the fraction
*
*/
public static function getFractionString (num : Number) : String
{
var fracString : String
var fracArray : Array = getFraction (num)
switch (fracArray.length)
{
case 1 :
fracString = num.toString ()
break
case 2 :
fracString = fracArray [0].toString () + '/' + fracArray [1].toString ()
break
case 3 :
fracString = fracArray [0].toString () + ' ' + fracArray [1].toString () + '/' + fracArray [2].toString ()
break
}
return fracString
}
/**
* Static class method, returns a fraction from a decimal as an array
*
* @usage com.lookmum.util.Fraction.getFraction(0.5) // returns [1,2]
* com.lookmum.util.Fraction.getFraction(1.5) // returns [1,1,2]
* com.lookmum.util.Fraction.getFraction(1) // returns [1]
*
* @param num the decimal to find the corresponding fraction for
*
* @return an array of the fraction of length 1-3
*
*/
public static function getFraction (num : Number) : Array
{
var fracArray : Array = new Array ()
var hasWhole : Boolean = false
if (num >= 1)
{
hasWhole = true
fracArray.push (Math.floor (num))
}
if (num - Math.floor (num) == 0)
{
return fracArray
}
if (hasWhole)
{
num = num - Math.floor (num)
}
var a : Number = num - int (num);
var p : Number = 0;
var q : Number = a;
resetIt ()
while (Math.abs (q - Math.round (q)) > accuracy)
{
addIt ()
p ++;
q = p / a;
}
fracArray.push (Math.round (q * num))
fracArray.push (Math.round (q))
return fracArray
}
}

4 Comments


My sordid Actionscript past

Over the last few days, I’ve been working on some changes to some really old projects here at Massmedia. One of which was the first thing i did when I started here, and the other is from nearly two years before that, full of all the tricks and hacks that flash required at the time. While I sat there looking through all this old code, I couldn’t help thinking what I would change if I had to redo the projects today.

The fact is that almost every Flash developer i know, or indeed most professionals in any related fields, are seldom happy with the work they did a long time ago, and it’s almost with a sense of shame that we pick through our first old projects. I suspect Colin Mook is spinning in his multiuser application grave as I navigate throught the spaghetti i used to write, while on my journey from someone who used flash purely for broadcast TV animations.

But surely this is a good thing. The day i pick up a project I did years ago and think “That’s great, I wish I knew how to do that now!” is the day I truely have to worry. Maybe it’s just me, and all of your first projects were a strictly typed synergie of design patterns and dynamically loading class libraries. I for one enjoyed reminising with a colleague about the hacks we used to use while flash was developing, and ourselves along with it.

I will always fondly remember the heady days of:

<em>if ( _root.getBytesLoaded() == _root.getBytesTotal() ){
gotoAndPlay(3)
}else{
gotoAndPlay(1)
}</em>

Oh onEnterFrame, how you spoiled all my fun :) .

Anyone else got Actionscript skeletons in thier closet they’d like to confess to?

1 Comment



  • SetPageWidth