Posts Tagged flex

FlexUnit 4 Testing Services In Flash Player Issue

We’ve created a number of FlexUnit 4 (FU4) tests for our current, large project and the suite of tests that seems to be of the most importance to both us and our client is the one that tests the services. Our client’s back-end services are simple JSPs that return XML payloads for a number of CRUD operations on various objects in the system, so we’d like to test sending good required data as well as bad required data to our delegate before hitting the service directly.

The issue we ran into was quite frustrating and it took me some time to figure it out — I actually had to explain the system of tests to my partner before it dawned on me what was going wrong. In order to actually hit the services and get data back, you need to be logged into our client’s system…except this isn’t done through a Flex login, but rather via the larger application’s HTML login in which our smaller app lives (SSO)…once you’re logged in, a cookie is sent back and forth between the client and server…such is the security design of our client’s application framework and there wasn’t any wiggle room to change this.

SWF Browser Association

Change SWF to Open With Browser

Now think about FU4 and how it actually runs the tests (when using Ant and not building and running with FlexBuilder)…it simply opens up a TestRunner.swf in the Flash Player to execute it’s tests…this means no browser wrapper for our SWF and thus no access to cookies…and ultimately no working services in my tests…grrrr.

So here’s a simple solution (on Mac)…open up Finder and locate your TestRunner.swf, right-click on it and select “Get Info”. Find the section “Open with” and change the application to your browser (I use FireFox), but don’t click the button change for all, as we just want to change this for this file and this file only. Voila! Now your TestRunner.swf will run in thr browser when your Ant buld runs and you will have access t cookies (assuming you’ve already logged into the system you need access to in the same browser session).

Post to Twitter Tweet This Post

, , , , , , ,

3 Comments

Headless Flex Builds on EC2 Using Hudson Against Remote SVN Repo on Assembla with FlexPMD

We’re doing a current project requiring continuous integration. We also maintain the SVN repo. There’s a lot here and you may/may not need all the pieces. We’re specifically doing headless Flex/DataViz Builds on Amazon EC2 Ubuntu with Hudson against a remote SVN repo on Assembla and have thrown in FlexPMD to see what it can add to our process.

First, some stuff I’ll assume you already have and know how to work with:

  • EC2 machine running in the Amazon cloud. We’re using one of the Ubuntu disty’s. I’m going to assume you have all the necessary ports open for things like email and such.
  • Hudson. We’re using version 1.326. We’ve used other CI tools but find Hudson to be very user friendly. You’ll need to have a servlet container ie Tomcat and you just pop hudson.war in and you’re ready to rock.
  • Remote SVN. You can be using a local one, but. We’re using Assembla since it’s got all the stuff we need to do business in one place and it’s simple to use. Time is money.
  • Java installed on your server. We’re using version 1.6.0_07

Stuff you’ll end up downloading/installing/configuring:

  • Flex SDK
  • Flex Dataviz components
  • SVN client
  • Ant
  • Flex Ant
  • Email

Step 1, Flex

We’re currently building with the latest stable build of Flex 3.4. Get yourself all logged into your EC2 account and let’s roll. I create a flex/3.4 directory and cd to that directory and then get the latest Flex rev. This is the latest URL:

wget http://download.macromedia.com/pub/flex/sdk/flex_sdk_3.4.zip

Let’s get the dataviz components as well since they’re a separate install

wget http://download.macromedia.com/pub/flex/sdk/datavisualization_sdk_3.4.zip

Oh yeah, and if you’re going to be doing unit testing, might as well get that sucker as well

wget http://download.macromedia.com/pub/flex/sdk/automation_sdk_3.4.zip

Great, so we have all the pieces we need so far. You’ll want to unzip and cp these to wherever you keep your software installs on the server. I’m no unix guru, but, near as I could find out, the common location is /opt.

So, create a /opt/flex directory and unzip the flex_sdk_3.4.zip files there. Then, copy the dataviz zip there and unzip it.

cp datavisualization_sdk3.4.zip /opt/flex

cd /opt/flex

unzip datavisualization_sdk3.4.zip

This will extract the following into the SDK 3 installation

  1. datavisualization.swc into the frameworkslibs folder
  2. datavisualization__3.0.9147.swz and datavisualization__3.0.9147.swf into the frameworksrsls folder
  3. datavisualization_rb.swc into the appropriate frameworkslocale<locale> folder

Let’s make sure we put the Flex compiler on the class path. On our server, the default shell is bash. You’re setup may be different, but essentially, you want to find the properties file for you shell (I’m using /root/.bashrc) and add the following line to the bottom of it:

export PATH=/opt/flex/bin:$PATH

Now let’s test it. You may need to log out and then back into your shell. At the command prompt, enter mxmlc and hit return. You should see something like

Loading configuration file /opt/flex/frameworks/flex-config.xml

Error: a target file must be specified

That’s a good error. It means that the Flex compiler is now accessible on your system. If nothing comes back, you’re just at the command prompt, you may not be using the right shell properties file.

In order to build projects that use the dataviz components without having the watermark on your charts and graphs, you’ll need to apply a Flex license to the installation. You do this in the flex-config.xml file located in /opt/flex/frameworks. Towards the bottom of the file you’ll see some commented out xml for doing so:

<licenses>
<license>
<product>string</product>
<serial-number>number</serial-number>
</license>
</licenses>

Step 2, SVN

We are accessing an SVN repo on our Assembla account. The easiest way to make this happen from the EC2 is to just install SVN. So, from the command prompt:

apt-get install subversion

If you run into any errors, I always find it helpful to refresh the list:

apt-get update


If all went well, you should be able to log into your remote repo:

svn –username <your_username> –password <your_password> –no-auth-cache checkout <some_project_name>


If successful, you’re going to have a checked out version of some_project_name in your current directory.


Step 3, Ant


We’re going to be using Ant as our build process. It will called via a Hudson job. Let’s get and install Ant.

apt-get install ant


Once that completes, you should be able to type ant at a command prompt. If it installed successfully, you should see something similar to (unless there happens to be a build.xml file in your current directory):

Buildfile: build.xml

BUILD FAILED


This is good. We now have Ant installed. The only other Ant specific thing we’ll need to do is copy the FlexTasks.jar from your Flex SDK into your new Ant install.


Let’s find where Ant was installed. At a command prompt:

which ant

(which will most likely return)

/usr/bin/ant


Now, navigate to your Flex SDK Ant lib directory. The Flex SDK now contains the flexTasks.jar we need.

cd /opt/flex/an/lib


Now just copy this to the location of your Ant install’s lib directory (typical):

cp flexTasks.jar /usr/share/ant/lib


If you do not copy this file to the lib directory, you must specify it by using Ant’s -lib

option on the command line when you make a project.

Step 4, Setup Hudson Job


Plugins

I’m assuming you have a working familiarity with Hudson. If not, there’s a ton of info via your install directly and on the web. We have a few extra plugins installed. The Violations plugin is useful for code analysis via PMD files if you structure your ant files to use it. The Email Extension gives you a bit more flexibility than the basic email tool.

plugins

Configuration

Here’s a look at few items we needed in the Hudon configuration page to get things to work smoothly

Specify the Ant location on your server.


ant

For the Extended E-mail Notification plugin. We’ve defined an email account on our system called hudson. We also use gmail for our corporate email. We’re essentially relaying to gmail which requires SMTP auth and SSL (note: we haven’t entered anything in the default Hudson E-mail section):


email

Job Setup

Go the usual steps of creating a new job. Here are the pertinent parts.

In Source Code Management, we’ll need to point to our remote SVN. When you click on the “?” next to the Repository URL, you will see the grey box and be able to provide login credentials to your SVN repo and test the connection:


svn

We’re not going to specify any build triggers. The reason is that Assembla gives the ability to access the post-commit hook in SVN via their “Webhook” plugin. In that tool, all we have to do is specify the Hudson job URL and with each check in of code, the project is checked out, built, and success/failure notification sent to our dev group. This is the key to the ‘continuous integration’ aspect of this whole setup.


webhook

We do need to tell Hudson to use Ant to do the builds. We have a target in the build.xml file (that is in the root of our Flex project) called main.hudson. To be on the safe side, I’ve specified the full path to the build file. We specify the ant install we configured in the Hudson configuration page earlier. It would probably be helpful to give it more meaningful name like ‘ant_version_x’.

jobant

FlexPMD is another great tool we use that profiles your code based upon a bunch of best practices defined by the Flex group at Adobe. You can also specify your own criteria to use in the analysis. It’s worth checking out. Note the format of the XML filename pattern used. It took a while to figure that part out!


flexpmd

We configure the Editable Email Notification accordingly:


jobemail

And that’s pretty much it. I’ll be pushing up a blog shortly that will walk through the whole ant build used for this project. It uses modules, all sorts of RSLs, FTP, and so on.

Happy Flexing.

Post to Twitter Tweet This Post

, , , , , , , , ,

3 Comments

Axiis Examples with Lots of Comments

We’ve begun using Axiis on a current client’s project. The application is loaded with graphs and charts and when we hand off the project, we needed to provide a framework for the development staff to quickly build and add new graphing components. Some of the charts are simple but there are some more complicated ones we need to build and will be built in the future. The current Flex DataViz components work fine for simple tasks. But, anyone who has had to go beyond the basics understands the pain that you quickly begin to feel.

Fortunately, I caught Tom Gonzalez’s, (BrightPoint Consulting) lecture at MAX this month and was blown away. The things they’re doing with the Axiis framework and Degrafa are off the charts! (pun intended)

I’ll leave the real discovery to you to check out the Axiis site, but, Axiis is a ’specialized framework that implements specific design patterns that can be used to create your own visualizations’. It’s not a pre-built collection of charting components. They’ve developed a great way of abstracting the basic building blocks of doing data visualization.

Axiis is currently in beta release. There are a lot of great examples on their site so check them out. If you’re new to Degrafa, it’s worth your while to do a bit of reading and check out the cool examples they have on their site as well since many of the examples use Degrafa.

Being in beta, the documentation is a work in progress. The examples from the site are great and really cover a lot of space, but I did struggle with some of the concepts at first. So I’ve taken three of the first examples we needed to borrow from and hyper-commented them for clarity.
I’ll continue to add to the collection over time.

Cluster Stack Example

Linear Series Example

Cluster Column Example

Post to Twitter Tweet This Post

, ,

2 Comments

Centering the Label Vertically in a FormItem

So you’re coding up some form items and the glorious designer is showing the label for the form item centered vertically, or, at the bottom.

centeredformlabel

Piece of cake says I and I start to look for the props to do so. Lo and behold, they don’t exist. WTF??

Google this and google that and no luck!!

Great, now what do I do?

Well, it’s kinda hacky, but it works.

I call this function on the creationComplete event of the FormItem:

private function centerLabel(evt:FlexEvent):void
{

var fi:FormItem = FormItem(evt.currentTarget) as FormItem;
var lbl:Label = fi.itemLabel as Label;
lbl.move( lbl.x, lbl.y + (lbl.height/2) );

}

Enjoy

Post to Twitter Tweet This Post

,

No Comments

Flex + Cairngorm + Spring ActionScript Part 5 Announcement

UPDATE: I’ve decided not to continue this tutorial at the moment as I’m really digging the lightweight, simple elegance, and less complicated Swiz framework. I will finish the path of this original tutorial and dig into BlazeDS + Spring + etc, but with the obvious replacement of Swiz over SAS + CG. Sorry for the confusion and delay.

I’m going to release Part 5 of the series shortly, although it’s taking a slight deviation from what I had planned originally…

The Spring AS (”SAS”) framework has been changing quite a bit and they’ve released new versions and new docs for both the framework itself and the Cairngorm (”CG”) extensions, so I’d like to revisit my SAS + CG implementation leveraging their approach.

I’ve also added in a login screen to set up the use of Spring Security with role based permissions on the Java side — it also allows me to illustrate the use of multiple Cairngorm Events + Command + Delegate paths with both hardcoded AS and XML Delegates.

The actual code is done, now I just have to write about it…I’m about 3/4 of the way through the actual post explaining the code, but it’s Friday and I need a beer so here’s the code to tide those waiting on it over. Again, the full blog post with details explaining the ins and outs to come some time next wk.

Assets:

Previous Tutorials:

Stay tuned for the real Part 5 in the series.

Post to Twitter Tweet This Post

, , ,

7 Comments

Convert Plain-Old Flex Project to Java Server Based Project

Ever start a project as a plain-old Flex project that doesn’t use a Java server and then later want to convert it? You’d think you could do this simply by examing the project’s server properties (Project -> Properties -> Flex Server) and adding a server…but no…you can’t…ehhh…not to fret, there’s still hope…don’t create a new project from scratch just yet and copy all your old projects files into your new project. We just need to modify a couple of the project’s .files and we’re good to go.

Modify the Project Property Files

Since we started our Flex project as a non-server based project, we’ll need to make some modifications to our .project, .actionScriptProperties, and .flexProperties files in order to convert the project to a server-based application. These files all exist under the root of the Flex Project’s directory — if you can’t see them, make sure you’re in either the Flex or Flex Debugging Perspective.

As a side note, under the covers we’re modifying the Flex Project’s Properties as if we right-clicked on the project and selected Properties.

NOTE: The following examples use a @@key@@ to indicate where you should substitute your own project, workspace, and server settings.

NOTE: This also assumes that you’re building your flex project to a directory in your Java project called flex — you don’t need to create it in WebContent on the Java side, as it’s generated by Flex Builder when you do a build or clean.

.actionScriptProperties

Open up .actionScriptProperties and locate the <compiler> node and add or change the following attributes to look like this:

  • outputFolderLocation=”DOCUMENTS/@@JavaProjectName@@/WebContent/flex”
  • rootURL=”http://@@Host@@:@@Port@@/@@JavaAppContext@@/flex”

Your .actionScriptProperties should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<actionScriptProperties
	mainApplicationPath="@@MyFlexApp@@.mxml"
	version="3">

<compiler
	additionalCompilerArguments="-locale en_US
	-use-network=false"
	copyDependentFiles="true"
	enableModuleDebug="true"
	generateAccessible="false"
	htmlExpressInstall="true"
	htmlGenerate="true"
	htmlHistoryManagement="true"
	htmlPlayerVersion="9.0.124"
	htmlPlayerVersionCheck="true"
	outputFolderLocation=
		"DOCUMENTS/@@JavaProjectName@@/WebContent/flex"
	outputFolderPath="bin-debug"
	rootURL="http://@@Host@@:@@Port@@/@@JavaAppContext@@/flex"
	sourceFolderPath="src"
	strict="true"
	useApolloConfig="false"
	verifyDigests="true"
	warn="true">

<compilerSourcePath/>
<libraryPath defaultLinkType="1">
<libraryPathEntry kind="4" path=""/>
<libraryPathEntry kind="1" linkType="1" path="libs"/>
</libraryPath>
<sourceAttachmentPath/>
</compiler>
<applications>
<application path="@@MyFlexApp@@.mxml"/>
</applications>
<modules/>
<buildCSSFiles/>
</actionScriptProperties>

.flexProperties

Open up .flexProperties and locate the <flexProperties> node and add or change the following attributes to look like this:

  • flexServerType=”2″
  • serverContextRoot=”/@@JavaAppContext@@”
  • serverRoot=”${DOCUMENTS}/@@JavaProjectName@@/WebContent”
  • serverRootURL=”http://@@Host@@:@@Port@@/@@JavaAppContext@@/”

Your .flexProperties should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<flexProperties
	flexServerType="2"
	serverContextRoot="/@@JavaAppContext@@"
	serverRoot="${DOCUMENTS}/@@JavaProjectName@@/WebContent"
	serverRootURL="http://@@Host@@:@@Port@@/@@JavaAppContext@@/"
	toolCompile="true"
	useServerFlexSDK="false"
	version="1"/>

.project

Open up .project and locate the <projectDescription> node and add the node <linkedResources> after the <natures> node inside <projectDescription> — simply copy and paste the <linkedResources> node from my code snippet below; your .project file should look like this:

NOTE: You need to put the full, absolute path on your machine to your Java Web Project in place of the @@FULL_PATH@@ key I subsituted down below for the path on my machine.

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
	<name>EmployeeManagementConsole4</name>
	<comment></comment>
	<projects>
	</projects>
	<buildSpec>
		<buildCommand>
			<name>com.adobe.flexbuilder.project.flexbuilder</name>
			<arguments>
			</arguments>
		</buildCommand>
	</buildSpec>
	<natures>
		<nature>com.adobe.flexbuilder.project.flexnature</nature>
		<nature>com.adobe.flexbuilder.project.actionscriptnature</nature>
	</natures>
	<linkedResources>
		<link>
			<name>bin-debug</name>
			<type>2</type>
			<location>
		@@FULL_PATH@@/@@JavaProjectName@@/WebContent/flex
			</location>
		</link>
	</linkedResources>
</projectDescription>

Check Flex Project Properties

Just to make sure we did everything correctly, let’s check the project properties by right-click on our Flex Project and selecting Properties -> Flex Build Path. It should look like this:

NOTE: The screen shots have my actual project, workspace, and server settings — these should help solidify the entire tutorial. They are from Part 4 of my Stack Tutorial Series.

  • Main source folder: src
  • Output folder: ${DOCUMENTS}/@@JavaProjectName@@/WebContent/flex
  • Output folder URL: http://@@Host@@:@@Port@@/@@JavaAppContext@@/flex
Build Path Properties

Build Path Properties

Next let’s check the Flex Server Settings: Project Properties -> Flex Server:

  • Root folder: ${DOCUMENTS}/@@JavaProjectName@@/WebContent
  • Root URL: http://@@Host@@:@@Port@@/@@JavaAppContext@@/
  • Context root: /@@JavaAppContext@@
Server Properties

Server Properties

Finished!

Post to Twitter Tweet This Post

, , , ,

5 Comments

Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Hibernate + MySQL Tutorial Part 1

Introduction

I’ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I’m really pleased with — since I’m reusing these terms throughout the series, please review the acronyms after each, as that’s how I’ll be referring to them in the tutorial:

To that, I’m planing on writing a series of tutorials where each one builds on the previous one. The final tutorial will cover: Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Spring Security + Hibernate + MySQL

Tutorial Goal: Flex + Cairngorm

Build a foundational Flex + Cairngorm application that provides a solid application architecture so that we can easily add new functionality in later iterations and tutorials — this will probably be a bit slow for most experienced Flex developers, so feel free to jump to Part 2 that introduces the Spring ActionScript framework (”SAS”).

Assets:

Prerequisites & Assumptions

  • Ability to create Flex and ActionScript classes with Flex Builder (”FB”). NOTE: I’m actually using Eclipse WTP with the Flex Builder Plugin so I can develop in both Java/J2EE and Flex projects in one IDE.
  • Used or understand Cairngorm’s basic flow and how it all fits together. If you haven’t, I recommend looking at the Cairngorm Diagram for some reference.
  • Understanding of OOP and basic Design Patterns.

What This Tutorial is Not

This particular tutorial is not focused on why I chose CG over one of the myriad other frameworks like Mate, PureMVC, Swiz, Bob’s New AS3 MVC-based Framework with some other obscure name, etc…I could have just as easily chosen PureMVC (”PMVC”), but since CG is more widely used and I want to keep things simple, we’re going with CG. Remember, this simply sets up the plumbing for later fun, so please leave the frameworks debate and why I chose CG for another time, or at least until another post where I actually want to argue the architectural issues that both frameworks possess.

Furthermore, I won’t go into great detail about CG’s complete ins and outs and/or best practices and extensions that my team at WASI currently uses in this first post…let’s just get a CG app up and running and then come back to that in a later, cleanup/best-practices post.

NOTE: Most of the code snippets are truncated to be concise and only highlight the lines of code that truly deserve the readers attention, so it’s highly recommended that readers download the accompanying project source files in order to follow along.

So without any further delay, let’s get at it.

Create a Flex Builder Project

NOTE: If you don’t feel like writing all this from scratch, just download my project.

Since this is part one in a n+ series of tuts, let’s create a new Flex project called “EmployeeManagementConsole1″. I originally created an address book application, but since I’ll be referencing Marcel Boucher’s Blog later in the series for his Flex + Hibernate (”HIB”) Employee Management Console, I’d like to be consistent…and why reinvent the wheel…thanks for the starting point bud.

Add Libraries and Dependencies

Next we’ll need to add the necessary libraries and dependencies to the project as SWCs and AS files; for now, we’ll just need:

Cairngorm 2.2.1 (non-enterprise edition) — Download the ZIP, extract it, and import the Cairngorm.swc into the libs folder of your Flex Builder project.

Create the Flex View

Again, since we want to keep this simple, we’re going to reuse the application UI from Marcel Boucher’s Blog, so we won’t spend any great amount of detail reviewing it. Create 2 Panels and put a DataGrid (”DG”) in the left one with 3 columns in with header names : Employee ID, First Name, Last Name. In the second Panel, create a Form with 2 FormItems corresponding with the First and Last Name fields we just added to the DG. Finally, below the DG put a Button with the label “Refresh List.” It should look something like this:

Employee Management Console UI

Employee Management Console UI

Hook Up Cairngorm & Get Some Data

First, create a ModelLocator and give it a public property of employeeList of type ArrayCollection for our DG view to bind to: CairngormModelLocator.as

/**
 * The CairngormModelLocator provides singleton access to all the
 * model/business objects in the application.
 */
[Bindable] public class CairngormModelLocator implements ModelLocator
{
	public var employeeList:ArrayCollection = new ArrayCollection();
...
}

Go ahead and create the necessary CG Event (”EVT”), Command (”CMD”), and Business Delegate (”BD”) to actually get us some data by implementing the get list of employees functionality — just make one small change to the BD — instead of calling it EmployeeDelegate, let’s call it EmployeeASDelegate, signifying that it’s returning hard-coded AS mock objects to your CMD; this will set us up to create different BDs for different data sets with SAS in the next couple tutorials. Notice the use of trace() statements as a primitive form of logging for this first iteration; again, we’ll add in real logging in a later tutorial. Your EVT, CMD, and BD should all look something like the following:

EmployeeEvent.as

package com.wasi.employeeconsole.events
{
	import com.adobe.cairngorm.control.CairngormEvent;

	public class EmployeeEvent extends CairngormEvent
	{
		/**
		 * The event type for getting all the employees.
		 */
		public static const GET_LIST:String = "getList";

		/**
		 * Constructor.
		 *
		 * @param type The event type for the event.
		 */
		public function EmployeeEvent(type:String)
		{
			super(type, false, false);
			trace("EmployeeEvent Constructor");
		}

	}
}

EmployeeCommand.as

package com.wasi.employeeconsole.commands
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.wasi.employeeconsole.business.delegates.EmployeeASDelegate;

	import mx.rpc.IResponder;

	public class GetEmployeeListCommand implements ICommand, IResponder
	{
		private var delegate:EmployeeASDelegate;

		public function GetEmployeeListCommand()
		{
			trace("GetEmployeeListCommand Consturctor");
			this.delegate = new EmployeeASDelegate(this);
		}

		public function execute(event:CairngormEvent):void
		{
			trace("GetEmployeeListCommand execute");
			this.delegate.getList();
		}

		public function result(data:Object):void
		{
			trace("GetEmployeeListCommand result");
		}

		public function fault(info:Object):void
		{
			trace("GetEmployeeListCommand fault");
		}

	}
}

EmployeeASDelegate.as

package com.wasi.employeeconsole.business.delegates
{
	import flash.utils.setTimeout;

	import mx.collections.ArrayCollection;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	/**
	 * A hard-coded delegate that creates mock objects and sends them back
	 * to the correspnding command as if it had actually called a real asynchronous
	 * service.
	 */
	public class EmployeeASDelegate
	{
		/**
		 * RPC Responder, used as a reference back to the command that made the request.
		 */
		private var responder:IResponder;

		/**
		 * Constructor.
		 */
		public function EmployeeASDelegate(responder:IResponder=null)
		{
			trace("EmployeeASDelegate Consturctor");
			this.responder = responder;
		}

		/**
		 * Get the list of employees.
		 */
		public function getList():void
		{
			trace("EmployeeASDelegate getList");

			// we'll fake an asynchronous service call with a slight delay
			setTimeout(result, 1000, new ResultEvent(ResultEvent.RESULT));
		}

		/**
		 * Handles the successful service request.
		 *
		 * @param response Object The success event coming back from the asynchronous
		 * service call containing the data payload.
		 */
		public function result(resultEvent:ResultEvent):void
		{
			trace("EmployeeASDelegate result");

			var response:ArrayCollection;

			response = new ArrayCollection();

			// pass the command the response object to do whatever it wants with it
			this.responder.result(response);
		}

		/**
		 * Handle the failed request. Pass it on
		 * to the command that originally requested it.
		 *
		 * @param faultEvent The fault event coming back from the asynchronous
		 * service call containing the error message, etc.
		 */
		public function fault(faultEvent:FaultEvent):void
		{
			trace("EmployeeASDelegate fault");

			this.responder.fault(faultEvent);
		}

	}
}

Don’t forget to add the EVT to CMD mapping in the FrontController (”FC”):

CairngormFrontController.as

/**
 * Map all the events to commands.
 */
protected function addCommands():void
{
	trace("CairngormFrontController addCommands");

	this.addCommand(EmployeeEvent.GET_LIST, GetEmployeeListCommand);
}

After creating the plumbing with our CG classes, let’s add in a click handler method for the “Refresh List” button called “getList()” and implement it by calling the CG EmployeeEvent:

EmployeeManagementConsole1.MXML

private function getList(event:MouseEvent):void
{
	trace("Application getList");

	new EmployeeEvent(EmployeeEvent.GET_LIST).dispatch();
}
...
<mx:Button label="Refresh List" click="getList(event)"/>

Flex Builder Console

Test the application in Debug Mode and you should see something like the following in the Flex Builder console:

[SWF] Users:brianmriley:projects:spring-hibernate:workspaces:flex3:EmployeeManagementConsole1:bin-debug:EmployeeManagementConsole1.swf - 1,073,390 bytes after decompression
CairngormFrontController Constructor
CairngormFrontController addCommands
Application getList
EmployeeEvent Constructor
GetEmployeeListCommand Constructor
EmployeeASDelegate Constructor
GetEmployeeListCommand execute
EmployeeASDelegate getList
EmployeeASDelegate result
GetEmployeeListCommand result

Now that we know our CG application flow hooked up, let’s add some data and populate our list of employees DG in the view. We’ll start by creating a simple client-side representation of an Employee object, sometimes referred to as a model, domain, business, or value object. Since we’ll ultimately map this Employee AS object to a Java object, we’ll place it in the client-side model package. Give it three public properties: id, firstName, lastName:

EmployeeModel.as

package com.wasi.employeeconsole.models
{
	public class EmployeeModel
	{
		public var id:int;
		public var firstName:String;
		public var lastName:String;
	}
}

EmployeeASDelegate#result(resultEvent:ResultEvent)

Next we’ll use this object to create a list of employees in our mock-object AS BD — open up EmployeeASDelegate and create an ArrayCollection (”AC”) of Employee objects in it’s result() method like so:

public function result(resultEvent:ResultEvent):void
{
	trace("EmployeeASDelegate result");

	var response:ArrayCollection;
	var employee:EmployeeModel;

	response = new ArrayCollection();

	employee = new EmployeeModel();
	employee.id = 0;
	employee.firstName = "Brian";
	employee.lastName = "Riley";
	response.addItem(employee);

	employee = new EmployeeModel();
	employee.id = 1;
	employee.firstName = "Tim";
	employee.lastName = "McGee";
	response.addItem(employee);

	employee = new EmployeeModel();
	employee.id = 2;
	employee.firstName = "Joe";
	employee.lastName = "Seiter";
	response.addItem(employee);

	// pass the command the response object to do whatever it wants with it
	this.responder.result(response);
}

GetEmployeeListCommand#result(data:Object)

Once our BD creates the data, it’ll pass it back to the CMD to actually set the data on the model, so we’ll need to make some modifications to the result() method in GetEmployeeListCommand:

public function result(data:Object):void
{
	trace("GetEmployeeListCommand result");

	var employeeList:ArrayCollection;

	employeeList = data as ArrayCollection;

	CairngormModelLocator.getInstance().employeeList = employeeList;
}

Bind Employee DG View to Model

Finally, let’s bind the DG to the list of employees in the model by means of MXML data binding:

<mx:DataGrid
	id="dgrid"
	dataProvider="{CairngormModelLocator.getInstance().employeeList}"
	width="100%" height="411"
	bottom="0" right="0">

	<mx:columns>
		<mx:DataGridColumn headerText="Employee ID" dataField="id"/>
		<mx:DataGridColumn headerText="First Name" dataField="firstName"/>
		<mx:DataGridColumn headerText="Last Name" dataField="lastName"/>
	</mx:columns>

</mx:DataGrid>

When you test your application, you should see something like:

Employee Mgmt Console Populated with AS Mock Objects

Employee Mgmt Console Populated with AS Mock Objects

At this point we have a basic Flex + CG app up and running…exciting, nah, not really. But we do have the bare-bones code base we’ll need to start having some real fun. Next, learn what SAS is and how to integrate it into this basic CG application.

Part 2: Flex + CG + SAS

References:

Post to Twitter Tweet This Post

, ,

7 Comments

Dealing with @Embed Tags, Ant Builds, and Paths to Resources

There’s plenty of evidence on the blogs, Adobe bugs, and elsewhere, that there are issues dealing with the compiler locating resources at compile time.

You ask yourself, where do I put my assets, my images, my CSS files?

Using one notation, Flex Builder will find the resources but switching to Ant causes all hell to break loose.

Here’s a simple and fairly elegant way to deal with it.

There are two things you need to know to understand what’s going on.

  1. The forward slash(/) operator is used to indicate the root. But what is root? The Flex compiler considers the ‘main source folder’ to be the root. Hence when you say ‘/’, you are actually referring to the ‘Main source folder’ (which you can set in Project>Properties>Flex Build Path>Main source folder), which in most cases would be set as the ’src’ folder.
  2. How to traverse a path. Pretty simple. If you do something like [Embed(source="/../assets/images/icon.jpg")] and src is your main source folder, the compiler will start at src, go up one level, find the assets folder and voila!

Post to Twitter Tweet This Post

, , , , , ,

No Comments

Flex vs. Ajax Revisited

This is a topic I’ve been delving into for some time (Flex or AJAX :: A Quick Litmus Test), as I’ve had the pleasure to implement production solutions with both Flex and Ajax; while I’m a diehard proponent of Flex, I gotta give Ajax some respect for bringing RIAs to the masses — that simple little acronym unknowingly brought me more RIA (again, both Flex / Flash and Ajax) work than my team can even handle!

…and so it seems it’s time for another round of the Flex vs. Ajax debate, with Forrester taking a stab this time: Ajax Or Flex?: How To Select RIA Technologies. Or, you can read Ryan Stewart’s and / or Yakov Fain’s quick summary of it…and if you’re too lazy to click to those, you can take away this extremely short version of it all: Flex is one, robust library / framework backed by Adobe, whereas Ajax usually includes choosing a framework (usually a tedious, in-depth process within itself…trust me…dojo still does it for me though, as it proves to offer the most extensive library at least backed by some of the major players) and a development tool-set backed by many or no one of consequence — I nabbed from Ryan’s summary of the report because it also hit home with me:

Choosing a commercial Ajax solution means adopting a proprietary framework and development tools. In this light, commercial Ajax vendors look more like Adobe than like open source Ajax tool kits.

I’m also still a fan of pushing the Flash Platform over Ajax for the following reasons:

Unified Cross Browser / Platform User Experience:

  • One virtual machine means one rendering engine means one code base and one set of coding standards.
  • Ajax / DHTML applications are subject to each browser’s implementation of the DOM and often require developers to provide workarounds for each variation thereof; this inherently creates additional, unnecessary code and ultimately adds to the development timeline. Large Ajax applications with rich user experience = large development effort.
  • While many Ajax / DHTML toolkits exist to facilitate this shortcoming by abstracting browser inconsistencies, they’re often extremely large in file size, immature, lack standards and documentation and ultimately fall short of a complete solution.

What’s Your Application Platform?

  • The Flash Platform provides a true application platform as a virtual machine that’s browser / platform independent, including a JIT compiler and strong typing.
  • The very intention for the Flash Player was to provide a container to perform operations like rendering complex animations and filter thousands of data sets at the same time, thus providing a desktop-like experience with comparable performance on the internet.
  • AJAX applications leverage the browser as the application platform, which is something it was never intended to be used for. The browser is nothing more than a text-based rendering engine, and was never conceived as a container for complex, client-side applications.
  • The performance implications of running a complex Ajax application are subject to the browser’s ability to interpret JavaScript and determine the type at runtime is it a string, a number, an object? whereas ActionScript 3 (AS3) eliminates type look-up because its strongly typed and compiled into bytecode rendered by the Flash Player VM this facilitates better responsiveness in your application.

Development Models

  • The Flex workflow and programming model follow a more traditional approach familiar to application developers. Flex applications are implemented using a combination of declarative tags (MXML) for the user interface / presentation and a scripting language (ActionScript) for complex business / application logic.
    • MXML is an XML based, declarative language that’s similar to HTML and is used for layout.
    • ActionScript is a strongly typed, classed based OO language analogous to Java, but with the flexibility of a scripting language.
  • While the MXML and AS aren’t native to most traditional app developers, the development paradigm is a similar model to that of JSP and Java development, making it an easy transition for seasoned developers.
  • Flex Builder offers a professional IDE based on Eclipse, with the usual myriad of tools an application developer expects.
    • Debugging is built on top of the Eclipse Debugging Framework and provides common tools like setting breakpoints and watching variables
  • While Ajax is the mesh of several, common client-side technologies, overcoming the browser compatibility issues often requires expert knowledge of each browsers interpretation of the DOM, and usually leads to hack-like workarounds. Even if you’re using an Ajax / DHTML toolkit, you’re still subject to the pains of cross browser issues.
  • Ajax often entangles both HTML and JavaScript to create rich user interfaces where the end result is a tightly coupled client application that’s often difficult to maintain and extend.

So then there’s the final question of openness…Ajax (and it’s encompassing technologies are all open)..what about Flex? This was a question that stumped me for some time…I used to just say, open, what are going to do with it even if the Flash Player is open? Are you going to create your own version of the FP so it branches like Java did years back, cuz yeah, that worked…and then I realized I needed to be a bit more practical with my response and read this: How truly open is Flash? Do we need “Open Flash”?

At the end of the day, I’m still going to arm myself with Flex as the weapon of choice in the RIA war. Perhaps the release of Apollo and other desktop-like browser apps will be the tell-tale.

Post to Twitter Tweet This Post

, ,

1 Comment