Category: Flex

  • Loading Random SWFs in a Strongly Typed Way

    In a hurry? Skip to the code.

    ActionScript 3 has given us true strong-typing; both compile time and runtime. This has many benefits from helping ensure code works once you actually compile as well as helping you debug runtime errors. The problem with perfect systems however is when you put in some chaos. The old adage, “garbage in, garbage out” holds true here. There are basically 2 ways to get weird stuff in Flash Player. You either load in external data and parse it, or you load in an external SWF.

    The former is a little easier to deal with. Using E4X, if some XML node doesn’t exist, your code doesn’t throw exceptions. You can test against undefined, and set default values that match your ValueObjects (strongly typed classes that represent your data). In short, you can correctly write an XML parser that shields your app from bad data. Granted, his job is the most important as he’s the guardian against all loose wrenches in the gears. I’d say the majority of the bugs in the software I write in AS3 comes from a Factory letting bad or missing data through without either compensating with default values, or dispatching an appropriate error. In the end, though, if you do it right, you’re good.

    External SWF’s, on the other hand aren’t really parsed. There are some bad asses doing some weird things with SWF’s, like loading them in for asset use only (since even Images are classes now that can be ripped out of externally loaded SWF’s, aka WinAMP skinning) or just Flash native data transfer objects like Aral does with SWX. For the most part, most use cases that call for loading in an external SWF are NOT positive beyond the 2 above. Some common use cases not including the above are:

    • loading in Flash Player 8, or below content
    • loading in Flash content created in the Flash IDE as opposed to Flex
    • loading in assets too big to compile into main SWF and un-linkable to Flex’ RSL work flow (audio, video)
    • 3rd party PRE-generated created SWF’s (even if AS3, still could use different component set)

    This entry will target #2 and #3. For #1, here’s some morphine. For #4, good luck in the politic-infused blame game meetings.

    Flash is damn good at creating creative content. Whether this is created in-house or outsourced to a 3rd party design firm, you can have this content be in Flash Player 9, AS3. While this sounds positive, it just sucks you cannot easily make this a part of your work flow. There are a few ways I’ve talked about in the past using the Flex Component Kit for Flash, which is now part of Flex 3, or simply writing wrapper classes. The Flex Component Kit is really great if you know ahead of time the scope of what the Flash will be, or it won’t be in flux. The same goes for the wrapper classes with those who are in more formalized programming environments.

    However, sometimes you just get this problem that just defies all conventional ways of solving it. For example, a not-too-small widget was created in Flash CS3 using the new components. It may not easily portable to the Flex components in a reasonable time frame. What do you do? Attempt to get the Flash components to compile, with assets in Flex? I’ve tried this myself and wasted a bunch of time on it. I’m sure it’s possible, but I’m past trying, instead getting work done.

    Real world scenario; DoubleClick’s In-Stream for AS3. Apparently you can get the SWC to work in Flex… we couldn’t. Even if we could, you can can’t test the S.O.B. locally, needs a webserver… So, you have no choice but to use Flash in this scenario.

    In those situations, all you can do is load it in at runtime. The silver lining? Both are AS3. AS3 SWF’s can talk to each other. Your Flex SWF can call methods on the loaded Flash SWF. However, to call methods, the Flex SWF must “know” about those methods; hence being strongly-typed. You’d then have to share the same class between SWF’s. While this wouldn’t be too bad, Flash CS3 broke exclude.xml, the ability to compile a SWF, but excluding certain classes from it. You did this so you could prevent compiling the same class into multiple child SWF’s that you knew would have the same class waiting for them in the parent.

    Sanders commented on my past blog entry about this that there is apparently a way to get it to work. I haven’t read into it, but using intrinsics (namespace internal) seems a valid solution. Using JSFL, it’s also tons easier to create code generating and others tools for Flash than it is for Flex and ANT. Then again, I haven’t tried Europa’s (Eclipse 3.2) JavaScript API yet… me? Digressing? No way…

    Dirk originally came up with the idea of using interfaces when loading Flash content into Flex. At the time, Flex was Flash Player 7 only, and Flash was at Flash Player 8. Flash Player 8 had all the new effect filters; Flex did not. Using interfaces, you could utilize BlurFilter for example via a SWF liaison; file uploading too.

    The reason Interfaces are nice in this scenario is firstly because it’s small; it’s just a tincy class, usually less than 1k (micro-small in bytes when compiled to bytecode). Since you will be adding this interface to 2 or more SWF’s, it helps to lessen the damage. Secondly, it’s strongly typed, even in AS3. You cast things to Interfaces and even test if something implements an interface the same way you test to see if an instance is a class via:

    trace ( cow is IBigPimpin ); // true
    
    trace ( cow is ISpendinGeez ); // true
    
    var rad : IUberYum = cow as IUberYum;

    The steps for loading in a strongly-typed SWF are as follows:

    1. Create an Interface that both Flex and Flash will utilize.
    2. In Flash CS3, have your Document class implement that Interface.
    3. Compile your SWF (aka Test Movie).
    4. In Flex, load in the SWF.
    5. In the Event.COMPLETE handler, cast the result to the interface, and store it as a class member variable.

    Here’s a sample interface that we use at work to handle a loaded Dart.swf. It loads pre-roll videos and ads (animated GIF’s or SWF’s). Notice the events… they give you code hinting in FlexBuilder for loaded SWF’s (Flex 3 only suckaz), woo WOO!

    package com.multicastmedia.doubleclick.core
    
    {
    
            import com.multicastmedia.doubleclick.events.DartEvent;        import flash.events.IEventDispatcher;
    
            [Event(name="gotCompanionAd", type="com.multicastmedia.doubleclick.events.DartEvent")]
    
            [Event(name="prerollDone", type="com.multicastmedia.doubleclick.events.DartEvent")]
    
            [Event(name="error", type="com.multicastmedia.doubleclick.events.DartEvent")]
    
            public interface IAdModule extends IEventDispatcher
    
            {
    
                    function loadPreroll(adx:String,sz:String):void;
    
                    function getCompanionAdURL():String;
    
                    function getCompanionAdClickThrough():String;
    
                    function setVolume(val:Number):void;
    
            }
    
    }

    …yes, I know the DartEvent is compiled into both SWF’s, HOWEVER, it is tincy, and in this case worth it since it’s needed.

    Here’s some psuedo code to load the SWF into Flex:

    // reference to the SWF so you can call methods on it later
    
    var dartSWF:IAdModule;// this can be a SWFLoader in Flex instead, doesn't have to be Loader
    
    var loader:Loader;
    
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
    
    function onComplete ( event : Event )
    
    {
    
            // once loaded, cast t3h SWF as an IAdModule
    
            dartSWF = loader.content as IAdModule;
    
    }

    The caveat to this, which I haven’t tested, is if you load your classes into a different ApplicationDomain. The only person on the planet I know who does this is me, so you don’t have to worry about it.

  • PureMVC Frustrations and Code Behind Thoughts

    Over the holiday’s, I went to PureMVC.org to read over the documentation. PureMVC, although a year old, is the new framework on the block for developing Rich Internet Applications atop the Flash Player. There are plans to port the framework to other languages and runtimes like PHP & Silverlight in the future. Like Cairngorm, it’s a framework that uses coding conventions based on design patterns, namely the meta pattern, Model View Controller written in ActionScript 3. Unlike Cairngorm, however, it has no ties to the Flex SDK. This means you can use it with Flash CS3, Flex, or just pure ActionScript 3 projects.

    If you are a computer scientist, you’ll love the documentation. It’s chock full of design pattern discussions, justifications on framework implementations, and visual diagrams all in a nicely organized website. If you’re like me, the docs will get old after 30 seconds. I went straight to the example Flex project you can download to learn how it works.

    Upon digging, I found some familiar coding styles, and some unfamiliar. When I saw the use of View Mediators, however, I immediately got a bad taste in my mouth. I composed myself, and sent off a non-leading email off to Joe Berkovitz asking his opinion. I’m still waiting to hear back from Thomas B. I won’t speak for their replies, but it’s nice to know that not everyone finds PureMVC uber-perfect as the blogsphere’s reaction this past year has suggested.

    My first gripe is with View Mediator’s. A View is form, GUI, or some other visual control; it’s what the user sees in MVC. View’s can read from the Model, and ask the Controller to do things, inform the Controller of user events, and be informed by the Controller of the Model changing. A Mediator is a class that allows various classes to talk to each other without tight coupling. It is the de-facto design pattern in developing Flash & Flex applications. Farata Systems has a great post talking about it in context. A Flash Developer explanation is, “It’s a MovieClip that holds other MovieClip’s and allows them to talk to each other without them ‘knowing’ about each other”.

    In PureMVC, a View Mediator is created for each View. You don’t need to create this for all View’s since some via Composition (View’s used inside of other View’s) aren’t all that complicated and thus you don’t need to create all this code for such a simple class. The purpose of the Mediator as I’ve seen it used in the example Arch101Demo is to respond to Application state changes and/or events in the form of Notifications. Secondly, it can interact with Proxies to data; basically liaison’s to the data.

    There are a few problems I have with the first part. The Notifications contents are not strongly typed and thus suffer from the same problem that Cairngorm’s Delegates do that implement mx.rpc.IResponder. In Cairngorm, your Commands (classes that do Controller logic) can implement an interface called IResponder. This allows them to work with Delegate’s, classes that make web service calls. They return either a result or a fault. While the onFault is great in that you get back a FaultEvent that contains detailed failure information, ResultEvent is useless. You have to make assumptions on the data you get back since ResultEvent.result is cast as an Object. If I ask the server to give me a Person object matching an specific ID, I should get that back in my result event. If not, something went wrong, and my fault should be called. Instead, you have to force the Command (assuming you follow the standard Cairngorm Command way of implementing the IResponder interface) to “parse” data. Parsing data should not be in the realm of Controller logic, and instead be done strictly by services. Notification’s getBody, and other functions suffer from this same problem.

    It’s not the end of the world; people cast flash.display.Loader.content to what they “think” they are loading all the time. However, PureMVC had the opportunity to get things right here and they didn’t. The INotification interface’s list of functions (excluding getName) should at the very least return a type interface instead of Object. If you’re going to follow the whole “programming by contract” methodology, do it across the board and not just where you feel like it to support your framework.

    The other gripe is with ApplicationFacade events. You define Notification types (like Event types) that your Application will dispatch as constants. Your Mediator’s can then listen for these specific Notifications and react to them. This allows multiple Medator’s to listen to a single Notification. Whether they re-created their own event system instead of using Flash Player’s built in EventDispatcher system with custom Event classes for framework reasons, or whether they were trying to prevent application developers from burning themselves with un-registered Notification listeners causing memory leaks isn’t my main frustration. What is bad is that I fail to see how putting all of these events on ApplicationFacade will allow your application to scale in size.

    The whole reason you extend the AS3 Event class is to provide context to those who respond to those events. Some don’t care about context; for example, Application startup. However, when clicking on a List control, you need to know what item was selected, what was the previous item if any, what is the index of that item, and for View’s a strongly typed reference in case the Event bubbled up to you from a deeply nested View and you have no way to access the List in a parent child way. You can’t do that if you have a bunch of event names in the form of Notifications. Granted, you could package the payload into the Notification itself so it can act like an event, but the Notification has no strongly-typed way of doing that based on the INotification interface, and suddenly your packing in information into a Notification that others may not need. Granted part deux, yes, you could create your own Notification class, but explain to me why we’re not extending the built in Event class again? Event’s can bubble and be intercepted.

    Mediator’s have a reference to the View instance they are representing. The problem is, it’s up to the developer to handle this marriage. Cairngorm had something similar called a ViewHelper. It’s now deprecated, but the point of a ViewHelper was two-fold. First, it did the same thing Mediator’s in PureMVC try to do; greatly simplify the amount of logic in View’s. Second, they provide a non-GUI based class that can interact with others, preventing the View to have to know too much about the framework it’s in. In Cairngorm, they had an extra bonus of working well with a ViewLocator; a globally accessible class that allowed anyone to access a View’s ViewHelper by a magic string; it flattened the tree of GUI View’s.

    Mediator’s in PureMVC are definitely successful in those goals. If you look at their code and what the View’s in the example app are doing, it’s certainly more readable. There are also a lot less dependencies than say, Cairngorm where the second a View dispatches an event via CairngormEventDispatcher, it “knows” about Cairngorm.

    However, the down-side was in Cairngorm, ViewHelpers were created by the View’s. There was a 1 to 1 relationship that was instantiated when the GUI View was created. You couldn’t really screw that up. Although it was opt-in, a lot of people new to Flex just created 1 ViewHelper for every View. In PureMVC, they suggest you not only instantiate a Mediator yourself in a Command, but you also hand it the View instance yourself. While not major since ActionScript 3 allows us some strong-typing to ensure we “have the View we think we have”, why in the hell is not done for you? It’s an area where a developer can mess up; either they forget to actually create their Mediator, or pass in the wrong View reference. This is minor, but the whole point of a framework is to help you write less code, not more.

    Worse, what if I have multiple View’s? Do I then have to have each dispatch a new Notification (onUserEditViewCreate) just so I can create a new Mediator with a new View instance reference in a Command? WTF… the framework should handle these low-level details.

    The biggest gripe I have with PureMVC, and the one that made me all negative was how Mediator’s have access to Model Proxies. The ONLY person in MVC who should be able to SET data on the Model is the Controller. A Mediator, although merely having a reference to a View, IS associated with a View. It should NOT be setting data on the Model; the Commands should be doing this by listening to events (Notifications, whatever) dispatched from the Mediator’s. Just because a Command creates them doesn’t suddenly bequeath them Controller ‘esque powers. This is probably done this way because of my last gripe…

    …PureMVC Commands do not follow a true Controller pattern of setting data. One is instantiating a Mediator (StartupCommand) while the other is updating the Model (DeleteUserCommand). What the hell? I’d argue the DeleteUserCommand is correct, and the StartupCommand is wrong. In fairness, that’s because I’m comparing them to Cairngorm Commands. I’ll admit, this is the weakest argument I have, yet you have to agree it’s not consistent on what Commands are really for based on the example. Updating data? Creating things to have them update data? What if the Command wants to intercept the Notification and do something first, preventing the Mediator from doing it? Without a core Controller, you now have multiple types of classes setting data on Proxies. I can see it now… “Did I set the data in the Command or the Mediators…? Man, this’ll be a long morning…”.

    Thoughts on Code Behind

    On a side note, this is the second time I’ve seen a framework cater to a View code behind model. The theory and practice of code behind as it relates to Flex has been talked about and lauded a lot so I’ll leave it to Google to give you more details. The idea is that you utilize 2 classes or files; 1 for GUI and 1 for logic. The reasoning behind it is “separation of concerns”, the traditional computer science idea of making a large program easier to manage by breaking it up into pieces that each manage their area of interest. A lot of code in complicated View’s has absolutely nothing with drawing visual graphics to the screen, and is merely the logic behind the View. The current reason I don’t support this methodology in Flex is that FlexBuilder does not support it well.

    Silverlight & WPF on the other hand have tools built around this idea. In Blend, you control the actual real guts of the View; it’s layout, visual look, and transitions via XAML (like MXML). In Visual Studio, you code the logic behind it in C# or VB (like AS). In Flex, this currently feels forced. While convention helps, you don’t really get any help from the IDE in doing this methodology. This doesn’t bother me as I like coding my View’s to be 1 file and encapsulated. This can reduce readability, however, for complicated View’s that have a lot of code that doesn’t really relate directly to how the View displays itself.

    Cairngorm was the first framework I saw advocate this methodology via the aforementioned ViewHelper, leading me to believe that this is something Enterprise Java devs are used to doing. PureMVC is the second with the added twist of using the code behind not just as a separation of concerns, but also as a mediator the rest of the program that the View interacts with, hence the appropriate name. I typically use Mediator’s via Composition like Farata Systems linked above describes it. It is definitely a creative way of handling SoC and code behind in a framework way.

    Maybe if Thermo could create well written MXML and Flex 4 well written generated code-behind, I’d dig the idea and actually use it on projects.

  • Silverlight on TV and in Startups

    I get exposed to a lot of girly TV shows. The reason is, my wife is one of those people who can leave the TV on for background noise, but not actually watch it. I’m the opposite. If a TV is on, I tune out everything else and get enraptured. During the working day when I’m at home, I’ll get up to get coffee or some food from the kitchen, and then return to my office to continue working. This path takes me past the living room where the Tivo has selected some weird show about modeling or some other celebrity thing.

    One particular show was Entertainment Tonight. Walking back to my office, I saw the Microsoft Silverlight logo. Naturally I slammed on the breaks, and stood there staring. This guy, one of the ET hosts, talking in all announcer voice went “Go to ET online where you can view other video content powered EXCLUSIVELY by Microsoft Silverlight”. Wow. I think I’d convulse on the ground like a 1980’s break dancer if they said that about Flash Player. If Ice-T wasn’t enough, now we have TV shows marketing it. Holy fish.

    Miles away from Adobe. Granted, both companies I think do a great job at engaging developers, but while the Adobe community makes their own banners, Microsoft fronts the bling for a media blitz.

    In other news, I got my first Silverlight 2 startup email. All through 2006, bit smaller amount in 2007, I’d get a least 3 new emails a week from startups looking to create some web app using X back-end with a Flex or Flash front end. It was really weird timing. I just told my CTO last week that we should hold off on any huge Silverlight endeavors that are greater than video players until at least Q1 2009. The reasons were Silverlight 2 is still in alpha, there are no official components yet, and we’re still at an early stage. For all of my positivity about Microsoft’s toolsets, Silverlight the plugin still needs to become ubiquitous in reality. Everyone can talk about how Microsoft can use Windows update, installation CD’s, etc., but it’s all talk and no action. Until I see numbers of successful installations and I can duplicate the ease of install on multiple computers, it’s not viable.

    Hopefully by Q3 of 2008, we’ll have all the toys ready to play with. At that point, we can start doing some serious investigation into the realities of porting some of our existing Windows Media content into a more Flash based realm; where video is dynamic and multimedia centric. Granted, we can do this now with all the alpha bits. Tons of people and companies did this with Adobe’s Flex 2 Alphas and Betas, building real-world projects, just waiting for the final release. They are doing the same thing now with Adobe AIR; in beta 3 and people are chomping at the bit to release on a final version with their already built products. I just mean actual development that isn’t considered skunk works and done off the company clock to make real progress with investigations.

    I can see how a company could perceive on how they could effectively build a product on alpha bits given both public videos such as Top Banana, and Adobe’s track record with usable beta’s. However, Silverlight doesn’t have a component framework out yet. If I’m wrong and it has an alpha version, then you’re good to go; if not, there is no point. Spending your time creating a List component vs. using a List component to build your product is a waste of time unless you plan on somehow monetizing your component work.

    Anyway, the tone of the email was the same as the rest I’ve seen in the past. Meaning, there will be more emails like this one. The Silverlight marketing is working.

  • Mix n Mash 2k7, Bill Gates, Web, Blend, and Silverlight

    I had the honor of being 1 of the lucky 10 invited to attend the Mix n Mash 2007 event held by Microsoft. This is the 2nd one. It’s an event where they invite you to Microsoft’s HQ to see what they are working on, give feedback, and meet Bill Gates.

    Here’s a picture of the Mix n Mash invited attendee’s getting their picture taken with Bill Gates (I somehow got in there, booya!)

    From left to right:

    Jonathan Snook, Julie Lerman, Kelly Goto, Rob Howard, Bill Gates, Molly Holzschlag, Kip Kniskern, Jesse Warden (me!), Keith Peters and Erik Natzke

    (more…)