You are currently browsing the archives for the News category


AIR Cairngorm 2.0

I have received quite a few emails since the release of AIR 1.0 and Flex 3.0 regarding the AIR Cairngorm API which I developed last year. In the time since I have been working primarily with a modified version of AIR Cairngorm which I used on a number of successful real world AIR applications, however I simply have not had the time to document and refactor for general use until recently.

In case you are not familiar with AIR Cairngorm it is an open source project built on top of Adobe Cairngorm which provides a framework for working with the Adobe AIR SQLite API while building an application with Cairngorm.

AIR Cairngorm is built around the SQLService class which essentially wraps the AIR SQL APIs to provide a uniform interface which can be utilized as a service, much in the same way one would work with RPC services in a typical Cairngorm application. SQLService provides an API for both synchronous and asynchronous implementations.

In the time since the initial development and release of AIR Cairngorm, which was during the early alpha releases of AIR, there has been many changes to the SQL APIs in AIR. In addition I have also developed some new best practices for working with Adobe AIR and Cairngorm, all of which I tried to roll into this latest release where possible.

The following is a brief description of the current AIR Cairngorm API:

AIRServiceLocator: The AIRServiceLocator is a sub class of Cairngorm ServiceLocator, therefore it inherits the same API as ServiceLocator while also adding additional support for working with local databases via the getSQLService and hasSQLService methods.
AIRServiceLocator

SQLService: The SQLService class essentially wraps the SQLStatement and SQLConnection classes. SQLService allows developers to create an mxml implementation defined on a Cairngorm ServiceLocator just as one would with typical RPC services (e.g. HTTPServices, WebService etc.)
SQLService

ISQLResponder: ISQLResponder provides a consistent API from which asynchronous SQLStatement execution results and faults can be handled. ISQLResponder is very similar to IResponder in that it defines both a result and fault handler however with a slightly different signature which is specific to a SQLStatement result / fault, (i.e. strongly typed parameters).
ISQLResponder

SQLStatementHelper: SQLStatementHelper is an all static utility class which facilitates substituting tokens in a SQL statement with arbitrary values.
SQLStatementHelper

I have also created a custom version of my Cairngen project specifically targeting AIR Cairngorm code generation. In addition I will be making some future updates to AIR Cairngorm which will include support for various other AIR APIs in Cairngorm, so stay tuned.

Below I have provided downloads to the source, binary, air.cairngen and asdocs as well as asynchronous and synchronous example projects:
source
binary
examples
asdoc
air cairngen
air cairngorm (all)

Passing …(rest) parameters between functions

At some point when developing an application with ActionScript 3 you may need to pass a …(rest) parameter to a subsequent function call, and although at first this may appear to be pretty straightforward, doing so will not produce the results one might expect.

For example, consider the following method doSomething which accepts a single …rest parameter:

public function doSomething(rest) : void
{
    var n:int = rest.length;
    trace( "…rest.length = " + n );

    for (var i:int = 0; i < n; i++)
    {
         trace( rest[i] );
    }
}
doSomething("a","b","c");

// outputs:
// …rest.length = 3
// a
// b
// c

Let’s say we also have another function we need to invoke called doSomethingElse which accepts a …(rest) parameter as well:

public function doSomethingElse(rest) : void
{
    var n:int = rest.length;
    trace( "…rest.length = " + n );

    for (var i:int = 0; i < n; i++)
    {
         trace( rest[i] );
    }
}

Now suppose we need to pass the ...(rest) parameter from the doSomething function to the doSomethingElse function. The result would be as follows:

public function doSomething(rest) : void
{
    var n:int = rest.length;
    trace( "…rest.length = " + n );

    for (var i:int = 0; i < n; i++)
    {
     trace( rest[i] );
    }
    doSomethingElse( rest);
}
// doSomething outputs:
// …rest.length = 3
// a
// b
// c

// doSomethingElse outputs:
// …rest.length = 1
// a,b,c

So what went wrong? What happens is the original …rest parameter (passed to doSomething) is now being passed as a single parameter of type Array to the subsequent function (doSomethingElse), not as an Array of individual arguments as you may have expected.

This can easily be resolved by using Function.apply(); as can be seen in the following:

public function doSomething(rest) : void
{
    var n:int = rest.length;
    trace( "…rest.length = " + n );

    for (var i:int = 0; i < n; i++)
    {
     trace( rest[i] );
    }
    doSomethingElse.apply( null, rest);
}
// doSomething outputs:
// …rest.length = 3
// a
// b
// c

// doSomethingElse outputs:
// …rest.length = 3
// a
// b
// c

What we are doing is applying the call to the doSomethingElse function with the original rest parameter as if we were invoking the function directly. So keep this in mind should you ever need to pass a …rest parameter to a subsequent function.

IExpense Online (IEO)

With Income Tax Returns approaching, now is as good a time as ever for me to blog about IExpense Online (IEO).

IExpense Online is the creation of my friend and co-worker Michal Glowacki. It is one of those Flex apps that really showcases what can be accomplished in Adobe Flex with a little creativity and dedication.

Built entirely in Flex, Cairngorm, PHP and MySQL, IExpense is a Free Tool which allows users to intuitively and intelligently manage their expenses and make sound budgeting decisions. You can try it out by logging in as a guest or creating a free account.

So make the most of your tax returns and check out IExpense Online (IEO).

IExpenseOnline

Collections API update

I recently made a number of updates to my collections API which include some minor changes to the existing code as well as a few additional classes and interfaces which have been added.

The most significant updates involve three additional operations which have been added to the IMap interface which are as follows:

  • putAll(table:Dictionary) : void;
    Allows an Object or Dictionary instance of key / value pairs to be added to an IMap implementation.
  • putEntry(entry:IHashMapEntry) : void;
    Serves as a pseudo-overloaded implementation of the put(key:*, value:*); method in order to allow Strongly typed key / value implementations to be added to a map.
  • getEntries() : IList;
    Returns an IList of HashMapEntry objects based on all key/value pairs
  • I have also added two new additional IMap implementations to the collections API; LocalPersistenceMap, which can be utilized to provide an IMap implementation into a local SharedObject and ResourceMap which allows developers to work with a ResourceBundles via an IMap implementation. All IMap implementations; HashMap, ResourceMap and LocalPersistenceMap have been updated to implement the new operations.

    The IIterator interface has been renamed to Iterator. In addition the remove() operation has been omitted in order to enforce that a concrete implementations can not modify an aggregate. Additionally, ICollectionViewSortHelper has been renamed to CollectionSortUtil.

    Some design decisions worth mentioning involve the inclusion of multiple IMap implementations; HashMap, ResouceMap and LocalPersistanceMap. Initially I identified an AbstractMap from which these classes would extend, however I realize some developers may want to minimize dependencies as much as possible therefore I decided to simply have each concrete map implement the IMap interface rather than extend an abstract map implementation.

    The source, binary and ASDocs for the new Collections API can be downloaded here.

    The Collections API is published under the MIT license.

    Cairngen Project moved to Google Code!

    Since the initial release of Cairngen 1.0 there has been an amazing amount of interest in the project and your feedback has been very encouraging. In addition I have received a number of extremely valuable customizations from community members, many of which have made it into subsequent releases.

    In order to provide a solid foundation to help facilitate a collaborative Open Source initiative for the Cairngen Project I have decided to move the project to Google Code.

    Moving Cairngen to Google Code allows for a number of significant development benefits for the Cairngorm Community. This includes regular development updates, access to all releases, availability of all source code revisions, better documentation, defect lists, feature requests and much more.

    I am currently accepting requests for new contributors so if you feel you have added new functionality which would provide benefit to the project visit the Become a Contributor page. All comments on the project are welcome and encouraged. In addition I strongly recommend the if you have any issues with Cairngen, especially environmental issues you should log them to the Issues Page.

    Along with the new Cairngen Google Code Project I have also released Cairngen 2.1.1 which aligns the source project with the new SVN repository.

    So go check out all of the new information on Cairngen at the new Cairngen Project Home.

    Using multiline values in properties files

    When building localized Flex applications with ResourceBundle there are a few tricks you may not be aware of which can come in handy should you need them.

    I have had quite a few people ask how multiline values can be specified in a properties file. This is a pretty common question and luckily the answer is very simple: backslash (\).

    For example, suppose you have a properties file which contains a string resource with a really long value, like a paragraph. Typically the property value will just be one really long String on one line. However you can use the backslash (\) character to continue the value on multiple lines in order to make the properties file more legible, such as in the following example:

    title   = Welcome
    message = Lorem ipsum dolor sit amet, consectetur elit, \
    sed do eiusmod tempor incididunt ut labore et dolore magna \
    aliqua. Ut enim ad minim veniam, quis nostrud exercitation \
    ullamco laboris nisi ut aliquip ex ea commodo consequat. \
    Duis aute irure dolor in reprehenderit in voluptate velit \
    esse cillum dolore eu fugiat nulla pariatur. Excepteur sint\
    occaecat cupidatat non proident, sunt in culpa qui officia \
    deserunt mollit anim id est laborum.
     

    So if you have properties with very long values remember to use backslash (\) to help clean up your resources.

    example

    LocalPersistenceMap

    When developing browser based Flex applications, SharedObject provides just about everything one needs to facilitate local persistence of application data. While being somewhat restricted by certain rules governed by the Flash Player Security Model, in general, it provides a rather simple solution for most needs.

    The data property of a SharedObject provides read/write access to the underlying data which is persisted to the SharedObject. Personally, I prefer to have a consistent API available when working with dynamic objects, thus I developed the IMap interface.

    LocalPersistenceMap provides an IMap implementation into the data property of a SharedObject instance. It allows clients to work with the underlying data of a SharedObject just as one would with a HashMap, ResourceMap, etc.

    Below is a basic example which demonstrates how LocalPersistenceMap can be utilized to provide an IMap implementation into a SharedObject:

    var map:IMap = new LocalPersistenceMap("test", "/");
    map.put("username", "efeminella");
    map.put("password", "43kj5k4nr43r934hcr34hr8h3");
    map.put("admin", true);

    The LocalPersistenceMap constructor creates a reference to a local SharedObject based on the specified identifier and optional local path. A reference to the underlying SharedObject can also be retrieved via the sharedObjectInstance accessor.

    In addition to the new LocalPersistenceMap, I have also packaged the Collections API which can be downloaded here. Complete documentation and code examples for the Collections API are also available here.

    Embedding assets with application/octet-stream

    Awhile back one of the guys on my team discovered an interesting way to embed files in ActionScript using the “application/octet-stream” mimeType with the Embed metadata tag.

    When using the Embed tag it is not common to explicitly assign a specific mimeType to an asset. Because of this Flex uses heuristics to determine the appropriate mimeType based on the extension of the embedded asset (i.e. file).

    The Adobe Flex documentation states:

    “You can use the [Embed] metadata tag to import JPEG, GIF, PNG, SVG, SWF, TTF, and MP3 files.”

    However when specifying application/octet-stream (which is essentially an arbitrary byte stream ) as the assets mimeType it is also possible to embed a file of any type. If the file type is not supported natively, such as XML, developers can write custom parsers which can read the file utilizing the ByteArray (Flex 2) or ByteArrayAsset (Flex 3).

    Below I have provided a basic example which demonstrates how the application/octet-stream mimeType can be utilized to embed a file, in this case an external xml document which serves as a config file.

    package example
    {
      import mx.core.ByteArrayAsset;
       
      public final class Config
      {
        [Embed("config.xml", mimeType="application/octet-stream")]
        private static const Config:Class;
       
        public static function getConfig() : XML
        {
          var ba:ByteArrayAsset = ByteArrayAsset( new Config()) ;
          var xml:XML = new XML( ba.readUTFBytes( ba.length ) );
           
          return xml;    
        }
      }
    }
     

    In the above example an XML document is embedded as a Class object from which the contents of the file are read as a string via ByteArrayAsset and converted to an XML object.

    Based on this example it would also be possible to create arbitrary custom types in conjunction with custom parsers to allow additional support for numerous other file types in Flex as well.

    AS3 ResourceMap API

    Of the many APIs I have developed and published as Open Source to the Flex community, the AS3 HashMap has been one of the most popular. My assumption is that this popularity is in part due many developers expecting a HashMap to be provided as part of the Flex Framework, and rightfully so. After all that is why I developed it in the first place.

    With the upcoming release of Adobe Flex 3 there are many new additions which have been added to the Framework. These new additions and features are outside the scope of this article; however, one which is of relevance is the ability to directly access the underlying content of a ResourceBundle.

    For the most part I tend to think of the content of a ResourceBundle as not begin much different than a HashMap as it essentially is just an aggregation of name / value pairs, just like a HashMap. With that in mind I have developed a ResourceMap API which allows developers to work with a ResourceBundle via an IMap implementation (a.k.a. HashMap).

    ResourceMap implements the IMap interface allowing the underlying content of a ResourceBundle to have CRUD specific operations performed on it. To utilize the ResourceMap one only need to instantiate an instance of ResourceMap and pass in a ResourceBundle, as in the following:

    import com.ericfeminella.collections.ResourceMap;
    import com.ericfeminella.collections.IMap;
    import mx.resources.ResourceBundle;

    [ResourceBundle("resources")]
    private static const rb:ResourceBundle;

    var map:IMap = new ResourceMap( rb );

    The above example is all that is required to work with a Resourcebundle as a HashMap. From there you can work with the ResourceBundle just as you would with a typical HashMap.

    The benefit to this approach is it allows developers to dynamically add, remove, update and delete resources at runtime, whereas the new Flex 3 ResourceManager (much like the Open Source ResourceManager API I created last year – had to add that in) does not provide an API for setting resources. In addition, all of the getters defined by the IResourceBundle interface and implemented by ResourceBundle have been deprecated in favor of the new ResourceManager. However, IResourceBundle now provides an additional operation called getContent(); which exposes a reference to the underlying content Object which is created when a .properties file is compiled. Therefore it is possible to take advantage of this by accessing the content object.

    Admittedly the thinking behind the ResourceMap API takes a somewhat “outside-of-the-box” approach to working with ResourceBundles as one typically tends to think of resources as constants, especially when working with localized applications. However with all of the new capabilities available in the Flex 3 Resource API (such as loading compiled resource swf’s at runtime, etc) the opportunity to experiment with different things is well worth it!

    ResourceMap is published under the MIT license.

    Principle of Least Knowledge

    One very important (yet often overlooked) design guideline which I advocate is the Principle of least knowledge.

    The Principle of Least knowledge, also known as The law of Demeter, or more precisely, the Law of Demeter for Functions/Methods (LoD-F) is a design principle which provides guidelines for designing a system with minimal dependencies. It is typically summarized as “Only talk to your immediate friends.”

    What this means is a client should only have knowledge of an objects members, and not have access to properties and methods of other objects via the members. To put it in simple terms you should only have access to the members of the object, and nothing beyond that. Think if it like this: if you use more than 1 dot you are violating the principle.

    Consider the following: We have three classes: ClassA, ClassB and ClassC. ClassA has an instance member of type ClassB. ClassB has an instance member of type ClassC. This can be designed in such a way which allows direct access all the way down the dependency chain to ClassC or beyond, as in the following example:

    // ClassA defines a member of type ClassB and provides
    // access to the instance
    public class ClassA
    {
        private var b:ClassB;
       
        public function getB() : ClassB
        {
             return b;
        }
    }

    // ClassB defines a member of type ClassC and provides
    // access to the instance
    public class ClassB
    {
        private var c:ClassC = new ClassC();
       
        public function getC() : ClassC
        {
             return c;
        }
    }

    // ClassC could expose additional members and on and
    // on creating more and more direct dependencies
    public class ClassC
    {
        public someType:SomeType;
        …
    }

    // client implementation
    var a:ClassA = new ClassA();
    var sometype:SomeType = a.getB().getC().someType;
     

    The above example is quite common, however it violates The Principle of Least Knowledge as it creates multiple dependencies, thus reducing maintainability as should the internal structure of ClassA need to change so would all instances of ClassA.

    Now keep in mind that in all software development there are trade-offs to some degree. Sometimes performance trumps maintainability or vice-versa, other times readability trumps both. A perfect example of where you would not want to use The Principle of Least Knowledge is in a Cairngorm ModelLocator implementation. The Cairngorm ModelLocator violates the Principle of least knowledge for good reason – it simply would not be practical to write wrapper methods for every object on the ModelLocator. This is the main drawback of the Principle of least Knowledge; the need to create wrapper methods for each object, which are more formally known as Demeter Transmogrifiers.

    The goal of good software design is to minimize dependencies, and by carefully following the guidelines provided by The Principle of Least Knowledge this becomes much easier to accomplish.