Monthly Archives: May 2007

Developers will swear by Programming Flex 2

After being disappointed by other Flex books out there, I finally found a book that delivered, and I’m more than happy to begin recommending it. Where many Flash developers swear by the Essential ActionScript books by Colin Moock, I expect that Programming Flex 2 by Chafic Kazoun and Joey Lott to gain the same reputation. It’s very straightforward, the authors are obviously knowledgeable, and it should be able to get anyone started developing with Flex.

One of my favorite parts is the forward written by Mark Anders, Senior Principle Scientist at Adobe. Mark gives a detailed history of his move from Microsoft, as the leader behind the team that created ASP.NET, to Adobe where he helped shape Flex 2 and ActionScript 3.0, the language behind the framework. He finishes with a look at the future, including Flex’s support for the upcoming Apollo runtime.

Early chapters focus on the basic parts of Flex. As expected, the authors give a look at ActionScript 3.0, MXML, the tools behind Flex, like Flex Builder, FDS, and even SWFObject, one of the best embedding solutions for placing SWF files into webpages. I’m impressed that Chafic and Joey took the time to mention SWFObject because it’s my personal favorite, and because the Flex SDK includes Adobe’s own solution, so mentioning others written by third-parties isn’t strictly necessary. Consider that an extra point for attention to detail.

The Framework Fundamentals chapter goes well beyond fundamentals, in my opinion, but that’s not a bad thing. In fact, I think readers will file away a lot of useful information, such as how the Flex SystemManager and preloaders are handled, and move forward with some great knowledge that they might normally discover much later. The authors introduce ApplicationDomains right away too. Personally, I rarely find myself using these, but again, always good to know about them.

In the next few chapters we read about layout, standard components, and containers. These chapters give the reader their core knowledge of the visual side of Flex. The layout chapter extensively covers layout components like Canvas, HBox, and VBox, constaint-based layout, and even some less-obvious containers like Forms, FormItems, and FormHeadings. The UIComponent and Container chapters, as you would expect, go into detail about each of the available component. I found myself a little bored by these chapters, but I’ve worked with most of these components for well over a year, so you can imagine that I’m familiar with the available features.

The rest of the book’s chapters cover other specific features that the framework provides. We have a chapter on managers for drag-and-drop, modal pop-up items, and mouse cursors, some information on media such as sound and video, effects and transitions, application states, and styles and skinning. Of particular note are chapters on working with data, including validation and formatting, connecting to remote data sources like web services, socket servers, and initiating file uploads and downloads. I was impressed to see a chapter that focused on Flash Player’s LocalConnection and SharedObjects.

The final two chapters of the book focus on components. First, we take a look at building components with MXML. For good reason, the authors recommend breaking up an application into multiple modular pieces. It’s all straightforward, with a focus on encapsulation and other important considerations for object-oriented programming. The last chapter shows the reader how to build a new component with pure ActionScript 3. The content is focused and to-the-point. Seeing as I have a strong interest in building custom components, I found myself a bit disappointed by such a short, well, introduction. Certainly, the authors wrote a strong chapter that includes all the essential details, but I simply hoped for a bit more. As they say at the conclusion, though, an entire book could be written about Flex component development. I can definitely agree, so I guess I shouldn’t complain too much. 😉

Personally, I learn the most when I dive right into the Flex documentation. However, I know a lot of folks like to grab a physical book and read it a little further away from their computer monitor. Programming Flex 2 is the best hard-copy source for Flex information that I’ve found so far. It’s a little less dry than the documentation, and Chafic and Joey present you with the essential knowledge to get you started developing with Flex very quickly. You’ll find this book on my personal list of recommendations, and I hope you enjoy as I have.

More XML filtering with E4X in ActionScript 3

If you haven’t read my first post about filtering data with E4X, go check it out now. Today, I’ll expand on it to add a few more options that you have at your disposal when working with XML in ActionScript 3.

The following is a simple XHTML document that I will reference in the examples below:

var html:XML = <html>
<body>
	<ul class="links">
		<li><a href="http://www.yahoo.com/" class="josh">Yahoo!</a></li>
		<li><a href="http://www.adobe.com/">Adobe</a></li>
		<li><a href="http://joshblog.net/" class="josh">Josh's Blog</a></li>
	</ul>
	<div id="intro">
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
	</div>
	<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</body>
</html>;

Consider a situation where you want to retrieve all the paragraphs from an XHTML document. Each paragraph could be nested in DIVs, lists, tables, or anything. If we want to retrieve an XMLList of every paragraph in that document, we need to use E4X’s .. operator. A single dot only allows you to access direct children of a node, but this operator allows you to drill-down into the hierarchy of every descendant in an XML object to access grandchildren and more.

var paragraphs:XMLList = html..p;

You can combine this new operator with the filtering methods I introduced last time to build some pretty complex queries. The following example retrieves the URLs from all the anchors (links) in unordered lists with the class “links”. Notice that I must use the attribute() function because class is an ActionScript keyword.

var urls:XMLList = html..ul.(attribute("class") == "links")..a.@href;

Of course, we don’t need to access attributes through the complete hierarchy of their containing elements. Consider a situation where you want want a list of all the values of “class” attributes in an XHTML document. This attribute could appear on almost every element in the document. In most cases, you can directly reference the attribute with the @ symbol.

var classes:XMLList = html..@class; //error for "class"

However, like the previous example, we can’t access the “class” attribute as easily because it’s an ActionScript keyword. Instead, let’s use the decendants() function, which returns every element (not limited to direct children) that is below an XML node, along with the attribute() function to get the “class” attributes. The query will be a little more complex, but I don’t think it’s unwieldy.

var classes:XMLList = html.descendants().attribute("class");

You’ll notice that the query returns every single class attribute in the document, including duplicates. For instance, there are two anchors in document that I have given the class “josh” because they happen to point to sites that have content created by me (this blog, and my employer, Yahoo!). What if I want a list containing only unique items? In other words, how can I get results where the “josh” class only appears once?

Unfortunately, E4X doesn’t provide a native way to retrieve a list with only unique values. That’s unfortunate because I’ve found that it’s a common requirement. Based on my previous knowledge of combining E4X with ActionScript (remember the trace() call from my last post?), I built the following query that should do the job:

var filteredClasses:XMLList = new XMLList();
html.descendants().(filteredClasses = addUniqueValue(attribute("class"), filteredClasses));

That snippet calls a simple function addUniqueValue() which I’ve included below.

private function addUniqueValue(value:Object, list:XMLList):XMLList
{
	if(!list.contains(value))
	{
		list += value;
	}
	return list;
}

As I demonstrated last time, code within parentheses in an E4X query basically runs in a loop for every item in an XMLList. I’ve used this to my advantage to call a function for each item in the list that checks to see if has been included in the filtered list. Once the full query finishes, an XMLList with unique items has been placed into the filteredClasses variable.

By the way, did you notice that XMLLists support the += operator to append additional items? I didn’t know that until I just tried it. Nice.

That should cover everything you need to know to go crazy with E4X. Keep in mind that E4X can be a bit slow if written poorly, and it’s important to optimize your queries for large datasets. If you need to filter your data, like I did to get unique values, remember that you can call ActionScript functions and assign values within the parentheses. Finally, don’t forget about the attribute() and child() functions. They’re very useful for using dynamic strings in your queries. E4X rocks.

Update: I’ve written a followup article:

And be sure to check out the original:

Six reasons why I think Joost is lame

Lately, I’ve been hearing a lot of buzz about Joost, a new Internet video platform. People seem genuinely excited about it, and the invites are flying left and right. After picking up an invite of my own, I downloaded the application, tried it for a few minutes, and I came to a simple conclusion almost instantly: Joost is pretty lame.

Don’t get me wrong, I enjoy that I have hundreds of channels to watch on my PC. However, the application’s interface sucks. A lot. Seriously, it’s a usability nightmare. I made a decent list of some of the more obvious problems with the interface while exploring the catalog to see the available content:

  1. When in full-screen mode, it doesn’t immediately recognize my mouse movements. I have to wiggle my mouse for a couple seconds. Show me the interface already! I mean, come on. This is one of the most basic functions of a video player. Don’t make me wait. I moved my mouse for a reason.

  2. I can never seem to find the back button. It’s in the top-left, which should be pretty obvious based on my experience with a web browser, but it’s not obvious enough. Since I can’t find it, I start my search for new shows from the beginning by clicking the “Channel Catalog” button (which is the easiest UI element to understand). I think if the arrow button were in the middle of the left side, and maybe a little bit bigger, I’d have an easier time simply going back one screen.

  3. If I leave a video playing while clicking through the menus, it’s not obvious how to get back to the video. After specifically clicking on various buttons just to figure out what they do, I discovered a strange circular button on the top-right of the screen that does the job. You can also click anywhere outside the menu (on the video itself), but that’s not obvious to an inexperienced computer user, or to someone who has never encountered a similar interaction in a video player. Why isn’t there a button on the bottom next to the button labeled “My Channels” or “Channel Guide” that lets me switch between menu modes. If I saw a “Back to Video” button down there, I would instantly know what I needed to do. Plus, with only a single button on the bottom, it feels pretty empty anyway.

  4. The buttons to scroll up or down in the list of my favorite channels appear on the right side. I kept finding myself trying to find these buttons on the top and the bottom of the list. If you can’t tell, I’m finding the interface difficult to navigate. In fact, based on the fact that I’ve gotten lost several times makes me wonder if Joost doesn’t follow common interface guidelines. I’m also starting to think that the UI elements simply don’t stick out enough, as if the constrast were way too low.

  5. Browsing through the channel catalog is slow and requires too many mouse clicks to get more information that should all be put in one place. For example, I start by clicking on the channel catalog button to view the global channel listing. Next, I pick a category, such as Cartoons and Animation. Now, it shows me a listing of all the channels in the category. Things start going wrong here. I only see the logo for the channel, its title, and a few very small screenshots. I can’t play the channel with one click. There’s no description, so I’m left guessing if I should try to learn more about the channel. Even if I already knew I wanted to save the channel, I can’t add it to my favorites in one click. All of these actions require at least two more mouse clicks. Give me a description on mouse-over, or even right on the list, and some quick buttons to get things done without another page to load (which doesn’t always load quickly either!).

  6. The list of my favorite channels shows even less information. There’s an icon that doesn’t seem to tell me anything useful and the channel title. That’s it. There’s no screenshot. The other menu had four of them; why doesn’t this menu have at least one? Thankfully, each item has a few extra buttons like I wanted for the channel catalog. I can click a play button, click an information button to view the channel’s description, or I can choose to view the full channel page. Not bad, but I believe the channel’s description should either appear on a mouse-over, or it should be included in the list by default. I want to scroll through the list quickly much like I do with search results on Google or elsewhere on the web. Navigation should be fast!

Again, I just want to say that Joost has potential, and I love the idea of viewing a lot of video content, like full TV shows, for free, right on my PC. However, I get the impression that this application wasn’t planned, but put together quickly, with many new features added over time without refactoring. I’ve been reading about Joost in sites like Digg for a while now, so I know they’ve had multiple releases, and there was a more restricted beta with fewer invites before, so I’m a pretty disappointed by the lack of polish.

I recommend Democracy Player if you want a clear and easy interface. It’s a little more focused on video RSS feeds (which, by the way, didn’t appear to be an option in Joost), but I definitely found it easier to add and find content with Democracy. What’s interesting is that the options in Democracy aren’t necessarily as rich as Joost, but Democracy’s design is more like a traditional desktop application, and I think that left me with fewer expectations when it comes to the richness of the UI.

For Joost to win me back, I think they definitely need to focus on the user experience–especially in the areas I described above. Once I got my first look at the Joost interface, I think I expected to see a nice mix between Apple’s super-crisp FrontRow interface and Democracy Player. Instead, I discovered a clutter of indecipherable icons, too many mouse clicks to get anything done, and a general sense of “alphaness”. Ultimately, I think I got caught by the hype. The invites make Joost seem exclusive in some way. It worked for GMail, but when I started using GMail, it was already pretty polished.

Explore Digg’s Keywords with WordWeb

The deadline for Digg’s API contest is less than a week away. Always ready for a coding challenge, I immediately knew I’d be building something when I first heard about the contest at the Digg Millionth User Party last month. My entry analyzes the keywords from the top stories on Digg, and builds a graph that shows the relationships between those words and the stories in which they appear. For example, the keyword “apple” is often related to “mac” and “ubuntu” is often related to “linux”. Keywords that appear most often will be larger and more prominent than words that appear only once or twice. Clicking on a keyword will re-focus the graph and the user can explore deeper relationships. Try it out!

Screen capture of WordWeb application for Digg's API

If you can’t tell, the application was built with Flex. Under the hood, I’ve used a modified version of Mark Shepard’s SpringGraph component. Modifications of note include some customization options for the SpringGraph’s appearance, such as line thickness, and I built in some events for mouse interactions with nodes. I’ll have to contact Mark to see if he’d like to use my changes. They certainly make the component more useful.

The keyword analysis engine is based on the one I built to chart top keywords in my MXNA Dashboard application. Basically, it accepts a list of strings, breaks them apart into individual words, and tracks the number of appearances for each word. You can also pass in a list of words to exclude. In this case, I chose to exclude many common words like “the”, “his”, “were” and others like that. I wish I remember where exactly I found it, but I discovered a great list of nearly 1000 that someone had compiled and offered for free use within this sort of program. With a few changes to stop excluding important words like “president” and “congress” (obviously, people talk about politics a lot), the list became an excellent filter.

Of course, source code is available! You’ll notice that it uses Cairngorm. I’m not necessarily following 100% best practices for this framework (no delegate classes, for instance), but I still like to use it for MVC purposes. This application is mostly quick-and-dirty, so commenting is pretty much non-existent. I don’t expect to touch the code again, so it didn’t seem too important. I figure someone will probably find it useful regardless. Enjoy!

Ways to use E4X to filter data in ActionScript 3

ActionScript 3 in Flash 9 includes powerful support for reading and manipulating XML. It’s called E4X, and it gives us developers some useful new syntax. Read on for a super quick introduction to E4X followed by some powerful ways to filter your data using this feature.

E4X is powered by the new XML and XMLList classes. The most common way to declare a variable of one of these types is to pass it and XML string. However, many developers might miss the fact that you can declare XML directly within your classes or ActionScript code. It’s supported natively by the compiler.

var data:XML =
	<items>
		<item name="Wii">
			<source>Amazon</source>
			<price>364.00</price>
		</item>
		<item name="Wii">
			<source>Target</source>
			<price>249.99</price>
		</item>
		<item name="X-Box 360">
			<source>Amazon</source>
			<price>399.99</price>
		</item>
		<item name="PlayStation 3">
			<source>Amazon</source>
			<price>599.99</price>
		</item>
	</items>;

E4X lets you drill down into the data to get the information you need without any excessive looping or strange calls to parent and child nodes. The following example gets a list of all the item names defined in the XML from the previous example. Notice that the name attribute is specified with the “@” symbol at the beginning.

var itemNames:XMLList = data.item.@name;

To take it a step further, you can filter the same set of data to find items with “Amazon” defined as the source value. Place a statement within the parentheses to check for a specific value. In this case, we check to see if an item’s source is equal to a string value.

var amazonItems:XMLList = data.item.(source == "Amazon");

Interestingly enough, you can place just about any ActionScript statement within the parentheses. In the following example, I’ve included a trace statement to display each item’s name in the console. I find this particularly useful for debugging.

data.item.(trace(@name));

You can filter by multiple fields as well. This example filters items from Amazon with a price under $400.00.

var items:XMLList = data.item.(source == "Amazon" && price 

Let's take it a step further. Say that your application filters items by source, like in the example where we only wanted items from Amazon. However, the filtering is controlled by the user through a ComboBox or another user interface component. E4X will let you compare attributes or children against a variable as well!

var sourceName:String = "Target";
var itemNames:XMLList = data.item.(source == sourceName);

Please note that you must be sure the variable name is different than the name of the child. If I had named my variable source, instead of sourceName, the statement within the parentheses would never access the item's source value because it would always use the variable. In exact terms, (source == source) most definitely won't work!

Let's make things a little more interesting. What happens if the name of the value by which we're filtering should be dynamic as well? In the previous examples, we've accessed attributes directly, but you can call functions on the XML object too. Here, we call the attribute() to get an attribute's value by its name. This will also work for the child function.

var filterBy:String = "name";
var filterValue:String = "Wii";
var items:XMLList = data.item.(attribute(filterBy) == filterValue);

Finally, let's finish with something a little complex. Say the application's interface allows the user to filter across multiple fields, but each field is optional. We can do that too, but not directly through E4X (as far as I know; please prove me wrong!). This example shows how to filter by items from Amazon that cost exactly $599.99, but the fields Array could contain any number of items with additional items to filter by.

var filtered:XMLList = data.item;
var fields:Array = [{name: "source", value: "Amazon"}, {name: "price", value: "599.99"}];

var fieldCount:int = fields.length;
for(var i:int = 0; i 

I'm sure you can think of interesting ways to expand on that last example to create some very powerful filtering systems. In this particular case, I've only checked for equality, but with some simple changes to the logic, you could check for prices greater than or less than a certain value, or you could even search for substrings within a value. For instance, you might want to search for "PlayStation", and include results for PS2 and PS3 systems. E4X is very, very powerful.

Update: I've written two followup articles:

Yahoo!’s Web Messenger built with Flex 2

Seeing as Flash Player 9 is at 84% penetration, it’s time for the big guns to start releasing content that targets this awesome new version. Obviously, a bunch of Flex 2 applications are already in the wild, but I imagine that the next several months will bring an explosion of great new additions. Today, Yahoo! announced the beta version of a Yahoo! Messenger client for the web. Even more exciting, its built with Flex 2! Cross-platform goodness for everyone.

Of particular note, you’ll see that it has a Yahoo!-themed skin, and only a few elements look like the Flex defaults. Personally, I’d like to see the Messenger team push it a step further to skin everything, but its a good first step. I like the integration with search, avatars, and all the cool little menus around the application.

Here’s my favorite: if you mouse over one of your contacts, you’ll notice that a little down-facing arrow appears to the right. Mmmm… a custom list item renderer. When you click on this arrow, a menu pops up with additional options for that specific contact. This is a very interesting choice because the desktop version of Messenger uses the right-click context menu. While Flash Player allows you to customize its context menu pretty easily, very few applications make use of this feature. I imagine even fewer users realize that this menu will ever look different than the defaults. I know I never check to see if someone used it. The developers of this application are showing their mojo by realizing that the web-based version needs some specific alterations to maximize usability. I love it! I need to build my own version of this component. 😉

Congrats Messenger team and Yahoo! on releasing a great new app built with Flex 2!