Monday, July 30, 2007

Unloading Flex Modules Cleanly

Flex 2.0 offers developers the ability to define a truly modularized application through the use of <mx:Module/> tags. The Flex Developer's Guide dedicates Chapter 31 to using this tag for creating modular applications-- all 9 pages of it.

We are building a massively large application that relies extensively on modules so that we can load and unload portions of the app on the fly and conserve memory. Without getting into the low level details, some of our modules use the XmlSocket to connect to our proprietary multi-threaded server that delivers some specialized content over the wire in real-time. We encountered a unique problem with modules, and I figured it was a big enough issue that I should share the solution with the blogosphere. When we launch the module, we established our connection to the server. When we unloaded the module, we weren't properly informing our server that the module had been unloaded. Sure, there are timeouts and other mechanism to recover server-side resources, but nothing beats a clean exit. And to do that, we needed to know that the module was unloading!

If you look at the <mx:Module> tag, there is no "unload" event on the module itself. In fact, the unload event is on the <mx:ModuleLoader/> and by the time it fires, the module's reference has already been set to null!

All is not lost, however, and by using a bit of OO know-how there is a clever and simple work around to this problem. In this posting I'm only going to demonstrate solely how to handle the unloading of the module in a module-independent way; it is academic to extend the class with new methods as required.

Step #1:
Create a new .as file that defines a single method, like this:


package com.beadlefox
{
import mx.modules.Module;

public class UnloadableModule extends Module
{

public function unloadModule():void
{
//
// Do nothing stub
//
}

}
}


Then, instead of rooting your Module implementation using <mx:Module>, root the module using your new class, like this:


< UnloadableModule
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns="com.beadlefox.*"
...>


Each module can then merely override the stubbed out method defined in UnloadableModule:


public override function unloadModule():void
{
//Unload your resources here
}


Finally, in the application shell that contains your module loader, a simple and effective class checks allows you to invoke the unloadModule method prior to physically unloading the module. In this code snippet, the activeLoader is of type ModuleLoader.


if(null != activeLoader)
{
if(activeLoader.child is UnloadableModule)
{
var um:UnloadableModule = activeLoader.child as UnloadableModule;
um.unloadModule();
}
activeLoader.unloadModule();
}


By leveraging a bit of OO-power, the shell can now maintain independence from the individual modules, and those modules that need to explicitly release resources prior to being unloaded are given the chance to do so.

Sunday, July 22, 2007

Localized Flex Development

Localizing a Flex app is not a task for the weak. Unlike Java and the .NET languages which rich localization capabilities, Flex and AS3 are, in my mind, very immature. Sure, Flex offers just enough features to allow one to check off that "Localization Capabilities" check box when evaluating the software, but having build several applications now that had to be localized, I assure you- Flex has a long way it can go to improve.

First and foremost, there is the way Flex compiles a localized application. There is also the runtime exceptions the player throws when it can't find something- but I'm getting ahead of myself.

To truly appreciate how convoluted the Flex approach is, let's review (at an uber-high level) the Java localization capabilities.

Java has these things called Resource Bundles. The Resource Bundle goes inside of the .jar file, and it is a tree by its very nature.

root
-- en
-- -- en_GB
-- -- en_US
-- es
-- -- es_ES
-- fr
-- -- fr_CA
-- -- fr_FR

From this tree, if your specific locale is say France, then your browser and app could be localized to French, French (fr_FR). If you livBe in Canada and speak French, your locale would be French, Canadian (fr_CA).

Suffice to say, Java gives you "failover" capabilities. For example, if you live in Belgium, your locale would be fr_BE. Notice our tree doesn't support that, so Java automatically will fall back to "fr" and the bundle deployed there. And likewise, if you lived in say Germany, since there is no German locale, it would fall back all the way to the root level resource bundle.

In contrast, Flex requires that you specify a single locale prior to compilation. That means that if your Flex application needs to support 5 languages, you have to compile the application 5 times. Which leads to additional overhead-- it means that page serving up the Flex application needs to have the logic to decide which localized swf should be sent across the wire. In the case of Java, this logic is usually in the Servlet or JSP page. In addition to the programming logic, there is also the file management problem. Now instead of deploying one swf to the web site, you'd need to deploy 5 swf files, preferably with a naming convention that reflects which localized compilation it is.

Flex also could easily check that your resources are the resource bundle. The compiler is smart enough to report an error at compile time if the resource file is missing, but if the file is there but the property isn't, you only find this out at runtime. And in fact, if you don't have the Flash Player Debug version installed, the results can often be a "blank screen" with no dialog or indication that the app failed because a localized string that was requested was missing from the resource bundle. Now, arguably after the translator localizes the app, another round of testing should be done to catch the error- but there is nothing more annoying then a JIRA case opened that simply reads "Spanish version of the app doesn't run and results in a blank screen."

Flex could really save developers some time by verifying that the name-value pair exists in the resource bundle. Likewise, if it doesn't look up the resource bundle until runtime, why can't the bundle be specified as a URL-- let Flex go back to the server and load up the bundle on the fly! After all, even in our application we load the stylesheet as a separately compiled swf file-- so why not offer that for localized names? Forcing a full recompilation of the entire app means that the entire app has to be retested, possibly just because "Title" was misspelled as "Tilte" or something as trivial as that.

So what are the tips here you're asking?

1) Let each screen have its own .properties file, even if it means having some duplicated words. Experience has shown that while 99% of the screens might be ok with the label "Save" there will always be "the exception" to the rule. And if a junior member of the team doesn't realize that "button.save=Save" is used everywhere, suddenly the whole application will have replaced the label "Save" with say "Export" and cause grief.

2) Localizing pick lists means that your code can't make decisions based on the label, and ordinal position is usually out of the question too because most lists are sorted alphabetically. To get around, here is the pattern that we've used on our applications. In the resource bundle define a label and a unique ID, like this:

status.label.1=Active
status.code.1=1
status.label.2=Inactive
status.code.2=2
status.label.3=Unknown
status.code.3.=3

Bind your list to your CombBox is done through a bindable decorated ArrayCollection, like this:

[Bindable]
private var statusList:ArrayCollection = new ArrayCollection();

...

<mx:ComboBox id="dgStatus" dataProvider="{statusList}"/>

And then in an initialize method you can programmatically push the label-code pairs into the collection as Object instances. In all of your code, you make your branch/logic decisions like this:

switch(dgStatus.selectedItem.code)
{
     case 1:
          // Active
           ...
           break;
      case 2:
           // Inactive
           ...

As an alternative way of populating the collection, you can drop the variable declaration and do it all in MXML, like this:

<mx:Array id="statusList">
  <mx:Object label="{rb.getString('status.label.1')}"
      code="{rb.getString('status.code.1')}"/>
  <mx:Object label="{rb.getString('status.label.2')}"
      code="{rb.getString('status.code.2')"/>
  <mx:Object label="{rb.getString('status.label.3')}"
      code="{rb.getString('status.code.3')"/>
</mx:Array>

This way binds properly, but the compiler does throw a warning about any future changes to the bound properties won't be detected-- which is fine given that you can't dynamically "swap out" the resource bundle at runtime in Flex.

3) If you aren't automating your build already, you need to be. Perhaps that's another posting for another day. Suffice to say that your build scripts should automatically compile and rename your swf files for all of your supported locales automatically.

4) Gibberish is your friend. The "locale" that you specify to Flex doesn't have to be a real locale-- or even the letters are real, what your property values are don't have to be. The point I'm making is that in English you might label something with the word "Tag:" and find you have enough real estate. What happens when you translate to the Spanish equivalent, etiqueta? I like to have a locale full of gibberish that define long labels, thus ensuring that a localized bundle doesn't break my screen flow. After all, as the developer of the screen I know that button 1 does this, button 2 does this, etc.- so I can easily perform a visual "unit test" with such gibberish words. The result is that I can cut down on JIRA cases that report "not enough space on translation." In my case, the locale "gb" stands for gibberish, and I often do a "gb" locale build prior to commit for a visual unit test on my spacing.

5) If you build using Ant or in another manner, your flexconfig.xml file can use the variable {locale} within it. In this way, whatever locale is passed to the compiler, the appropriate subdirectory would be polled for resource bundles. In my case, my directory structure on a Module looks like this:

$ROOT/src
$ROOT/locale
$ROOT/locale/en
$ROOT/locale/es
$ROOT/locale/fr
$ROOT/locale/gb
...

As you can see- there at the end of the list is my "gb" for gibberish locale. Thus a command like this:

mxmlc -locale gb

pulls in my length gibberish labels that I've described.

6) The final tip isn't so much a Flex tip as it a Servlet/JSP/PHP/etc. tip for the page that serves up your application. If you decide to depend on the content-language HTTP/1.1 header field, always be prepared with a "default" language to fall back on. We've found people in the UK that bought a PC in the states and weren't getting en_gb, but were getting en_us because that was the default setting. That isn't too bad, but what happens when someone from Peru decides to access your application and there is no es-pe regionalized locale? You shouldn't just fail them over to English, you should fail them over to "es" if possible, then if that isn't available, over to "en."

7) You may also want to save the locale into the session. This makes the locale in use easily available to your server-side logic, like Axis web services, with a simple lookup instead of a convoluted string of function calls to get back to the request. Odds are the same locale will be used for the duration of the session anyways.

8) Database design. Localizing the app often means that your lookup tables, if database driven, will also need to be localized. There are a couple of approaches that can be taken, and the one we chose looks like this (using a generic "widget" as an example):

TABLE: Widget
widget_id
widget_internal_name
widget_java_class

TABLE: WidgetDescription
description_id
widget_id
locale VARCHAR(5);
l10n_name
l10n_description

Essentially, all programmatic decisions are made off of the "widget_id" from the Widget table. However, all pick lists and such relay on retrieving the localized content from the WidgetDescription table. Thus, the field "l10n_name" would show up in say the ComboBox and the "l10n_description" would be the tooltip help that would be displayed, but programmatically we could code against the widget_id and not worry about what language changes occur down the road-- widget_id 32 is always going to be widget_id 32, regardless of the user's locale.

In closing, writing localized applications is inherently a time consuming process. Flex can do it, but it takes some time and effort to ensure that you design the application properly. These tips will get you going in the right direction and hopefully save you some time.

Wednesday, July 18, 2007

The Inaugural Post

Flex.

Flex seems to be taking over the UI programming world these days. There are very few of us who can lay claim to writing Flex 1.x applications that went into production.

Getting here hasn't been all sunshine and roses, however. Even with the advent of Flex 2, there are some things about the language and its architecture that just royally piss me off. In all fairness, though, there are things in Java, C++, C#, and all of these languages that royally piss me off, too.

This blog is going to be about solving real-world problems. Basically, when I stumble on a mind-boggling problem, I'm going to post the solution here, regardless of how (un)elegant the work around may have been.

So sit down, shut up, and learn from my mistakes :-)

(And Michigan still sucks...).