Skip to content


Flex Util classes

Like reading documentation, checking out the Flex util classes can be very eye opening. There is some extremely handy stuff available.

A few examples:

  • URLUtil
    1. getProtocol
    2. replaceProtocol
    3. isHttpsURL
    4. urisEqual
    5. hasUnresolvableTokens
    6. replaceTokens
  • UIDUtil
    1. createUID
    2. getUID
    3. isUID
    4. toByteArray
    5. fromByteArray
  • StringUtil
    1. trim
    2. trimArrayElements
    3. substitute
    4. repeat
    5. isWhitespace
  • ColorUtil
    1. adjustBrightness
    2. adjustBrightness2
    3. rgbMultiply
  • ObjectUtil
    1. stringCompare
    2. numericCompare
    3. dateCompare
    4. hasMetadata
    5. getClassInfo
  • ArrayUtil
    1. getItemIndex
  • DisplayUtil
    1. walkDisplayObjects
  • So, that is a few of the handy methods available on Util classes. But there is also the flash.utils package, which offers methods like:

    1. describeType
    2. getQualifiedClassName
    3. setTimeout
    4. getDefinitionByName
    5. getTimer

Posted in Almost Random.


Handling results of multiple delegated asynchronous calls

Working on migrating an application to PureMVC, and was setting up a particular Proxy/Delegate relationship this afternoon that involved four or five different calls via the Delegate.

I’m still pretty new to PureMVC and wasn’t sure how to handle the relationship. Still not sure if this is the best option, but I’m pretty happy with it.

In the PureMVC world, the Model layer is responsible for communication with the server side – this is because the Model layer is comprised of Proxy (basically just a plain model object with a few features specific to the framework) and VO objects, which are long-lived, while the Control layer is comprised of Command objects which are fire/forget.

So, the basic breakdown is that I have a Proxy class that makes service calls via a Delegate. I’ll call them UserProxy and UserDelegate. The Proxy class implements IResponder, so it defines a result method and a fault method. When the UserProxy needs to make a service call, it delegates the communication work to the UserDelegate – setting up the connection to the server and making the call. However, the result/fault will be handled by the UserProxy’s result or fault methods. There isn’t any direct connection between the Proxy and the Delegate, so there isn’t a way to distinguish between result sets if there is more than one service call made by the Proxy.

The basic relationship is managed like this:

In the Proxy, a call is wrapped in a function that creates an instance of the Delegate and then calls the associated method on the Delegate. The result will be handled by the Proxy’s result method.


public function getUserProfile(user:UserVO):void
{
    var delegate:UserDelegate = new UserDelegate(this);
    delegate.getUserProfile(user);
}

When the UserDelegate object is instantiated, it stores the reference to UserProxy as its responder, and creates a reference to the service it is responsible for communicating with.

The corresponding getUserProfile method on the Delegate object looks like this:


public function getUserProfile(user:UserVO):void
{
    var token:AsyncToken = service.getUserProfile(user);
    token.addResponder(responder);
}

All it does is make the service call and route the result/fault handling to the responder, which is the UserProxy object.

Now, this works great when the service involved has only one method, but not so well when the service has more than one method. This is because the result and fault methods just received the ResultEvent or FaultEvent and have no idea which method was called. And you can’t set up multiple result/fault handlers in this situation – the Proxy class implements IResponder, which defines only result and fault.

So, how to work with a service that has multiple methods?

Again, this may not be the best option, but I think it’s clean and simple and works well with the constraints of PureMVC.

In the Proxy class, create a Dictionary object called tokenList, and then create a private constant for each method on the service. Something like this:


private const GET_USER_PROFILE_ASYNC_KEY:String = "getUserProfileAsyncKey";
private const GET_ORGANIZATION_LIST_ASYNC_KEY:String = "getOrganizationListAsyncKey";

private var tokenList:Dictionary = new Dictionary();

Next, go to the UserDelegate class and modify the functions there to return the AsyncToken, like so:


public function getUserProfile(user:UserVO):AsyncToken
{
    var token:AsyncToken = service.getUserProfile(user);
    token.addResponder(responder);

    return token;
}

We now have a way to keep track of which result goes with which method. In the UserProxy class, modify the getUserProfile method like so:


public function getUserProfile(user:UserVO):void
{
    var delegate:UserDelegate = new UserDelegate(this);
    tokenList[GET_USER_PROFILE_ASYNC_KEY] = delegate.getUserProfile(user);
}

Finally, we get to the part where we handle results. The result method originally looked like this:


public function result(data:Object):void
{
    // ...
}

Now, though, we can match the AsyncToken associated with the service call to the result object returned from the server. The result method is updated like this:


public function result(data:Object):void
{
    switch(ResultEvent(data).token)
    {
        case tokenList[GET_USER_PROFILE_ASYNC_KEY]:
	    handleGetUserProfileResult(data);
	    break;

	case tokenList[GET_ORGANIZATION_LIST_ASYNC_KEY]:
	    handleGetOrganizationListResult(data);
	    break;
    }

    delete tokenList[ResultEvent(data).token];
}

Posted in Almost Random, Development.


Simple validation of XML input, not totally simple

Ran into something at work today where I needed to provide very basic validation of XML pasted or typed into a TextArea.

I started off looking for a regex that would do the job, expecting to find a ton of available examples that actually did more than I needed – but I found NONE. I did find, though, several suggestions of just converting the input to XML and checking to see if the conversion worked or failed. Right — smart.

But, the following code will run with no problems:
var inputAsXml:XML = new XML("abcdefg");

I ended up with some code that includes a little additional logic if the ‘xml’ in question is simple (that is, only one line). In this case, I look for a leading “<" character, and an ending ">” combination.

private function handleAdvancedCustomXMLChangeEvent(e:Event):void
{
	var targetText:String = e.target.text;
	var passed:Boolean = false;
	var inputAsXML:XML;

	try
	{
		inputAsXML = new XML(targetText);
		passed = true;

		if(inputAsXML.hasSimpleContent())
		{
			e.target.text = StringUtil.trim(targetText);

			if(targetText.charAt(0) != "<" || targetText.charAt((targetText.length - 1)) != ">" )
			{
				throw new Error("");
			}
		}
	}
	catch(e:Error)
	{
		passed = false;
	}
	finally
	{
		if(passed)
		{
			viewModel.customXML = advancedCustomXML.text; toggleSaveBar(true, 'Advanced');
		}
		else
		{
			toggleSaveBar(false, 'Advanced');

			if(targetText != "")
			Alert.show("The input XML is not well-formed.  Please check the entry and try again.");
		}
	}
}

This logic is being used to check XML that is typed or pasted into a TextArea, and works reasonably well except for one thing – ActionScript considers the following to be valid XML:


<aNode>
    <bNode>blah blah</bNode>more blah
</aNode>

Maybe there is some sort of ‘strict’ switch I can flip, that I don’t know about yet.

Posted in Development.


Versions – SVN client for OS X

Finally, an SVN client for OS X that works.

Versions is made by Sofa, which makes a couple of other cool products, including a file comparison tool called Kaleidoscope.

I haven’t used it a whole lot, yet, but I’m liking it, so far.

The only drawback I’ve come across, so far, is that you don’t seem to have the ability to remove a file from the list of files to commit, in the commit dialog. This makes for a slightly awkward experience if you want to upload some, but not all, of the modified files from a particular directory.

Other than that, I’ve been very pleased with Versions.

UPDATE: Ouch. Also, you can’t branch, switch, or merge with Versions. I still like it, but a lot less.

Posted in Development.


Lol – The ‘down to’ operator

Last week, I ran across this blogpost about an undocumented operator called the ‘down to’ operator.

var a:uint = 20;
while ( a --> 0 ) trace(a);

This will trace out the numbers 20 through 1 in the Output panel.

I’d never heard of this, so I tried it out. It worked as stated, but I couldn’t find _anything_ about it anywhere but this post.

I wanted to use this operator this morning, but from a slightly different angle, so I started researching the ‘down to’ operator, again to see if it was possible to do what I wanted to do. And also just to see what all it was supposed to do.

Came back to the same post – but this time I noticed that he learned out this secret operator from a StackOverflow question, so started looking through that thread – in doing so, I found this related question, which contained a comment which sorted things out.

The deal is that this is NOT an undocumented operator. It’s two totally documented operators with the whitespace removed (-- and >).

while (a --> 0)

is actually while (a-- > 0)



Really had me going because I was doing this:

var f:int = versionListExclusions.length - 1;
while(f --> 0)
{
if(subDirectory == versionListExclusions[f])
...

‘versionListExclusions’ is an Array, and I was getting one less iteration out of the while loop than I was expecting – cause the first thing I was actually doing was decrementing the value of ‘f’.

Correct usage is:

var f:int = versionListExclusions.length;
while(f --> 0)
{
if(subDirectory == versionListExclusions[f])
...

Though, really, truly correct usage is:

var f:int = versionListExclusions.length;
while(f-- > 0)
{
if(subDirectory == versionListExclusions[f])
...

HAHA. LOL. -1 HOUR OF MY LIFE.

Posted in Ouch.


Eclipse keyboard shortcuts

One of my co-workers recently threw his Win machine out of a window (is that irony or is that something else?), and replaced it with a MBP. He’s a Linux guy and hasn’t worked much with OS X, so he was asking me questions as he set himself up, but that quickly turned into him giving me lessons on Eclipse.

Eclipse is at the top of the list of things I need to learn more about. It’s nestled next to Terminal, Python, and ANT.

I’m sure there are several comprehensive lists available, but here are a few new keyboard shortcuts that I’m currently pretty fabulous about:

Command + / – comments out selected lines with single-line comments. I’m nearly ecstatic about this one.

Command + Option + right arrow – drills to a highlighted method or property. This is the same as Command + click, or Function + F3.

Command + Option + left arrow – go back to where you drilled from. Nice.

Command + Option + up/down arrow – duplicate current line (up arrow duplicates it on line above, down on line below).

Command + right/left arrow – go to end/beginning of line.

Command + up/down arrow – go to top/bottom of document.

Command + right/left/up/down arrow + Shift – selects content between cursor start and end positions.

Option + right/left arrow – move to start/end of word.

Option + up/down arrow – moves current line up/down.

Option + left/right arrow + Shift – select to start/end of word.

Posted in eclipse, keyboard shortcuts.


Shared singletons

Heard on The Flex Show #84, today, that when you load a SWF into another SWF, by default they will share matching Singletons.

This makes a lot of sense, as the SWFs will share all matching Class definitions, due to being in the same Application Domain.

Yow. That’s something to be aware of.

Posted in Development.


Capturing phase

UPDATE: This is actually kind of wrong. A static object can dispatch an event – it is just not inserted into the event flow. However, that’s not too big of a deal, since most event handling is done at the targeting phase, anyway. Maybe I will update/delete most of this post soon…

We’ve been doing a fair amount of interviewing for an open dev spot at work, and I came up with a question that I felt would help me get a sense of where a given candidate was at, whether or not he/she knew the answer.

“Why can’t you dispatch an event from a static method?”

Technically, that should probably be something like, “Why can’t you successfully listen to an event dispatched from a static method”, but the point of the question is to get a feel for how deeply the candidate has looked into or thought about how events work. Or, failing that, how well they can think about it on the spot.

My answer is that a static method is not associated with an object instance, and therefore can not participate in the Display List chain, which the event model is based on – so, no propagation path, no capture phase or bubble phase, and definitely no target phase.

Incidentally, I came up with this question after trying to dispatch an event from a static method…

After thinking about it some more, I realized that this question represents the extent of my knowledge of ActionScript 3′s event model. Like, okay, that’s probably a correct answer but I can’t provide any insight on exceptions to this rule, or any work that has been done to allow a developer to dispatch events from static methods, or anything at all beyond my simple answer (which is really pretty obvious if you have a basic understanding of events, but maybe you’ve just never thought about it).

Here are some examples of other things I don’t know about, regarding the event model:

  • Why is there a capture phase? Why would you use it? What makes it computationally expensive (according to Adobe documentation)? Why can you only use either the capture phase or the target/bubble phases (unless you use two event listeners)?
  • Is there some other way to dispatch events so that data-only relationships can be event-based?
  • Is there a way for a static method to dispatch an event that can be listened for?

That bit about the capture phase being computationally expensive is killing me. WHY??!! I mean, wouldn’t it be computationally less expensive to handle an event in the capture phase and then stop propagation?

After some light research, I feel far less knowledgeable, in spite of actually knowing more.

I started here, with a post about Robert Penner’s AS3 signals, and then moved to a couple posts by Penner critiquing and learning about events in AS3 (1, 2, 3).

From there I moved on to the specification behind the event model – it’s called DOM Level 3 Events. The fact I’d never even heard of this probably says a lot about how much I don’t really know about events.

Then, there’s this post by Darren Schall, which is specific to Flex, but highlights the EventPriority class, which I was not aware of. Not really germaine to the particular problem that is bugging me (why does the capture phase exist, when would it be used, why is it expensive), but interesting in that setting up default event listeners is a really useful thing to know about.

UPDATE: Had some interesting conversation about the capture phase last night at the Austin Flex User Group (which, like this blog, is a treasure trove of people who are a lot smarter than me). No one else really had a good answer as to why you would ever use the capture phase – much less why it is any more expensive to use than the bubble phase, but:

1) Someone asked if I had done any tests to determine if the capture phase actually is more expensive than the bubble phase.

2) A group of us (and some beer) worked our way loudly to a couple of fairly esoteric situations where you might want to know that an event has occurred, but prevent all registered listeners from hearing about it. So, you’d catch the event in the capture phase, run whatever logic you want to run, and then stop propagation.

3) I also struck on the idea of catching an event during the capture phase, modifying it, and then dispatching a clone. Presumably after un-registering the capture phase event listener.

I could see #2 and #3 being potentially useful in a situation where you had to mash your own code against some compiled code that you didn’t have any control of. But, I’m pretty obsessed about this, now, and I want to hear someone who knows what they’re talking about give an answer.

UPDATE: My friend Jason pointed me to this question on StackOverflow. It’s about JavaScript, which is based on the same spec as the event model for ActionScript. There’s an interesting and enlightening comment by El Yobo:

Focus/blur events don’t bubble, but can be delegated at a higher level during the capture phase – quirksmode.org/blog/archives/2008/04/delegating_the.html – El Yobo

So – there’s some practical use of the capture phase.

In the meantime, I’m trying to put together some meaningful tests to see if the capture phase really is more expensive than the bubble phase, in AS. This is not my strongest suit, and I may be approaching this completely incorrectly.

Test #1: Create 30,000 event listeners on a particular event, and time how long it takes them to all fire. Do once using the bubbling phase, and once using the capture phase.

For the first version of this test, each event handler evaluates whether it is the first or last to fire. If it is the first, it writes the time as milliseconds to a textfield labeled ‘Start Time’; if it is the last, it writes the time as milliseconds to a textfield labeled ‘End Time’, and then writes the difference to a textfield labeled ‘Total Time’.

So, 28,000 of the 30,000 listeners are doing nothing more than running the conditionals and seeing that they have nothing to do other than update a counter value.

I ran the test a few times, closing and re-publishing the test SWF in between each test, and got the following:

Bubble phase: 321 ms; Capture phase 333 ms
Bubble phase: 323 ms; Capture phase 324 ms
Bubble phase: 326 ms; Capture phase 323 ms
Bubble phase: 324 ms; Capture phase 324 ms
Bubble phase: 321 ms; Capture phase 322 ms

I ran the same test at 12 fps and at 60 fps, to see if I could get a noticeable variation that way, but didn’t see any modification of the results.

Next version of this test will be for each listener to draw or move something on the stage.

Posted in Development.


Server. Acknowledge. Failed.

DO NOT send undefined complex datatypes (seems only relevant to Arrays, actually, but not 100% certain) to a remote method when using BlazeDS to manage your client/server communication.

I mentioned in a recent post that we suddenly started getting this non-helpful message when calling a method that we have been calling for about eight months.

This is a message you can get when using BlazeDS (maybe LCDS, as well?), and it basically means that there is a communication problem between the client and BlazeDS. At least that’s what I think it means based on the evidence in front of me.

Evidence

  1. We’ve been using this method for quite awhile. However, something about it changed, which set off this issue. The method was modified to accept a new object – let’s call it ‘A’, which contained a few simple properties and an array of objects (the datatype of which was also new – let’s call it ‘B’).
  2. Using an http proxy debugger, of some sort, I can see that the data makes it to the server, and the server returns a correct response. The server also explicitly states that there were no errors. Obviously, this doesn’t necessarily mean that no errors occured, but since the correct and expected response is returned, it sure looks like there weren’t any. Even though the error message begins with ‘Server’.

I found virtually nothing helpful online (it’s not you, Google, it’s me), except for this, which is currently one of my top five favorite blog post titles:

http://ria-coder.com/blog/serveracknowledgefailed-another-amfphp-ballache/

After a LOT of crying, and some debugging, I finally found/realized that the ‘logic’ I had written was creating an undefined value in Object A for the array of Object B elements.

I won’t get into what I did to accomplish this, but it was pretty dumb.

The point is that, just like my friend with the AMFPHP-flavored ballache, I was sending an undefined complex datatype across BlazeDS. Note that this is not the same thing as sending an empty or null value – the array was undefined (as in declared, but never given a value).

I would have realized this obvious yet invisible mistake about a thousand years earlier if ActionScript didn’t fail silently if you attempt to push items into declared-but-undefined array. Hm, that one’s going in my list of things that bother me about ActionScript.

Posted in Ouch.


RemoteObject vs. mxml.RemoteObject

The product I work on has some unique requirements, which create some very unusual problems to solve on a pretty consistent basis. That’s fun and challenging, so Great. But, sometimes the problems take it too far.

The application is built in Flex. Flex 3, to be specific.

That’s fine, BUT we build against the 3.3 SDK, which is basically a more buggy version of the 3.5 SDK (which was released like, a year ago). We build against the 3.3 SDK because of a common reality of software development in mid-sized/large companies.

About half a year ago we started having really wonky issues with our builds. Short story: it was because our build machine was using the 3.3 SDK and none of the developers realized it (also due to a reality of software development common in mid-sized/large companies). We all thought everything was on 3.5. Several of us started working on the project after 3.5 was released and never even thought to ask what version of the SDK we should be using. Bad on us.

We decided at the time to stick with 3.3, even though we were having a bunch of problems with event dispatching / value commitment in DataGrids (a specialty in 3.3 in terms of bugginess). The idea being that ‘after this release’ we would upgrade to 3.5.

Continued…

Posted in Ouch.