This blog isn't maintained anymore. Check out my current project, an agile/scrum management tool.

Monday, March 24, 2008

AIR / Browser API example

AIR / Browser API example

The other day I blogged about a wrapper class that I wrote to handle the AIR / Browser integration API.  Below is an example of another class that I wrote that uses that wrapper class.  It's capable of detecting two different AIR applications, installing them, and running them.  It relies on the wrapper class to do all the heavy lifting, but I thought this might be a good example to help people get started.

package com.agileagenda.web
{

import com.roguedevelopment.air.AIRBrowserRuntime;

import com.roguedevelopment.air.AIRBrowserRuntimeEvent;

import flash.events.IOErrorEvent;

public class InstalledApplications

{

public static function get instance() : InstalledApplications

{

if( _instance == null ) { _instance = new InstalledApplications(); }

return _instance;

}

protected static var _instance:InstalledApplications = null;

protected var api:AIRBrowserRuntime;  

protected static const PUBLISHER_ID:String = "F49A4D8DF78A1FEE7A3BE440DC11BAB18D922274.1";

protected static const TRACKER_ID:String =  "com.agileagenda.AgileTracker";

protected static const MAIN_APP_ID:String = "com.agileagenda.AgileAgenda";


protected static const AGILE_AGENDA_INSTALL:String =  "http://www.agileagenda.com/download/AgileAgenda.air";

protected static const AGILE_TRACKER_INSTALL:String = "http://www.agileagenda.com/download/AgileTracker.air";


[Bindablepublic var isReady:Boolean=false;

[Bindablepublic var hasAIR:Boolean;

[Bindablepublic var agileAgendaVersion:String = "";

[Bindablepublic var agileTrackerVersion:String = "";

public function InstalledApplications()

{

  api = new AIRBrowserRuntime();

  api.addEventListener(AIRBrowserRuntimeEvent.READY, onReady );

  api.addEventListener(IOErrorEvent.IO_ERROR, onAirFail );

  api.load();

}


protected function onAirFail(event:IOErrorEvent) : void

{

  trace( event.text );

}

protected function onReady(event:AIRBrowserRuntimeEvent ) : void

{

  hasAIR = api.getStatus() == 'installed';

  isReady = true;

  api.addEventListener(AIRBrowserRuntimeEvent.APP_VERSION_RESULT, onTrackerVersionResult );

  api.getApplicationVersion( TRACKER_ID, PUBLISHER_ID );

}

protected function onTrackerVersionResult(event:AIRBrowserRuntimeEvent) : void

{

  trace("Tracker version installed: " + event.detectedVersion );

  agileTrackerVersion = event.detectedVersion

  api.removeEventListener(AIRBrowserRuntimeEvent.APP_VERSION_RESULT, onTrackerVersionResult );

  api.addEventListener(AIRBrowserRuntimeEvent.APP_VERSION_RESULT, onAppVersionResult );

  api.getApplicationVersion( MAIN_APP_ID, PUBLISHER_ID );

}

protected function onAppVersionResult(event:AIRBrowserRuntimeEvent ) : void

{

  trace("Application version installed: " + event.detectedVersion );

  agileAgendaVersion  = event.detectedVersion

  api.removeEventListener(AIRBrowserRuntimeEvent.APP_VERSION_RESULT, onAppVersionResult );

}

public function launchAgileAgenda( args:Array ) : void

{

  api.launchApplication( MAIN_APP_ID, PUBLISHER_ID, args );

}


public function launchAgileTracker( args:Array ) : void

{

  api.launchApplication( TRACKER_ID, PUBLISHER_ID, args );

}

public function installAgileAgenda(args:Array) : void

{

  api.installApplication(AGILE_AGENDA_INSTALL, "1.0", args );

}


public function installAgileTracker(args:Array) : void

{

  api.installApplication(AGILE_TRACKER_INSTALL, "1.0", args );

}


}

}

Labels: ,

Sunday, March 23, 2008

Interacting with an AIR app from a browser based app

Interacting with an AIR app from a browser based app
We've all seen the AIR installation badges that let you install an AIR application from a website. But the API exposed to do that lets you do more than just a simple badge. I've been working on a web-based service for AgileAgenda. One of the components of that is to manage the list of files you've saved to the service and be able to open those in the desktop AIR application. So right from within the online Flex based app it sure would be nice to detect if the application is installed, give the user the option to install, and then launch it for them and automatically open the desired file. Something like this...
To implement that we need to:
  1. Detect whether or not the application is installed.
  2. Display the version number if it is. (Disable the "Open schedule in..." button if it's not)
  3. When clicking on the "Open" link, launch the application with a few parameters so it know what to open.
  4. When clicking on the "Install" link, install the application and pass a few parameters so it know what to open when it launches directly after the install.
Doing things like that falls outside of the normal AS3 web development API. But Adobe provides a swf that you can load at runtime and them make calls to. You can read all about that over here: http://livedocs.adobe.com/air/1/devappshtml/help.html?content=distributing_apps_3.html.
But there's an annoying thing with that. You need to load up that remote swf and then access it like a dynamic object. No compiler-time type checking. Not the standard event mechanism. And no code-completion from within Flex Builder.
Luckily for you, I went through and made a wrapper class that you can download from here:
This will handle the loading of the remote swf, dispatching events when it loads (or fails to load) and then wraps the API for the entire process. There's nothing revolutionary in there, it's mostly takendirectly from that livedocs page above.
So now that you have that handy-dandy wrapper class, lets look at how to actually get something done.
Setting up your AIR application to work with your website (Important)
First thing, go into your AIR application's -app.xml file and make sure allowBrowserInvocation is set to true. By default it's set to false.

<allowBrowserInvocation>true</allowBrowserInvocation>

If you don't do this, you won't even be able to query version information on your application. But, be careful. By doing this you're letting any website launch your AIR application from a web page. You need to be careful in how much your app trusts command line arguments passed to it. For instance, you should never pass a file to delete on the command line.

Now that you've set allowBrowserInvocation to true, create a new .air file and post that to your website somewhere.

Using the wrapper class to interact with your application

Either open an existing Flex or Actionscript project in FlexBuilder and put the source to the AIRBrowserRuntime.as somewhere that the compiler will find it. Somewhere in your main application, create an AIRBrowserRuntime object, set some event listeners, and call the load() method to load the air.swf file from Adobe's servers.

var api:AIRBrowserRuntime;

...

api = new AIRBrowserRuntime();

api.addEventListener(AIRBrowserRuntimeEvent.READY, onReady );

// Optional: api.addEventListener(IOErrorEvent.IO_ERROR, onAirFail );

api.load();

Once the READY event is dispatched, you can start calling methods to query application versions, install apps, or launch applications.

Checking if AIR is installed

To see if the AIR runtime is installed, call the getStatus() method. It will return one of three values.

available - The AIR runtime can be installed on this computer but currently it is not installed

unavailable - The AIR runtime cannot be installed on this computer.

installed - The AIR runtime is installed on this computer.

Example:

switch( api.getStatus() )

{

case "available": trace("AIR is available, but not installed."); break;

case "unavailable": trace("AIR is not available for this computer."); break;

case "installed": trace("AIR is already installed on this computer."); break;

}

Checking the version of an installed application

The getApplicationVersion method will check to see if a given application is installed and give you the version if it is. This method operates asynchronously so you have to create an event listener before you call it. If you look at the method signature...

public function getApplicationVersion(applicationID:String, publisherID:String) : void

You'll see that it takes an applicationID and a publisherID. The applicationID is just value of the <id> tag of your application descriptor (the -app.xml file). It'll probably be something like this, but you need to make sure to make each application unique:

<id>com.agileagenda.AgileTracker</id>

The publisherID is a little trickier to find. That doesn't get assigned until you actually sign your .AIR file with your code-signing key. I know of 2 ways of finding it, but there's probably an easier way (please leave a comment if you know how).

Warning about Publisher ID:  If you change the key your sign your app with, the publisher ID will change.

Option 1: Get it at runtime.

In your application's main MXML throw up an Alert message with the publisher ID. Then build a .air, install the .air and run it. Copy & Paste the result.  Example:

<?xml version="1.0" encoding="utf-8"?>

<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"

    creationComplete="init()" >

  <mx:Script>

  <![CDATA[

    protected function init() : void 

    {

      Alert.show( nativeApplication.publisherID);

    }

  ]]>

  </mx:Script>

</mx:WindowedApplication>

Which results in something resembling:

It's hard to see in that picture, but the publisher ID is: F49A4D8DF78A1FEE7A3BE440DC11BAB18D922274.1 as it wraps to two lines.
Option 2: Get it after install
This is probably a bit easier, but I'm not 100% sure where this directory goes on a windows box.
On OSX (maybe on Windows, I'm not sure exactly where) the application storage directory that gets created for your application has the publisher ID appended to it. So if you look in your user directory -> Library -> Preferences, you should see a directory that starts with your application ID and ends with your publisher ID.
As you can see there, we get the same publisher ID value as Option #1.
On to checking installed version
Now that you have your application ID and your publisher ID you can make a call from your web application to the API to request the installed version of your AIR application.  This operates asynchronously so you'll need an event listener for the result.
Example:

api.addEventListener(AIRBrowserRuntimeEvent.APP_VERSION_RESULT, onTrackerVersionResult );

api.getApplicationVersion( "com.agileagenda.AgileTracker", "F49A4D8DF78A1FEE7A3BE440DC11BAB18D922274.1" );

...

protected function onTrackerVersionResult(event:AIRBrowserRuntimeEvent) : void

{

trace("Tracker version installed: " + event.detectedVersion );

}

The event.detectedVersion that comes back will be the value in your application descriptor version tag.  Mine looks like this:

<version>v1</version>

So the trace output looks like this:


Tracker version installed: v1

Launching an installed AIR application

Assuming you followed along in the previous section, you have an Application ID and a Publisher ID ready. To launch an AIR app from a web app you just call

api.launchApplication( "com.agileagenda.AgileTracker", "F49A4D8DF78A1FEE7A3BE440DC11BAB18D922274.1" );

launchApplication has a third, optional, parameter called arguments and is typed as an array. Anything you pass into that will be passed along to the application in an INVOKE event. This way you can pass information from the web application to the AIR application. Example:
api.launchApplication( "com.agileagenda.AgileTracker", "F49A4D8DF78A1FEE7A3BE440DC11BAB18D922274.1", ["Argument1","Argument2" ] );
Be careful, the arguments are very restrictive in what characters can be passed. Things like dashes, percent signs, underscores, all cause a runtime exception on the web application. You're probably safest only using alphanumeric characters. I haven't found a comprehensive list of what characters are or are not valid. If someone has that, please leave a comment below.  This was done for security reasons.
Installing an AIR application
To install an AIR application, all you need to do is call the installApplication with the absolute URL to the .air file you want to install. Example:
api.installApplication("http://www.agileagenda.com/download/AgileTracker.air");

This will take care of installing the AIR runtime, installing the application, and launching it for the first time. installApplication has two more optional parameters. The AIR runtime that the application requires, and arguments that can be passed to the application for it's first run. Example:

api.installApplication("http://www.agileagenda.com/download/AgileTracker.air","1.0",["Arg1","Arg2"]);
That's all there is to it.
So that's it, pretty simple, huh? You might also want to look into using a LocalConnection to do realtime communication between your web-app and your air-app once the air-app has been launched. Recap of the links:
Wrapper Class:
Adobe's Documentation:
My Blog (where any updates to the wrapper class will be posted)
The actual air.swf that does all the heavy lifting (This URL is wrong in some of the docs!)

http://airdownload.adobe.com/air/browserapi/air.swf


Labels: ,

Saturday, March 22, 2008

ObjectHandles Demo

Here's a short demo of some of the stuff that ObjectHandles (my Flex library for moving & resizing stuff) can do with a very minimal amount of code.  



The custom things I did:
  • Has a MOVING / RESIZING event handler to show a custom tooltip (hides the tooltip on MOVED / RESIZED)
  • Has custom resize handle images that look like grey horizontal bars
  • Only allows vertical resizing (allowHResize = false).
  • On a MOVED event, the objects have an animation that snaps them to a column.
It's a little hard to see in that video, but the duration & start time in the tooltip update as you move or resize the boxes around.

Labels: ,

Boston Flex Users Group

I saw this posted today by Joe Berkovitz and it made my day.  There's a new Flex users' group starting up and the best part, it's in Newton which is a few short miles from where I work.

http://www.bostonfug.org/


Labels:

Monday, March 17, 2008

The power of RSS

A year ago I didn't read any RSS feed. I browsed the internet like it was meant to be browsed, through websites! I read 3, maybe 4, sites daily. I occasionally viewed another dozen less frequently.



A year ago I started to add sites to my "web clips" bar on the top of my GMail account. They were all development related sites, mostly flash/flex. Pretty soon I had a dozen or so and I found myself clicking that little ">" button on the webclips bar over and over and over again to see more and more and more.



Six months ago I switched to Google Reader. I copied my list of RSS feeds from web-clips. And I added a few more. This was great, way easier reading them from the webclips interface. I subscribed to my Bugzilla bug list at work, no more refreshing a page to get a list.  I unsubscribed from a few mailing lists I was a part of and picked up their feeds.

I now had a single, central, place to go to look for news items about software development.

A month or two after that I started adding feeds for other topics besides development. Project management, web comics, even a blog from a guy making art out of bent objects.

It's around that time that the RSS reader became my first destination when browsing the web for any reason. I wouldn't hit slashdot, or cnn, or whatever. I'd hit my RSS feeds. I'd be able to quickly browse over more content, in nice neat categories, than I ever could before.

Now, I have two main jumping points for the web. 1) Google when I'm searching for a specific thing. 2) My RSS reader for everything else.

So when I go to a website that I might want to remember in the future, I don't instinctively go for that add-bookmark button. I look for the little "RSS" icon.

I think more and more people are ending up like this. I was certainly a late-comer to the world of RSS in the group of "geeks", but I wonder if we'll hit a point like the www hit when only geeks used a web browser, to everyone using a web browser.

I ran a survey for AgileAgenda on what features people are interested in seeing in future versions. Out of curiosity I put in "Subscribe to schedules through an RSS feed." Amazingly, that was the only option with near 100% "yes" votes. I didn't even know what that means. I've talked to a few people and they all thought it was a great idea, but then I pressed on why.  Nobody seemed to quite know what type of data those feeds should have in them.  

It feels like the time we hit a few years back when "everything" has to be on the web. But now it's "everything" has to be in an RSS feed. When deciding to put things in an RSS feed, I hope our web-lessons help and we can tell between what is an Amazon.com idea, or a Pets.com idea.

If you're writing Flex/Flash code to parse out RSS feeds, you should check out:
It handles the differences between the various RSS/Atom formats for you.

p.s. I've since come up with a plan for RSS based schedules, but don't want to spoil the surprise before it's ready.  It's going to rock.

Labels:

Custom Cursors + Multiple Windows

Quick tip.  Don't use CursorManager.setCursor anymore.  It works fine for single-window flex apps, but breaks once you have an AIR app with multiple windows.

UIComponent now has a cursorManager property that references the cursor manager for the current window.  If you use that it'll work all the time, not just in web Flex apps.

I understand why they left CursorManager in there for backwards compatibility, but it's a shame we can't mark it as @deprecated like in the Java world.

Labels:

Saturday, March 15, 2008

Flex-Spreadsheet update

Fixed a few bugs, and made a couple improvements on the Flex-Spreadsheet component today.  This fixes most of the flickering problems when using the scroll wheel.  It also addresses some placement issues with item editors when the user did "funky" things with changing focus.

View the project page, or download the latest version of AgileAgenda to see it in action.

Friday, March 14, 2008

Degrafa + ObjectHandles

Here's a neat little experiment I did with combining Degrafa  and ObjectHandles.  (View-source is enabled for the example.)

It lets you move and resize shapes drawn with Degrafa by using the ObjectHandles stuff.  It was amazingly simple to make this work, essentially just something like:


<oh:ObjectHandle id="myHandle">
  <degrafa:Surface left="0" top="0">                                  
  <degrafa:fills>             
    <degrafa:SolidFill id="aqua" colorKey="aqua"/>                     
  </degrafa:fills>                  
  <degrafa:GeometryGroup>             
    <degrafa:Elipse width="{myHandle.width}" height="{myHandle.height}}" fill="{aqua}" radius="20"/>                    
  </degrafa:GeometryGroup>              
</degrafa:Surface>
</oh:ObjectHandle>


I bet it'd be amazingly simple to make some sort of impressive drawing or charting application with this.

Flex-Spreadsheet first release

The first public release of my Flex spreadsheet component is now available from Google Code.  This component is very similar to the Flex datagrid with a few notable distinctions:  
  • It's designed for extensibility, not for speed or ease of use.
    • Item Renderers or Item Editors can implement a custom interface to get more information and control over the spreadsheet they're in.
      • They get more data about the spreadsheet.
      • They can dispatch a variety of events to cause the spreadsheet to do things
      • Editors don't neccessarily need to be confined to the size of the
  • It's designed primarily for data-input, not data-display
    • The spreadsheet can have a "placeholder" row.  
      • This row is created by the spreadsheet and is only inserted into the underlying data model when it's "valid".  
      • You can specify a class factory for creating these, and a custom validator class to determine when a row is or is not valid. 
      • Visually, it's slightly greyed out.
  • Keyboard navigation is sane
    • Tabbing between cells
    • Using the arrows between cells.
    • Using the arrows within while editing a cell 
    • Hitting enter submits an entire row.
    • Leaving a cell submits that cell
    • Build-in support for auto completion of cells with sane keyboard navigation of the auto-complete
    • Hitting escape cancels a cell-edit
I originally wrote this for AgileAgenda, recently we began using it for another project at my day-job.  Seeing how it was general enough for that, I thought it might be worth sharing for comments / suggestions / etc.
This component is not ready for general-use.  If you want to try it out expect:
  • It's not well documented.
  • There are bugs
  • For large data sets (300+ rows) it's slow
    • I do have several specific plans for greatly improving this, but I like to optimize last.  You never know when feature changes can really affect performance.
  • The partitioning feature will be completely re-written, don't play with it yet.
  • You will have questions.  I don't have time to answer them right now.
  • Many of the features (like sorting) have only been implemented enough to support my current projects and are not general enough to support every need yet.
So why am I posting this now?  I'm looking for feedback.  What works well, what doesn't.  What other things might you need to use it in your projects?
Getting started:
Grab the source and look at Main.mxml, it has a moderately commented example of using the component.  Also, Spreadsheet.as has a few comments in it that may be useful.
If you want to test out a sample, go here:
Eventually, more information about the project will be at that URL.

Labels:

Thursday, March 13, 2008

Kasai

I've been looking for an open source user management system to build project upon. Someone pointed out Kasai to me a while back and I took a quick look. It' seemed to be about 1/2 of what I wanted.

But I just took a more in-depth look at the docs and it might actually be much closer to what I was hoping to find. It looks promising. Hopefully I'll be able to give it a try sometime soon and see how far it gets me.

http://kasai.manentiasoftware.com/

Sunday, March 09, 2008

Timezone freakiness

Just solved a mind-boggling problem I was having with some date manipulation.


The Date constructor returns a date with a different timezone depending on whether the date is today & before, or in the future.


var today:Date = new Date();

var yesterday:Date = new Date( today.fullYear, today.month, today.date - 1 );

var today2:Date =    new Date( today.fullYear, today.month, today.date     );

var tomorrow:Date =  new Date( today.fullYear, today.month, today.date + 1 );

trace( yesterday.timezoneOffset );

trace( today2.timezoneOffset );

trace( tomorrow.timezoneOffset );


Traces output:

300

300

240


What's worse if you then subtract a day from "tomorrow" it doesn't equal today.


tomorrow.date--;

trace( tomorrow.time == today.time );

trace( tomorrow == today );


Output: false / false


Guess why?


Today's daylight savings switchover day.  Arghhh.


I really wish Actionscript had a date-only type.

Saturday, March 08, 2008

New pulse particle build posted

A new version of Pulse Particles has been released.

This one has one new feature.  If you create a MovieClip for your particle, there's a new rule which will randomly pick a frame in that MovieClip to use.

From the particle explorer, you just have to check off the box on the "intial" tab to get this functionality.


This lets you create a single effect with multiple particles very easily.

If you were using animated particles you could still do that by placing an animated movie clip on each frame of the main particle's movie clip.  Or don't check that box off and nothing changes.

Thursday, March 06, 2008

OSF Book on Amazon

I've been working with a few other (much more well known) authors on an open source flash book and it just hit Amazon for preorders. Neat stuff!

http://www.amazon.com/Essential-Guide-Source-Flash-Development/dp/1430209933/ref=sr_1_1?ie=UTF8&s=books&qid=1204814390&sr=8-1

Check it out :) Too bad they spelled my name wrong.

-Marc

Wednesday, March 05, 2008

Any open source user management/subscription systems?

A while back I probed around to see if there are any open source user management systems out there and didn't come up with any great leads.

Weird thing, at my day-job, yesterday, the general manager asked me the same question.  Clearly there is a need for something like this.

My original list of requirements went something like this:

  • Allowing users to sign up (email verification, catpcha support, configurable list of user details to require)
  • Assign various access levels (or attributes?) to users.
  • Allow users to log in / log out 
  • Detect multiple failed logins for a user or from a source host with configurable temporary lockouts
  • Provide a simple API to use in applications that build upon it to get login status & access level (preferably language-agnostic)
  • Mechanism for retrieval of forgotten passwords (email? security question(s)?, combination?)
  • Provide a simple html based UI to handle all of these functions (including administrative functions like approving, disabling, changing access, etc.).
  • Provide an XML-RPC based interface to perform all of the functions so it's easily customizable by application that build upon it.
A new requirement that this request brought up was:
  • Support for paid subscriptions
So here's another blog post, and I'll go hit up the OSFlash mailing list to see if anything comes up.

PS


Ever see something that's just screaming to be run through photoshop?  I just couldn't help myself this morning.

Sunday, March 02, 2008

Detecting whether running in ADL vs. installed AIR

I noticed something while implementing the solution I talked about yesterday for dealing with self-signed vs. CA signed AIR apps.

The publisherId field is a blank string when running from within ADL.  It's an easy way to detect an installed AIR version vs. a version running within the debugger or just directly using ADL.  

I haven't really needed it so I haven't searched the docs.  There might be an explicit way to detect that scenario in the AIR api (feel free to comment and point it out), but if not and you need it, there you go.

Saturday, March 01, 2008

Self signed vs. CA signed AIR apps

I got my official Thawte code-signing certificate this week.  It turns out you can't upgrade an application from a self-signed to a CA-signed version in AIR.  If you have the same problem you might be interested in the solution I'm going to use.

First, here's my goals:

  1. Migrate people to the new CA signed version
  2. Don't force most people with the Self-Signed version to upgrade immediately
  3. Keep both self and CA signed versions up to date (for a limited amount of time)


I'll be moving the website download to the signed version 
  • New people will get the signed version.
  • Existing users who go to the website to upgrade will be told they can't install it.  Those people will have to manually uninstall their version, and install the new signed version.

I have an auto-upgrade option in the software.  Most people use this to upgrade.  Previous versions checked a file called appUpdate.xml to see if there was an available update.  I'll start publishing two versions of that file.
  • appUpdate.xml - This will continue to point to the self-signed version
  • signedAppUpdate.xml - This will point to the new CA-signed version
In my application, I'll add code to determine which of those to choose.  Luckily, the nativeApplication.publisherID variable will be different depending on how the AIR app was signed.

if( nativeApplication.publisherID == "MY_SIGNED_PUBLISHER_ID" )

{

// This is our officially signed version

appUpdater.updateURL = "http://www.agileagenda.com/download/signedAppUpdate.xml";

}

else

{

// This is our self signed version

appUpdater.updateURL = "http://www.agileagenda.com/download/appUpdate.xml";

}



And finally, I update my ANT build script so I generate two different .air files, and create both the appUpdate XML files.


I'll also put a nag into the self-signed version's upgrade window saying something like:


We've recently started cryptographically signing our applications for your safety.  Unfortunately, you can't upgrade from a non-signed version to a signed version.  For your security we suggest that you uninstall this unsigned software and then download and install from our website.  You may continue using unsigned versions if you prefer.




And then someday I'll completely disable the auto-update of the self-signed version when enough people have migrated over.