AirAppDuplicator: Run two versions of an Adobe AIR Application simultaneously

Since the initial release of the Adobe AIR runtime, one sought after feature has been the ability to run multiple instances of an application at the same time. The AIR runtime inherently prevents this by limiting each application to a single running instance.

This is done by reading the ‘id’ field defined in each application’s XML descriptor file. Any time a user attempts to run an AIR application, the runtime determines if an application with the same ID is already running. If an active instance is found, it is given focus, rather than launching a second instance.

There are some AIR applications where it may be beneficial to run multiple instances side-by-side. I have developed a small utility application that permits you to make copies of existing AIR applications and run the duplicated versions in tandem with the original. This is accomplished by copying the original application’s contents to a new location and specifying a new application ID for the copy.

It is important to note that each copy of the application will have its own independent storage directories. Depending on the architecture of the app, this may impact performance or data integrity. At the very least, do not expect stored information from one installation to carry over to another.

This is a hack, but I have found it useful in several situations. Your mileage may vary.

The application and source gode may be found on github: http://github.com/chrisdeely/AirAppDuplicator
Please check it out and tell me what you think (either here or on github directly).

AirAppDuplicator Demo from chris deely on Vimeo.

4 Comments

Flash IDE code hints for TweenLite – built with CSDoc!

In my last post I released my new AIR app CSDoc for generating Flash IDE code hints from ASDoc comments.  The app is very useful for people that create AS3 libraries, but it can also be employed by the end user.  Any library that is released with source code can be processed by ASDoc, and subsequently converted into code hints using CSDoc.

As an example, I have run CSDoc against the popular TweenLite/TweenMax animation package developed by Jack Doyle at http://www.greensock.com.   You can download the resulting Flash extension here (MXP).

To generate this package, I followed these steps:

  1. Downloaded the library source
  2. Ran asdoc on the package with the “-keep-xml” flag (I highly recommend Grant Skinner’s ASDocr for this task) ***Use Flex SDK 3.4 or LOWER***
  3. Ran CSDoc on the resulting toplevel_classes.xml file
  4. Packaged the resulting files into an MXP using the Adobe Extension Manager

That’s it!  This should work on any open source AS3 library, provided you have the appropriate supporting libs available.

Please let me know if you find this extension useful or if you’d like to see packages made for any other popular libraries.

,

No Comments

CSDoc – Create Flash CS3 & CS4 code hints using ASDoc

For the past few years I have been managing a sizable Flash API that is distributed to clients via an Adobe extension (MXP). Managing the compilation of the MXP file is a headache on its own (and worthy of a separate post). In addition, there is little to no documentation on building an extension that integrates nicely with the Flash IDE.

Sure, you can get your class files to install into the IDE’s class path, but what about adding code hinting and highlighting? I have not found many reliable resources on this topic, and everything I’ve learned has been by digging into the guts of the installed IDE files.

So, long story short, I’ve developed an AIR app that will use ASDoc to analyze your AS3 API and generate the files needed to add code hints within the Flash IDE.

The application, CSDoc, can be installed from the badge below. It is extremely simple (read: ugly) but gets the job done. Just follow the steps below to get the required XML docs for addition to your MXP:

Note: You do not have to actually use ASDoc comments in your code, but it is recommended.

  1. Run ASDoc on your project with the added argument: -keep-xml
  2. Use the “Browse” button to locate the toplevel_classes.xml file created by ASDoc
  3. Review the XML generated (if you really care…)
  4. Export the XML files to disk (I recommend keeping them in a directory with your project) and include them in your MXP

Please let me know in the comments if you find this useful or have any problems.

[swfobj src=”http://blog.webdeely.com/CSDoc/badge.swf” width=”217″ height=”180″ flashvars=”appname=CSDoc&appurl=http://blog.webdeely.com/CSDoc/CSDoc.air&airversion=1.5.3&imageurl=http://blog.webdeely.com/CSDoc/csdoc_badge.png”]

For anyone interested, this all started with a post by Rob Dixon, which is pretty outdated now:  Use ASDoc to drive new processes

2 Comments

Great Article on UDP in AIR 2.0

Ian McLean has written a multi-part article on using the UDP protocol in AIR 2.0. Interesting read, be sure to check it out: http://www.insideria.com/2009/11/udp-socket-connections-for-los-1.html

No Comments

“Fixing” the FileSystemTree

I recently ran into some painfully slow performance issues using the FileSystemTree to display file system contents in an AIR app. It seemed that when accessing directories containing a large number of files, the app would simply hang for ages, never populating the tree.

This occurred most readily when accessing network drives. I chased the issue down a number of avenues, including looking at “funky” file types and network speed. Nothing pointed me in the right direction.

Finally, I spent some time placing breakpoints directly into the FileSystemTree class and dug into the guts to find the answer. As I stepped through the code, I found that the file records for the large directory in question were returned from the OS almost instantaneously. This was not what I expected to find, but it was great news, as it meant the processing delay was somewhere inside the Flex SDK or my own code.

Sure enough, there is some code in the FileSystemTree class that significantly slows down the processing of large directories. After loading the raw directory listing from the AIR framework, the child items are processed through the following function:

 mx_internal function insertChildItems(subdirectory:File, childItems:Array):void
 {
    var childCollection:ArrayCollection = new ArrayCollection(childItems);
       
    childCollection.filterFunction =
        helper.directoryEnumeration.fileFilterFunction;
    childCollection.sort = new Sort();
    childCollection.sort.compareFunction =
        helper.directoryEnumeration.fileCompareFunction;
    childCollection.refresh();

    FileSystemTreeDataDescriptor(dataDescriptor).setChildren(
        subdirectory, childCollection);

    expandItem(subdirectory, true, true);

    helper.itemsChanged();
}

The problem here is that the file records returned from the OS are now filtered and sorted before populating the Tree. This is fine for relatively small sets of data, but when dealing with large directories (1600+ files in my case) it grinds to a halt.

The only way I have found to improve the performance of this component is to prevent the filtering and sorting from taking place for large directories. I extended the FileSystemTree (source attached) and overrode the insertChildItems function.

The full class is below:

package com.webdeely.file
{
    import flash.filesystem.File;
   
    import mx.collections.ArrayCollection;
    import mx.collections.Sort;
    import mx.controls.FileSystemTree;
    import mx.controls.fileSystemClasses.FileSystemTreeDataDescriptor;
    import mx.core.mx_internal;
    import mx.utils.DirectoryEnumerationMode;

    use namespace mx_internal;
   
    /**
    * This class overrides the AIR FileSystemTree class' insertChildItems to prevent sorting of directory contents when
    * there are a great number of children in the folder. This is far from perfect, as the children may be listed randomly,
    * however it is better than the default behavior where the app chokes.
    **/

   
    public class FastFileSystemTree extends FileSystemTree
    {
        /** Adjust this number to set an acceptable threshold for sorted/unsorted children **/
        public var largeDirectoryThreshold:Number = 500;
       
        public function FastFileSystemTree()
        {
            super();
        }
       
        override mx_internal function insertChildItems(subdirectory:File, childItems:Array):void
        {
            var childCollection:ArrayCollection = new ArrayCollection(childItems);
           
           /* This is the only change to the function.  If this directory contains a large number of children,
              just append them as they are listed from the OS, rather than filtering or sorting them. */

            if( childCollection.length < largeDirectoryThreshold )
            {
                childCollection.sort = new Sort();
                childCollection.filterFunction = helper.directoryEnumeration.fileFilterFunction;
                childCollection.sort.compareFunction = helper.directoryEnumeration.fileCompareFunction;
                childCollection.refresh();
        }
   
            FileSystemTreeDataDescriptor(dataDescriptor).setChildren(
                subdirectory, childCollection);
   
            expandItem(subdirectory, true, true);
   
            helper.itemsChanged();
        }
    }
}

This is definitely not a great solution, as the contents of large directories may not appear in exactly the right order. I’ve had mixed results.

The real issue is that this type of operation on large quantities of file references should really be executed within the AIR framework itself, and not by the AS3 components running on top of it.

I am very open to suggestions on how to approach a better solution, but for now this at least allows the user to access their files; albeit in possibly the wrong order.

Get the class source

3 Comments

Storing Custom AMF files for AIR Apps

In my current AIR project I have a need to store persistent user data across sessions. Because the amount of data is fairly small, but the objects are complex, a SQL Lite database wasn’t ideal. I also couldn’t use standard SharedObjects because of the file size limitations and the fact that crashed our IDE (more on that in a later post).

The solution I came to was to make my own SharedObjects, or rather custom files using the AMF data format. It was actually much easier than I had initially feared. I got my start by reading this article by Ted Patrick.  (Unfortunately, the article is hosted on a Sys-Con property, and I’m not a fan of their tatics.)

Ted’s article is short and sweet and shows simply how to read and write AMF-encoded objects from/to a ByteArray.  Since we can easily save ByteArrays to disk and read them out again later, this is a perfect solution to the storage needs.

var byteArray = new ByteArray();
// the writeObject() method encodes any object into AMF
byteArray.writeObject( { myBool: true, myString:"Hello World" });

//the readObject() method decodes the AMF into a standard AS3 Object
var myObject:Object = byteArray.readObject();

So, this approach works great if you are only using simple Objects made up of Flash Player core types. Things get a little more complicated when you need to save complex custom objects. AMF doesn’t automatically recognize your custom objects. This effects all AMF transport methods, including SharedObject, LocalConnection and Remoting.

In order to inform AMF which classes it should recognize, you need to use the registerClassAlias() method:

import flash.net.registerClassAlias;
import com.webdeely.MyCustomClass;

// pass in the path to the class definition and a
// reference to the actual Class
registerClassAlias("com.webdeely.MyCustomClass", MyCustomClass);

var mcc:MyCustomClass = new MyCustomClass();
mcc.message = "Hello World!";
mcc.favoriteNumber = 12;
mcc.userName = "MiltonB";

// ByteArray will now recognize all of your custom class' properties,
// and encode them to AMF
var byteArray:ByteArray = new ByteArray();
byteArray.writeObject( mcc );

// ...and they can be decoded directly back to your class!
var mcc2:MyCustomClass = byteArray.readObject() as MyCustomClass;

Ok, so now we have the encoding and decoding working properly, but we still need to save the file to disk in order for any of this to be useful. For this we’ll use AIR’s File and FileStream classes:

import flash.filesystem.File;
import flash.filesystem.FileStream;

private function writeFile( bytes:ByteArray ):void
{
  // save our data to the user's desktop, in a file called "test.sol"
  //  btw, 'sol' is not a required extension, in fact you don't need an extension
  var file:File = File.desktopDirectory.resolvePath("test.sol");

  // Create a file stream to write stuff to the file.
  var stream:FileStream = new FileStream();

  // Open the file stream and write the data
  stream.open( file, FileMode.WRITE );
  stream.writeBytes(bytes,0,bytes.bytesAvailable);
  stream.close();
}

private function loadFile():ByteArray
{
  var bytes:ByteArray = new ByteArray();
  var file:File = File.desktopDirectory.resolvePath("test.sol");
  var stream:FileStream = new FileStream();

  // Open the file stream in read mode
  stream.open( file, FileMode.READ );

  // read the bytes directly into the ByteArray
  stream.readBytes(bytes, 0, stream.bytesAvailable);
  stream.close();
  return bytes;
}

Hopefully this will be helpful to anyone faced with similar challenges. I have found the de/serialization of the AMF objects to be extremely fast, reliable and convenient. It works wonders and was a very quick switch over from the standard SharedObject process.

I have put together a simple Flex project file for an AIR app that allows you to experiment with the code here. You can download the package here.

,

7 Comments

CS4 doesn’t like the combo of internal classes and interfaces in AS3

Just prior to the public release of CS4, I had to spend some time at work testing how our API would install into the new Flash IDE.  Aside from some MXP file funkiness (which I may cover later) I encountered some very strange compiler errors.  Specifically, the compiler complained about many classes that implemented interfaces:

1044: Interface method foo in namespace IFoo not implemented by class MyClass.

Now, I knew for a fact that all of the interfaces were implemented properly and all of the classes compiled properly in Flash CS3 (and Flex 2 & 3).  Nevertheless, we rechecked all the code over and over.

The startling realization was that all of the classes effected were Singletons!  The Singleton pattern I generally use is the one from the excellent “Advanced ActionScript 3 with Design Patterns” by Joey Lott, Danny Patterson.  The gist of the pattern is that it makes use of a second class declared inside the main class’ AS file.  Non-public classes are accessible only to the main class of the file, and not anywhere else in your package.  (You can see the relevant pages here.)

Here is some code to illustrate the setup in use:

First, the main class, which implements IFoo and uses the Singleton Pattern

package
{
    public class MyClass implements IFoo {
        /** Singleton object */
        static private var _instance:MyClass;

        /** The constructor will throw an error if you do not
                      pass a SingletonEnforcer instance */

        public function MyClass(s:SingletonEnforcer){   }
       
        /** Method to retrieve an instance. */
        public static function getInstance():MyClass
        {
            if (!_instance) _instance = new MyClass( new SingletonEnforcer() );
            return _instance
        }
 
        /** Function required by IFoo interface */
        public function foo():void {}
    }
}

/** The enforcer class cannot be accessed outside this .as file */
class SingletonEnforcer {}

 
And, here is the definition of IFoo:

package
{
    /** A simple interface */
    public interface IFoo {
        function foo():void
    }
}

Easy enough, right? The method foo() is obviously implemented in the class. But as it turns out, CS4’s compiler doesn’t agree.

Once we discovered that the combination of the interface and the Singleton pattern was to blame, we started looking at all of the Singletons in the API. By a stroke of luck, we found one that did NOT generate the compiler error. The difference in that class was that it implemented TWO interfaces!

Bizarre as it seems, adding a second interface to the scheme above fixes the issue, and CS4 compiles the code without further issue. We decided to add an empty ISingleton interface which was then used to correct the issue wherever it cropped up.

package
{
    public class MyClass implements IFoo, ISingleton {
        /** yadda yadda */
    }
}
package{
     /** Add an empty interface to fix the issue */
    public interface ISingleton {}
}

Many thanks to Tim O’Hare for his help in diagnosing and fixing the issue.

Feel free to download the source files referenced here.

UPDATE: There is an ActionScript compiler bug logged for this issue. It is marked as Closed and transferred to the main bugbase, so hopefully it will be addressed.

,

7 Comments