Archive for the 'flex' Category

09
Sep
08

When to use Security.loadPolicyFile(url:String) in your Flex app

Often is the case where you’ll need to test your application on multiple boxes and for multiple clients, so you can’t just assume the crossdomain.xml file exists at the root of the domain or even in the same location…this forces you to pass in the crossdomain file’s location at run-time and then load it into the Flash Player before you make your first request for data / et al, and so I often wondered when the best time was to do this to ensure the file was loaded and thus eliminate any possible race conditions.

After searching around on the Flex 3 docs, I read that the best place for this call was in the root Application class’s preinitialize event handler — oddly enough I found this tidbit in the “Loading modules from different servers” section of the docs, but I also ran into this very race condition just recently in a web services based application as well.

Advertisements
03
Apr
08

Flex Panel’s Not Scrolling When Expected Fix

I wouldn’t call this a fix, as this is more of a misunderstanding of the Panel component in Flex…simple yes, but it took myself and a coworker a couple minutes to figure it out.
We had a Panel component that sat inside a Container whose height was < the Panel’s height, and we expected the content’s of the Panel to scroll; unfortunately, the entire Panel scrolled so we sat down and created a small example to see how we could get around this.
Check out the following code — in the first Panel, we were hoping the contents (for example purposes TextInputs) would scroll, but instead the entire Panel scrolled. In the second example, we changed the layout property to a value of “absolute,” and this gave us the desired results — the content’s of the Panel scrolled. Note the use of a Box Container around the TextInputs — without this the TextInputs sat on top of each other since we’re telling the Panel to use a Canvas instead of a VBox to house it’s contents.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
	xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="absolute">

	<mx:VBox width="100%" height="100%">

		<mx:Box width="100%" height="100">

			<mx:Panel
				width="100%" height="100%"
				title="Bad :: Unexpected Scrolling">

				<!--
					This Box is unnecessary since there's a VBox in
					a Panel by default, but it's here for consistency
					since it's necessary to get the second Panel to
					scroll as expected.
				-->
				<mx:Box>
					<mx:TextInput />
					<mx:TextInput />
					<mx:TextInput />
					<mx:TextInput />
					<mx:TextInput />
					<mx:TextInput />
				</mx:Box>

			</mx:Panel>

		</mx:Box>

		<mx:Box width="100%" height="100">

			<!--
				This Box is unnecessary since there's a VBox in
				a Panel by default, but since we've specifed
				the layout as absolute, it's a Canvas
			-->
			<mx:Panel
				width="100%" height="100%"
				title="Good :: Expected Scrolling"
				layout="absolute">

				<mx:Box>
					<mx:TextInput />
					<mx:TextInput />
					<mx:TextInput />
					<mx:TextInput />
					<mx:TextInput />
					<mx:TextInput />
				</mx:Box>

			</mx:Panel>

		</mx:Box>

	</mx:VBox>

</mx:Application>
28
Mar
08

ThunderBolt :: Firefox Debugging Tool for Flex / AS3 / AS2

I usually use the built-in debugger in Flex Builder accompanied with FlashTracer (when I’m not running in debug mode and/or in prod depending on some query string params I toss in) to debug my Flex applications, but my buddy John pointed me to this new plugin for Firebug for FireFox called ThunderBolt; it provides the usual trace statements like FlashTracer with some additional features like a tree for complex objects and a memory snapshot. I don’t want to repeat what the site already says about it, so I’m just going to provide a link to get you there.
Since I’m on the topic of debugging I thought I’d also add in my other handy weapon of choice: ServiceCapture. It’s a simple HTTP proxy that catches all your data going across the wire (from flex to your server and back); the really cool part is that allows you to inspect your request and response objects of any of the following types: plan text, xml, web services, and AMF (the binary protocol used to perform Flash Remoting or Java-RPC in Flex).
I’m curious to hear people’s thoughts on this, so what are you using?
14
Mar
08

Remove Annoying XML Namespaces in Flex/AS3

My buddy pointed out another approach that I show here — it’s easier and doesn’t actually remove the namespace.
XML namespaces can be a real pain in the a$$ in AS3, so I often just rip them out. I mean think about it…when you get some XML payload back in a web service response, do you really care or need the namespace? Nah….just rip that bad boy out and starting using your XML baby.
Here’s my quick and dirty AS3 XML Namespace Ripper — for the sake of argument and a quick example, just assume this is in a Responder object like a Caringorm business delegate, but it should probably exist in a static XML util:
public function result(response:Object):void
{
var xmlString:String;
var xmlnsPattern:RegExp;
var namespaceRemovedXML:String;
var responseXML:XML;

// get the XML payload
if(ResultEvent(response).result is XMLList)
{
response = ResultEvent(response).result as XMLList;
}
else
{
response = ResultEvent(response).result as XML;
}

// convert it to a string
xmlString = response.toXMLString();

// define the regex pattern to remove the namespaces from the string
xmlnsPattern = new RegExp("xmlns[^\"]*\"[^\"]*\"", "gi");

// remove the namespaces from the string representation of the XML
namespaceRemovedXML = xmlString.replace(xmlnsPattern, "");

// set the string rep. of the XML back to real XML
responseXML = new XML(namespaceRemovedXML);

// do something with the XML
}
Thanks for the quick refresher on regex Johnny!
04
Oct
07

Flex / AS3 Reserved Word “to” in Packages

I tend to reserve TOs (Transfer Objects) as the objects I pass back and forth over the wire between Flex and Java and use VOs (Value Objects) as encapsulated data that I pass around my client (only), usually after collecting data from a view and passing it to a CairngormEvent, so I would like to create a package structure that looks like:
com.domain.project.to
and
com.domain.project.vo
respectively…but I can’t.
Unfortunately, the “to” in the package name is a reserved word in AS and throws an error when you try and compile classes with this namespace. My buddy Jon Marston encountered this on our last Flex project, and I forgot all about it until I went to implement it on my current proj…just some advice for anyone else that runs into this issue. I renamed the package to:
com.domain.project.transfer
14
Aug
07

Flex Code-Behind Data Binding :: Part 1

I’m a little nutty when it comes to writing my view classes in Flex; I use MXML exclusively for layout and presentation, and code all the application and business logic in ActionScript…so you might be thinking, big deal, don’t you have to do that…well no…not really…in your MXML views you can set event handlers and data binging directly in the MXML, but I hate that, so I follow the code-behind technique pretty religiously, but with my own added twists here and there. And sure, it creates an extra abstraction layer, and the agile or ruby-type-simplistic-coders might say that’s overkill, but since most of my projects are quite large, I feel like the additional layer creates cleaner views that are ultimately easier to debug and unit test because of this decoupling.
That being said, I ran into a binding issue due to the chaining mechanism automatically done for you by binding in MXML. Let’s look at a very quick example — I’ll post a Part 2 that ties this into an actual application using Cairngorm soon.
Imagine that you have first and last name label components in a MXML view called EmployeeView.mxml and you want to bind those to a EmployeeModel in your ModelLocator; for the purpose of this example the view will also contain a button that makes a server call for the employee object, which is ultimately set to the EmployeeModel on a successful request — it might look something like this:
NOTE: This is all psuedo-code and has not been tested. Again, I’ll put up a more detailed version of this in a second post.
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas
    xmlns:mx="http://www.adobe.com/2006/mxml"
    width="400" height="300">

    <mx:Script>
        <![CDATA[
        import com.brianmriley.sandbox.codebehind.model.MyModelLocator;

        private function getEmployeeButtonClickHandler(event:MouseEvent):void
	{
	    // assume we're using Cairngorm and dispatching a GetEmployeeEvent
	    // that's mapped to GetEmployeeCommand that uses GetEmployeeDelegate to
	    // request the employee XML with an HTTPService and then returns
	    // the successful response to GetEmployeeCommand, which does something
	    // like the following in it's public result(data:Object) method:
	    // MyModelLocator.getInstance().employeeModel = EmployeeModel(data);
	    //
	    // ...and theoretically the first and last name labels are then populated
	}
	]]>
    </mx:Script>

    <mx:VBox>
	<mx:Label
            id="firstNameLabel"
            text="{MyModelLocator.getInstance().employeeModel.firstName}" />
	<mx:Label
            id="lastNameLabel"
            text="{MyModelLocator.getInstance().employeeModel.lastName}" />
        <mx:Button
            id="getEmployeeButton"
            text="Get Employee" click="getEmployeeButtonClickHandler(event)" />
    </mx:VBox>

</mx:Canvas>
Now let’s change this to use code-behind. First I create a base AS component for EmployeeView.mxml and call it EmployeeComponent.as — I typically make a base, abstract-like AS class for some of this functionality too:
package
{
	import flash.events.MouseEvent;

	import mx.binding.utils.BindingUtils;
	import mx.containers.Canvas;
	import mx.controls.Button;
	import mx.controls.Label;
	import mx.events.FlexEvent;

	public class EmployeeComponent extends Canvas
	{
		public var firstNameLabel:Label
		public var lastNameLabel:Label
		public var getEmployeeButton:Button;

		public function EmployeeComponent()
		{
			super();

			this.addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
		}

		protected function init():void
		{
			this.setMXMLViewEventHandlers();
			this.setMXMLViewBindings();
		}

		protected function setMXMLViewEventHandlers():void
		{
			this.getEmployeeButton.addEventListener(MouseEvent.CLICK, creationCompleteHandler);
		}

		protected function setMXMLViewBindings():void
		{
			BindingUtils.bindProperty(this.firstNameLabel, "text", MyModelLocator.getInstance().employeeModel, "firstName");
			BindingUtils.bindProperty(this.lastNameLabel, "text", MyModelLocator.getInstance().employeeModel, "lastName");
		}

		private function getEmployeeButtonClickHandler(event:MouseEvent):void
		{
			// assume we're using cairngorm and dispatching a GetEmployeeEvent
			// that's mapped to GetEmployeeCommand that uses GetEmployeeDelegate to
			// request the employee XML with an HTTPService and then returns
			// the succesful response to GetEmployeeCommand, which does something
			// like the following in it's public result(data:Object) method:
			// MyModelLocator.getInstance().employeeModel = EmployeeModel(data);
			//
			// ...and theoretically the first and last name labels are then populated
		}

		private function creationCompleteHandler(event:FlexEvent):void
		{
			this.init();
		}
	}
}
And change the EmployeeView.mxml to the following:
<?xml version="1.0" encoding="utf-8"?>
<local:EmployeeComponent
	xmlns:mx="http://www.adobe.com/2006/mxml"
	xmlns:local="*"
	width="400" height="300">

	<mx:VBox>
		<mx:Label id="firstNameLabel" />
		<mx:Label id="lastNameLabel" />
		<mx:Button id="getEmployeeButton" text="Get Employee" />
	</mx:VBox>

</local:EmployeeComponent>
But if you run this, the data binding will not fire because we’re binding directly to the firstName and lastName properties in the EmployeeModel, and we’re updating the entire EmployeeModel (in the command). This does not happen when you bind directly in the MXML because it notation forces the binding to chain up the object, so it will detect the change on the entire employeeModel in the ModelLocator and fire the binding for it’s properties. To get around this in the code-behind technique, one must change the following line from:
BindingUtils.bindProperty(this.firstNameLabel, "text", MyModelLocator.getInstance().employeeModel, "firstName");
BindingUtils.bindProperty(this.firstNameLabel, "text", MyModelLocator.getInstance(), ["employeeModel", "firstName"]);
This does enforce the binding to chain (like in the MXML version) by saying, first look at the employeeModel, and if it changes, then fire the binding for it’s property firstName.
Another approach to this is the following:
var employeeModelChangeWatcher:ChangeWatcher = ChangeWatcher.watch(MyModelLocator.getInstance(), "employeeModel", employeeModelChangeWatcherHandler);

private function employeeModelChangeWatcherHandler(event:Event):void
{
	this.firstNameLabel.text = MyModelLocator.getInstance().employeeModel.firstName;
}
And while it is indeed more code, it may allow you to do more than just bind the property — you might want to run some other related functions when the properties of the employeeModel changes…
10
Jan
07

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, iin-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 toolset 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 with it’s 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.
Followed by, 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 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 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.
And the 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? …and then I saw 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.