Downtime

Sorry If I inconvenienced anyone, somehow my server got unplugged and I didn’t notice.

Clicking Through a Sprite in Flex/Actionscript

I ran into a problem recently where I wanted to add a rectangle to the stage but still wanted users to be able to click through it. Here’s a solution I found:

private function addClickThroughSprite():void
	{
	overlay = new Sprite();
	overlay.graphics.beginFill(0xFF0000,0.2);
	overlay.graphics.drawRect(0,0,width,height);
	overlay.graphics.endFill();
	overlay.hitArea = new Sprite();
	rawChildren.addChild(overlay);
	}

Basically you set the sprite hit area to a blank sprite, which exposes the components beneath. If anyone has a better solution feel free to share it.

Integer Division In Flex/Actionscript

If you’re used to C and other elemental high level programming languages, you know that 5÷9 = 0 and 10÷7 = 1. ActionScript being higher level than C automatically coerces the quotient of two numbers to the Number class, producing a decimal. To get the correct integer quotient, use the Math.floor function, which drops the decimal.

//This produces 4
var integer:int = Math.floor(14/3);

Intro to Try/Catch in Flex/Actionscript

Sometimes when you’re making a Flex application, you’ll expect a certain piece of code to fail at some point. This is the job of try and catch. For example, say I wanted to loop over a bunch of components I had within an HBox:

<mx:HBox id="myHBox">
		<mx:Panel title="1"/>
		<mx:Panel title="2"/>
		<mx:Panel title="3"/>
		<mx:Panel title="4"/>
		<mx:Panel title="5"/>
		<mx:Panel title="6"/>
		<mx:Panel title="7"/>
</mx:HBox>

To loop over these panels without setting a specific id for each, we can use the DisplayObject’s getChildAt() function. So within the block I could make a function that does the following:

private function averageTitles(box:HBox):Number
				{
				// initialize some variables
				var tempTotal:int = 0;
				var i:int = 0;
				var length:int = 0;
				var isEnd:Boolean = false;
				var tempPanel:Panel;
				//loop until the isEnd variable is true
				while(!isEnd)
					{
					//Try to get the child at location i
					try
						{
						tempPanel = box.getChildAt(i);
						tempTotal += parseInt(tempPanel.title);
						i++;
						}
					//if it fails, we have reached the end of the panels
					catch(e:Error)
						{
						isEnd = true;
						}
					//we always want to increase the length,
					//since the length is longer than the index
					finally
						{
						length++;
						}
					}
				//return the average
				return tempTotal / length;
				}

(Obviously the length is unnecessary, Its just an example)

The try block is what the program will attempt to execute first, and the code you expect to fail. In this example, the myHBox.getChildAt(i) is undoubtedly going to fail at some point when the HBox runs out of panels. When this happens, the program will throw an error, more specifically a RangeError, meaning you’re attempting to access something outside the array’s bounds. The catch block will quite literally “catch” the error before it escapes to the main application and causes a runtime error(the window that pops up when something goes wrong in a flash movie in your browser). The catch block will then execute the code within its block. A catch block can catch many kinds of errors; in my example I use the error type Error, meaning it will catch all errors. Since I know what kind of error will occur in my code, I could have just as easily written:

catch(e:RangeError)
	{
	isEnd = true;
	}

And the effect would be the same. You can also catch multiple types of errors within a try block using multiple catch statements where appropriate.

For a list of all types of errors, look at the Subclasses of the Error class in the Adobe Flex Language Reference.

You may also have noticed the finally block which increments the var length. The finally block is used to execute code regardless of when an error happens. So in the finally block in my code:

finally
	{
	length++;
	}

The length will always be incremented if there is an error or not, as we need the total number of items to find the average.

That’s basically it, I’ll write a more advanced tutorial later on things like throwing new errors and such. Good luck in your coding endeavors.

Black SMS-Chat Skin for Windows Mobile

For those of you who use the new SMS Chat for Windows Mobile, I created a new skin to replace the crappy black one that comes as the default. It works with SMS-Chat 1.25, so upgrade if you don’t have the latest version.

Unfortunately the developers hard coded in a lot of color information so we’re stuck with the blue for now(I’d rather have it as a green). Just download the black.bmp and black_alert.bmp files and copy them to /Program Files/VITO/SMS-Chat/skins/bin directory and overwrite the existing ones. Hope you enjoy!

Exporting to Excel using ColdFusion

Sometimes you’ll have a query that you want your users to be able to export to an Excel file. If you have ColdFusion 9, you could use the cfspreadsheet tag to do this, however ColdFusion 8 users and below don’t have this luxury. Fortunately the workaround isn’t all too bad. Here’s what you do:

<cfcontent type="application/msexcel">
	<cfheader name="Content-Disposition" value="filename=myFile.xls">
	<table>
		<tr><!-- A row -->
			<td>A Cell</td>
		</tr>
	</table>
</cfcontent>

That’s all there is to it. Basically you format the spreadsheet using HTML for a table. You can also format the cells using CSS, although results vary by which version of Excel or Open Office Spreadsheet your using. Office 2007 and 2010 allow for more customization using CSS than 2003 does, but for the most part generating simple spreadsheets using this method works pretty well. For example if I wanted to change the background color and set up a 3 column table with a header:

<cfcontent type="application/msexcel">
	<cfheader name="Content-Disposition" value="filename=myFile.xls">
	<table style="background-color:#366092; color:#FFFFFF;">
		<tr><!-- Header Row-->
			<td colspan="3" style="font-size:15px;">This is a header</td>
		</tr>
		<tr>
			<td>A Cell</td>
			<td>A Cell</td>
			<td>A Cell</td>
		</tr>
		<tr>
			<td>A Cell</td>
			<td>A Cell</td>
			<td>A Cell</td>
		</tr>
	</table>
</cfcontent>

Which yields:

Excel 2010

Just remember to use cfoutput when exporting ColdFusion data.

Flex: Introduction to ItemRenderers

A critical thing to know for any Flex programmer performing data-visualization is the itemRenderer. The itemRenderer in Flex can be a tricky beast, however they’re the best way to interact with content within a datagrid, or the various list controls(tileList, horizontalList, etc).

An itemRenderer is basically an object that sits in the list in the place of the default component(For example, the default component of a datagrid is the Label class). Most itemRenderers have access to all data in their row. You can use them to improve the user experience when performing operations on data. You can use either an MXML component or an ActionScript component as an itemRenderer, however the MXML is more straightforward, so we’ll start with this. Here’s a simple example:

dgexample

Here’s a datagrid with some users populated(creative, I know), now I’ve used an itemRenderer to add my custom button component into the datagrid to delete a user. Here’s the MXML:

<mx:DataGrid dataProvider="{nameArr}">
	<mx:columns>
		<mx:DataGridColumn
			headerText="First Name"
			dataField="firstName"/>
		<mx:DataGridColumn
			headerText="Last Name"
			dataField="lastName"/>
		<mx:DataGridColumn
			itemRenderer="comp.DeleteBtn"/>
	</mx:columns>
</mx:DataGrid>

Please note that a column that contains an itemRenderer does not need a dataField attribute, as it already has access to all dataFields for a particular row. The itemRenderer property contains the path to the class you wish to use in that column. The MXML component comp.DeleteBtn that is used as the itemRenderer looks like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Button xmlns:mx="http://www.adobe.com/2006/mxml"
	label="Delete"
	dataChange="update();"
	click="deleteUser();"
	>

	<mx:Script>
	<![CDATA[

	//The unique Identifier for my user list
	private var UID:int;

	//this function is run whenever the data is updated
	//you cannot rely on the creationComplete event to work if you're using a remoteObject
	private function update():void
		{
		UID = data.uid;
		}

	//this is run whenever the button is clicked
	private function deleteUser():void
		{
		//I would run a remoteObject that deletes this user from my database
		}
	]]>
    </mx:Script>

</mx:Button>

So Flex creates a DeleteBtn object for every row in the datagrid, and each DeleteBtn component has access to that rows data. While the update() function is not required(as you could use data.uid instead of UID) it simply serves as a reminder that you need to be conscious of when the data an itemRenderer is receiving changes. You also cannot use the creationComplete function to perform actions when the data changes, as the itemRenderer is not recreated when a dataChange even occurs.

Here’s Another Example:

dgexample2

In this example I’m summing the columns to make a total, and formatting the result based on its value. In this particular instance the value will turn red if it is below 20, and green otherwise. I used an ActionScript itemRenderer for this one.

package comp
	{
	import mx.controls.Label;

	public class Sum extends Label
		{
		//Constructor
		public function Sum()
			{
			super();
			}
		//You'll need this function to update how the label looks in the datagrid.
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		     {
		     //This runs the default action for refreshing a Label object, you need this.
		      super.updateDisplayList(unscaledWidth,unscaledHeight);

		      //Sum the sales numbers
		      var sum:int = data.popcorn + data.cotton + data.apples;

		      //Assign the labels text property to display the sum
		      text = sum.toString();

		      //Adjust the fontSize and fontWeight
		      setStyle("fontSize",14);
		      setStyle("fontWeight","bold");

		      //////////////////////////////////////////////////
		      //  conditional formatting based on total sales //
		      //////////////////////////////////////////////////

		      //if the total sales is less than 20
		      if(sum > 20)
		      	{
		      	//set the color to green
		      	setStyle("color",0x00AA00);
		      	}
		      else
		      	{
		      	//set the color to red
		      	setStyle("color",0xAA0000);
		      	}
		     }
		}
	}

For the most part you’ll be overriding the updateDisplayList method to change the look of a component using an ActionScript class.

So there’s a tutorial for basic itemRenderers. A more advanced tutorial is to follow.

Populating a PDF From ColdFusion

ColdFusion provides a lot of handy features that make it really easy to do something that seems incredibly complicated. Creating and populating a PDF dynamically is one of them.

Heres what you do:

Create a PDF with a form, that has fields that are not read only. You also need to name each field uniquely.

For this particular example I was making a PDF for a Bill of Lading.

Sample Form

Sample PDF Form

This PDF needs to be saved on the server in a location accessible to ColdFusion to be used as a template.

Next, populate the PDF with the following code:

<cfpdfform source="#sourcefile#" destination="#destinationfile#" action="populate" overwrite="no">
    <cfpdfsubform name="form1">
        <!--- Begin Field Params --->
        <cfpdfformparam name="sampleFieldName" value="#someValue#" >

The cfpdfsubform is required. The default subform created by LiveCycle/Acrobat is form1, so its usually a safe bet to just go with that unless you’ve been messing around with the subforms. You can really make sure by going into the XML view of the PDF in LiveCycle.

You can read more about this tag and its uses here:
LiveDocs

Access Specifiers in Flex/Actionscript

There are four types of basic access in Flex:

Access Description
public All objects and classes can access
private Only objects with the same class can access
protected Only objects with the same class or derived classes
internal Only objects in the same package(essentially the same directory in flex)

There are custom namespaces and other operators that exist to to limit access, but these are the basics that you’ll use the most.

Flex Auto-Resizing Datagrid

If you’ve ever wanted to make a datagrid that re-sizes to fit its content, heres how…

Make a function that computes the size necessary to accommodate all the data:

private function datagridChange():void
	{
	var newHeight:int = sampleDG.rowHeight * sampleDG.dataProvider.length
		//this is for the column headers, and the extra empty row
		+ 2*sampleDG.rowHeight;
	sampleDG.height = newHeight;
	}

Flex automatically adds an empty row at the end of the datagrid, which accounts for the addition of two extra rows(the other coming from the column headers). You can get around this by setting the datagrid’s verticalScrollPolicy to “off”, then change the extra row addition back to one:

<mx:DataGrid id="sampleDG" verticalScrollPolicy="off">
private function datagridChange():void
	{
	var newHeight:int = sampleDG.rowHeight * sampleDG.dataProvider.length
		//just for the column headers now
		+ sampleDG.rowHeight;
	sampleDG.height = newHeight;
	}

Finally add that function to the dataChange event property of the datagrid.

<mx:DataGrid id="sampleDG" dataChange="datagridChange();" verticalScrollPolicy="off">

In the case where you have a pre-determined dataProvider for the datagrid, you may also want to add the function to the creationComplete event as well.