Archive for the 'Actionscript' Category

OpenID From AIR

I’ve been working on some web services recently.  There’s both plain old browser accessed HTML pages plus an AMF interface to them.  One feature of the HTML version is OpenID authentication.  Now OpenID is all fine and dandy for a web application, but we get some problems when we want to use an AIR desktop client to connect and authenticate through OpenID. 

If you’re not familiar with how OpenID works, here’s a quick summary.

  1. User goes to an application (Usually a web-app)
  2. User types in their OpenID URL to that app
  3. They get forwarded to their OpenID page where they can either grant or deny access.
  4. That page then forwards them back to the original web app with an authentication token set.

Obviously, it’s kind of hard to redirect back to a desktop application.  I was thinking up some wacky work-a-rounds for this but then it hit me.

In the AIR app I can just use the HTML component and point it towards the login form of the web services.  The user can then log in using either username/password or OpenID just like they do on the website.  Now, here’s the cool part…  The AIR HTML component shares a network stack with the AIR/Flex NetConnection object.  That means any session/cookies/whatever opened in the HTML component carry through to the remoting calls I want to make from Actionscript. So I can authenticate using a web form, but then consume BlazeDS/LiveCycleDS/AMFPHP/Red5 services using AMF over Netconnection.

I did up a quick proof of concept and it works on both Windows and OSX.  I was able to successfully call a remoting service that requires an authenticated session.  So this was actually a much easier problem to figure out than I had feared.

Now, I’ll just need to make the web page that loads after a successful login somehow indicate to the AIR app that the user is successfully logged in.  I’ll probably either use a tiny Flash component that signals over LocalConnection, or I’ll just make the AIR app watch for when the HTML component gets to a specific URL. I’m pretty sure I can get this to be a completely seamless experience for the user.

Oh, and as a bonus… the user can sign up for a new account instead of log into an existing one from "within the app" instead of going to an external website to do that.


Model Adapters - A binding pattern using an Adapter

Binding in Flex is great. It’s an ultra convienent way to get information from your data model to show up in your views. But it does have some limitations, and to work around those limitations I’ve been using the “Model Adapter” aka the “Wrapper” or just plain “Adapter” pattern (some info, and more).

The basic idea is you shouldn’t have to modify your data model to use it in a specific view. If you need to filter, sort, or summarize the data for a view you can do that through an Adapter so your model doesn’t need to understand that logic and you’re view isn’t reliant on a specific implementation of your model.

Example: If you had a list of books in an array, and you want to filter by some property of books (say publisher) you shouldn’t apply the filter directly to the model. Instead, create an adapter that can watch that array, and have that adapter apply the filter (or sort, or whatever).

More Examples: Consider Timeliner XE, a product I’ve been working on at my day-job. The main data model is a list of events. There are several views for that data. We have a text based / grid view, and some graphical views. Here’s a couple screenshots:

Each of those screenshots has 2 views active at a time, the grid, and then a seperate graphical view. That makes 3 views that all want to bind to our data model. But, notice the grid has 5 events in it, while the graphical views only have 3. This is because only 3 of those events are valid to plot (they have a date). It’d be nice if we only had to bind to a list of events that actually has the data we want.

Now take a look at these three screenshots from AgileAgenda, my project scheduling application.

In all of these the data we have is a list of tasks. The first two show one view with two different filters applied to the data. The third shows a large grid with all of our tasks, and a much shorter pulldown that only has the tasks that are also milestones. (A milestone is a specific type of task)

To create an adapter:

  • Create a new adapter class
  • Create a constructor for that class that takes in the “source” data model, and any options that might be specific to the adapter.
  • Add event listeners to the “source” model.
  • Write event handlers in the adapter to update the adapter’s internal state when the source changes.
  • Write accessors in the adapter, so other components can get data from it.

A simple example…

Click here to run a simple example. View-source is enabled in that. Here’s a screenshot of the example:

When you run the example, it creates a simple data model, populates that data model with 4 sample items, and then creates 4 panels. Each of those panels represents a view. The example also creates 4 different model adapters all from the same data model, but with different options set. Then each panel gets a different adapter.

As you add items to the data model, you can see that the 4 views update depending on whether or not they are filtered and sorted.

Our Data Model:

package
{
    public  DataItemExample
    {
        public var name:String;
        public var amount:Number;
        public var active:Boolean;
    }
}

—-

package
{
    import mx.collections.ArrayCollection;

    public  DataModelExample
    {
        [Bindable] public var myDataItems:ArrayCollection = new ArrayCollection();

    }
}

As you can see, it’s a pretty simple data model. There are items with a name, amount and active properties, and then there is DataModelExample class with an array of those. Notice that no view-specific data is in there.

Now, lets create our adapter and name it “AdapterExample”

First, create a constructor and some variables to hold some information about the adapter. We’ll have 2 options. onlyActiveItems and sorted. For sorted, we’ll also create a Sort object to actually do the sort for us. And we’ll also create an array to hold our filtered/sorted list of items. Note that we add an event listener for the COLLECTION_CHANGE event. This is how we’ll propogate changes from the data model to our adapter. We’ll see the handler for that later.

 public  AdapterExample extends EventDispatcher
    {
        protected var model:DataModelExample;
        protected var filteredDataItems:ArrayCollection = new ArrayCollection();
        protected var _onlyActiveItems:Boolean;
        protected var _sorted:Boolean = false;
        protected var sort:Sort;        

        public function AdapterExample(dataModel:DataModelExample, onlyActiveItems:Boolean, sorted:Boolean)
        {
            _sorted = sorted;
            _onlyActiveItems = onlyActiveItems;

            model = dataModel;
            model.myDataItems.addEventListener(CollectionEvent.COLLECTION_CHANGE, onItemsChanged );    

            if(sorted)
            {
                sort = new Sort();
                sort.fields = [new SortField("name",true)];
            }

            rebuildFilteredArray();
        }

Notice that we called rebuildFilteredArray above. Lets write that next. All this method does is loop through our data model and grab all the items from it (respecting our filtering option) and adds them to our internal array. It also applies the sort if neccessary. At the end we dispatch two events which will be used for binding later.

  protected function rebuildFilteredArray() : void
        {
            var tmp:Array = [];
            for each ( var item:DataItemExample in model.myDataItems )
            {
                if( (! _onlyActiveItems ) || (item.active) )
                {
                    tmp.push(item);
                }
            }                        

            filteredDataItems = new ArrayCollection(tmp);

            if( sort )
            {
                filteredDataItems.sort = sort;
                filteredDataItems.refresh();
            }

            dispatchEvent(new Event(”dataItemsUpdated”) );
            dispatchEvent(new Event(”totalChanged”) );
        }

So now if we made an adapter it would start up, read in the source data model, and populate our internal array of items. But it wouldn’t respond to changes in the source data model. So lets create the event handler that we set up in the constructor. We’ll also create a couple helper methods

    protected function onItemsChanged(event:CollectionEvent):void
        {
            switch(event.kind)
            {
                case CollectionEventKind.ADD: addItems(event.items); break;
                case CollectionEventKind.REMOVE: removeItems(event.items); break;

                case CollectionEventKind.MOVE:
                case CollectionEventKind.REFRESH:
                case CollectionEventKind.REPLACE:
                case CollectionEventKind.RESET:    rebuildFilteredArray();
                                                break;

                case CollectionEventKind.UPDATE:  

            }

        }

        protected function addItems(items:Array):void
        {
            for each ( var item:DataItemExample in items )
            {
                if( (! _onlyActiveItems ) || (item.active) )
                {
                    filteredDataItems.addItem(item);
                }
            }
            dispatchEvent(new Event("totalChanged") );
        }

        protected function removeItems(items:Array):void
        {
            for each ( var item:DataItemExample in items )
            {
                var index:int = filteredDataItems.getItemIndex(item);
                if( index != -1 )
                {
                    filteredDataItems.removeItemAt(index);
                }
            }
            dispatchEvent(new Event("totalChanged") );
        }

For adding/removing items we’re going to our internal array and manually adding or removing items from it. We’re making sure to account for filtered items, but the sort object is taking care of the sorting for us.

For the other types of events, we’re kind of cheating. We only really care about adding / removing operations so we’ll just rebuild our entire internal array on other types of events. If your application uses those types of events often, you should implement them in the adapter in a more efficient manner.

Exposing data from the Adapter

We now have the internal state of the adapter updating as the model changes. So the only thing left to do in there is expose some properties so we can get at that info from our view. Let’s write two bindable getters. One of them will summarize the data (get total()) the other will give us our filtered list (get dataItems())

Note that we set the event=”" property in the [Bindable] tags so our views can correctly know when these properties change.

  [Bindable(event="dataItemsUpdated")]
        public function get dataItems() : ArrayCollection
        {
            return filteredDataItems;
        }

        [Bindable(event="totalChanged")]
        public function get total() : Number
        {
            var total:Number = 0;
            for each ( var item:DataItemExample in filteredDataItems )
            {
                total += item.amount;
            }    

            return total;
        }

Using the Adapter

Once you’ve done all of that, you can actually use your adapter. So create your data model, create your adapter, and use it!

 [Bindable] protected var dataModel:DataModelExample = new DataModelExample();
 [Bindable] protected var example1:AdapterExample = new AdapterExample( dataModel, true ,true);

    <mx:Panel x=”10” y=”218” width=”250” height=”200” layout=”absolute” title=”Filtered, Sorted>
        <mx:Label x=”10” y=”132” text=”Total:/>
        <mx:Label x=”56” y=”132” text=”{example1.total}/>
        <mx:List x=”10” y=”4” width=”210” height=”120” dataProvider=”{example1.dataItems}” labelField=”name></mx:List>
    </mx:Panel>

If you look at the source of the example, we actually create 4 adapters with varying options.

Beyond this basic example

If you want your adapter to respect changes to individual items, your items should implement the IPropertyChangeNotifier interface. So in our example if we edited an item so it’s active flag changed, the views would not update. To make that work we would implement that IPropertyChangeNotifier interface, and then write some code for the CollectionEventKind.UPDATE event.

Often times only one or two views are visible at a time and it’d be nice if all the views in the background weren’t madly updating themselves every change. To accomplish that I often write an enable() disable() method on the adapter. They usually look something like this:

protected function enable() : void

{

model.myDataItems.addEventListener(CollectionEvent.COLLECTION_CHANGE, onItemsChanged );

rebuildFilteredArray();

}

protected function disable() : void

{

model.myDataItems.removeEventListener(CollectionEvent.COLLECTION_CHANGE, onItemsChanged );

}

The Essential Guide to Open Source Flash Development

The book I’ve been working on, The Essential Guide to Open Source Flash Development, is now out in stores.  It’s hard to believe that I started working on it about 11 months ago!  It’s really great to see all of that hard work finally in print.

So What is it about?

The book does a few things.  First, about a third of the book introduces you to some open source tools for doing flash development.  Things like FlashDevelop, MTASC, SwfMill, ANT, and ASDT.  It’ll show you how to create an AS2 and an AS3 based flash application using completely free and open software.  This goes all the way from installing the tools, creating a sample app, writing up some unit tests for it, and then to publishing it to the web.  Along the way it’ll give you a brief introduction to each tool, explain what it does, and then give a quick example of how to use it.  (That’s the 5 chapters I wrote)

The remaining 2/3 of the book dedicates a chapter to various open source projects going into a little more detail about them.  There’s a chapter on Papervision 3D, SWX, FUSE/Go, HAXE, AMFPHP, two for Red5 and a couple more.

This was a lot of fun to work on, and my only regret is not getting to know the other authors better.

If you’re looking for a place to buy it, check out Bookpool.   I worked for them for a year and they’re really stellar guys.  They offer good prices, but more importantly;  as long as the book is in stock, they do their damndest to get it on a truck the day you order it. (Of course, you’re at the mercy of the publisher if it’s out of stock)

New Object Handles release

I just whipped up a new ObjectHandles release.  Couple notable things…

They now automatically remove themselves from the SelectionManager when removed from the stage (they add themselves back when added as well).  This fixes a fairly serious memory leak.

I’m deprecating the useage of the Handle class.  It draws the handles through the drawing API.  Now, instead use the ImageHandle class which draws the handles from an embedded image.  There was some wonky logic in there that turned clipping on or off depending on this setting and that was just plain dumb.  Lets just do it one way.  I included sample .png files to simulate the old look.

I fixed some weird flickering when resizing to the left or up.  It only happened on certain cases, and I’m not sure why.  I think it had to do with delayed execution of the Flex layout manager.  Now, I delay the setting of x,y,width, and height and force a validateNow() right after setting those.  Let me know if this causes any problems in your application.

I still don’t have conditional compile for Flex2/Flex3 in there, so this will only compile under Flex 3.  Does anyone know how to get that conditional compiling to detect Flex version without having to pass an extra compiler param?

 

Case Study: Three large Flex/AIR applications

I’m currently wrapping up three different fairly large AIR applications developed in different ways. In this blog post I hope to describe the methods used in them, what worked well, and what didn’t work so well.    Hopefully this will be useful to others starting up projects in the near future.

I’m going to call these “large” applications since they go a lot deeper than a simple toy or small experience site that most Flex apps seem to be.  Your definition of “large” may differ.  These are full blown desktop applications, not a web-app ported to the desktop or a simple desktop app to augment a web-app.  All three were planned on being desktop apps from the start.  It’s not a common target audience for AIR, but I believe in the platform for this use.

A description of the projects

First, a quick rundown of the apps.

AgileAgenda

This was my entry for the Adobe AIR Derby so the beginnings were a rapid no-holds barred get-something-out-the-door effort.  There was no good planning that went into this, and no framework used.  This is one of my solo projects.

It’s since gone through several major UI revisions, with some parts of the application completly changing how they work or look several times over.

It’s a project scheduling application focusing on allowing users to create a schedule by entering tasks, priorities, and durations while letting the software calculate start/end dates.  Besides that it’s got some nifty sharing functionality, a PDF export, and a few different ways to look at your data.  I’ve been selling it commercially for while and not doing too bad, take a look and let me know what you think.  I’m always interested in feedback.

 

 


 

AgileTracker

AgileAgenda was doing pretty good, and a time-tracking application to work with it seemed like the next logical step.  I had been looking around and found Parsley and was fairly impressed so I decided to give it a shot. This is also one of my solo projects.

The AgileTracker allows you to subscribe to a schedule in AgileAgenda to get your list of tasks.  Then you can use the built in timer, or manually enter time to keep track of how long you spend on various tasks.  Someday, it’ll have full read/write capabilities to AgileAgenda for a full round trip exchanging of data.

 

 


 

TimeLiner XE

This is probably where I learned the most.  I acted as the project lead on a 3-5 engineer team that grew or shrunk throughout the process depending on other needs.  It was developed in a commercial setting (at Tom Snyder Productions, my day-job, which I’ve been very fortunate to find)  We’ve got a formal art, engineering, and QA team over there.

TimeLiner XE is the 6th major revision of one of the best selling desktop applications my employer publishes.  Previous versions were written in C++ with a proprietary cross platform layer.  It was a big gamble betting on Flex/AIR instead of sticking with C++, but we’ve been pretty happy so far.  The built in WebKit HTML renderer made one of our features (a web based research mode) a “killer feature” and doing that in a cross platform way in C++ would have been a huge investment compared to what we accomplished in AIR fairly simply.

You can see a pre-recorded webcast seminar at the TimeLinerXE web page. http://www.tomsnyder.com/timelinerxe/
If you jump to about the 3 minute mark, that’s where they start actually showing off the software. 

 

 


 

Quick summary

App Name Info Framework
Agile Agenda ~ 25,000 Lines of Code             

1 Developer

First released on AIR Beta 1

None             

(Developed Quickly & AdHoc for the Adobe AIR Derby)

Agile Tracker ~ 8,000 Lines of Code             

1 Developer

First released on AIR 1.0

Parsley MVC + IoC
TimeLiner XE              

 

~ 100,000 Lines of Code             

3-5 Developers

1 Designer

Several QA engineers

Not yet released

Cairngorm

LoC numbers above are just to give an idea of the scope of the project and does not include code from libraries (either internally developed or open source).  There’s a similar coding style in all three, so it’s purely meant to give an idea of the relative size of the projects.  The AgileTracker is larger than listed, because it reused a bunch of code from AgileAgenda which isn’t reflected in those numbers.

 

 


 

 

Things we did right

QA / Bug Tracking

Tom Snyder has a first class QA team. Having them involved early in the project helped direct it to be a project that was easier to test, and of higher quality than might otherwise have been possible.  Having a dedicated and passionate QA team is the single best thing that can happen to any software project.  We’re using Bugzilla for tracking which works pretty well, but will be moving to HP’s Quality Center in the near future (which I hope works even better!)

On the AgileAgenda side of things, this wasn’t so great.  I’m looking to rectify that in the near future, but finding the right person (at the right price) is difficult.  Since it’s a simple 1-person project I’ve been using TaskPaper to keep track of my list of bugs, my list of future features, and my general todo list.  I’m currently looking for a good end-user bug reporting system, but haven’t found anything that really fits my needs yet.

Open Source!

All three applications use some very good open source projects.  Without these, the development would have taken a lot longer, and been a lot more labor intensive.  Two of the more important libraries were…

Object Handles (Open Source)

ObjectHandles is a library I wrote a while back that makes it easy to create interfaces that let the user drag and resize components around the screen.  It’s amazing how having a library like that can make you add that type of functionality into places where you may not have wanted to spend the time implementing without it.  Take a look at AgileAgenda’s Light Table.  The Light Table is one of the features I get the most positive feedback about.  It took an afternoon to implement with this libray.  Without it, it would likely have taken a week and would have never gone into the 1.0 version.  Almost the entire TimeLiner interface was build with this library.

AlivePDF (Open Source)

The printing in AgileAgenda is completly done with AlivePDF. This lets the usercreate a PDF to print, send to a colleague, post on a website, etc.   It’s amazing easy to use and creates high quality PDF’s.  (Yeah, AgileAgenda doesn’t deal with margins well right now, that’s my fault and not AlivePDF’s).  

Parsley (Open Source)

Parsley is great, unfortunately it was only used in the AgileTracker.  Using an IoC container for applications like these makes perfect sense, and the MVC infrastructure it provides makes it super easy to stick to the MVC model without being tempted to just have the UI muck around with your data.  The only frustrating thing I’ve found with it, is that it’s harder to debug a parsley based application when problems occur.

When you’re using Java/Spring on the server side, it’s also helpful to use a client side framework where you can think in the same way. 

Perforce

We use Perforce for the version control system for all the mentioned projects.  It rocks, hardcore.  Even for my single-developer projects I find myself more organized with less of chance for losing something important because of it.  Subversion, CVS, whatever other version control system you use is fine too, but just make sure to use one!

ANT

All three projects can be fully built through a single ANT command.  The release builds of all the projects are made in this way.  It doesn’t matter if a developer updates his build environment, or if your FlexBuilder license gets funky, you can always make a known-good build through a simple single command line. 

For AgileAgenda we actually end up making several builds (ready why), plus update the download page all automatically from the build script.  No more creating a release version from FlexBuilder, copying it to the web directory, using FTP to transfer it and editing a file to update the version on the website!

If you’re making release builds of your software from within Flex Builder, you really are missing out and wasting a lot of time.

CruiseControl (Continuos integration)

For TimeLiner we’re automatically running builds through CruiseControl after every single code checkin.  When you have between 3 and 5 developers, it’s very easy to submit code that builds for you but nobody else.  By using CruiseControl, whoever submits a change to perforce like that gets an email telling them within 10 minutes.  No more yelling “Who forgot to add SomeWeirdClass.as to version control?”

For a while we had it running our unit tests as well, but unfortunately we don’t anymore (see below).

We didn’t try to hire Flex developers

Well, we did try, and then gave up.  Flex Developers are hard to find.  Really hard.  Many people out there claiming to be a Flex Developer are really just coders and not software engineers.   Going into TimeLiner there was Me and one contractor that knew flex well.  Everyone else was either completely new to ActionScript or only had Flash experience.  But every single one of our developers was a good engineer.  Having smart people who can get things done (certainly not my original idea) was the best way to go, especially given the duration of the project.  Teaching an engineer flex is easy compared with teaching a flex coder to be a flex engineer.

I think a big part of the problem here (besides Flex being so new) is Adobe doesn’t really focus on the developer market all that much.  A lot of (non-flash/flex) developers out there still see Flash simply as a way to make annoying advertisements where you punch a monkey or watch a video of a kid setting himself on fire.  Adobe is really great to their developers, but I really wish they would go after those developers letting them know what most of us know, that Actionscript is a full featured application development language, and Flex provides a great set of components.  When do we get to see Kevin Lynch on stage shouting “DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS“?  Of course, I hope they never lose their designer focus, it’s what sets the platform apart.

Design / Artwork

Having a great design team on TimeLiner really made the project.  It looks amazing.  Unfortunately, I didn’t have the budget for that in AgileAgenda.  I ended up getting my design from three main sources.

1) An eager student in France was willing to do some of this for me.  Unfortunately as time went one his priorities changed and it was hard keeping that relationship going.  (You rock Olivier)

2) I bought a pack of icons from IconShock.  I don’t know how I lived without these.  Now, whenever I’m creating something new I can look through that library of images and pop on an icon that really spruces things up and maintains a consistent feel throughout the app.  Just imagine this, without any icons, booooring.

3) And lastly, I needed a logo.  For $150 I ran a contest on a logo design website and got my final design.  You can’t beat that price, and it’s better than anything I could have done myself.

It may not win any awards, but it looks pleasing enough and the process of creating it didn’t distract me too much from the development of the software.

 

Things we did wrong

Plan for modules

The biggest thing I learned is to plan for modules in large applications from the start.  At one point during the TimeLiner development we were approaching compile times of 2-3 minutes.  Making a 1-line change and then waiting for several minutes kills productivity.  We abstracted all of our styles, graphics, and sounds into modules and got that back down to a semi-reasonable compile time, but I think if we had properly planned for modules and broke the application up in a logical manner it would have been even better.

Printing (AlivePDF for screen grabs)

If you’ve been reading along, you might have noticed AlivePDF above and be suprised to see it listed here as well.  Well, it’s not a problem with the library, but a problem with how we chose to use it in TimeLiner.  We made the mistake of thinking we could take an on screen visual timeline, grab a screen scrape, and dump it into a PDF for all of the benefits mentioned above.  Turns out that the antialiasing of text looks horrible after you print one of these out.  It’s a problem with the difference in resolution from screen to print.  We wrote a lot of printing code targetted at AlivePDF and it turned out not to be high enough quality when we put those PDF’s on paper.  Luckily, at least 80% of that code was re-used to create a printing system using the normal Flash/Flex printing API.  So in TimeLiner, you can now use a file->export command to make a PDF using AlivePDF to get a PDF that looks great until you print it (and then it just looks “ok”) or you can use the File->Print command to get a great looking printout.  This lets people share it either in paper or digitally with decent results in both.

Using AlivePDF’s methods to add text does not have this type of problem.

Unit Tests

For a while we were running our unit tests as a part of the TimeLiner build, but AIR 1.0 broke our unit tests and we never found the time to go back and fix them.  I wish we had, because it would have prevented some bugs from going through the QA/Fix/Verify process and saved us some time.

Data Binding directly to the model

TimeLiner and AgileAgenda’s interface both used to bind directly to the data model.  That’s fine for smaller applications, but for things of this complexity they break down.  Try using AgileAgenda sometime, the interface feels sluggish.  That’s because I haven’t done anything about it over there yet.  But we did do something about it in TimeLiner. Instead of binding the user interface to the data model, we created intermediary “model adapters”.  These adapters act as delegates to the model and only pass on the events that cause binding updates when they’re active.  This makes it easy to “turn off” a big part of the UI in on central place.  It also makes it easy to present the model data in different formats so we can do things like summarize a table of data for a “totals” label right inside these.  Using these adapters, it’s easy to turn on or off access to the model to various parts of the UI without complicated logic in the UI iteself.  The work we did covered about half the binding that was in place and makes a noticeable difference.  Given more time, I’d convert the entire app over to data model adapters.

Cairngorm

Cairngorm is a great framework.  It’s a good implementation of the command pattern and does define a decent set of methodologies of doing things.  It suited TimeLiner well and hasn’t given us many problems.  It has certainly solved far more problems than it has caused.  The only reason I place it in the “things done wrong” category is I believe Parsley to be superior, I wish we had used it for all three projects.  Parsley solved all the problems that Cairngorm solved for us, but it also managed to solve a few more.

Also, Cairngorm needs an easier name to say and spell :)

Not using AIR distribution

For business reasons, we’re not using the AIR distribution model for TimeLiner.  It’s a shame that we have to ship a physical CD to our customers since keeping a .air file on a website somewhere is so much more cost effective. Making an installer, pressing CD’s, printing a user’s guide, and shipping all of that is just a pain and keeps the software away from the end user for an extra few weeks after the end of development.  Plus, it’s a whole lot harder to get program udpates out there.  (AgileAgenda does not suffer from this problem)

Problems with the tools

Disclaimer… I like Flex Builder.  It works well and gets the job done.  With Thermo focusing on the designer crowd and Flex Builder reportedly re-focusing on the developer, I think most of these problems will be worked out in future versions.

Eclipse/Flex Builder doesn’t do the “Run in background” thing very well and will constantly re-pop that compile progress dialog up.   Before going the module route, this absolutely killed TimeLiner.  Afterwards, it was still a constant annoyance.  Even with modules we might be interrupted, at seemingly random times, by the “Building workspace” dialog for 5-25 seconds.  If the little “stop” button would always work instantly, this wouldn’t be a problem.  But it doesn’t.  Turning off automatic compiling can help, but then you don’t get all the functionality of FlexBuilder.  When FDT gets decent MXML supprt, I’m going to seriously look into it.  In the past I’ve used it on AS2 projects and problems like this simply didn’t happen over there.

Coming from an Eclipse/JDT and an Eclipse/FDT world, FlexBuilder is missing a lot of functionality.  Snippets, decent code generation, and refactoring like “extract method” or “create delegate” would be very helpful.  From what I hear, with Thermo coming out, the FlexBuilder team will be focusing on developer-centric ideas like this which will be great.  If Adobe just made it easier for people to extend FlexBuilder, I’m sure those things would get written by the developer community.

The Flex compiler will sometimes, seemingly randomly, start throwing unknown variable errors in code completely unrelated to what we’re working on.  Doing a clean build doesn’t fix it.  Going in, editing the file where the “error” is found by deleting and re typing a character, and letting it rebuild seems to be the only solution.  I think this has to do with the Flex compile cache, but I haven’t had time to investigate it further.  It happens at least once a day to me.  

Much of the development was done with Beta versions of AIR and Flex Builder.  I underestimated the impact that would have on development.  Beta versions are buggy, and they do suck time out of your schedule.  Little things like installing new versions every few weeks, or crashing more often add up.  But I do think the benefit of using those vs. using the older stuff was worth it this time around.  Unfortunately, I don’t know if that would always be the case, and I don’t know how to judge that impact before a project starts.  I guess I’ll just tend to opt for released versions unless the project requires something in a beta version.

The future

I’ll be moving AgileAgenda over to Parsley bit by bit. Thinking about that framework, it should be pretty easy to move smaller pieces over that I might be working on without disrupting the bigger picture.  AgileAgenda will most likely be in light continuous development for years to come.

The AgileTracker will continue on as-is.  I’m very happy with how it works and flushing out the rest of the features and functionality is “all” that’s left :)

TimeLiner will stay a Cairngorm application.  Due to the way commercial educational software companies work it will probably go through cycles of being untouched for months, and then heavy development for a new release.   Those months of quiet and then bursts of activity will give us further insight on how easy it is to maintain a Cairngorm app.  Someday, I hope we do a web version of the software.

Conclusion

Overall, I believe Flex/AIR is the way to go for cross platform applications like these. I’ve done both Java and C++/QT cross platform apps, and neither of those was as easy to get working consistently accross platforms as AIR and Flex. 

So, if I were to start a new project today I’d probably go with the Parsley MVC + IoC approach.  I found it to be easy to work in and it solved more of my problems than the Cairngorm approach. 

If I could find experienced Flex engineers, I’d make my team out of them, but it wouldn’t be a must-have since I’m convinced any smart software engineer can pick this stuff up. 

I’ll be using the data model adapter “pattern” instead of direct binding for now on for anything except the most trivial of applications.  I’ll write a full blog post really explaining this sometime.

Modules will be planned from the start.  I think a lot more in all three applications could have been split into modules without any additional labor if we had just kept it in our minds from the beginning.

Disclaimer - I’m an employee of Tom Snyder Productions.  Anything said in this blog post should be considered solely my own opinion, and may not be representative of my employer.

 

ArrayCollection weirdness

I ran into a head-scratcher today…

How can this code:

var index:Number = rows.getItemIndex(partition.placeholderRow );trace( index + ” ” + (rows.getItemAt(0) === partition.placeholderRow ) );

give this output?

-1 true

rows is an ArrayCollection with one element. partition.placeholderRow exists and is a valid object. I haven’t mucked around with rows.source at all.

Answer follows in comment (so you don’t peek ahead and cheat!)

New ObjectHandles Build

I posted a new ObjectHandles build yesterday.  It fixes a couple bugs and integrates some patches people have sent me including:

1) Graphical handle support
2) Fixed aspect ratio support
3) Ability to detect transparency & clicks 
There will likely be another build in the next week to integrate another patch and fix a few a performance issue.

XML Facade instead of value objects?

I have a project I’m working on where it’d be great if older versions of the software preserved information in the XML file format that it didn’t understand. For example, imagine if Version 1 (V1) of the software had this for a file format:

<data>
<value>1</value>
</data>

Now imagine if V2 of the file added an attribute

<data>
<value type=”number”>1</value>
</data>

It’d be great if you opened that second file with the V1 software and then saved it again, it would preserve the stuff it didn’t understand. Unfortunately that’s not how I usually write my value objects. Usually I do something like:

public class ValueObject{public var value:Number;public static function fromXML( xml:XML ) : ValueObject{var v:ValueObject = new ValueObject();v.value = xml.value;}

public function toXML(  ) : XML{var xml:XML = <data>;xml.value = value;return xml;}}

As you can see, anything in the file that it doesn’t understand is lost. But what if we followed a facade pattern for our data objects and did something more like this:

public class ValueObject{protected var source:XML;

public static function fromXML( xml:XML ) : ValueObject{v.source = xml;}

public function toXML() : XML{return source;}

public function get value() : Number {return source.value;}public function set value(val:Number) : void {source.value = val;}}

They both have the exact same API, but the second one will preserve XML attributes (or even nodes) that it doesn’t understand.

What about AMF based projects, especially when passing rich objects with a Red5 server? I know there’s a pretty seamless mechanism in place if properties aren’t known, but how do you get those unknown properties back to the server?

What other solutions or best-practices do other people follow for solving this issue?

Slow Flex Builder compile and refresh solution - Modules

For the past month I’ve been plagued with up to three minute compile times on Flex Builder 3 Beta 2. I’ve also been plagued with long several minute waits of “Refresing bin/”.

Last week I solved the issue for one of my projects and prevented it from happening to another.

Apparently embedding graphics causes a performance hit in compiling, refreshing directories, and even just before launching. So if you have a hundred or so of these:

<mx:Button icon=”@Embed(…)” />

You’ll be in a world of pain. The easiest solution is to move those embed calls into your style sheet and then compile your style sheet as a module.

Here’s how to make a style sheet module:

1) Create a new MXML module (file->new->flex->MXML module)
2) Add your stylesheet reference to that.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Module xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”absolute” width=”0″ height=”0″
creationComplete=”trace(’iconsloaded’)”>
<mx:Style source=”style.css” />
</mx:Module>

3) Next, remove the reference to your style sheet from your main application.
4) Now, in your main MXML or AS file add some code to load your module.

protected var styleLoader:ModuleLoader;protected function init() : void{    styleLoader = new ModuleLoader();    styleLoader.addEventListener(ModuleEvent.READY, onModuleLoad );    styleLoader.addEventListener(ModuleEvent.ERROR, onModuleError );    styleLoader.url = “IconsModule.swf”;       styleLoader.loadModule();}protected function onModuleLoad( e:ModuleEvent ) : void{    maximize();    var mainApp:MainApplication = new MainApplication();    mainApp.percentHeight = 100;    mainApp.percentWidth = 100;    addChild(mainApp);   }

protected function onModuleError(e : ModuleEvent ) : void{    Alert.show(”Could not load module IconsModule.swf”,”Error”,Alert.OK );}

You can see there that I intialize my main application component after the module has loaded. I didn’t have to do this in a Flex app, but in my AIR app that component wouldn’t get all of the new styles if created before the module was loaded.

Option 2

Sometimes, it wasn’t practical for me to put the embedded graphic in a stylesheet. In those cases I:

1) Made an interface listing all the embedded graphics

public interface MyGraphicsModule{// Bindable tags are there purely to suppress warnings,// these properties never change after startup.[Bindable(event="moduleChanged")] function get addIcon() : Class;…}

2) Make a class that implements that interface and extends ModuleBase, also embed the graphics in there.

public class MyGraphics extends ModuleBase implements TimeLinerGraphicsModule{[Embed(source="/art/toolbars/add.png")]protected var _addIcon:Class;public function get addIcon() : Class { return _addIcon; }

…}

NEVER import or otherwise use this class into your application. The goal is to keep it completely separate.

3) Create a module manager class

public class MyModules{[Bindable] public static var graphics:MyGraphicsModule;}

4) Set MyGraphics to be a module that gets built in your Project->Properties->Flex Modules settings.

5) Load your module somewhere at startup

public function loadModules() : void{graphicsModuleLoader = new ModuleLoader();graphicsModuleLoader.addEventListener(ModuleEvent.READY, onModuleLoaded );graphicsModuleLoader.addEventListener(ModuleEvent.ERROR, onModuleLoadFailure );graphicsModuleLoader.url = “MyGraphics.swf”;graphicsModuleLoader.loadModule();}

protected function onModuleLoaded( event:ModuleEvent ) : void{if( event.target == graphicsModuleLoader ){var o:Object = event.module.factory.create();MyModules.graphics = event.module.factory.create() as MyGraphicsModule;}}

6) Find the spot in your code that used that icon and replace it

So this:

[Embed(source="/art/icons/addIcon.png")]public var addIcon:Class;

Would become this:

public var addIcon:Class = MyModules.graphics.addIcon;

This all seems like a pretty tedius job to do, but I ended up writing a perl script to scour the source tree, find all the references, and replace them for me. Unfortunately I did that script as part of my day-job and can’t share it with everyone right now. I’ll ask for permission on Monday.

The end result was we went from a 3.5 minute wait from saving a code change to executing the application to a 20 second wait. Not too shabby considering the size of the codebase we have.

SwfControls (Graphical Buttons and Popup Menus)

On Saturday I blogged about a new component I was working on and I got a few responses saying it looked really useful. So I threw up a project page and it’s available for download.

I’m calling it “swfControls” for now, but I’m hating the name the more I think of it. Any suggestions? At this point, I’m really considering bundling ALL of my controls together, maybe I should just do that to avoid naming them all.

http://rogue-development.com/swfControls.xml

Right now there’s just a binary SWC for download, I’ll get full source posted soon.

Enjoy!