Category: Flex

  • Cairngorm vs. Joe Berkovitz’s MVCS

    Skip Intro

    You can’t go too long talking about Flex without also talking about Cairngorm. Cairngorm is a micro-architecture and lightweight, yet prescriptive framework. In English, it’s a set of classes and conventions you use to make large applications in Flex. It’s usually the main framework most bigger companies use when doing Flex work. I say most loosely because there is always the possibility of the loudest minority syndrome. While it may be lightweight, it certainly expects a lot of developer foreknowledge & experience at the get go.

    Cairngorm is meant for large teams working on large projects. Does that exclude it from small teams and small projects? No. Is it worth it? Depends on the scope of your project and less so on the amount of people on your team. There is nothing inherently wrong with 1 person coding Cairngorm as far as I’m concerned. It is made with the multi-developer project in mind and is suited for 1 person as well. However, if you are working on disposable software such as a demo, prototype, informal test case, or even a simple form, to me it’s not appropriate. The Pragmatic Programmer has something they call Tracer Bullets, which can be dangerously similar to a demo; you are creating an app for upper management to see. The temptation is to use the demo as the product. This happens more often than people care to admit, so… when in doubt, use Cairngorm to CYA. Steven Webster, one of the creators, has his take as well as when to not use Cairngorm.

    Getting back to the requirements, you have to appreciate OOP, mainly, the encapsulation aspect. OOP typically suggests to make your code black-box routines; you put something in and get a result out without knowing the details. One class shouldn’t know how another one works without following rules and patterns that justify it and keep it under control. If you don’t recognize the reasons behind encapsulation, Cairngorm won’t make much sense.

    Secondly, Cairngorm uses a lot of design patterns. Design patterns are a series of engineering theories that have proven themselves useful and predictable in their application in the real-world. They’ve then been adopted to the software engineering world and have helped a lot. Some are built into the programming languages themselves, such as ActionScript, whereas others can be developed by the programmer; some can exist in both. The keyword here is they are theories, and like all scientific theory, they can be proven empirically true time and time again, but never become fact. In my opinion, if they did, the software industry wouldn’t be as f’d up as it is right now. If you don’t recognize the need for patterns, or find their usage in large numbers tedious, you won’t like Cairngorm nor understand it’s value.

    Third, Cairngorm is a good, solid platform for a LOT of code. When I say a lot, mean Enterprise level projects where hundred of thousands to millions of lines of code are normal. A lot of rules breakdown at large numbers; Space-time inside a black hole for example and search algorithms with regard precision vs. recall. Google’s recall ability is what made it so successful [Ambient Findability]. If you aren’t going to write a lot of code (not vs. don’t plan to; 2 different things), and your application is extremely small in scale, you won’t like Cairngorm because writing a lot of the setup code for Cairngorm will feel repetitive and pointless; you’re writing flexibility you’ll never use.

    Fourth, which goes along with the third point, Cairngorm is setup for large teams. I’m not really sure what RAD development means, but I do know it’s spoken in tandem by managers with “a bunch of developers working on the same thing at the same time”. Cairngorm facilitates this in that the various parts that make up your application can be worked on by different people. One or more can work on the View’s, others on the use cases via creating Events & Commands, and yet others on testing their back-end services via Business Delegates; or multiple people on different classes therein. In the early days of Flash development, I had a hell of a time figuring who could work on what, and when. On larger projects where you have more resources, it’s now easy to find a spot for someone to work in tandem with others on the team. Although I am not a big proponent of large teams, I still like Cairngorm. If you are the sole developer… well, you’ll just have more code to write than you already do. If you can’t open source what you are working on to get help, you may see Cairngorm as more effort than it’s worth since you are the only dev. This assumes of course you have your own methodology.


    Cairngorm, in a nutshell, provides a nice Model View Controller framework solution for allowing mid-size to large teams to write code collaboratively, where the framework scales with the size of the project if used correctly.

    So does Joe Berkovitz’s MVCS.

    Now might be a good time to go read Joe’s article if some of the above points turned you off from Cairngorm. If they didn’t, cool, go read to see Joe’s somewhat simplified framework, and gain context for other solutions beyond the Cairngorm / ARP / Fast way of doing things. This blog post can wait longer than I can.

    Done? Pimp! Notice any similarities? A lot, huh? This blog entry sounding like I’m writing leading prose? I’m honestly not trying to, but when I read Joe’s article, to me, I found an extreme amount of commonalities. Joe’s been doing this stuff for over 30 years. I’ve barely done 6. The difference between Joe and I beyond the experience difference, however, is that I fail to see how you can develop anything without Cairngorm that is an application. If it’s a demo / prototype, fine. If it’s a single form, fine. A widget, fine. A 2 month throwaway project or something strictly written for a presentation, fine.

    …anything more? Why not start right from the beginning? Is it really that bad to dive right in?

    Unfortunately, it’s not that cut and dry. While it’d be nice if everything were measured in 2 weeks, 2 months, and 2 years development cycles, they aren’t, and there is a ton of in between, hence the confusion on when to implement a framework like JB’s MVCS, Cairngorm, ARP, and/or others, parts of frameworks, etc as well as when to do so. A variety of facets go into determining these things, way beyond a developers reactions to the 4 Cairngorm expectations I listed up top.

    If there is one thing I’ve learned my short stint in this industry, it’s that you never stop learning, and plateau’s are merely brief respites that are really temporary purgatories between your next large climb. Once you realize a new concept, you level up, assign your new skill points to various personal skills, and start heading for the next level. You then realize how much you really don’t know. Every time I go to a conference, I meet smart developers, and wonder how I even survive in this industry with so many smart engineers.

    So, hopefully some of the following confusions & frustrations Joe and others can comment on and give context so I can learn yet more.

    Before I rant (I already did?), I want to give context as to why I’m doing this. First, someone I respect said they respected Joe’s viewpoints in his article and really identify with them in terms of doing their real world development. After reading even just other bloggers’ comments that linked to the article, this kind of floored me because of previous expectations. Second, I’ve gone through blood, sweat, and tears to get to the understandings and appreciations I have now for various programming and design pattern concepts. For someone to offer an alternative approach who has a lot of clout… well, it certainly was a how did I get here moment. Third, Leif Wells wrote an entry going over Cairngorm, and some of the typical resistance you may run into. In describing the benefits, pro’s and con’s, it helped give me context to how team leaders view use of frameworks as well as Cairngorm’s public perception to others. His entry really made me think about if there truly is a line when it’s “too much”.

    Let’s touch on the first 30,000ft view point of Joe’s article. All 9 pages have one common theme; respect of good programming practices. Frameworks cannot exist without these; if they do, you shouldn’t be using them. They say wisdom of crowds can also be the mob insanity. To me, decades of smart engineers all agreeing through various blogs, books, forums, and scholastic disciplines about programming concepts being valuable as well as being implemented into real-world languages is enough for me. Like Descartes, I trust collected history of human experiences, ecspecially engineers. The great thing about programmers is that they are quick to point out there is an exception to ever rule. Therefore, even though we can all agree Object Oriented Programming has done a lot of wonderful things for this industry… JSFL in Flash doesn’t have classes for a reason. Procedural programming has a lot of valid offerings. The key here is that programming concepts, once learned, are a lot like language. Once you learn Literature (English as it’s called here in the US), you then get your poetic license. You can break the rules when writing because you know why you are breaking the rule; you are breaking it with impunity, intent, and have a desired effect. The same for programming. It’s okay to violate encapsulation if you have a good reason for doing so. It’s okay to use convention in place of stringent language features.

    Bottom line, to me, the crux of Joe’s article is that he espouses good programming practices. If you do too, inevitably your code will be good, and more easy to scale. Use what you need, leave out what you don’t.

    Let’s look at the similarities. Cairngorm has a model, a view, and a controller. JB’s MVCS has a model, a view, a controller, and a service. Cairngorm has a ServiceLocator, but that is merely for getting a reference to the service via a string name, keeping in centralized in case you change a CFC’s name server-side, or your Java FrontController moves to another server. JB’s MVCS Service, then, is more like Cairngorm’s Business Delegate’s, Delegates for short. Both invoke “server-side stuff”. Both create asynchronous operations, like making an HTTP request, calling a web service, making a Flash Remoting call, or even reading a local config file. Delegates get the locations of these things from the ServiceLocator, but inevitably “knows what they are”, and creates them. My Flash Lite 2 project, these are just a LoadVars. In my work project with Flex 2 and Java, these are HTTPRequests; about the same thing. Flash asks the server for JSON; Flex asks the server for JSON. It could be an XML request, a WebService, whatever. To me, these could be perceived as Operations. JB’s Services create Operations that make calls to the server as well. Both get and parse the data.

    Key point here, namely page 5 of 9, last paragraph. He makes a good point about the client side ValueObject’s (which both frameworks have), specifically, about optimizing client-side versions. I agree. One of the most challenging things I find in some of these database driven projects is mediating the lingo between me and the server-side developer. Sometimes, a project can go on for so long, I become unfamiliar with all of the back-end database table names, and DAO objects. Sometimes, the server-side dude’s expectations are of me that the client should match the back-end. This is idealistic, and unwieldy. I’ll usually “translate” back-end business-logic-translated-for-the-back-end-developers-desire-to-have-a-relational-data-scheme to something more reader friendly on the front end. Yes, we both have PersonVO’s with an ID, firstName, and lastName properties. But things like PersonPatientCrossRefVO’s, and various other meshes of value objects that are either base classes, representing a database has-a table basically, or just some back-end concept that has absolutely no relevance to my front end GUI, but has some ID I need to get data… I have to handle these things. You might not want to take a shower and wear a suit, by you do so to the interview to get a job. So, while the panacea for years for me was to have my server-side and client side ValueObjects be the exact same… this was doomed to never happen. Some stuff on the server I don’t need to know about… just enough to get an ID I need to “barter” with them to give me the data I need. The same holds true for me. A lot of my optimized VO’s, or neat Collections have nothing to do with the back-end, and are merely there to make it easier for me to make a good looking, responsive, and easily maintainable GUI that works well with data. Optimized bindings, organized lists, etc. In my blind rush to get everything to match, I learned that Remoting, in the end, was merely a more efficient client to server communication technology. It took a large project for me to see my folly. Smaller projects? Maybe still valid.

    It also implies, too, that Factories won’t go away. Neither Cairngorm, nor JB’s MVCS technically have the Factory pattern, but I use it in every single project I do now. Typically this is “throw some XML in, get a ValueObject out”, or JSON, and vice-versa. These are used in Cairngorm’s Delegates, or JB’s MVCS Services. Having a Factory create a nice client side version of our VO’s is very useful, encapsulated, and you end up with easier to read Delegate / Service classes.

    I disagree with page 8 of 9 where it talks about Service objects passing data to the View. View’s should get their data in 2 ways; either through binding to a ModelLocator, or better yet, passed in via a parent. Joe does write about this. However, a View knowing status of a service operation is a valid need. I’ve written my own Cairngorm modifications just to facilitate this. My way was invented when I brainstormed with my team (Nahuel Foronda, Tom Link, and John Yanarella). A View has a callback it passes into the event it emits for Commands. These Commands then call these callbacks when they are “done”. It passes back Callbacks, which are like events, but are strictly there for context since I personally was uncomfortable with the idea of the same Event class playing double-duty. Either way, in Cairngorm, setting Model data is it’s sole duty. There is a reason for this: You’re back-end can change from XML to JSON, and your Commands don’t change. In JB’s MVCS, you’d have to change the same services class.

    Is this bad? With few developers, no. Changing 1 class, or 1 bigger class is the same to me; just quicker to do the former via scanning. In a team environment, that won’t, fly, though. It’s pretty easy for me to have a Delegate in Cairngorm throw back a fake JSON object, and the rest of my team can continue working, even with the use cases (Commands). Additionally, while Command classes become significantly easier to read, for smaller projects, you’ll quickly wonder why you are writing 40 lines of code in a new class file that effectively do only 1 thing: set some data on the ModelLocator.

    JB’s MVCS has the nice benefit here of a View knowing the “status” of a call. In Cairngorm, your default knowledge is “I emit an event, and go about my business”. Usually, Flex devs will set their RemoteObject calls to show the busy cursor. So, Flex apps work a lot like web apps in that a background process goes off and the user can continue working. A lot of times, this can be dangerous. If the user clicks save on the form, and assumes the data truly is saved, closes their browser and leaves, that’s a bad thing. You need to give confirmation, and other times, you don’t need confirmation, but you need to lock the GUI. There are various non-Cairngorm ways of remedying this challenge. State variables in ModelLocator that the Command can set or my callback approach are two. JB’s MVCS doesn’t have this problem. The Service can set all kinds of variables in the Controller which the View can access and/or bind to to know the “status”. To me, that’s a nice way to say “state variables”. In the end, your View is not built to a VO, but a few state variables in the Controller. I hate state variables. They are a bitch to manage on larger projects. Regardless, so far, my Event callbacks at least allow my View to know when things are “done”. I cannot for example show a progress bar for uploading a file easily without breaking the spirit of Cairngorm, whereas in JB’s MVCS, it’s easy and legit.

    If you look at the first bullet on page 8 of 9 about the Controller having functions that a View can call being a lot easier than dispatching Events to run Commands in Cairngorm, he doesn’t say Cairngorm, but he implies it. Yes, it’s a pain in the neck. By why is it better? Parameter order. A function in ActionScript 3 has a strict order of parameters. These cannot change. If they do, you need to change all View’s that use the functions. Parameter View typically changes for the same reasons you’d need to change a property on an event. So, this is a mild benefit here that shouldn’t be underestimated.

    It is kind of frustrating, though, managing Event classes in Cairngorm. Some Events have nothing to do with Cairngorm, like flash.events.MouseEvent. Now, luckily, that’s intrinsic. But, your custom ones need to reside somewhere in your folder structure either in the same package as the Cairngorm ones, or not. I vote for not, but some people like re-use of Event classes.

    On page 9, he hits the interfaces questions, which are really good gut feeling metrics which I really agree with. Another really simple one to add: If others are going to use your code after you, use an interface. That way, they can’t whine about your inheritance tree, only your method requirements which is way more subjective. The fact that they can, by rules, play in your code with their code is much better than having to extend your code to play in your code.

    That’s why Cairngorm 2.0 to 2.1 was half a PR move; it made all the Cairngorm hackers like me happy! I could use my own modifications, and yet still be officially using Cairngorm 2.1 on a project.

    Additionally, on Singleton metrics, his first bullet point about asking yourself “could there ever be more than one of these, in this project’s lifetime?”. The exact same argument should be used for bindings vs. public getter / setters. Joe mentions this too, about having a parent set data on the child vs. having the child bind. It might not be apparent why you’d do this when binding is great. Beyond Joe’s reasons, debugging bindings is the most painful experience since a lot goes on under the hood when data changes. It’s easier to put debugging statements inside setter functions to recognize what really is getting set, and by whom. It also makes your View’s, like Joe says, flexible.

    So, as you can see, Cairngorm and JB’s MVCS have a lot in common. A lot of Joe’s concepts are heavily based on good programming practices. I’m not going to say that Cairngorm allows you to be a dumb programmer, but following the rules, you can have a variety of skill sets on a project, and still be very productive getting real, useful code out of the team. The Delegate code, for example, could be nasty, but at least it gives the data to the Command correctly, and later can be re-factored. I suppose one could use the same argument about a Service object, but again, they do 3 things, not 2, (get data, parse data, set model) thus open the doors for more trouble.

    To recap the similarities & differences, both have View’s, and agree that View’s should bind to a global Model of some sort, typically a Singleton using Flex’ built in data-binding. Cairngorm doesn’t explicitly state it, but having parents set data on View’s is more reusable like Joe says, for both. Both have a global singleton Model class of some sort. Both advocate making more than one if the class gets too big. Both respect the MVC approach of having View’s ask the Controller to change data on the Model, even though they have a reference to the Model to display data in it. JB’s MVCS has a Controller to do “stuff”. Cairngorm’s is done in Command classes, JB’s MVCS in the Controller class. I still haven’t figured out how you make the Controller class scale as opposed to Cairngorm Commands; when I used the Controller class in Flash, that thing got huge after awhile (aka a bunch of functions on _root). Cairngorm Commands set data on the Model and Business Delegates to get the data and parse it back for the Command which makes them. In JB’s MVCS, Services create Operations which do all 3, and can return that data directly to the View. Cairngorm does not have a standard way of doing this; it assumes that Views’ binding to a piece of data on the ModelLocator will have their data-bindings fired, which does work. Calling the Controller in JB’s MVCS is easy; you call a method on the Controller singleton class. In Cairngorm, you make an Event and dispatch it via the CairngormEventDispatcher singleton class. Neither proposes “return values”.

    Hopefully reading Joe’s article will do a few things. First, it should give you an understanding that regardless of what framework you look at, good programming practices are paramount. Second, there are simpler frameworks than Cairngorm. Third, you can understand more about Cairngorm now that you have something to compare it against.

    Me personally? I’m sticking with Cairngorm. I don’t see how the Controller in JB’s MVCS can scale, I don’t like being tied to parameter order in Controller functions, and I dislike the triple duty Service objects have after learning time and time again the benefit of using Delgates as a shield to changing middle-tier requirements. Regardless, if someone was using either framework on a project, I’d immediately know “how the app was built” which is something that shouldn’t be underestimated. There is nothing cooler going to a random client who needs Flex 2 help with an existing app, and they go “We used Cairngorm”. I immediately know how the app is built and can dive right in assuming they implemented Cairngorm correctly which is hard to screw up if you read the docs or hit up Flexcoders to ask if you are on the right track (or blog it).

  • Integrating a Flash Interface into Flex 2

    Flash Flex Design Example

    Flash Design in Flex Application Proof of Concept.

    To see a video walk through describing the code base, skip to the Code Walkthrough section.

    To get the source, head to the Source Code section.

    Introduction

    Unlike my previous article on getting a Photoshop interface into Flex, my goals here are to integrate Flash with Flex, not treat it just as a design asset tool, but a contributor to the functionality of the client; using Flash for enhancing the design, and helping reduce transition code which tends to be verbose in Flex. Below I’ve got a sample application that has integration of a complicated Flash design done using many different techniques. I describe the reasons for why you would want to work this way, compare with other techniques, and walk through the code & files in my example.

    To be clear, this is a proof of concept, and uses a variety of techniques for the purposes of showing developers a variety of ways to do things. It is not meant to indicate all ways to integrate Flash & Flex, nor necessarily the best ways for all occasions. Yes, I did in fact abuse this design fo schizzle my nizzle.

    Why Integration?

    Early on in Flex 2’s release, many Flash Developers recognized immediately that there were serious interop issues with Flash & Flex. This stems from the Flash Player 9’s new AVM, or ActionScript Virtual Machine that runs the new ActionScript 3 programming language. ActionScript 2, ActionScript 1, and Flash Player 4 scripting on down uses the old AVM engine. For security & various other engineering reasons, the AVM’s cannot talk to each other. This results in a SWF written in the Flash 8 IDE not being able to “talk” to a Flex 2 SWF. The need for doing such is that the Flash IDE allows creation of design content that Flex cannot create on it’s own. Flex 2 is an awesome programming environment compared to Flash, is approachable by developers, and is more geared towards large programming projects vs. multimedia. Therefore, there is much incentive to get them to work together, and not just by using a loadMovie approach (dynamically loading in the Flash created SWF at runtime).

    There are a few solutions out there. One is do just that; load in the content dynamically by using a SWFLoader component in a Flex 2 project. In the cases of a ActionScript 3 only project, you merely use the flash.display.Loader class. If the content can operate on it’s own, and/or show design content correctly, this is satisfactory.

    Another is to utilize a small set of classes to communicate via LocalConnection. LocalConnetion is a class that allows multiple SWF’s on the same computer to talk to each other. This helps bridge the AVM gap via viable API’s. This is asynchronous, however, and error checking is faith based.

    A third one is to utilize ExternalInterface. Flash Player 8 introduced the ExternalInterface, and API to allow Flash Player to talk, synchronously (aka to block) with its hosting environment and receive callbacks from those method calls. This not only allows strongly typing those external calls, but hosts can call into the SWF they are hosting as well. In this method an API is used to have the Flash Player 8 SWF that is loaded into a Flex 2 to make a call to ExternalInterface which calls out to JavaScript on the hosting HTML page. The hosting HTML page then forwards that call into the same Flex 2 SWF. The Flex 2 SWF can do the same thing going back since both SWF’s can independently register callbacks in JavaScript.

    A fourth option is to create the SWF using the Flash 9 Public Alpha up on labs. It has the ability to not only use ActionScript 3 in the Flash IDE, but can also produce Flash Player 9 SWF’s. One technique in doing this is to have have AS3 in the talk up to Flex who is loading it. There are some small gotchas with “digging” your way up to talk to Flex, but it can be done.

    So, why not use one of the above methods. First off, Flash is powerful; it’s not just a design asset. So, simply being loaded in isn’t good enough for some functionality; Flash & Flex need to talk. Secondly, LocalConnection isn’t syncronous, and doesn’t have good error checking. This makes debugging long and frustrating. Third, Externalnterface uses JavaScript. You’ve now gone from 2 languages to 3; ActionScript 3, ActionScript 2 (or 1), and JavaScript as well as at least 2 different tools; Flex Builder for ActionScript 3 and JavaScript and Flash 8 for

    What does integration get you?

    I’m making it sound like integration is actually not the best solution, but rather, the less of the evils. It is. This is how things are, and even when Flash 9 is released, things wont be much better. Regardless, Flash can produce design content that Flex cannot, and used together the tools are powerful with the right team. Integrating Flash into the developers work flow rather than a design afterthought is the best thing to do on larger programming projects; which is typically what Flex is used for. Either that, or the primary skill set on your team is traditional programming, and thus the natural choice is Flex vs. Flash, in which case, Flash is the odd man out, but still a valid contributor.

    As mentioned above, you can use the same code. You can write a Flash component in ActionScript 3, and use that same component in Flex. You can integrate it into the same Flex project and check it into the same version control. Traditional programmers will get that good feeling they typically don’t get with Flash projects with regards to maintenance.

    You can compile the same code in both programs. Since you are using ActionScript 3, Flex Builder, mxmlc, and Flash 9 can compile it. Granted, there are caveats with embedding, and it’s a bitch. If I knew RegExp, I’m sure I could get an Ant script to do it. Leif suggested to look into it, but this isn’t my strength. Either way, you can even create Flash based test cases that you only use to test the Flash symbol class using the new Document class feature. Flex, which typically wraps the symbol class created in Flash in a UIComponent class via composition, can have it’s own test case.

    You can compile once in Flash. Like the MTASC days of old, mxmlc, the commandline Flex compiler, has the ability to do bytecode injection; aka compiling incrementally. What this means is, you can compile in Flash for the mere sake of “getting the design assets into theSWF”. If you later change the code in Flex, it’ll merely change the code, but leave the original SWF design assets intact. Since you are embedding the symbol class into a main Flex SWF anyway, it’ll compile the assets in the Flash SWF into the main one, and use the updated code you just changed. This is nice because it basically treats the SWF’s as little design asset DLL’s so to speak, and uses the most up to date code. Unlike DLL’s, the SWF’s aren’t needed at runtime . It also means, you don’t necessarily need Flash to compile the Flex project, which scores major points with some traditional programmers. Third party developers and/or contractors, based on requirements, can deliver just a SWF to some clients or a SWF and a class(es) without having to turn over a FLA. I always give my source to clients, but I know some people have legal reasons for not being able to do so.

    Finally, you can produce more types of components. Since Flash can do some crazy design ideas that Flex can’t, or can’t quickly, you can integrate a lot of that into components to be used in Flex; 3D exported to FLV integration, various compositing, and other hardcore visualizations.

    How does integration work?

    For a simple example, you can see here where I use a Flash 9 button in Flex 2.

    Integration starts with coding the component in Flash you wish to use in Flex. Everything is a component; you think in that mentality, no matter how small the asset, and you’re good to go. You write an AS3 class that represents the asset in Flash. Like the AS2 days of old, you make the linkage ID of the symbol in Flash point to your AS3 class. Since everything is a class now in Flash Player 9, your Flash design component asset is too. This class, by my convention, ends in “Symbol”. So, if you are creating a glowing button, it’s “GlowButtonSymbol”. The “Symbol” denotes a Flash based asset. That way, when you see the class amongst hundreds of others, you can immediately identify it as Flash specific. Typically, the only thing you would do in Flex Builder to this class is add the Embed tag at the top. Flash IDE will ignore the Embed tag when compiling.

    The second step is to create a UIComponent based class in Flex. This class will use your Flash class via composition. You are not required to extend UIComponent; you could extend Container or Canvas for example. A lot of Flash components, however, are design assets using low-level, boilerplate design functionality, so UIComponent usually is sufficient. Everything has to be at least extend, or be wrapped in, a UIComponent. If it’s not, Flex will throw an exception.

    That’s it!

    You can take this a little farther. I like to create test cases, classes that test to see if the component, and only that component, works. They basically throw it on the stage, and calls their exposed methods, if any. This makes debugging a lot faster and a lot less frustrating. It may seem to take longer at the beginning; it does. You’ll find, though, in the long run you spend less time compiling your whole application only to find one stupid thing in your component made everything else blow up.

    In Flash, this is just test_GlowButton.as. This class is a Document class that you input into the Document class field in the Flash 9 IDE. It attaches the component and hits some of it’s methods. I like to use keyboard commands to test methods and such. You can save this in the same Flash folder as well, thus segregating it from the rest of your code base.

    In Flex, I basically do the same thing: make an application class, embed the component, and test it’s methods. Flex Builder 2 makes me keep these on the root folder, though, since they are Application files… *cough* *Flex Team* *cough* *fixplz* *cough*.

    Pitfalls & Frustrations

    “Is it that simple?”

    No. There are a plethora of gotchas. I’ll try to list the most glaring here.

    The most annoying is embedding of sound and images in Flex. For example, Flex doesn’t have a library. You therefore use embed tags in your Flex code. This associates an external image or sound with a variable, and you can thenceforth treat that variable as a link to the asset. This embeds it in theSWF, so you don’t have to worry about preloading, unlike using loadMovie on external images or Sound.loadSound for streaming MP3’s. Flex wraps these assets in special classes called “Asset” classes. Sort of the same thing when you import a sound into the Flash Library, and export it with a linkage name. When you embed a Flash MovieClip symbol in an eternal SWF , it wraps it in a mx.core.MovieClipAsset class. When you embed an image, it wraps it in a mx.core.BitmapAsset class. This is nice. You get strong-typing with embedded assets.

    The bad news is, Flash doesn’t have access to these classes. I reckon you could use intrinsics, a class that implies “it’ll be in the SWF at runtime”, and allows Flash to compile. These have to be installed in the Flash 9 classes directory, though; if you put it in Flex’s project directory, things could get dazed & confused and Flex isn’t from da erf. If you have to recompile in Flash for whatever reason, you have to comment out the sound code, compile, then undo your comments. Running Flash + Flex Builder at the same time with design intensive files open uses a lot of RAM, thus your comp goes slow, further exacerbating the frustration.

    Fonts. Are. The. WORST! Flex 2.0.1, which isn’t yet, apparently has fixed some font importing challenges so you can import more than just polite ttf’s. In the past, if you wanted the Flash Player 8 FlashType (aka Saffron) engine to show really nice looking fonts, you had to embed them using Flash 8, and then reference that SWF as the font source in the Flex CSS. Either way, it’s commonplace to utilize fonts willy nilly in Flash without thinking about what you are embedding. Static text fields, for example, embed fonts by default. There of course is the issue between how they are embedded. Bold or not? Animation anti-alias or readability? Did Flex already embed the font? Who killed JR?

    For example, I finally get a build working last night. I then implement the preloader via the preload attribute on the Application tag. Suddenly my navigation fonts don’t work. Huh? After 2 hours, I finally got it working again. The Flashpreloader had 2 static text fields that were using the same font that Flex was using. The difference? The preloader wasn’t using the readability version. It’s crap like that that eats away at your productivity and makes you want to start smoking again. Fonts have always been hard in Flash; now you REALLY have to micro-manage that stuff.

    Flex Builder caching is another gotcha. When you recompile in Flash, you have to refresh your Flex Builder project. I usually refresh the whole thing; I click on the Flex project base folder, and hit F5. This can take as long as the dreaded “Building 0%” you see on the bottom right of Flex Builder / Eclipse. Basically, it’s just copying the updated SWF to your bin folder and/or re-compiling it into our main Flex SWF . This can drive you nuts if you are compiling, and fail to see your changes. Refreshing isn’t always enough. Sometimes, if you recompiled fonts or bitmap stuff in Flash, an actual Clean project is appropriate via the Project menu. Takes longer, but it works EVERY time. Good sanity check, that is.

    Flash doing whack AS3 builds is another problem. It’s probably because I have alpha bits, because sometimes, if your class path changes, it’ll compile theSWF, but not with the real class. I’m not sure if Flash 9 is caching ABC files (AS3) vs. ASO (AS2) or what, but I’ll call methods on the class, and Flash compiles, but at runtime claims the method doesn’t exist. Go strong-typing. Anyway, you’ll go nuts staring at correct code, when in fact, the problem is your class path. I suffered a lot from this since I transfer code back and forth between my Mac and PC as well as re-factoring twice.

    Framerate really can suffer in Flex. There are a plethora of reasons for this, but I’m having a hard time finding the time to make reproducible test cases to track down the issues. Here are some theories. First, I think Flash is better at producing SWF’s that “know” how to preload themselves. So, if you have a long PNG sequence, the SWF will playback well because… well… because Flash is good at doing animations. The same animation in Flex, though, is slow. Now, this isn’t as clear cut as that sentence reads. For starters, most of the Flash stuff I use is in states. States in Flex utilize the Flash Player 9 DisplayList. The DisplayList allows you to have a MovieClip exist, but not be drawn. My guess is, this violates the typically, “Hey, there is a long timeline with a lot of assets about to be played, let’spreload it.” Now, it’s “We don’t have to draw anything, so just chill…”. Thus, it doesn’t preload the required assets, and the animation plays slow.

    States have the benefit of removing children that are not applicable to a state you are in. So, in the case of a LoginForm class that has the states of “signIn”, “error”, and “register”, the actual registration fields are not shown. They can actually exist to support databinding, but the actual vector graphics that represents them isn’t drawn. This is great.

    For Flash animations, this isn’t so great. Especially when they are shown, and it now has to play the animation AND preload the assets, thus reducing your intended frame rate. That’s my theory, anyway.

    Worse, states have the nice feature of removing children from the DisplayList that aren’t being drawn in the current state. My guess is, Flash Player uses this as an opportunity to run Garbage Collection on the not-being-drawn-assets. Remember, the unofficial ways the Flash Player 8 garbage collector works is A) every 60 seconds and/or B) when RAM usages increase by 20% or more. In the case of 60 PNG’s , each utilizing a meg of RAM (compressed!), that’s a ton of memory usage. Naturally, as soon as that animation is removed from the DisplayList, he’s a prime candidate for collection. Meaning, the PNG’s are no longer in RAM. When the animation is played again, it’s slow because the frames have to be loaded into memory yet again. That’s my theory too.

    For the preload, my fix was pretty simple. You basically make a frame called “asset preload”, and throw EVERYTHING that animation needs on that frame. You can even put it at the front of the animation, in a graphic, alpha’d to 0. This forces Flash Player to throw all the assets in RAM. Since Flash Player is generally good at not running Garbage Collection while animations are going, you can usually be sure your animation will then run well. Did in my tests, anyway. This does NOT work if your computer itself is running low on RAM. For example, I ran a bunch of these examples at once, and my computers GC + Flash’s I guess were running at the same time, cause it’d freeze during the animations. That’s just my CPU being a pansy, though. No soup for you, sucka.

    For the latter… not sure what to do. In Flash, this was easy. You just make a MovieClip’s visible property false. It’s still there, just not being shown, but as soon as you make visible true, it draws immediately. It IS being drawn, though, and taking up system resources. The DisplayList does the same thing with remove child. You can actually have an animation playing, but not in the DisplayList , taking up resources. It’s better than visible = false, that’s for sure. Either way, my guess is, visible = false is a better safeguard against Garbage Collection unloading your preloaded animation from memory vs. removing it from the DisplayList altogether. This is easy in Flash, hard in Flex if you are using states.

    Sound compression is kind of frustrating too. For Flash, there are a multitude of ways to compress it with more codecs. In Flex, it’s a little harder. If you are sharing a lot of assets, you may run across the same sound sounding different because Flex compressed it differently. Really annoying. Or, you forgot to re-comment-in your code that you commented out to compile an ebmedded SoundAsset in Flash… thus you never compiled your sound into the SWF. How’s your brain’s cookie trail?

    Resource usage is the biggest kicker. Eclipse 3.1 on my PC came, get this, standard with a max of 40 megs in the Eclipse ini. That’s right, 40 megs! AH, to be a full-time Java Developer, and need only that much. When dealing multimedia content, us Flashdevs need all the RAM we can get, and then some. Specially since FlexBuilder can actually render some of those SWF’s in real-time in Design View. It actually got so bad at one point, I couldn’t even compile! Java 1.5 would collapse on my Windows XP page file faster than Mike Foley, the guy who lives in a trailer down by the river, does on your coffee table. I closed every program to no avail. After finding this blog post, I upped mine and immediately everything worked fine. For the record, didn’t have this problem on my Intel MacBook using the standalone install of Flex Builder. In fact, I gave up looking for the Eclipse.ini on the Flex Builder install (non-plugin) because the performance was acceptable.

    That’s the worst of the minefield.

    The rest really have to do with the new ways Mouse, Keyboard, and focus events mesh with the updated and now built-in EventDispatcher and making sure you know exactly how things are working in ActionScript 3. For example, when listening for MouseEvent.CLICK events from your Flash created button, you’ll get 2. This is normal. By default, it sends one, as does your UIComponent. Since MouseEvent click events bubble, they’ll get to whoever’s listening. You should intercept it in your UIComponent wrapper, call stopPropagation on the event, create a new event, and dispatch something more meaningful.


    Application Example

    Flash Design in Flex Application Proof of Concept


    Code Walkthrough

    Here is a video tutorial walking through the code. In it, you’ll see animations created in Flash and then used in Flex in a variety of ways. I’ve also implemented someCairngorm 2 action with real dynamic data to showcase this isn’t just a proof of concept with no substance.

    Code Walkthrough Video Tutorial


    Source Code

    Please note: I cannot give you access to FLA’s and fonts because I legally don’t own the design. The video tutorial should show you enough about how they are made. The actual code that made them I did include, as well as theSWF’s. Therefore, you CAN compile this in Flex using the provided SWF’s.

    If you want the design, you can purchase it at Templatemonster.com, direct link to the design here.

    Source Code to Flash Design in Flex App Example – View Source | ZIP

  • Flash Player Can’t Read Ur Stuff & Access T3h Internets @ T3h Same Time

    Can’t sleep, must blog. I’m thinking of rigging up a dart frog blow dart gun next to my office desk. I can basically lean forward to my right, pull a nylon + silk, 1 inch thick drape rope, much like the Adam’s Family did to summon Lurch, and I’ll promptly be knocked unconscious with the dart protruding from my neck. Insomnia sucks. Might as well put it to good use. I was accused of having a similar setup in high school, except, instead of a blow dart, it was red velvet curtains that would part, and a salt lick would slide down; a massive slab. Salt licks are stationary blocks of salt left to attract dear; typically used by hunters. Instead of salt, however, it was a massive slab of solid caffeine that I apparently licked every morning before arriving to school. This wasn’t true, although, red velvet curtains sounds h@wt! Drinking coffee at 14 isn’t such a good idea; note to self for future teenagers.

    …anyway, Flash Player. Flash Player 8 had this (yet again) new security model put into place. They call it a “sandbox” so you think it’s this happy place to keep honest people honest. Basically, a SWF can (only) now:

    – contact interweb sites, but not local files
    – load local files, but not internet sites
    – do both with a modified configuration file installed on a user’s computer in a special directory

    An EXE, aka, a Projector, is exempt. If it’s not, you’ve got a virus, abort, abandon ship, JesterXLs’ and women first.

    Granted, you “can” theortically get the 3rd option to work via Settings Manager, but I’ve never heard of anyone publicly getting it working. Using that tool myself makes me cringe. It’s easier to just ask someone that trusts you to run an .exe you made for them via a 3rd party Flash Projector. Unfortunately, a few people who published CD-ROM’s in the past without such projectors had their content break when their users updated.

    I believe the Flash IDE allows this via the special player that it uses when you do a Test Movie ( Control + Enter). I could be wrong.

    I DO know that Flex Builder 2 utilizes the config files I mentioned. It basically writes them to exempt your bin folder. That way, you can load XML files locally for configuration stuff AND have that same SWF access various back-end services, either local, or on the web. When you do a new project, it’ll point this config file to our bin directory, thus making a SWF in there capable of having a wonderful time… like Optimus Prime or Gman for example.

    What if this ISN’T written? You’ll get a security error. You can compile SWF’s to do one or the other in Flash 8, as well as Flex Builder’s mxmlc. For both, you’ll need an EXE, or access to the user’s box. Naturally, the 3rd never happens for most of us. In development, though, it’s all us. I’ve seen this fail for the first time, today.

    We’re not allowed to check in bin, html-template, .settings, .project, and .actionscriptSettings into CVS, which I agree with. However, apparently when you do an import project in Eclipse, it doesn’t do any Eclipse magic without the main project files in there. Even “Adding Flex Nature” to your newly created Eclipse project doesn’t seem to add the entry. If you delete the project, and then re-import with the goodie config files in there, it apparently goes and writes the config file. Example path on PC:

    C:\Documents and Settings\[username]\Application Data\Macromedia\Flash Player\#Security\FlashPlayerTrust

    Why should you care?

    If you start testing things in Flex Builder, and it starts bitching that your SWF “isn’t allowed to access” either local files or remote files, call bs on FB, promptly add the entry, and reboot your browser. The last part ensures that Flash Player reloads the .cfg files and knows who’s allowed to break the laws of nature. For me, there were 2 entries in 2 files. The flexbuilder_plugin.cfg and the flexbuilder_plugin.fbr files. The first is easy; you just paste the bin directory’s file path. The latter is… weird. Just copy and paste the one above it.

    Granted, you’ll hopefully never have to do this. I only write for the poor sod searching late at night on Google for ytf his stuff isn’t working.

    More specific information (still relevant to Flash Player 9).

  • Double Line Breaks in Flex Builder 2 ActionScript Files

    Check out a fresh build today of a project I’m working on, and all the AS files have double line breaks in them while the MXML are fine. So, instead of:

    public function Class
    {
    }

    It was:

    public function Class

    {

    }

    wtf?

    Open in Notepad. Looks fine.

    Open in WordPad. No line breaks.

    WTF?!

    Open up Flash 8, do a LoadVars, and inspect the onData result in the debugger. \r\r\r\n after each line. Huh? Didn’t have this problem with various other people on PC’s & Mac’s using Eclipse, Flex Builder 2 plug in, and SubEclipse. My setup was different than last week. Instead of a MacBook using the above, I had switched to my home setup; PC, 2 directories (one for source, one for development), TortoiseCVS, and Beyond Compare as my diffing tool.

    Mike Morearty
    hit Google for me and found that this is a common problem with some CVS setups. Basically, CVS does a good job at handling multiple systems. Eclipse will even inject the necessary line breaks for viewing, but SubEclipse will take ’em out so Unix is happy. Actually, it’s not that simple. The post Mike found is like 9 frikin’ pages about line breaks and such.

    Bottom line, I had to check this one check box on the 3rd tab of TortoiseCVS when checking out a project to “keep Unix line endings” or some such, and all was well. Thanks Mike!