Author Archive for seth

King of the LocalConnection

The Challenge:
Make a small mp3 player that's no more than a play button. Scatter many of these miniPlayers on a single web page. When one is clicked to play, the currently playing one needs to stop.

The Problem:
Multiple movies cannot be connected to a localConnection at one time. LocalConnection only allows for a one-to-one connection.

The Solution:
King of the Hill! Since only one swf can play at a time, then that swf becomes king of the hill. If another swf pushes him off, then the new swf takes over the localConnection.

Here's how it works:
First, notice that we're using a flashvar to pass in the reference to the mp3. In the downloadable code, there will be an index.html file which sets the flashvar using swfObject.

When the user clicks the playButton, the miniPlayer performs a localConnection.send() function and passes along it's uniqueId. The "King" of the connection will receive the call and if the uniqueId is not its own, he'll step down off the hill and close it's connection. The new King then calls localConnection.connect() and claims the localConnection throne. That's really the whole story.

Below is some sample code. The full code is here:


Setting Up FlexMonkey

FlexMonkey is a new tool to perform automated testing on your Flex applications. With it, you can record a set of interactions, save those commands into a TestCase class, add the TestCase to your TestSuite, and include it as part of a FlexUnit testing workflow.

Unit Testing and Test Driven Development is an encouraged agile method for reducing bugs. Up until now though, Unit Testing has been restricted to testing everything but the User Interface. Sure, we can easily test our functions, utility classes, etc. but the real challenge for the Flash/Flex community has been how to test actual interactivity. I believe that FlexMonkey is on its way to solving this. FlexMonkey incorporates the popular FlexUnit testing framework. Here are some good tutorials to learn more about FlexUnit: Adobe Flex Cookbook

The big question to ask yourself is if you're ready to change your work flow and start writing tests first. Those who practice and advocate TDD (FYI, I'm still learning) will tell you that it changes the way you approach writing code. By writing tests first, it forces you to determine necessary functionality upfront. Cleaner code leads to less bugs. The other huge benefit is that functionality is constantly being tested. If a new feature breaks existing functionality, you will be notified immediately rather than it going undetected until a user finds it.

Steps to set up FlexMonkey.
There are really very few steps to get FlexMonkey up and running.

  1. Download the latest swc, at the time of writing this its in version .5:
  2. Copy the FlexMonkeyUI.swc into your projects lib directory.
  3. Write your first TestCase class. I'm calling mine BaseTestCase and storing it in a test package.
  4. Add your compiler arguments. These are going to be unique to your system. You'll need to know where your Flex sdk folder is located in order to include the automation swcs. You'll also need to point to your FlexMonkeyUI.swc. The reason for these absolute references is because FlexMonkey does a Mixin to reference the BaseTestCase.-includes tests.BaseTestCase -include-libraries "/Applications/Adobe Flex Builder 3/sdks/3.2.0/frameworks/libs/automation_agent.swc" "/Applications/Adobe Flex Builder 3/sdks/3.2.0/frameworks/libs/automation.swc" "/Users/seth/Flex/tutorials/projects/flexMonkey/libs/FlexMonkeyUI.swc"
  5. Write your first test and run!

Click here to see an example (right-click on the example to download the code):

To make FlexMonkey run, click the FlexUnit Runner tab -> Run.

There are circumstances where you'll need to use these properties in your classes:

  • automationName: I've used this when there has been a scope conflict - two components with the same id. Even though they live in different classes, the automation only recognizes them by their name. To fix it, I've added their uid to their id name.
  • showInAutomationHierarchy: This has also helped with scope conflicts in a ViewStack.

Even though FlexMonkey is only at version .5, I'm already finding it to be a useful tool. When manually testing begins to feel like Groundhog day, its time to automate and make FlexMonkey work.


Seth’s 360|Flex Recap

Brian and Seth's trip to 360|Flex. (filler at the end shot this winter at A-Basin, CO)

My first 360|Flex was awesome. It was full of Flex rock stars. Not hard to imagine, I left knowing more than when I had arrived. The best part of the conference for me was participating in the charity Flex Code Jam where we built a Warm Meal Finder application. The app enables (not necessarily homeless) people to search by zipcode to retrieve a map and directions to locations of warm meals in the San Jose area. This app will run on the Second Harvest website as well as locations like libraries and perhaps as a kiosk.

Here's a quick recap of the sessions I attended.

Day 0 - Preconference:
Ribbit. Ribbit is awesome in that they're inspiring new ideas. Some of the new features for their 2.5 release include conference calling, call forwarding, and iTunes-like "app store" called Amphibian, which will allow Ribbit developers to sell apps.

Day 1
Following Adobe's keynote, I jumped in to learn about Merapi. Merapi is pretty cool. It's an AIR to Java bridge. It provides more access to low level hardware on a users machine. Their best example was an app that accessed a machine's accelerometer. It displayed graphics which tumbled to the tilt of the user's machine (see Adam Flater in my video above). Also cool was a bluetooth-controlled Legobot that was controlled by an AIR interface. This was presented by Jordon Snyder.

Mate framework. Laura Arguello's presentation was really well executed. Mate (pronounced like the Maté) uses an EventMap mxml class which provides a quick and easy hook for setting up services and handlers. Its tag based format promotes simplicity and good model/view separation. I'm still concerned with using it on larger projects but we did use it for the Flex Code Jam, and it worked well.Here's the Flex Code Jam code.

Creating reusable components. Ben Clinkenbeard is super smart and provided some good tips, though his presentation ended with about 45 minutes short. Some good tips: Make things easy for other developers. Expose things the framework doesn't. Add default behavior to your components, otherwise it makes more work for those using it. Default behavior can have a flag isDefaultPrevented flag to determine if default behavior was overwritten. He also recommended providing default styles and using selector.defaultFactory rather than selector.setStyle to set default style.

With my additional time from Ben's presentation, I jumped into the Swiz Framework presentation by Chris Scott. It is an inversion of Control MVC framework. I'm definitely curious and would really like to learn more.

I finished the first day of presentations by attending Andy Powell's introduction to Blaze and LCDS. It was a great overview of how Blaze and LCDS compare and contrast. It was also a good starting point for Brian's presentation the following day.

Following the presentation, I joined the Flex Code Jam project and kicked it off Scrumtastic style!

Day 2
Ben Stucki's How to Build a Framework presentation was inspiring. Where does he find the time to make so many useful frameworks? It wasn't a discussion about specific frameworks but rather tidbits of insight he's learned along the way.

"beautiful code represents an idea and the underlying logic exists only to support that idea..."

Stucki also provided simple reminders like a class should do one thing only. He defined simplicity as being achieved through refactoring in two common ways. Seperation - refactor one class into two, and Singularity - combining things together. Always start with interfaces and if you only reference interfaces, you'll come up with a pretty good architecture.

Then I caught SQLite Performance by H. Paul Robertson.
His knowledge on the subject was quite helpful. Here I learned that one should encapsulate sqlStatements instead of reusing them. ie, it's less expensive to store query statements in a Pool than to reuse and rewrite them - hope that makes sense. He also recommended using transactions for batch insert/update/delete - This takes a snapshot of your change and writes it into memory first. Then it sends the completed batch to SQLite. Use indexes but use them wisely. Additional resources he provided include: - uses a vo. Jacob Wright's active-record: and - which uses pools.

Finally, I attended Brian's presentation on Real Time, Collaborative applications. My opinion may be biased, but he did a stellar job. He kept it interesting by showing real world examples, which I think really helped people understand what one can do with a real time application. Examples of projects built on both LCDS and Blaze DS were shown. He also showed a good tour of server side Java code as well as front end Flex code. Go and watch his presentation on Adobe Media Player.

Day 2 didn't end there though. Actually it never really ended. Not long after Brian's presentation we were back in the Flex Code Jam. We had a good Scrum and basically started coding...until 4am. It was good fun, working with new people and apparently Adobe is making a documentary about it!

Day 3, or rather, after three hours of sleep, we were back at eBay for the final keynote. Tom and John announced conference numbers, and revealed that they finally made profit, congrats! A few silly chachkes gifts to each other later, and then they brought Ali, the organizer of Flex Code Jam, to the stage. Ali, who I don't think slept at all, presented our application with great pleasure to one of the Directors from San Jose area's Second Harvest. The app was flawless, and it honestly was a feel-good moment.

Following keynote, I attended one of the best presentations, in my opinion, Renaun Erickson's presentation on Test Driven Development. We've been looking for a good solution to unit test for Flex, his RIALogger could be the one. It seemed simple and easy to understand. I learned that TDD is more of a work philosophy than just a tool by requiring you to write your tests before writing code, it forces you to think in terms of usage rather than methods. Now I just need to start doing it. :)

I then attended Jun Heider's presentation on the Flex 3 profiler. The profiler is something I also need to use more of. Although my own concentration was diminishing from sleep deprivation, Jun showed the important parts of using the profiler to test performance and memory usage.

Following a nap next to eBay's koi pond, I finished 360|Flex by listening to Eric Ko discuss reflective programming. Honestly, I saw what he was doing, but I couldn't understand it's real world use.

So that's it. If you read this far, thanks! Now get back to work!


SQLite with AIR tutorial, conquer the DB.

Not uncommon for Flex super heros like ourselves, we haven't needed to occupy our time with the smaller details of web development. Databases you ask? That's the job for our side kick, backend dude. We've got interactivity and usability to deal with. But when Adobe Air arrived in our tool-belt, we had no choice but to suck it up and learn...SQL statements! Here' a tutorial on how to create a to-do list with AIR.

What we're going to build is a basic item list that looks like this:

Or if you just want the Air application, click here:

Please upgrade your Flash Player This is the content that would be shown if the user does not have Flash Player 9.0.115 or higher installed.

Stuff you will need:

  • The complete code

  • You'll want a SQLite Browser
  • I recommend downloading a SQLite browser which will enable you to see and test your database. There are two that I know of:
    Firefox plugin
    And SQLite-Admin-for-Air, developed in Air.

    I do prefer and recommend the Firefox plugin. It has a Browse & Search functionality making it easier to display rows in a table. In contrast Admin-for-Air is less robust and will be harder to use for beginners. For example in order to browse a table, you write your own query (eg.: select * from myTable). Not hard, but intimidating for newbies.

Item List Tutorial

Opening the Database

The first thing we want our Application to do is open a SQLConnection with a database file.

If the file doesn't exist yet, it will be created with the name you specify. Otherwise if you have already run the application before, it will open the existing file.

  • Where is the .db file stored?
  • The recommended location to store the .db file is in your Application's storage directory. Its important to know where this location is on your local machine. We will be using it to point your SQLite browser to this file.

    On a Mac:
    /Users/yourname/Library/Preferences/applicationName/Local Store/file.db

    On a PC:
    C:\Documents_and_Settings\username\Application Data\yourAirAppName\Local Store\test.db

    If you're having trouble finding the file, or for testing purposes, try storing the file on your desktop by changing the resolvePath call to:

Asynchronous vs Synchronous connection

You might have wondered about this line:
Air gives your application two options to connect to SQLite.

Asychnronous means that your code will have an event listener on the SQLConnection and an event handler for the response.

Synchronous means that your application will make an "inline" call to SQLite where it performs the operation and then moves on as if it were any other line of actionscript code.

Synchronous uses less lines of code, but could potentially stall your application if its trying to process a large dataset. Asynchronous on the other hand will allow your application to continue running and SQLite will return operations when it has completed them.

For example compare the two trace statements below:


*Note: the sample app for this tutorial is using the asynchronous method.Also here's what Adobe labs has to say.

Create a New Table

If one doesn't exist, the sql text will look like this:

(Don't forget, to see all the code checkout the project with SVN here)

Note on SQL statements for the unfamiliar:

Think of an SQLStatement as a string with directions on what you want SQLite to do. Air Documentation provides a list of supported SQL syntax. Most of this is useful for someone familiar with SQLite, but admittedly, I'm not one of those people. Below, I've written basic SQLStatements that get the job done.

If you need help, hopefully you have a backend dude to refer to. If he or she have questions about what SQLite supports, refer them to the link :P Otherwise, feel free to post a question in our comments.

Insert an Item Into our table

Our SQLStatement looks like this:

Note the ? mark in the INSERT statement. This is a sqlStatement parameter.
Parameters are used to allow for typed substitution of values that are unknown at the time the SQL statement is constructed.
In this case it is our Date so that we can record when this item was added.

To read everything in your Table

You use the SELECT Command:

The listener then gets the results by calling the getResult() static method. This method returns a SQLResult object. The results are included in the data property.

When we add an item, we will also want to display it in our DataGrid. Although the new item isn't returned with the SqlResult, a rowID is. The rowID is the Primary Key we set when creating the Table. If you don't set a Primary Key or have multiple Primary Keys, Sqlite will create a rowID behind the scenes which relates to the affected row. With the rowID we can then make another SELECT call like so:

-execute(1) is a bit redundant but I'm using it show that if you want to control the number of rows returned, this is how it's done.

You're done

I recommend diving into the project and opening my SimpleConnection class. Run it along side your Sqlite browser and watch it go.

Congratulations Flashy Super hero, you are on your way to defeating the Mad SQLite Golem. I'd also like to thank John, our trusty Java-dude, without whom I would have never been able to write these SQL statements, as basic as they are.

Where to go next:

  • Ok, I've shown you how to Read and Create. How about Delete?
  • Look into Wrapper classes. I've tested a couple. Peter Elst has a nice blog post. I've also had limited success but am curious about the Air Active-Record code.

Feel free to comment with questions. Thanks!


slice 9 my as*

Workaround hack for slice 9 not scaling.

Problem: Your designer hands you a .fla with a movieclip that has a proper linkage name. You want to use it as a custom backgroundImage for a VBox. You set the backgroundScale="100%," everything is written perfectly in your Flex code yet the Slice 9 symbol is still NOT SCALING.

Solution: Most likely the symbol is a png or a movieclip. In order for it to properly scale, you must break apart the png or clip first. THEN, you must separate each slice-9'ed piece. I cut and paste each piece into separate layers for cleanliness. Recompile and you should be golden.

Download the example: slice9example.fla

As you can see below, the difference is between a scaled graphic which looks tight and the same one which looks like an obvious mess.
[kml_flashembed movie="" height="500" width="400" /]