Robotlegs, Mediator and PopupManager

Recently I have shifted my framework of preference from Cairngorm to Robotlegs. Cairngorm has been my choice of framework mainly because it has a large user-base support, so I can point developers to learn the framework on their own. Cairngorm has its limitation, and the one gives me the most heartburn is singleton model, which makes the code difficult to write unit test for.

Just a few hours of reading this awesome book ActionScript Developer’s guide to Robotlegs, I am sold. Within a short time, I am able to rewire up a Cairngorm-based applications into Robotleg’s fashion. Mediator in Robotlegs is an awesome designer. Without Mediator, my control’s container would have to know how to pass data and events back and forth. It gets cumbersome when there are layers of containers. Mediator mapping relies on listening the control’s ADDED_TO_STAGE event, then maps the control to the mediator class. However, the event listening is done on the context root of the Robotleg’s configuration. In a Flex application, typically the context root is set to the Application itself like the following


		<context:TabletApplicationContext contextView="{this}" />


This works great in most cases because all the controls are usually added to the display tree of the Application, therefore the context is able to capture the control added event. However, when a control is introduced by PopupManager or Callout component, the control is not added to the application but application’s parent, therefore the event is not captured by the context.

There has been discussions and samples to work around this problem. The solutions most discussed would use “Command” to perform the Popup instead of the component itself. This gives me a heartburn because Command is NOT supposed to interfere with UI implementation.

The Solution
Since the cause of the issue is the context is not able see the popup added simply because the popup is added outside the contextView, my solution is to find out what that “outsider” is. A quick dig around of PopupManager’s implementation I found out it uses application’s systemManager as the place to add the popup control. So I quickly implemented the solution below:

	<context:TabletApplicationContext contextView="{DisplayObjectContainer(this.systemManager)}" />

But it does not work as somehow the context is not instantiated. That’s when the contextView is assigned, the systemManager is not added to the stage and the application is not ready. That’s not too obvious, but we can always delay the contextView assignment until the application’s creationComplete event is fired. So I modify my application as follows:

<s:Application creationComplete="initContext();" 

		<context:TabletApplicationContext id="context" />

			private function initContext():void
				//Use systemManager as contextView so popups instantiated by PopupManager would be wired up properly
				var contextView:DisplayObjectContainer = systemManager as DisplayObjectContainer;
				context.contextView = contextView;


Since then, the mediator is happily working with the popup control ever after!

Robotlegs 2
I read in the forum posts that the upcoming Robotlegs 2 is supposed to alleviated this pain. I will follow up with a post once I get RL2 and popup working with my new application.


Vectors in ActionScript 3

Vector class is a strongly-typed array implementation in ActionScript 3.  There are lots of blog posts or Stackoverflow posts related Vector, I am simply aggregating a few I have found useful

1. How to instantiate a Vector type with values?

var vec:Vector.<Number> = new <Number> [1.0, 1.0];


2. What kind of performance advantage Vector has over Array?
Answer: A lot, and each iteration of Flash Player may have different merits. The latest result shows Vector has more than a 100% speed advantage over Array.
(Credit: ActionScript performance test for Array, Object, Vector literals and Array.push, Vector.push methods)

3. Any drawback of Vector?
Answer: One drawback I see so far is Vector has no AMF equivalent. If you don’t know what AMF is or would not use Vector to transfer data back and forth to server, then you don’t have to worry. Otherwise, a work-around would be translate Vector to Array or ArrayCollection at transport. This little overhead is minimal as it only occurs at transport. I would strongly recommend anyone use Vector as much as possible.

Another drawback of Vector would be that it is a primitive type like Array, therefore it lacks sophisticated events notifying change of a Vector. Though the latest Apache Flex 4.9 has VectorList and VectorCollection implementation, the implementation offers little or adversed performance advantage, and I would not advise using VectorList/VectorCollection just yet.

Prevent SQL Server from Caching Results

SQL Server has an advantage of caching results of executed queries, so when an expensive query is executed, the server only takes the heaviest hit during the first execution, any subsequent execution would take significantly less hit.

Such approach, however, could make SQL tuning job difficult, because it is hard to know if the tuning actually works faster or it is the caching that does the magic. However, with caching is disabled, the tuning may become apparent. This could be achieved with the following snippet:


Note that CHECKPOINT could be “harmful” if abused in Production environment, so the above is only recommended in development environment.

Export Outlook Mails into Excel

Once in a blue moon I have a need to analyze emails in my Outlook, I would need to get my emails into structural data so I could run my analysis and statistics. I have come across this article, and thought I would re-post it with abridged steps.

  1. Start Outlook
  2. Hit ALT-F11, and Visual Basic for Applications should show
  3. Choose Insert -> Module
  4. Copy and Paste the following source code into the Edit
  5. Choose Tools -> References, and make sure that Microsoft Excel is part of the reference
  6. Hit F5 and Run, pick the folder you wish to Outlook export the mails from
' The source code is adopted from
Sub ExportToExcel()
    On Error GoTo ErrHandler
    Dim appExcel As Excel.Application
    Dim wkb As Excel.Workbook
    Dim wks As Excel.Worksheet
    Dim rng As Excel.Range
    Dim strSheet As String
    Dim strPath As String
    Dim intRowCounter As Integer
    Dim intColumnCounter As Integer
    Dim msg As Outlook.MailItem
    Dim nms As Outlook.NameSpace
    Dim fld As Outlook.MAPIFolder
    Dim itm As Object
    strSheet = "OutlookItems.xlsx"
    strPath = "c:\"

    strSheet = strPath &amp; strSheet
    Debug.Print strSheet

    'Select export folder
    Set nms = Application.GetNamespace("MAPI")
    Set fld = nms.PickFolder

    'Handle potential errors with Select Folder dialog box.
    If fld Is Nothing Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub
    ElseIf fld.DefaultItemType  olMailItem Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub
    ElseIf fld.Items.Count = 0 Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub
    End If

    'Open and activate Excel workbook.
    Set appExcel = CreateObject("Excel.Application")
    appExcel.Workbooks.Open (strSheet)
    Set wkb = appExcel.ActiveWorkbook
    Set wks = wkb.Sheets(1)
    appExcel.Application.Visible = True
    'Copy field items in mail folder.
    For Each itm In fld.Items
        intColumnCounter = 1
        Set msg = itm
        intRowCounter = intRowCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.To
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.SenderEmailAddress
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.Subject
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.SentOn
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.ReceivedTime
    Next itm
    Set appExcel = Nothing
    Set wkb = Nothing
    Set wks = Nothing
    Set rng = Nothing
    Set msg = Nothing
    Set nms = Nothing
    Set fld = Nothing
    Set itm = Nothing
    Exit Sub
ErrHandler:      If Err.Number = 1004 Then
        MsgBox strSheet &amp; " doesn't exist, please create a empty spreadsheet at the location before running this Macro", vbOKOnly, "Error"
        MsgBox Err.Number &amp; "; Description: ", vbOKOnly, "Error"
    End If
    Set appExcel = Nothing
    Set wkb = Nothing
    Set wks = Nothing
    Set rng = Nothing
    Set msg = Nothing
    Set nms = Nothing
    Set fld = Nothing
    Set itm = Nothing
End Sub

How to make your pictures, music and video available to all your TV, iPad, iPhone and more via SheevaPlug

Over the years, I have gradually built up a collection of videos, photos and music, the collection size has gone up to terra-byte level that is far beyond my laptop SSD.  I have decided to store the media on external drive.  On a second thought, given I have devices such as iPhone, iPad, WDTV, Sony TV and many other computers at home, I started to dream about having a server that could serve all the contents to all of my devices, so I can watch and show them anywhere my home network could reach.

The Challenge

While sharing media among computer is easy, I can easily designate a computer as server, and have other computers connect to the server; the real challenge comes to sharing the media to iPhone/iPad given Apple’s close ecosystem.  The closest answer that I have found working is Stream To Me, a $2.99 application which comes with a handy free server component, Serve To Me.  It not only can share out contents to all devices well, but also can do on-the-fly media transcoding to best fit the form factor, device capability and bandwidth.  For example, iPhone/iPad cannot play formats such as mkv and avi, Serve To Me would quietly transcode the media on-the-fly when I try to watch mkv contents off my iPhone.

However, I am not settled with Stream To Me/Serve To Me solution.  My main concern with the approach is that I need to dedicate a computer for the purpose, which eats up precious real-estate in my office and lots of electricity.  My ideal solution is to employ a server as small and as lean as possible.  The solution from PlugComputer Community, SheevaPlug, seems to be a natural fit to this requirement.  The plug computers are fairly inexpensive, for less than $200, I can order a powerful computer that’s just barely larger than my palm, it comes with Debian server, and host of features such as USB connectivity, gigabit ethernet and WiFi.

Yet, the solution is still not readily available, the challenges remain as:

  1. Out of the box the computer OS cannot read NTFS, which is the file format I use for my external hard drives.  I intend to keep it that way, so I can use the hard drive with any of my Windows computer directly.
  2. Application such as Serve to Me does not have a Linux counter part that works on Plug Computer as the solutions I found were designed for x86 processors, but my Plug Computer runs ARM.

The Solution

After a few sleepless nights, numerous trial and failure.  I have finally arrived at a solution that makes me smile.

Global Scale Dream Plug

Server Side

  • I choose GlobalScale’s DreamPlug as it is only plug that has descent reviews on Amazon, and I can enjoy the good customer service from Amazon too.
    • To make the plug ready for the following steps, I had to update the software on the plug, this can achieved by running (warning, this could take quite a few minutes)
      • apt-get update
      • apt-get upgrade
      • apt-get upgrade-dist
    • Install gcc and g++ compilers
      • app-get install gcc
      • app-get install g++
  • I run NTFS-3g to gain full read/write access on NTFS hard drive.  NTFS-3g is an open-source solution which comes with handy description on how to obtain the solution, and build.
  • To make sure the server uses NTFS-3g to mount the NTFS volume.  SheevaPlug seems to regard USB ports as /dev/sdd1 and /dev/sdd2
  • For media serving software, I choose TVMobili.  It works well with iOS applications such as PlugPlayer and AirPlay.  To install
    • Download the Debian Linux distribution of the software, I would use wget url to download the .deb file, then install the .deb file.  For example
      • wget
      • dpkg -i tvmobili-all-universal.deb
    • TVMobili by default runs on port 30888, so it can be managed through http://plug_address:30888/
    • Through the web interface, I can add my hard drive contents to TVMobili


  • Install PlugPlayer (AirPlayer or media:connect would do the job too)
  • In many cases, the software should be able to detect the server, in case it does not, it can be manually added with the Device URL http://plug_address:30888/__rootDevice


  • VLC Player from VideoLan is an excellent free open-source player.


  • WDTV Live supports uPnP Media Server, the server can accessed through Video -> Media Server
  • Video quality is better than I expected given the less-than-ideal 802.11n signal strength I have in my house

Sony Bravia TV

  • My Sony TV acquired from Costco could also support uPnP DLNA Media Server.  While this was not part of my plan to support, nonetheless it was a pleasant surprise.

Other Thoughts

TVMobili is not free.  It comes with a 10GB a month limit, beyond the limit, the company would charge $1 each month or a small fee for lifetime overage.  Although there are completely free solutions such as MediaTomb and uShare, they are either not actively maintained or don’t work right out of the box.  Other commercial solutions seem to only gear towards Windows, Mac or a particular storage.  After quite a few painful hours to trial and failure, I have arrived at TVMobili, which is inexpensive, reasonable and decent implementation.

As for client side, a list of DLNA/uPnP players can be found at Wikipedia.

Some NAS (Network Attached Storage) servers may offer uPnP, but most don’t come up on-the-fly FFMpeg transcode, which means videos that are not MP4 or M4V would not be playable in iPad/iPhone.  Though some of the NAS may provide means to install software, the processor in those machines are not known to be fast enough to perform the job.

Reindex entire database in SQL Server

DECLARE @DatabaseTable VARCHAR(255)
DECLARE @fillfactor INT
SET @fillfactor = 80

OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @DatabaseTable
SET @sql = 'DBCC DBREINDEX('''+ @DatabaseTable + ''')'
PRINT (@sql)
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @DatabaseTable
CLOSE TableCursor

Viewing ActionScript Documentation offline, fast!

Back in the days of Flex Builder 3.0, Adobe has bundled an offline reference for ActionScript and Flex framework API.  The reference is more than just an HTML documentation as it provided a nice outline view of all the packages, classes as well as method and properties.  Starting Flash Builder 4.0, such feature has gone away.

Doc? has come and filled the void, and it does more than just providing references for Flex framework.  It is a parser that parses through online/offline ActionScript documentations, index and store the documentations in local database, which is extremely useful as I collect a bunch of open-source libraries, and the documentations come in handy.

So hit the link and give the program a try.  Don’t forget to send the project donation (or beer 😉 ) if you find it cooler than I say in the blog.