Category: Flex

  • Building Tracer Bullets with Flex Builder

    Skip to “Flex Tracer Bullets” to bypass all the philosophy and justification.

    Preface

    The Pragmatic Programmer, a must have programming book, talks about using Tracer Bullets to help clarify and further define requirements. In military terms, a tracer bullet is a special round of ammunition that burns brightly when fired from a weapon. It’s every few rounds, so not every round is a tracer round. It is very easy to see, and thus the person firing can adjust their aim accordingly. In essence, you build an early version of your software that matches the client’s requirements as closely as possible, and get it to them as quickly as possible. The Pragmatic Programmer makes special note that Tracer Bullets are different than prototypes. Prototypes are usually disposable whereas Tracer Bullets are built with the understanding that they will eventually be used in production level code.

    If you’ve read any of the Ruby on Rails books, one thing they espouse is client involvement. Getting the client something tangible to see and play with in mere days. The “play with” is important. Many times in my career “comps”, visual wireframes with some design treatment used to illustrate the entire application, have been treated as the front end developers final requirements. They never end up being this, are never thorough, and resist change (because of the expectations of them). A picture of an application, and an actual application are 2 different things. Giving the client something tangible, that appears to work like the real application, gets them as close to the application as possible. This intimacy generates the most valuable feedback you can get next to user testing. The difference is, this is pre-launch feedback, so you can implement it before you deliver.

    This is important, not just because the client is actually happy the day you deliver the final build of software that meets their expectations, but because of all the bad things you’ve prevented. I’ve read and heard many stories about how weeks were spent in development going down a path the client approved, only to head off exactly the reverse direction for another few weeks, with extremely frustrated developers. Worse than that are the miscommunications , whether by the telephone effect, or the mere lack of anyone I’ve ever met to actually effectively extract customer requirements that are factual. You then think you are going in the right direction, only to have the client say that wasn’t what they were looking for at all.

    Bottom line, it’s better to spend 3 days hashing out some ideas with fake data in your code for sales or the client to see and play with rather than 1 week on requirements gathering, and then 2 weeks in development. The problem with the latter is that you have no guarantees the requirements didn’t change, they were accurate in the first place, or the client will even like what you’ve done even if the requirements and what they wanted were one in the same. Requirements and software are 2 different things. Furthermore, even if you are agile to changing requirements, requests on paper and experiences using software are vastly different as well. In the end, clients are paying for the latter.

    I’m pretty harsh on requirements, I know. That’s because my personal philosophy is, “What do you want the software to do?”. Once told, I go build something, show the client, and go from there. Using early builds (a build meaning a working version of the current, compiled code) as tracer bullets has worked well for me. Sadly, I haven’t found out how to get tracer bullets to work for fixed budget projects. When you don’t even have time for a prototype, you usually just have to rely on your experience and hope you have aim like a sniper.

    You build a tracer bullet, an early & working build, to give to the client and let them use it. You garner feedback, and adjust your direction from there.

    Flash vs. Flex, Prototype vs. Tracer Bullet (again)

    Flash Prototypes

    If you would of asked me a year ago what’s the best way to do tracer bullets, I’d probably have said take a hybrid approach. Build a Flash prototype, and if the client digs it, you can then transition into production code once your direction is more solidified. You can then show them builds every few days (or Thursdays so they can play with it on Friday). The cheapest and quickest way I’ve seen this work is to have a Flash Designer work with the Interaction Designer/Information Architect (maybe they are all the same person), and produce a series of working screens in Flash. The data is fake, but the buttons do in fact work. These are most effective if you can even have some simple use cases working as well.

    For example, if the user needs to “create something”, the prototype will actually have the data the user inputted into the forms actually update a DataGrid for example. Even smoke and mirror effects such as this work wonders with sales and real clients in my experience. Most don’t really care the data isn’t live, and you even run the risk that prototypes are fraught with: that they are perceived as a real application, and are immediately latched onto. At that point, you better hope you can duplicate all of what the designer created in production code. Common problem, but a good one. The biggest point of contention was getting a Flash Developer who could duplicate accurately whatever the Flash Designer had created.

    It’s even worse nowadays for some Flex Developers. As our industry grows and we start taking on traditional programmers who are skilled at code, but do not have a lot of the multimedia experience a lot of Flash Developers sometimes have, a lot of Flex Devs shudder when they just even get complicated “looking” design comps. It’s one thing when your IDE has a timeline, and boilerplate level graphical control, but it’s completely another when you are at the mercy of the component framework you are building upon. Component developers will scoff at this notion, as it is definitely true that you can build components around any design. Either way, those things take time, are not easy, and are typically code centric vs. design centric implementations. It’s even harder when your tool wasn’t designed for it.

    Bottom line, I’ve seen a lot of value in Flash prototypes. Pre-ActionScript 3 is more loosely typed, and Flash is a RAD tool, allowing you quickly build working applications with tight design control, even if “working” is faked. The product of this work makes a great shock troop; quickly in sales/the client’s hands, with next to immediate understanding of how on/off base you are.

    Rapid Application Development isn’t Bad, it isn’t Good, it just is

    Flash prototypes work for more design centric RIA‘s as opposed to larger scale applications. This is because these types of applications, such as an online banking application, or a financial planning tool, are usually business driven. This means the visual aesthetics are usually the least important part of the entire project. For the record, I hate that and strive daily to change that. Yes folks, it IS possible to have a financial planning tool that not only provides sound advice on your economic future, but looks hot doing it. “R” in “RIA” for the win. Regardless, the default Flex components work wonders in looking “good enough” for any application. With working functionality, they shine.

    Flex Builder 2 specifically on it’s own, however, isn’t as RAD as Flash with regards to design projects. I’d argue the reverse for business projects. Either way, both allow you to end up with something that you can use later if coded with as much best practices as possible given the time constraints. This is key because I’ve seen a lot of blogger comments critical of the “RAD” term, feeling like they’ve been sold a bill of goods. They immediately perceive RAD as un-scalable and I don’t think this is fair. They are immediately implying success.

    Let’s take Twitter for example. A few in the blogsphere used Twitter’s performance issues as proof in the pudding that agile/rad languages/frameworks may get you something that works quickly, but that working application doesn’t work well under pressure. I liked the counter argument one commentor, John Ballinger, posed as a rhetorical question in this blog entry (scroll to comments):

    Could Twitter have used any other language (YES of course) but would they have been able to build it in the time and been agile to the constant changes that “may” have ultimately lead them to the current explosion of traffic they have today?

    What I believe John is implying here is that by using a language & framework that allows them to produce a good and working product quickly, they become victims (in a good way) of their own success. If they weren’t quick to market with the flexibility to respond quickly to their users, they wouldn’t be in the situation they are just getting over now because they wouldn’t have a mass of users to begin with. Bottom line, I’d much rather have scalability problems that I can solve with my teams’ programming know-how vs. a scalable site (in theory) with no users. No one cares about scalability if you’re not successful… after the fact anyway.

    Going with RAD (rapid application development) really meaning what it says and not being inherently evil, just being what it is, I believe Flex is a RAD tool just like Flash. The difference here is using it to write code that is a good foundation.

    Flex Builder Tracer Bullets

    So how do you write Flex Builder Tracer Bullets knowing that Flex can be a RAD tool and Tracer Bullets are good to do? Here’s 2 lists:

    Technicals

    1. Don’t use ActionScript, use MXML
    2. Use states, don’t use transitions
    3. Write strongly-typed ValueObject’s based on client’s data needs
    4. build workflows, then build use cases
    5. use copious amounts of tagged builds in Subversion (or whatever source control you use)
    6. componetize sections
    7. use Canvas first, Panel later
    8. make builds easy to see
    9. use fake data from real ValueObjects
    10. put event handlers in Script tag, not in MXML

    Esoterics

    1. Find in a friend in sales (or a stakeholder at your client)
    2. Write emails to stakeholders (sales/client) that ask a question that can be answered
    3. recognize opportunity, and take it
    4. use a phone, not email or IM

    Don’t use ActionScript, use MXML

    Flex Builder can render MXML components pretty accurately whereas ActionScript components not so accurately. This means you can see, in the Design View, your application as it’s coming together. This includes GUI controls and your use of states. Having to compile your app just to see one component visually is slow. Build in MXML because it’s faster to write, and faster to see.

    Use states, don’t use transitions

    A lot of screens have specific states. Some have none. The majority, do, though. It’s quicker to make 1 LoginForm with 3 states than 3 different MXML views that make up a LoginForm. Quicker to edit, too. Flex Builder can show you those states visually, and automatically write the code for you to add & remove controls as well as changing their properties when the state changes. It’s always easiest to start with “main_state”, and go from there. If you don’t, you may later have to copy and paste MXML you’ve already written into AddChild tags individually which are themselves in state tags. Total pain the arse. Do it right the first time.

    Transitions, the animated changes between states, add a lot and make the user’s eye-focus putty in your hands. Don’t do it yet, though. Wait until you’ve gotten direction on your app before you start directing the user’s attention. Transitions are probably the most volatile code in your application, and are also the most subjective. Finally, they cause unexpected changes later when you start throwing data at components that causes their state to change (like custom item renderers for example).

    Define clear states for each View (component), and build them using Flex Builder. It’s ok to hand type MXML as well.

    Write strongly-typed ValueObject’s based on client’s data needs

    Understand the data you have, as a client developer, early. Whether it’s coming from your server team, the client’s server team, or both, understand what you are going to be able to represent that data model in a strongly type set of classes. These do not need to match the server, and new ones can be created specifically to make GUI development easier, including properties. Getting these done allows you to be build View’s (components) that actually have accurate GUI controls on them to represent the data. No VO’s, and your just guessing. VO’s give your GUI design direction, give it purpose.

    If there is contention in the VO’s, you have a communication problem. Solve it, learn the nomenclature, get the lingo down. Collectively agree with all parties involved to have 1 name for everything. While some developers will say 2, “We call it an asset ID, but the customers call it an item ID” you’re just making it more confusing for you in meetings, emails, and IM’s. Bad communication will sabotage any project, and clear data is the key.

    If they are strongly-typed, when you decided to re-factor, you’ll get compiler errors in Flex Builder which makes it easy to quickly change names in places that your global find and replace didn’t catch (or if you were just too paranoid to do so, by hand). In this way, you’re application is resilient to change… and it’s not even really an application yet.

    build workflows, then build use cases

    A task that the user needs to accomplish is solved by an effective workflow. A workflow is the way a user accomplishes that task by being guided or “led” via the user interface. These are the most important parts of an application, and need to be nailed down first. They are also the first cement to dry when coding your application (meaning hard to change later without drastic consequences) so it’s best to really think these out based on sales/client dialogues. More is better. If you have more than one idea to make an interface that allows a user to create a widget, go for it. If it’s up to your Information Architect or Interaction Designer, let her/him know in no uncertain terms the clock is ticking.

    Once you get a workflow down, “The user is shown a list of their savings plans. They can then interact with these savings plans”, it’s now time to build use cases around them. The user needing to upload a file is one, the user needing to be able to filter visible data is another. Use cases are things the user needs to do. They usually collectively make up the task the user needs to accomplish. Sometimes, they can be task in and of themselves. The point here is to ensure you have a solid workflow first, THEN start working on satisfying your use cases.

    Both should be put in builds and thrown at your client with abandon. It’s ok to walk them through it in guided demos; this is brainstorming, not user testing. This is how your application will effectively work, so make sure you client can do what they need to do and can see what they need to see.

    use copious amounts of tagged builds in Subversion (or whatever source control you use)

    If you get a working build with specific functionality, make a tagged build in Subversion. If you are not using Subversion, mark the current build in your repository with a special label (in CVS), or some other verbose comment with an accepted convention so you can find that exact build of code later. No source control? …just make a copy of the code.

    This way, if you or the client wants to refer to an older example, you’ve got the mofo on ice, and can thaw it in minutes, ready for any meeting.

    componetize sections

    This has less to do with OOP, and more to do with MXML readability. Because Flex Builder is nice in that the Design View will write all the code for you via dragging and dropping controls on your forms, it doesn’t have that human touch. So, even if you don’t format it by hand, you’ll still end up with a ton of MXML tags spewed out over hundreds of lines if you build an entire application in one MXML file. The first pure MXML app I ever saw in my life was a pure MXML RSS Reader posted on Flexcoders. While I respected MXML’s power, I couldn’t read it for $h1werwer….

    If you have a big form, put it in a component. That way, 30 lines of MXML becomes ““. Omg, 1 line of meaningful code… hells yeah, I can read that at light speed! Furthermore, if you hold Control (Command on Mac), you can then click on “UserForm” as a hyperlink, and open the file in question. Supa-fast!

    use Canvas first, Panel later

    While Panel gives you a nice container for your mini-components of your application, they merely serve as pretty looking trappings for your lack of requirements insecurity. Use Canvas, set horizontal and vertical scroll policies to off, and let it be raw. You need to see the gaping holes in your UI, not hide them in pretty chrome.

    make builds easy to see

    The point of builds is to get client feedback, and get it early with real software. If the client can’t see the software iteration, they’ll question “this whole ‘Agile’ thing”. Don’t send EXE’s over email, nor SWF’s. Find a reliable FTP site, upload it, and run it. This is easiest if you don’t have any local file dependencies, the SWF makes no data calls (locally or externally), and doesn’t require any weird arse things to make it run (“Oh… well, lemme reset my host file to be localhost, and then reploy the war file…”. What? Dude, just upload the SWF with accompanying HTML file. If you can’t do that, you’re not writing a Tracer Bullet, but instead a real application build that wasn’t meant to be agile.

    If the sales person/client can’t see the SWF, neither will your users. If you don’t want to deal with Flash Player install issues, don’t do Flex development. Once you get it out of the way, you can always depend on your salesperson/client being able to see your latest build from there.

    use fake data from real ValueObjects

    A great way to point out immediate problems, and make make your application feel more real, is to throw fake data at it in the form of ValueObjects populated with data. Obviously, you may be way ahead of the server team (yours or the client), so it helps to have factory methods; functions that can generate a bunch of fake data for you quickly. You can then throw this at the GUI time and time again to test something. Pain in the neck to write, but you’ll use them a tons afterwards.

    Furthermore, this ties in really well with the “make builds easy to see”. Instead of praying that your database call works while the client is viewing your SWF, or if the back-end guys will have their code done by the meeting, you instead don’t have to worry about it; it’s embedded in the SWF, and will work even if the Internet connection suddenly dies (after they’ve downloaded the SWF).

    For Cairngorm, a technique I learned from Darron Schall was using “Mock Commands”. You make 2 Command classes; 1 for real data that may use a Delegate to make a call to the server, and 1 that just gets fake data from a Factory class and has a timer to simulate a delay. That way, you just change 1 line of code in your Controller class to switch to fake-data mode.

    put event handlers in Script tag, not in MXML

    The thing that’ll change the most as you hop around files modifying GUI stuff is your MXML. Since most MXML is for showing GUI controls, it’ll be volatile from the get-go. Putting code there is just asking for it get in the way, and maybe even get waxed. So, instead, have your Buttons for example call a function in your Script tag for their click handler instead of do things directly in the MXML. That way, you can even delete the MXML, replace it, and then easily wire it up again.

    Find in a friend in sales (or a stakeholder at your client)

    Sales can go either way. They can be a developer’s worst enemy, or you’re biggest fan base. I prefer the latter. I’ve been in too many situations where sales sold something that was impossible and I had to make the impossible possible. AKA, “Flash Developers at Design Agencies”.

    The first thing to do is find out who in sales (assuming just 1 individual) is interacting with the client, and basically catering the project to their needs. Start up a dialogue with this individual assuming your project manager doesn’t mind, and get to know the client. You may wish you hadn’t, but do it anyway. Learn the needs that sales is trying to satisfy by using your code as a conduit. When they start asking for specific functionalities, you’ll know why, and be more informed in suggesting ideas, changes, or options.

    The ideas are cool because sales usually perceives engineering being “fun governors”; depending on the organization. The last thing they expect is MORE things for the developer to do coming FROM the developer. The changes are good because as an engineer, you know how hard something will be to make, how it may work differently in practice, or know the ramifications of a design path whereas sales might not. Rather than saying no, you can make an informed suggestion about how to get the result sales is looking for. This may seem like something you can do in a meeting, but trust me, it’s tons easier when you already have an established rapport with the individual, and almost give the suggestion in passing, almost like you and the sales guy have already got it all planned out.

    Finally, options are key here. Being successful at software is the middle ground between doing everything sales wants, and coding just enough to get it solid and working. Enough flair to make the sale, enough OOP to ensure it doesn’t blow up. Combined, you win. A lot of times, you as a developer may not know what that balance is. The easiest way I’ve found is to put the ball back in sales or management’s court. If they ask for 5 things, you spec them out, give time estimations with risk assessments, and any additional optional ways to implement certain features in increments. Giving sales options is way better than ultimatums. It’s important that your time estimations for your articulated options with possible incremental milestones are not bs. You need to be sincere, honest, and thorough. If it was easy, they wouldn’t call it “work”.

    Naturally becoming friends with the client is dangerous. It’s all fun and games until business gets involved. That doesn’t mean you still can’t build up a rapport to better communicate with the client, and thus understand where they are coming from. I’ve seen a lot of managers in my time offer to shield me from meetings. If the meeting is with the client, I highly recommend you lower shields, and go. Even if you don’t converse in a dialogue, you can still listen.

    Write emails to stakeholders (sales/client) that ask a question that can be answered

    When you are in the process of figuring things out, it’s really easy to give that laid back, relaxed feeling others in conversation. The no-pretense, “What do you think?”. Don’t ask open ended, non-focused questions like that to stake-holders. Be direct, and know the type of feedback you want before hand. If you do, 1 of 2 things will happen, both of which are good. Either the salesperson/client will answer your question in written form so you can refer to it later and thus continue working on your GUI, or they’ll have no clue, in which case you can propose some ideas and look straight pimpin’ (really smart and capable).

    recognize opportunity, and take it

    If your sales/client has no clue what any form of Agile is, or what a “build” is… find a way to educate them. That is, find an appropriate time and place to introduce the concepts. Don’t start ranting about Agile Development on a sales call for example. Instead, if you have a question about how a certain section works on a design comp the client sent you, use that as an opportunity to send them 2 builds, and choose the one they like, or perhaps choose a different one. If they respond positively (or not negatively), boom, you win. You just set the expectation you can send them working prototypes to play with. Suddenly they’ll be hip to the notion you’re sending them working software to play with that is representative of what they’ll actually be using… and that’s a pretty accurate assumption on their part. Their shaping of it also ensures you’re never wrong because you’re basically doing what they tell you to do. Obviously, famous last words for a programmer. Either way, if your the IA/ID or not, you can also use this opportunity to suggest ideas, again giving yourself an opportunity at least appear intelligent.

    If there is a client phone call/meeting, and you have the opportunity to attend, do so. If it is appropriate, start a dialogue to challenge your assumptions about their comments to the recent builds you sent them. Engage with them (and/or sales) in the process.

    Use a phone, not email or IM

    If you’re unsure about something, and you have access to sales, go talk to them in person. Make sure you brushed & flossed first, obviously. If they are unavailable, send them an email. If they are remote, call them, and then only email if they aren’t around and don’t return phone calls. In person dialogue is ideal, whereas phone voice dialogue is 2nd best. Email and IM are not the best form of communication, and communication is the most important thing in a software project. Use the best kind you can to ensure success.

    Caveats and Gotchas

    There are some caveats and gotchas. The more time your team is writing tracer bullets, the less time they are moving forward with traditional visible results. The Agile crew would argue that it is better to spend 4 hours on 2 ideas, allowing the client to pick one they like as opposed to spending 1 week on requirements and then 2 weeks on development for animplementation the client won’t like, which then ends up being another 2 weeks to code to the new idea. Even 2 weeks of bouncing ideas with near production code is better than 2 weeks of “coding off a spec”… well, unless you’re doing government work. It’s hard for some to see the value in writing code that has fake data, and an ever changing interface, seeing the same things in different ways without seeing in their eyes tangible progress on milestones. My retort is they can’t prove their milestones are accurate without the client having some form of involvement in confirming those milestones were met without allowing the client to play with a build that shows that milestone in action.

    Regardless, it’s hard to argue with a Subversion log that says “everything under the View’s folder has changed a lot the last week, but everything in the Cairngorm business, command, and events folder has not… what exactly HAVE you accomplished this week? Can you name one requested feature you’ve completed?”. Valid question, and one that management & sales need to manage; IA/ID & developers can help, but ultimately they aren’t accountable for resource management. Look at it this way: You’ll either be re-coding this at beginning more quickly with less stress using a series of tracer bullets as opposed to slowly at the end with less malleable code under more stress. Use that fact to empower sales. Take the initiative.

    If you don’t have leadership approval, it won’t work. If your manager looks at you funny when you send a “half finished application” the client, you’re already in deep trouble.

    If the client doesn’t care, you’ll really need to leverage your sales rapport. You’ll need to educate the client how software works, and that is extremely hard… but fun. If you don’t, they’ll just expect it to be “done and finished by X date”. That’s not how things work in the real world and they need to realize no matter how much money they spend, they can’t change that. It’s in their best interest to get a good feeling with the software early because it’s easier to change early, harder to change later. If you get those feelings early on, most changes later won’t be so drastic as completely changing workflows.

    Regarding MXML, I’m a big fan of writing my components in all ActionScript. That way, I can re-use them since I have lower level control and can make them really flexible. Again, Flex Builder won’t render these unless you convert them to a SWC (via a Flex Library project for example), so save the uber-OOP for later. If you stick with pure MXML, the tool will work well, and you won’t be fighting it to adopt your best practices. If you have a lot of members on your team, this is also something you can throw at other developers to handle, even junior ones. They can cut their teeth on making a reusable component while you continually define the app via multiple iterations.

    A couple notes on branches and prototypes. First, I’m not a big fan of using branches for one Flex Dev to make some design iterations while the rest of the team “moves forward”. The Flex Dev(s) doing the design iterations should be in the real code. If the rest of the team has qualms with this, you’ll need to setup an easier way for them to test, whether by writing formal/informal unit testing for them on GUI & non-GUI code. For example, one of the benefits of Cairngorm is that it allows multiple developers to work in tandem. One strategy is to have multiple developers handling all Events, Commands, Factory, ValueObject, and Business Delegate code. This leave the Views in the hands of whatever developer(s) handling building the tracer bullets to show sales/the client. The rest of the team can either use the latest build in source control to throw data at and see what happens, and just comment out the actual Cairngorm Event dispatching when they check the code in, but I’ve found it’s easier to just make informal test cases; MXML applications that test your whole Cairngorm use case setup. A la, you build a simple View with a GUI control data bound to the Model, dispatch an event, and see if it works.

    Regarding prototypes, for larger projects I think these are more the than justifiable. Throw away code is quicker to write than tracer bullets, and it’s always good to play with some code ideas before committing more rigorous practices to it before you know the idea will actually fly (strong-typing, encapsulation, etc.). There comes a point though where you should start leveraging the code you are writing in a good base, and really put the code to the test in early builds to see if she holds up.

    Finally, being intimately familiar with Flex Builder helps. I think I’m pretty adept at it, and I’d say that significantly contributes to my ability to quickly modify code without making it spaghetti. My experiences in Director and Flash have contributed to my ability to fake a lot of interactions for the sake of communicating a point. Finally, using OOP, encapsulation, and strongly-typed code to get the tool to help you find errors are all ways to write flexible code. While the temptation is to not even use strong-typing, and use a procedural approach, you’ll spend too much time trying different ideas because you can’t share code easily. Remember, it’s ok to do this stuff on paper or your favorite UML tool first. I just use paper, personally and plaster comps on walls in front of my desk. Now, that experience doesn’t just happen over night. Regardless, I was responding to bi-weekly changes on software projects at my first job of which I didn’t know OOP or how to write classes, nor did I know what design patterns were. I didn’t even know how to return a value from a function (I just modified global values instead). Yet, I found a way, so you can too.

    Conclusions

    Iterative development through speedy coding with Flex Builder. Following the tips above, you can hopefully build your Flex apps a little faster via Tracer Bullets so you can play with some workflow / use case / design ideas and throw them at the client. What they throw back you can then start coding for real on… and then toss that back… rinse, repeat.

  • Flex Example: HTTPService & Cairngorm 2.2

    ws_icon2.jpgPreface

    Cairngorm 2.2 was released on labs today. Upon reading Eric’s blog entry, I noticed they fixed a WebService bug. Hoping it was the one that sabotaged my original example, I downloaded and implemented. It did fix it, but Amazon had since changed their XML format, thus ruining it anyway. While perusing Amazon’s developer API docs, I noticed they had a REST implementation (variables on a URL string) as well as their web service implementation. I always like using REST implementations over web services because they are just easier to debug and the code makes more sense looking at it in my opinion.

    So, I’ve modified my old WebService example that utilized Cairngorm 2.1. This one uses HTTPService instead, and Cairngorm 2.2. I only changed 1 line of code for the Cairngorm update; score for backwards compatibility.

    Introduction

    This is a simple Flex 2 example application that fetches books from Amazon.com. It shows how to use the Cairngorm 2.2 MVC micro-architecture with an HTTPService. It utilizes Amazon’s developer API, so if you don’t have web developer API ID with them, you’ll need one to compile this example yourself. If you just want to use it, scroll to the bottom. The code that’s changed from the original example is updating this example to use HTTPService instead of WebService . Additionally, my E4X skills have improved (a tad… *ahem*) since I wrote the last example, so I updated that factory code as well to be a little cleaner. Hopefully you’ll see how easy it is to parse XML using E4X. Finally, I removed all of the source code for Cairngorm and just use their SWC. You then just link this to your project:

    1. Click the project
    2. Go to Project > Properties
    3. Select Flex Build Path on the left
    4. Click the Library Path tab on the right
    5. Click the Add SWC button
    6. Click Browse, and navigate to where your example is on your computer
    7. Choose the Cairngorm.swc, click Open, and then click OK, and finally OK

    For flow of the application and more context, read the original entry.

    Flex 2 HTTPService & Cairngorm 2.2 Amazon Example – App | View Source | ZIP

  • Flex Chronicles #24: ApplicationControlBar, ApplicationDomain, & Event Metadata

    Layout with ApplicationControlBar

    ApplicationControlBar has some weird borders that can make it screw up your layouts. Meaning, if you have a Canvas with 100% width and height, and have theApplicationControl bar in it, your Canvas will get scrollbars . Easiest way to fix is to (like a lot of things) wrap it in a Canvas with width and height of a 100%, as well as your vertical andhorizontalScrollPolicies set to “off”. That’ll make it flush and not cause scrollbars. This works for other components as well that give you layout grief.

    ApplicationDomain

    I used ApplicationDomain successfully for the first time this week. Short version is that you can now, as of Flash Player 9, control how your classes are used by loadedSWF’s. In Flash Player 8 and below, if you loaded a SWF , and each had the same class, they’d both use the parent (defined on _global). This was done for a few reasons, the 2 main ones being that most people don’t want childSWF’s overwriting classes in the “shell SWFs” and secondly for security reasons. Flash MX 2004 (maybe MX had it, can’t remember) introduced the exclude.xml file which allows you to name the file the same as the FLA, place it in the same directory, and list out all the classes you DIDN’T want Flash to compile into theSWF. For large Flash websites / applications, this was great because you could share classes in the main swf with multiple other ones, thus saving a few kilobytes (23k on one project I was on with 30 SWF’s using classes from that pile). On larger sites with booku amounts of traffic, this is a big deal.

    Using ApplicationDomain (don’t worry about security for right now), you basically have 3 choices how you want to handle classes in the Flash Player, specifically forrun-time loaded SWF’s.

    1. Partition the SWF into it’s own black box; it uses the classes it was compiled with, and doesn’t touch the parent SWF’s classes that loaded it.
    2. Adding the classes to the parent SWF; this is how Remote Shared Libraries work (think loaded run-time DLL’s… I think)
    3. Sharing, meaning the child SWF can utilize the parent’s classes. This is the default behaviour, and is in part what the Module’s concept is built upon.

    I used #1 this week, and it worked great. Mike Britton is creating a dashboard charting application, and has his own code base. I’m loading his dashboard into an application I’m working on that is an entirely new code base with a different version of Cairngorm as well as my personal modifications. Loading his SWF via the standard SWFLoader doesn’t work at all since his SWF see’s my classes (like ModelLocator), and fails to attempt to use them since they have different data then they were compiled with. Merely specifying a unique ApplicationDomain for his classes to live in makes it work great.

    var appDom:ApplicationDomain = new ApplicationDomain();
    loadedSWF.loaderContext = new LoaderContext(false, appDom);

    Furthermore, I can even pass it needed data via calling a function he has exposed for me on his Application.mxml file. Current problem is it’s not strongly typed, but we’ll probably use an interface later:

    public function onComplete():void
    {
            var obj = loadedSWF.content; // of type SystemManager, but in different namespace I think
            var o = obj.application; // of type Appilcation in specific namespace
            var r:Boolean = o.someMethod(Model.getInstance().someData);
            DebugWindow.debug("r: " + r); // prints out true
    }
    

    I got Modules working the reverse way, but… I’ve found Modules are no different than premature optimization; they are a pain in the ass to work with so best left till later in my opinion… depends on your deadline and team workflow obviously.

    Event Metadata Reboot

    Finally, Library Projects. I’m using them for Cairngorm 2.1 (just in case I have to modify ServiceLocator again…), my Cairngorm mods, and a front end API to our back-end services that multiple applications / vendors will eventually use. Every time I save a file in any of those projects, it’ll re-compile an SWC file. I’ll then run an Ant build.xml file in my main project that copies the updated SWC’s, if any, to my Flex Project’s lib directory. The downside to this is my code-clicking (when you hold Command / Control, your code turns into hyperlinks) doesn’t work because it looks inside of the protected SWC’s instead of my Library Project directory. The upside, however, is my code base is purely for the project only so is… somewhat more navigate-able . It’s also easier to work in those code bases by just closing all projects and leaving just the 1 Library Project open; easier to focus.

    The main problem, though, is code hinting for addEventListener. You get those when you use the [Event] metadata tag. While I can do a project refresh after I’ve copied the SWC into my project to get updated code hints, the addEventListener ones don’t work. I have to reboot FlexBuilder to get those to show up. If you don’t know what I mean, they look like this:

    When you choose one and hit enter, it’ll type the event name and type for you. If you use the [Event] metadata tag, you can make these for your classes as well. That way, when I distribute the SWC, it comes with helpful code hints. Rebooting the IDE to get these is kind of lame, though. Refresh and Clean don’t work.

  • Example for Flex Component Kit for Flash CS3

    If you saw the amount of work you have to do in my past article, you’ll appreciate how much work you DON’T have to do using the new Flex Component Kit for Flash CS3 (now on labs with 50% more beta!). I’ve modified my example from that article using the new kit to show you how much easier it is to both create Flash assets for Flex, but also to use them IN Flex 2. Deadline at work, so too little time to do another Captivate; hopefully images’ll do.

    First, let’s take a look at the FLA in CS3 on my MacBook. Notice, nothing on the root timeline / stage.

    Going into the BackgroundPanel symbol in the library, notice no code on frames. You can see the bottom layer is where I put my bounding box. This is a convention used since Flash 5 (before my time, hehe) which gives the MovieClip a “default width and height”. Now, for Flash components, this was typically used for the size methods written in ActionScript. In Flex, it does a whole lot more. Flex has a layout engine that measures MovieClip’s, and that way “knows” when to show scrollbars. By default UIMovieClip measures every frame so if your Flash animation increases in size, so too will your content in Flex. When you are playing inside of containers inside of Flex, this is VERY important. Here, though, I actually WANT to remain square. Therefore, I make a 800 x 600 MovieClip with an instance name of “boundingBox”.

    Now, the contract you have to abide by as a Flash Designer when creating assets for Flex is 2 things: states and transitions. You create different “states” that your component / animation exists in. In my panel’s case, these are: hidden, intro, main, and spin. Flash Developers typically would use either the timeline or different redraw methods. A Flex Developer uses the state tags. These 2 will now be combined. The Flash component will “represent” the state tags in Flex via frame labels on the MovieClip symbol’s timeline. This way, a Flex Developer can use the familiar syntax on your component:

    panel.currentState = “spin”;

    The second is transitions. Transitions are the changes that happen form one state to the next. For example, in my Login Form example, I show how you can change from one state to the other and give visual feedback to the user you’ve changed state. You represent transitions in Flash via specifically named frame labels.

    For good or ill, transitions are (at least with the version I have) all or nothing. Most Flash Designers who are timeline junkies will read that and laugh. That’s the attitude. I’ve found the component acts weird if you only define transitions for some states, and not others. Best to do at least the default transition to each state.

    One quirky thing is that the UIMovieClip will go to your state frame label when it’s done playing the transition, if any. I didn’t really like this. The compromise Adobe came up with is to put your state frame label on the same frame as your ending transition frame label. Now, most of us Flash Purists think putting 2 frame labels on the same frame is blasphemy… madness!

    …however, it actually works out well here (thanks Glenn Ruehle!). It makes it easier for as an animator to have my ending transition “end” on the state. However, for more complex animations, like the one Grant Skinner showed at 360Flex, it actually behooves you to animate unique transitions for each state change.

    For example, if I were animating a human character, he could have 3 states: stand, run, and sit. If I were to set the current state from sit to run, I wouldn’t want him to immediately start running; I’d have to animate him to stand first. For non-animators, this can seem like a lot of work. For those of us in the know, it’s necessary for a good looking component.

    So, again, you may find another frame label timeline convention you dig; no worries.

    The syntax for states are “my state”; basically whatever you want. The syntax for transitions is a little more complex. It follows the way transitions in Flex work. They have a “fromState” property and a “toState” property. Transitions are always bound to a state change. You can choose a state name as a string OR a *. A * means “any state”. So, if you write fromState=”*” toState=”spin”, that means anytime the state changes to spin, play this transition.

    Frame labels in Flash use a “from-to:state” syntax. Dissecting this, the from is your from state, and can be the name of the state, OR *. Same goes for the to; the to state name or a *. The state is the name of the state, and must be a state name. Always put a start and end set of transition frame labels. If you misspell the frame label, currently there is no JSFL to help you out, and the Flex Dev will most likely get an error dialogue that isn’t easily debug-able. He’ll probably blame you so just make sure for every “start” you see an “end”. Keep in mind too that for some transitions, it’ll use the end frame to play them backwards depending on what state you are changing too, so animate accordingly.

    You’ll notice for my simple example, I’ve been slack and just put the state frame labels at the end of the transition animations.

    For example, if the Flex Developer were to use this component, and set the currentState = “intro”, then it would do a gotoAndPlay for the “*-intro:start” frame.

    Same goes for the spin, regardless of what state you were on previously:

    Notice that the main state doesn’t really have any transition; it’s just the main state where you mainly are, and thus it is plain Jane, reflective a main type of state. Word. Yes, it does have an event sound, though.

    Now, when creating this component, you do what you typically do in Flash. Create a new MovieClip symbol, name it, and hit ok. You’ll notice the Linkage dialogue in Flash CS3 has a new field: All Your Base Class are Belong to Adobe. When you create a MovieClip in Flash CS3, it’ll default to flash.display.MovieClip. Good, leave it be, let it create your symbol.

    Later, you can run the Flex Kit JSFL command, and it’ll put the needed SWC in the Library, and then convert your symbol for you to have the correct base class (mx.flash.UIMovieClip); all you have to do is select it in the Library. It’ll tweak your FLA settings (in a good way) too.

    Poof; it’s exported as an SWC where your SWF usually is. Done!

    Few more quirks. Flex states are based around the Flash Player 9 DisplayList model. DisplayObjectContainers are basically MovieClip like things. Except, instead of createEmptyMovie, attachMovie, duplicateMovieClip, unloadMovie, and removeMovieClip, we have a brand new API. This API allows us to create MovieClips, but NOT have them draw. In the past, we’d stop it’s animations, turn it invisible, move it off stage, and pray. This didn’t work so well with a ton of MovieClips. Now, we can just go:

    var a:MovieClip = new MovieClip();

    And call methods on it, but not actually have it automatically have to be drawn in some depth. Now, we go:

    addChild(a);

    And THEN it’ll draw. Cool, right? You can even re-parent it, and remove it without killing all the code on it. Dope.

    Problem? Flex states are built atop this. When you go to a state, things are removed from the DisplayList and others are added. What happens to those that are removed? Flash Player does what it was built to do; it removes them from memory as needed.

    Great for application developers, suck for designers. From the day I got into this industry, I’ve made it my mission to ensure my stuff plays hot, and if it means taking all of your CPU and RAM to do so, so be it; it’s there for the taking Blackbeard style.

    The hack I showed at 360Flex has been modified slightly. Basically, I’d put all of the frames on a MovieClip, since those have to be preloaded before drawn, and then put it before the animation. Now, I’ve found better results doing the same thing, but having it last he entire tween. Notice the spin and intro preloader layers in the above pictures below the animations. You can see what’s inside of those MovieClips here. Technically, you should just put them all on one frame, but I ran out of time. I then just made them alpha 0. If you move the off-stage, the measuring code will think your Flash component got really really big, and then you’ll see scrollbars in Flex, and go wtf?

    So, what do you do with your SWC? You give to the Flex Dev, and smoke ’em if ya got ’em. The Flex Dev then, if he’s a purist, he’ll throws it in a lib directory. For this example, I just throw it in the root project. You then link it to your Flex Project via adding it to the Flex Build path as a Library via Project > Properties, and then Flex Build Path, Library Path tab, and then Add SWC button.

    You’ll notice a sample implementation here with Buttons setting the current state of the panel. Notice the lack of strong-typing; I’m such a rebel (-es=true -as3=false -strict=false 4 uber h@X!!!).

    Now, I think I broke something, but the convention is “boundingBox”… or it’s ilk. You name your MovieClip that, and that’ll define your component’s rect. In MXML (or AS if you were so inclined) you can set the bounding box instance name to use. I don’t recommend this, but hey, freedom’s rad, choose what you want.

    This’ll compile to something like this. If you’d like to play, click the image. WARNING: Has sound – she’s loud.

    To give you a visual example of what this would look like in Flex (uber simplified btw), here’s the states defined in MXML instead.

    And the corresponding (optional) transitions that match those states.

    Some dig MXML, some dig Timelines, I dig both.

    Few final tips. Every time you recompile a new SWC (Test Movie / Publish, whateva’), don’t forget to Refresh the Flex Project, or you’ll get the cached version. I usually use an Ant script to just copy the new .SWC from the assets directory (or however you setup your Flex projects). Also, not sure if it’s fixed, but if you’re Flex Dev starts getting code hints for “frame31():Object”, don’t be alarmed. If you put code on the timeline, I’m the only guy I know that fires people for that (except stops of course… I’m not THAT mean). These methods are merely created from code you have on that specific frame (thanks Robert Penner!).

    One thing to notice in some of the above images of Flash’s timeline is the Flex friendly layer vs. the Flash friendly. You un-guide the Flex friendly one for development and testing. That way, Flex Builder doesn’t chug loading all of those uncompressed PNG’s into memory, thus making Flex Builder compiling really slow. When ready, you just un-guide the Flash friendly one, and re-guide the Flex friendly one, and finally recompile. Naturally, most people are using video nowadays or hand animated bitmaps & vectors which are immensely less RAM intensive. Then again, good to know.

    Also, this whole example didn’t use any ActionScript. There is no reason I couldn’t make an ActionScript 3 class for my component. If you don’t write a class, Flash CS3 will make one for you. So, I didn’t have to make a “BackgroundPanel2.as” file. If I wanted to, I could of written an AS3 class to maybe play some other scripted animations, or play sounds… video, whatever.

    Finally, don’t forget to remind the Flex Dev to up his framerate via the Application tag (or compiler… either or)!