18 December 2008

Happy Holidays!

May you all have a wonderful holiday season! I'll be gone a few weeks.

16 December 2008

Next Generation Flex/Flash Design

The Flash Catalyst project (formerly Thermo) promises an incredible boost to UI design in Flash and Flex.

15 December 2008

Creating LiveDocs-style Documentation for Your Flex App

One powerful -- and hidden -- tool that ships with Flex Builder (and I think the SDK) is the ASDoc documentation utility, found here,
C:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0\bin\ASDoc.exe

You need to use the special code comments (/** */ and <!--- -->), otherwise ASDoc will ignore them. So a sample code block looks like this,

* Boolean indicating visibility of the Submit button.
public function get SubmitVisible():Boolean {
return _submitVisible;

You can read more about ASDoc and its switches on the Adobe Using ASDoc page. When you're ready to generate your documentation, you call the ASDoc utility from the command prompt with some switches. The parameters ("switches") tell ASDoc what to parse and where to put the output, among other options. One quick way to see the options is to run asdoc -help at the command line. Here's one sample call to ASDoc,
asdoc -library-path C:\FlexProjects\MyApp\lib -source-path C:\FlexProjects\MyApp\src\ -doc-sources C:\FlexProjects\MyAp\sr\MyApp.mxml -output doc-folder 

The above call tells the ASDoc tool to
  • Use the SWC files (if any) in the lib folder; these are often used for third-party components.
  • Generate documentation for the MXML file. In my case, I had a lot of ActionScript in the MXML and wanted it pulled.
  • And place the output in a folder called doc-folder.

11 December 2008

Verify Mobile Web Sites With New W3C Tool

New tool from the W3C makes validating sites for mobile users easier.

To Infinity and Beyond

A friend has a great blog post about infinity, how it exists and doesn't -- at the same time. It uses mathematics and will blow your mind.

Adobe AIR 1.5 Gets High Marks

InfoWorld gives a really strong rating of Excellent (9.3 out of 10) to AIR 1.5 in their article. Way to go, Adobe!

09 December 2008

New Article for Adobe Developer Connection

Please check out my new Flex article on the Adobe Developer Connection.

Update: You can write articles for Adobe by checking out their Author Guidelines page.

08 December 2008

ActionScript Cookie Utility

Handle cookies directly in Flex or Flash using this cool library.

Adobe Text Layout Framework

Adobe has built a very powerful Text Layout Framework for the Flash Player 10. Of course you can use the framework in Flex, as well.

Check out the demo. The features include,
  • Bidirectional text, vertical text and over 30 writing systems including Arabic, Hebrew, Chinese, Japanese, Korean, Thai, Lao, the major writing systems of India, and others.
  • Selection, editing and flowing text across multiple columns and linked containers, and around inline images
  • Vertical text, Tate-Chu-Yoko (horizontal within vertical text) and justifier for East Asian typography
  • Rich typographical controls, including kerning, ligatures, typographic case, digit case, digit width and discretionary hyphens
  • Cut, copy, paste, undo and standard keyboard and mouse gestures for editing
  • Rich developer APIs to manipulate text content, layout, markup and create custom text components.
You can download the beta and play around with it. As you work with the product, please be kind and provide feedback to Adobe at the framework's forum. Thanks.

04 December 2008

Some Cool Tools for Your Flex Apps, Part II

Here are a few more cool components and utilities for your Flex apps,

Display HTML File in Flex TextArea

For a current project, I needed to have a help file for a Flex app that anyone with some HTML knowledge could update. One solution was described by PeterD on his great FlexExamples.com blog post. You can even apply a stylesheet to the HTML. Some big caveats: Because the Flex TextArea is based on the the underlying Flash API's flash.text.TextField object, it only allows a very limited number of HTML tags; the LiveDocs have a list of the allowed tags. And anything but very basic CSS is ignored.

Deleting Files That Won't Go Away

Windows' Secrets newsletter has a great article on how to give the boot to files that can't be deleted. I've run into this many times and there are some powerful (and free) utilities to the rescue. The newsletter requires a login but you can find the utilities at Gibin Software House.

03 December 2008

Creating Photoshop Arrows

Quick Arrows in Photoshop from Jay Hilgert on Vimeo. You might be familiar with the arrow shapes that Photoshop contains. However, you can create custom arrows to fit your needs using the Line Tool and the tricks explained in this brief video tutorial.

02 December 2008

New Flex Learning Paths in the ADC

To make learning Flex easier, the folks at Adobe have created a new Learning Paths Project. It's also available as a Flex app (beta). It has a great role-based interface, which then splits you off into goals and tasks. Adobe is eager to get your feedback on the Learning Paths so go at it!

A Few Color Tools

Web developers (and others) often need ways to generate colors, detect a specific color on-screen, snap to web-safe, etc. Here are a few tools to make your life a little easier,
  • Color Wizard Ver. 3.0: An online tool to generate matching colors.
  • Color Cop: Grab any screen color, snap to web-safe, and much more. It gives the hex and RGB values of the color, making it easy to re-create the color in Photoshop and other apps.

Fix the WinXP File Search Bug

If you've ever searched the contents of files in Windows XP, you probably know that it only looks at some limited file types. Coming to the rescue is Agent Ransack, a free and award-winning file searching utility that even lets you save the results in CSV or plain text. You can save the search criteria, see the contents of the file in a preview pane, and use regular expressions for your searches. Very cool.

24 November 2008

Saving Money for the UNC System via IT

Hi, all. What are some ways that we can help the UNC University System save money via Information Technology in these challenging times? I've started the list but please chime in.
  • Sharing information and learning on IT. If you've found a free tool or some creative way to accomplish a task, more than likely others can benefit from it.
  • More cooperation among the UNC system institutions on IT projects; why not share code and ideas on projects? We're all working for the betterment of the State of North Carolina. But obviously, for such sharing to occur, there needs to be some form of state-wide communication among the IT departments of UNC schools.
What are your thoughts? What have you done to save money in your IT department (or because of your IT department)?

Build Flex Apps from within Visual Studio 2008

A new product from Ensemble and Adobe enables .NET developers to build (and debug) Flex apps from within Visual Studio 2008. The tool is free and holds great promise.

21 November 2008

LDAP Browsing

If you do web dev against an LDAP (Active Directory, Open Directory, etc.) and need to peer into the depths of this mysterious beast, try the free Softerra LDAP Browser. Ensure that you have at least read permissions to the LDAP, get the path, and fire up the browser. You can do filters/searches and do LDIF exports.

Free Alternative to WinZip

Tired of the Windows built-in Extract utility? Download the great freeware 7-Zip. I've used it for a few months and can say nothing but good things about it.

Run Multiple IE's on the Same PC

If you've ever needed to test your web apps on multiple versions of Internet Explorer, here's a neat utility that'll let you do just that: MultipleIEs. It lets me run IE 7, 6, 5.5, and 5.01 on the same machine.

Make Your Sites Come Alive!

You can add animated characters to your site to speak customized text and provide custom help to users. The technology's been around for awhile, but it's gotten progressively more sophisticated. Take a look at the SitePal.com option. This article outlines the benefits and the companies that offer the technology.

Great (and Free) SFTP/FTP Client for Windows

A friend told me about this great, freeware SFTP client for Windows called WinSCP. For an RIA project that resides on a Solaris box, this tool came in quite handy, with drag-and-drop capabilities from WinXP Pro. Lots of cool built-in features, including the ability to set permissions on uploaded files. Very useful when uploaing to a Unix box; even lets you set the permissions in octal.

20 November 2008

Adobe CS4 - Master Collection

Just got the CS4-MC and the box itself is beautifully designed. From Adobe: Provide an integrated venue for social networking, collaboration, inspiration, and improved productivity.

Services available at launch:
  • ConnectNow: Free real-time online collaboration from CS4 applications for up to 3 people
  • Adobe Community Help: Community based learning and information sharing in CS4
  • kuler: Color sharing and exploration online and in app
  • InContext Editing service: Direct web page editing (beta at launch)
  • Resource Central: Up-to-date information

Actionscript 3 Cryptography Library

For those who need to encrypt/decrypt information using common algorithms (RSA and MD5), then the as3crypto is the answer.

19 November 2008

What is an RIA?

Next time you wonder, check out this great page from Adobe.

Free CS4 Curricula from Adobe

Adobe has some excellent higher education resources for learning everything from the CS4 suite to RIA technologies.

Flex Data Models

One of the powerful features of Flex is the <mx:model> tag. You can bind fields and variables to it; when a user updates a value in a TextInput, if that field is bound to a model, the value in the model will be updated too. You can then pass the model object to your server-side technology. Recently, I needed to pass some search parameters to an HTTPService:

<mx:model id="serviceModel">

The above model object came in handy. It's basically an XML object with whatever structure you'd like to give it. Note the first two nodes off of <root> are bound to TextInput fields; the last is bound to a private variable. When the value of the variables change, so do their values in the model.

Then when I'm calling the HTTPService, I simply pass the model object to it:


When You're Stuck...

When you're a Flex developer, you will run into questions; it's inevitable. You'll exhaust Google (if that were possible!), and wonder where to turn to next. Adobe's Flex Forums are great. But don't forget the FlexCoders Yahoo Group. There seem to be experts on there 24/7 answering questions. Lots of Flex heavyweights are helping folks on a regular basis.

Amy's Flex FAQ - Lifesaver!

Here's an FAQ of common Flex issues/questions. It should be a must-read for Flex developers, beginners and experts. Thanks, Amy, for this great resource :)

11 November 2008

Setting a Flex Label to a Special Character

When setting a label's text property dynamically, you can't use the ASCII code for special characters; you must use the HEX value instead. For example, the following will not have the desired effect,

var date:Date = new Date();
lblFooter.text = "&#169; " + date.fullYear.toString() + " MyOrganization.";

This will produce the following result:

&#169; 2008 MyOrganization.

To correct this, use the HEX value instead,

var date:Date = new Date();
lblFooter.text = "\u00A9 " + date.fullYear.toString() + " MyOrganization.";

which gives you,

© 2008 MyOrganization.

Note that the HEX code must be 4 digits. If, as in this case, the code is only 2, you'd precede it with 0's. To look up the codes, go here.

07 November 2008

Search a Folder for a File in Java

Java has some powerful mechanisms to search your server folders for files. I recently had a project where files were created on the server with partially random names, such as ABCD123__199518631844.jpg, where the ABCD123__ was the known portion of the filename. Later, I needed to find and delete these files. Some research revealed the FilenameFilter interface which contains an accept() method, returning a Boolean to indicate if the file meets a certain condition. In my case, I needed to have the filename begin with a specified string,

import java.io.FilenameFilter;
import java.io.File;

public class FileFilter implements FilenameFilter
private String _namePortion = "";

public boolean accept(File dir, String name)
return (name.startsWith(_namePortion));

public void setNamePortion(String value)
_namePortion = value;

I added the setNamePortion() method to set the string that will be tested. Then in the servlet, I added the following code to find and delete the file(s) that met the criteria,

File directory = new File(uploadDir);
filter.setNamePortion(aString + "__");

File fileList[] = directory.listFiles(filter);
String filePathToDelete = "";
File f = null;

for (int i=0; i < fileList.length; i++)
filePathToDelete = fileList[i].getAbsolutePath();
f = new File(filePathToDelete);
filePathToDelete = "";

06 November 2008

Kap Inspect - Cool Tool Is Like X-Ray Glasses for Your Flex App

The free Kap Inspect tool from Kap IT, enables Flex developers to take a peek inside the workings of their Flex app. After installation, you hit Ctrl-Alt-F12 to get a popup containing the inner workings of your Flex app -- the styles, components, structure, etc. It's similar to the Web Developer Toolbar or Firebug in Firefox.

Degrafa for Flex Enables Control of Background Images

If you've ever wrestled with background images for Flex components, there's a powerful library to make your life easier: Declarative Graphics Framework (Degrafa). I'd implemented a paging mechanism for an AdvancedDataGrid; then I added a background image to the Application container,

Application {
background-image: Embed("global/media/flower.png");

The height property on the AdvancedDataGrid was set to 100% and the variableRowHeight="true"; however, this was giving me grief: For whatever reason, the record at the bottom of the grid was cut off. And the scrollbar stopped a few steps before it could completely reach it. After some trial-and-error, two solutions emerged:
  1. Take the height property off completely and keep variableRowHeight="true".
  2. Or set the rowHeight to some value and set variableRowHeight="false". The trouble was, this meant all the rows would be the same height. Not very aesthetically pleasing.
I opted for the first solution. But with this choice, it caused the grid to expand and contract as you paged through the records (the rows have different height values depending on their content). Not a big issue for the grid to resize vertically; but it was also causing the application's background image to grow and shrink as you paged the records. Again, not very pretty.

Some research led me to this great blog by Brendon Wildbore. The solution was to use his code example along with the Degrafa SWC file in the project's lib folder. Instructions on downloading and installing the SWC can be found on the Degrafa web site. Following Brendon's example, I changed the CSS to look like this,

Application {
background-image: Embed("global/media/flowers.png");
background-repeat: repeat;
background-position: center;
background-blend: normal;
borderSkin: ClassReference("com.degrafa.skins.CSSSkin");

And the problem disappeared. The image now stays the same size. However, the image was too dark; a check of the values and it was clear that the background-blend: multiply; was the culprit. Changed it to normal and all is well.

The Degrafa library allows for much more than this. Check out their site to see the capabilities.

04 November 2008

Wireshark - Must-have Utility for All Flex Developers

I was wrestling with a very subtle problem today: The Flex app was passing some variables to a Java servlet via an HTTPService,

var params:Object = new Object();
params.ServiceType = "INITIALIZE";
params.SearchID = searchID.text;
params.Description = searchDescription.text;

Using the Wireshark tool, I filtered the capture to only give me the packets for my server. I noticed that the above params data was being sent to the server as XML. Hmm. I had the following further up in the code,

serviceGridReader.contentType = "application/xml";

I created a simple HTML page with a form and a submit button, passing the same data in hidden fields. Lo and behold -- the servlet worked fine with that. Using Wireshark, I noticed the data was being passed in this format from the HTML form,


Once I commented out the line setting the contentType, the servlet was happy with a simple request.getParameter("ServiceType").

Java String Comparison

One little gotcha in Java is the string comparisons: Using the equality check == will tell you if the two variables are referencing the same object, not whether their string values are the same. To do a string comparison, use something such as this,

 if (string1.equalsIgnoreCase(string2)) {
//... do something

Otherwise you'll be wondering why your code isn't working ;)

31 October 2008

Reducing Images in Photoshop CS4 and Maintain Quality

For best results, sharpen your images before reducing them in size (Image > Image Size). Set Resample Image dropdown to Bicubic Sharper. After the reduction, apply a slight Smart Sharpen.

22 October 2008

Refresh a Flex DataGrid

To force a Flex DataGrid to refresh its data (say, after you've updated it), you can call the invalidateDisplayList() method. This causes Flex to in turn execute the component's updateDisplayList() method. This came in handy while writing an image-upload app; after the image is uploaded, I needed the DataGrid's selectedItem to show the image it was associated with; in the overridden set data() method of the itemRenderer, there's code to do a load() of the image from the server.

21 October 2008

Variable row height in Flex DataGrid

Here's an easy way to have your DataGrid's rows adjust to fit the height of each row's contents:
<mx:DataGrid id="myGrid" variableRowHeight="true"
You need to use the variableRowHeight and wordWrap properties to get the job done.

Flash Player Settings Manager

Here's an online tool for managing your Flash player's settings.

17 October 2008

AutoCommit in Java

Just spent some time debugging my Java code to figure out why the MySQL update statements weren't committing to the database; in fact, they were waiting to be committed and thus causing the table to appear to be locked. The problem was in the code I'd copied from a friend; it had this line in it,


This was put in to only commit a transaction when it was successful. Important safety tip: Either turn the false to true in the above code, or include conn.commit() statement after your DML statement to the database.

14 October 2008

Emerging Technologies Conference at UNC?

Hi, all. How do you feel about having an "Emerging Technologies" conference at UNC? Please post comments here and vote on the poll on the left. Some topics to get us started in the discussion include,
  • Rich Internet App tools/tech (AJAX, Flex, Curl, JavaFX, JBoss Seam)
  • Cloud computing (providing technology-enabled services over the Internet -- "in the cloud")
  • Mobile devices: Web access, development, etc.
  • Web 2.0 (social networking sites, blogs, wikis) -- though many of these are already established tech and not so much "emerging" anymore
  • Semantic search technology
Who would we contact to have such a conference? Are there companies and organizations that can help?

10 October 2008

InfoWorld Review of Flex Builder 3

From earlier this year, InfoWorld gave a glowing review to Flex Builder 3.

Adobe "Thermo" Announced

Adobe has a new tool under development to enable quick app UI prototyping, called Thermo. From the Adobe Thermo Labs site,
"Thermo" is an upcoming Adobe product that makes it easy for designers to create rich Internet application UIs. Thermo allows designers to build on familiar workflows to visually create working applications that easily flow into production and development.
Should be a great tool.

07 October 2008

Java and PNG File Uploads

I've run into an issue where a Java 1.4 servlet is having trouble with some PNG files: If the memory size of the image (not the disk size) is greater than 5MB, it gives a codecLib error when trying to read it during an upload. The IrfanView image utility came in handy for this (Image > Information). Haven't found any info on this.

One solution: Use the FileUpload object's size property to at least ensure the disk size is below 1MB; perhaps this will prevent those images with even bigger memory sizes from hitting the server until a better solution is found.

03 October 2008

Flash Security and the crossdomain.xml File

If you run into security errors with Flash while trying to fetch data, a handy little tool is the crossdomain.xml file on your server. This article talks about that.

How to Validate an Entire Flex Form

Flex doesn't have a way of validating an entire form; rather, it validates individual fields. To handle the form validation, Wheeler Street Design has come up with a cool and easy technique to do this. The source of the ValidateForm custom object is available by right-clicking the example Flex app.

Solution to Flex itemRenderer Recycling

Thanks to a friend, the solution to the itemRenderer recycling issue has been found. In the event handler for the button click, set a custom property on the datagrid's selectedItem,

dgMyGrid.selectedItem.UploadFileName = "myFile.jpg";

The custom property in this case is the UploadFileName. Also note that the data object, which would contain the row's values, is out of scope here. Perhaps this is because we're calling the function from inside the itemRenderer. So instead, we use the datagrid. However, the data object has that custom field set anyway so it can be accessed from the itemRenderer.

Then in the itemRenderer, we override the set data function,

override public function set data(value:Object):void {
super.data = value;

if (data.UploadFileName == undefined){
txtPhoto.text = "";
else {
if(data.UploadFileName == null || data.UploadFileName == ""){
txtPhoto.text = "";
else {
txtPhoto.text = data.UploadFileName;

02 October 2008

How to Display HTML in Blogger Posts

If you've ever tried posting HTML/XML to a blog, you'll notice that in most cases, it won't display. Here's a simple way to show HTML in Blogger posts. Convert the <> to their ASCII codes (&lt; and &gt;).

Curly Braces in Flex Control Properties

Curly braces can make a huge difference in your Flex components' properties. Found out the hard way. I had the following in a custom validator, and wondered why it kept getting passed as a string and not being processed as a function,

<myutil:FileExtensionValidator id="fileNameValidator"
errorMessage="You can only upload JPG, JPEG, GIF, and PNG files."
validExtensions="{new Array('.jpg','.jpeg','.gif','.png')}"
source="{fileName}" property="text" required="true" />

Note the curly braces in validExtensions; without it, no array was being created. Rather, the value was passed as a string. Ted's post helped with figuring out property binding. Duh!

30 September 2008

Flex itemRenderers and Recycling Issues

Here's a funky behavior of itemRenderers inside any List-based component (for example, DataGrids). I ran into this and it drove me bunkers until I discovered what was causing it. Here's the scenario.

You have a DataGrid that contains an itemRenderer in one or more columns. Let's say you have a Button control in the renderer that browses for a file on your hard drive and plugs the filename into a TextInput within the same itemRenderer. All is fine -- until you scroll the DataGrid.

You'll notice that other, random TextInput controls in the same column have the same value. What the heck is going on? First inclination is to doubt your event handling code -- it's probably writing to more than one row. After much blood, sweat, and tears, and a lot of research, the answer reveals itself: The itemRenderers are recycled in the List-based controls. In other words, as you scroll, you'll notice the same value present in other itemRenderers without you having updated them. Also, if you scroll up to your updated row, the TextInput field is now blank!

Some articles that will help are here,
There are solutions to this recycling issue (described in the articles). I'm implementing one and will write more as I get it working.

25 September 2008

Strange Behavior in Flex Builder 3

I've noticed that at least in my copy of Flex Builder 3, the code-completion feature doesn't seem to work entirely correctly. I was trying to define a variable of type ListBaseContentHolder, but typing the dot "." after listClasses brought up a list of available classes -- but not ListBaseContentHolder!

var lb:mx.controls.listClasses.

All the online documentation said it was there, but Flex Builder wouldn't show it. I typed it in manually,

var lb:mx.controls.listClasses.ListBaseContentHolder;

and it compiled just fine. What's going on here?

Update, 9/30/2008: Apparently, by design, the folks at Adobe don't want you accessing some of the more arcane classes. Not sure why -- this is not arcane; I've been using it to get my work done :-)

Online XML-to-DTD Converter

For those who know their XML structure but need a little automated help with generating the DTD, there's a cool online tool. Very cool.

24 September 2008

Flex Validator Error Message Issue - Found Solution

Flex's validators are great but they're a little too subtle in notifying the user of errors: They mark the error field on the form with a red border. If you roll over the field, you'll see the error in a red tooltip. Why not have an option to display the validation error when it occurs, instead of having to mouse over to see it?

Well, here's a solution by Steven Gemmen. When you detect the error, dispatch an event to fool the field into thinking there's been a mouseover. Of all the solutions I've seen, this is the best/easiest.

The only problem I've run into is that the ValidationResultEvent's field property is null, even though the field has thrown the error. So I'm storing the source property in the subfield, generated from a custom validator,

  _results.push(new ValidationResult(true, super.source.toString().substring(super.source.toString().lastIndexOf(".")+1), "BadFileName", _errorMessage));  
return _results;

Not elegant, but it fixes the issue. Back on the page, I call the custom validator's Validate() method manually and receive the ValidateResultEvent.

  if (results.type == ValidationResultEvent.INVALID){
var val:ValidationResult = results.results;

This calls the function to activate the error tooltip,

  private function setValidationFocus(objName:String):void{
var frmObj:TextInput = this[objName];

frmObj.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER));

Now to figure out why I'm not able to get the field property. Also, how do you remove the tooltip when the user clicks into the field?

22 September 2008

Adobe CS4 Launch Event

Hi, all. Adobe will launch their CS4 Suite on Tuesday, 9 a.m. Pacific Time. You can get details on the BrilliantEvent site.

Flex 4 - Download the Beta SDK

Flex 4, codenamed "Gumbo," is available for download from Adobe's OpenSource site. To get it installed and running in Flex Builder 3, you can use the tutorial at FlexExamples.

Exporting Data from SQL Server Express 2005

One area in which SQL Server Express is sorely lacking is its import/export capabilities. You can download the Microsoft SQL Server 2005 Express Edition Toolkit, but that still won't generate the INSERT statements to populate your tables on another server. If you navigate to following folder, you can run the DTS Wizard tool,

C:\Program Files\Microsoft SQL Server\90\DTS\Binn

After some Google searches, this result turned up from Vyas Kondreddi. With some tweaking, it can probably work for other databases, too.

Why Use Flex?

As Web developers, we have some options these days in the realm of RIA, AJAX being one. So why use Flex? To me, one answer is how Flex separates the presentation and data access layers.

This means that the Flex app is independent of the back-end: You can use any server technology that meets your requirements -- ColdFusion, J2EE, PHP, .NET... Because so much of Flex is designed around XML (even the MXML document), you can use something as basic as an HTTPService call to read and write data to your data store.

Thus, if in a few months your boss comes to you and says, "We're going with PHP," and you've been using .NET, you don't panic. The Flex front-end remains the same -- just change a little of the plumbing to connect to a PHP app instead. That's why the XML data format is so attractive: Any Web app can generate it.

What are some reasons you're using Flex? Feel free to post comments.

The Power of Flex's resultFormat E4X

While researching how to bind XML data to a Flex AdvancedDataGrid, I saw various examples that had the data converted to array objects. That might have been the only way to work with XML prior to ActionScript 3.0. Now however, a new set of classes and functionality, known as E4X (ECMAScript-for-XML), make life easier for developers.

Playing around, I discovered that, on the HTTPService object, a simple property allows the data to be accessible via simple XML calls,

service.resultFormat = "e4x";

This enables your datagrid's columns' dataField to simply have your XML element or attribute name as its value. For example, to read an id attribute off of the root element of your XML, you'd use dataField="@id".

Flex and XML - Don't Forget the ContentType

Hi, all. Hope everyone had a great weekend. I came across an interesting problem last week with Flex 3: A Java servlet produced perfectly fine XML via the SAX (Simple API for XML) package, but the SWF file kept having a hiccup when it tried to read the data,

private function useHttpService():void {
service = new HTTPService();
service.url = "http://myserver/myServlet";
service.method = "POST";
service.addEventListener("result", httpResult);
service.addEventListener("fault", httpFault);

private function httpResult(event:ResultEvent):void {
premiums = XML(event.result);

// Read the XML directly (E4X) in the datagrid.
this.dgPremiums.dataProvider = premiums.premium;

// Fetch the rootCause and display in Alert.
private function httpFault(event:FaultEvent):void {
var errorMessage:ErrorMessage = event.message as ErrorMessage;
Alert.show("rootCause: " + errorMessage.rootCause.toString());

In the above code, I changed the FaultEvent handler to display an object as an ErrorMessage, as per Sujit's great article. Finally, it showed the error,

IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: myServlet"

Hmm. Flex errors can sometimes be tricky. A quick check on a Flex error lookup tool, and this page provided some answers, though not what I thought. One person had posted about having to remove the contentType from the HTTPService object. Mine was missing it. So I added it and voila! Flex fetched the data with no errors.

A little more digging and I realized that my Java servlet was emitting XML data, with the contentType set to "text/xml". Flex needed that hint of what data to expect. So adding this line to the useHTTPService() method fixed the headache,

service.contentType = "application/xml"; // Must have this or will get IOError -- servlet generates XML document.