August 3, 2010

Fixing the horizontal scroll for the Flex Text Highlighter Class

Recently I happened to have to implement a textarea to highlight the research done inside a textarea. For this I found an excellent library that was just in my case: Flex Text Highlighter Class.
But if you turn wordwrap on the textarea and horizontal scroll appears that the library was unable to move to different results.
Then download this example you will find the library clean by this bug.

Demo --- Source

July 12, 2010

Adobe Alchemy: a comparative example

In my last post I introduced the Alchemy Project and I explained how to install/set up the Alchemy environment on a Window machine to compile a very simple "c" file in a swc.
Today I'll go deeper and talk about Alchemy through a comparative example: Alchemy aimes to allow users to take advantage of efficient C/C++ (existing or not) designed to accomplish very cpu-intensive tasks. The performance improvements of flex applications can be very significant e I'll try to give you a sample, with a simple test: I've implemented an inefficient and decidedly didactic ordering algorithm, the BubbleSort, either in Actionscript and in C/Alchemy. Then I've tested both implementation to order an actionscript reverse ordered array of integers with 20,000 elements(the worst case for the bubblesort algorithms).

Here is the Actionscript implementation:

public function bubbleSort(array:Array):void
{
	var temp:int = 0;
	var alto:int = array.length;
	while(alto > 0)
	{
		for(var i:int = 0; i<alto; i++)
		{
			if(array[i] > array[i+1])
			{
				temp = array[i];
				array[i] = array[i+1];
				array[i+1] = temp;
			}
		}
		alto--;
	} 
}

and here I show you the C implementation

void BubbleSort(int *array, int array_size)
{
   
  int i, tmp;
  int bound = array_size; 
 
  while (bound > 1)
  {
	for (i=0; i<bound-1; i++)
    {
        if (array[i] > array[i+1]) 
        { 
			tmp = array[i]; 
            array[i] = array[i+1]; 
            array[i+1] = tmp;
        } 
    }
    bound--; 
  }
}

Unfortunately I couldn't use the C implementation as it is. I needed to write some more code using Alchemy actionscript/C Api to realize the translation of the Actionscript array to the C integer array data structure:

#include <stdlib.h>
#include <stdio.h>
 
//Header file for AS3 interop APIs
//this is linked in by the compiler (when using flaccon)
#include "AS3.h"
 
//INSERT HERE THE C IMPLEMENTATION OF THE BUBBLESORT ALGORITHM
 
static AS3_Val orderArray(void* self, AS3_Val args)
{
	//Creating a C representation of the Actionscript Array object
	AS3_Val actionscript_array = NULL;
	AS3_ArrayValue( args, "AS3ValType", &actionscript_array );
	 
	/*
	 *         Translation process from Actionscript to C in 4 steps:
	 */
	//STEP 1 : calculating the dimension of the Actionscript array
	AS3_Val actionscript_array_size =  AS3_GetS(actionscript_array, "length");
	int array_size = AS3_IntValue(actionscript_array_size);
 	
	//STEP 2: declaring the C array to use with BubbleSort
	int array_c[array_size];
 	
	//STEP 3 : ActionScript function pop() of Array Class
	AS3_Val pop_function = AS3_GetS(actionscript_array, "pop");
	AS3_Val emptyParams = AS3_Array("");
 	
	//STEP 4(iterative): Extracting the actionscript integer values from the actionscript array
	//and storing them into the c array
	int i = 0;
	for(i = array_size-1; i >= 0 ; i--)
	{
		AS3_Val temp_actionscript_Int = AS3_Call(pop_function, actionscript_array, emptyParams);
		int tmp = AS3_IntValue(temp_actionscript_Int);
		array_c[i] = tmp;
		AS3_Release(temp_actionscript_Int);
	}
	AS3_Release(pop_function);
	/*
	 *   END of Translation process from actionscript to C
	 */
 	
	/*
	 *      Ordering operations: invoking the Bubble Sort on the c array of integers
	 */
	BubbleSort(array_c, array_size);
 	
	/*
	 *         Translation process from C to actionscript:
	 */
 	 
	//ActionScript function push() of Array Class
	AS3_Val push_function = AS3_GetS(actionscript_array, "push");
 	
	//Storing the ordered integer values into a new actionscript array object
	int j;
	for( j = 0; j < array_size ; j++)
	{
		AS3_Val int_to_push = AS3_Array("IntType", array_c[j]);
		AS3_Call(push_function, actionscript_array, int_to_push );
		AS3_Release(int_to_push);
	}
	AS3_Release(push_function);
 	
	return actionscript_array;
	/*
	 *   END of Translation process from C  to actionscript
	 */
}
 
//entry point for code
int main()
{
	//define the methods exposed to ActionScript
	//typed as an ActionScript Function instance
	AS3_Val orderArrayMethod = AS3_Function( NULL, orderArray );
 
	// construct an object that holds references to the functions
	AS3_Val result = AS3_Object( "orderArray: AS3ValType", orderArrayMethod );
 
	// Release
	AS3_Release( orderArrayMethod );
 
	// notify that we initialized -- THIS DOES NOT RETURN!
	AS3_LibInit( result );
 
	// should never get here!
	return 0;
}

As a consequence, when analyzing the test results, we have to consider the extra work the C/Alchemy implementation of the algorithm did to realize the ordering task.

To compile the previous code follow the instruction I showed in this post
to obtain a file .swc you can use in a flex test application as I did in may test example.

Here the code of my flex test application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" creationComplete="init();">
	
	<mx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			
			import cmodule.bubblesort.CLibInit;			
			
			private var startDate:Date;
			private var stopDate:Date;
			
			private function init():void
			{
				
				this.addEventListener("actionscriptSortComplete",handler);
				this.addEventListener("cSortComplete",handler);
				var intArray:Array = new Array();
				var intArray2:Array = new Array();
				for(var i:int = 20000; i > 0; i--)
				{
					intArray.push(i);
					intArray2.push(i);
				}
				list.dataProvider = intArray;
				list2.dataProvider = intArray2;
			}
			
			
			//INSERT HERE THE CODE OF THE ACTIONSCRIPT IMPLEMENTATION OF BUBBLESORT ALGORTHM
			
			public function orderArray(event:Event):void
			{
				startDate = new Date;
				
				if(event.target.id == "actionscriptOrderingButton" )
				{
					var source1:Array = (list.dataProvider as ArrayCollection).source;
					bubbleSort(source1);
					this.dispatchEvent(new Event("actionscriptSortComplete"));
				}
				else
				{
					var loader:CLibInit = new CLibInit();
					var lib:Object = loader.init();
					var source2:Array = (list2.dataProvider as ArrayCollection).source;
					list2.dataProvider = lib.orderArray(source2);
					this.dispatchEvent(new Event("cSortComplete"));
				}
				
				
			}
			
			public function handler(event:Event):void
			{
				stopDate = new Date();
				var diff:Number = stopDate.getTime() - startDate.getTime();
				if(event.type == "actionscriptSortComplete")
				{
					timeLabel.text = "time elapsed : "+diff/1000+" sec!";
					(list.dataProvider as ArrayCollection).refresh();
				}
				else
				{
					timeLabel2.text = "time elapsed :"+diff/1000+"sec!";
					(list2.dataProvider as ArrayCollection).refresh();
				}
				
			}
			
		]]>
	</mx:Script>
	
	<mx:List id="list" width="30%"  />
	<mx:VBox>
		<mx:Button id="actionscriptOrderingButton" label="Actionscript BubbleSort" click="orderArray(event);"  />
		<mx:Label id="timeLabel" text="..." />
	</mx:VBox>
	<mx:List id="list2" width="30%"/>
	<mx:VBox>
		<mx:Button id="cOrderingButton" label="C BubbleSort" click="orderArray(event);"  />
		<mx:Label id="timeLabel2" text="..." />
	</mx:VBox>
	<mx:Label id="lb2" text="" />
	
	
</mx:Application>

And here are some screenshots of the results obtained by the test application:
test-actionscriptbubblesort.PNG

test-cbubblesort.PNG

To order an array of 20,000 integers in the worst case:
- the actionscript algorithm spent : 32.031 sec
- the Alchemy/C algorithm spent : 7 sec
Using the Alchemy/C implementation of bubblesort I got an improvement in speed of about 75%.
This is certainly an encouraging result and an evidence that Alchemy can be exploited by developers to improve performance of the most intensive task executed by their flex application.

July 8, 2010

Managing Java Http sessions in GAE applications

When a J2EE developer starts the design of a Google App Engine application he has to face some problems and adapts some of the well-established design patterns in web application development. Let's start with a bit of introduction to explain what is a Google App Engine application.

What is Google App Engine

Citing the corresponding google page: "Google App Engine lets you run your web applications on Google's infrastructure. App Engine applications are easy to build, easy to maintain, and easy to scale as your traffic and data storage needs grow. With App Engine, there are no servers to maintain: You just upload your application, and it's ready to serve your users."
Basically Google App Engine is a service that lets you put your application "in the cloud", a cloud completely managed by Google, so you don't have to worry about the scalability or reliability of your application. Every request made to a page of your application will be managed by one of the server in this infrastructure, but no one can guarantee that the next request will be assigned to that machine as well.

How the http session is managed

Session handling must be explicitly enabled by adding to your app engine configuration file true and then you will be able to access the session from within RPC services with:
this.getThreadLocalRequest().getSession();

When you enable it, you will find serialized sessions among your datastore entities as _ah_SESSION, this is due to the fact that "the cloud" will read and write sessions from and to the datastore, and not from and to memory as the J2EE specification states (excluding an application deployed on a cluster).
Every time the HttpSession setAttribute method is invoked, the related datastore entity is updated and every subsequent invocation to the related getAttribute method will return the same object, as you would expect from a standard web application. The problem is when your services manipulate objects stored in the session, in that case your changes will be lost when another service will get the object from the session. A very simple sample:

Service A

Person p = new Person();
p.setName("Jack");
session.setAttribute("person", p);

Service B

Person p = (Person) session.getAttribute("person");
System.out.println(p.getName()); // prints "Jack"
p.setName("Andy");

Service A again

Person p = (Person) session.getAttribute("person");
System.out.println(p.getName()); // prints "Jack" in GAE, 
// prints "Andy" in a standard J2EE evironment

If you want a consistent behaviour you need to invoke setAttribute again after having modified the Person object in the session. This workaround will solve all the inconsistencies but has a pretty important trade-off, every setAttribute will trigger a new serialization and write to the datastore; ok, you are in the Google cloud, but the free resources are limited.

Alternatives to the http session

There are a lot of alternative implementantion of session utilities if you use Python: http://wiki.github.com/dound/gae-sessions/ (it also has a comparison table with other libraries). For Java developers the only alternative is to use the Memcache service and/or the DataStore service. While the former has the problem of the data expiration strategy: http://code.google.com/appengine/docs/java/memcache/overview.html#How_Cached_Data_Expires, the latter will suffer of the same performance problems of the GAE session implementation.


July 3, 2010

Flex Webservice: how to list available parameters for each operation

In a previous post I explained how to list available operations provided by a WebService, parsing the WSDL document using some undocumented classes of the Flex 3 and 4 SDKs.
This time I want to give you some suggestions about the next step: listing parameters of every operation.
NB: most of the classes in the package mx.rpc.wsdl have the tag [ExcludeClass] so they could change with an SDK update or they can be not stable. Flex Builder intellisense will not work for these classes, so you have to import them manually.
Note that I'm testing this code using a WSDL from a Axis2 WebService, it may not work on WSDL with a different structure or it may need some tweaks.

<mx:Script>
	<![CDATA[
		import mx.rpc.soap.LoadEvent;
		import mx.rpc.wsdl.WSDLMessagePart;
		import mx.rpc.wsdl.WSDLOperation;
		import mx.rpc.xml.Schema;
		protected function loadHandler(event:LoadEvent):void
		{
			if(event.wsdl) {
				for each(var op:WSDLOperation in event.wsdl.getPort().binding.portType.operations()) {
					var param:WSDLMessagePart = op.inputMessage.getPart("parameters");
					if(param) {
						var schema:Schema = event.wsdl.schemaManager.getResourcesForURI(param.element.uri)[0] as Schema;
						var element:Object = schema.getNamedDefinition(new QName(schema.schemaConstants.xsdURI,param.element.localName),schema.schemaConstants.elementTypeQName);
						trace(element.definition, element.schema);
					} 
				}
			}
		}
	]]>
</mx:Script>

This small script, based on the code of the previous post, analyze the inputMessage of the WSDLOperation. If there is a WSDLMessagePart with name "parameters", it looks for the related Schema and then it searches the definition of the element of the WSDLMessagePart. This definition is just the XML of the complexType of the parameter, then you have to write your custom logic to use it. Some WSDL may non have the "part" node, instead there is the name of the element, you have to slightly modify the code above.

This is just a sketch and not a ready-to-use solution but it can point you in the right direction.

June 24, 2010

Security Data Trasfer - AS3 Encrypting Libraries and Http Monitor Softwares

One of the most important problem in Application development is the Security of Data Transfer from\to Client to\from Server. The Flash Player environment has a lot of security rules and controls to safeguard data in the Web, but sometimes it's not enough, so we have to integrate them with Encrypting Algorithms develops in our ActionScript Classes. Now we are going to see a little overview that allows us a knowledge of the most simple and useful AS library for encrypting data.

The first library is the as3crypto library. This is available in the Google Code at this address . As you can see on the documentation, the library provides a lot of Hashing Algorithms, like MD5 and SHA-256, Public Key Encryption Algorithms , like RSA, and Secret Key Encryption Algorithms, and introduces a SSL engine. I suggest to see the demo with all the functionalities of the as3crypto library. Another Encrypting Library is as3corelib. Like the as3crypto, the as3corelib is published on Goggle Code at the address, here is the source code of the library and the documentation, but there isn't a demo about it. as3corelib also does not have Encryption Algorithms but only Hashing Algorithms.

Sometimes it is useful to measure the Security of our applications, so we can use these free products to see the data transfer between Client and Server : SWFScan by HP and Charles. SWFScan automatically find security vulnerabilities in applications built on the Flash Platform. It decompiles applications built on the Flash Platform to extract the ActionScript code and statically analyzes it to identify security issues such as information disclosure; identifies and reports insecure programming and deployment practices; and suggests solutions. You can download it from this site.
HP SWFScan offers several other features to help developers, code auditor/reviewers, and pen-testers examine the contents of Flash applications, including:


  • Highlighting the line of source code that contains the vulnerability to help better understand the context of the issue.

  • Providing summaries, details, and remediation advice for each vulnerability in accordance with Adobe's recommendation for secure Flash development.

  • Generating a vulnerability report to share and solve the detected issues.

  • Exporting the decompiled source code for use with other external tools.

  • Revealing all the URLs and web services the Flash Application contacts.

  • Flagging class names, function names, or variable names that may be of interest such as
    loadedUserXml or crypt().

Charles is an Http Proxy and an HTTP Monitor, it is enable to see all the data transfer in a browser web or between a client and a server, it is also ables to monitor the AMF protocol traffic. You can have more information here . I think it's a very useful tool for the visualization of Data Trasfer between client and Server and it takes a great support for evidence the bugs in security in our SWF Applications. Next time i will deepen all the functionalities of this Software.

Regards

June 11, 2010

UiBinder : a simple way to build Widget from XML markup

UiBinder helps developers to build GWT widgets in a few simple steps, exploiting the flexibility and maintainability of XML. This allows developer without a strong background in java to be competitive in the GWT code production.

Thus we see UiBinder in action : first of all we must create a web application that use Google Web Toolkit. To do this, I use the eclipse's plugin for GWT, so from the prompt do :
File --> New --> Other --> Google --> Web application project. Then fill the required fields, uncheck the "Use Google app engine" option and click "Finish".

Now we realize the following html page containing a simple widget :

simplewidget.png

Initially we have to modify the home page, an HTML page, in which we create a "div" element that permit us to inject content from a Java class, the entryPoint :


<!doctype html>

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<link type="text/css" rel="stylesheet" href="PostBlogUiBinder.css">

<title>Simple widget project</title>

<script type="text/javascript" language="javascript" src="postbloguibinder/postbloguibinder.nocache.js"></script>
</head>

<body>

<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>

<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
</div>
</noscript>

<h1>Sample Widget</h1>

<h3 align="center">Fill the following fields</h3>

<div id="simpleWidget" align="center"></div>

</body>
</html>


as you can see we have create a div element with id called "simpleWidget" that we refer from the entrypoint java class.

Now we have to inject into this page the widget that we want to create. We do this into the entrypoint class, called SimpleWidgetEntrypoint :



import com.post.uibinder.ui.SimpleWidget;
import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.user.client.ui.RootPanel;


/**
* Entry point classes define onModuleLoad().
*/
public class SimpleWidgetEntrypoint implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
SimpleWidget simpleWidget = new SimpleWidget();
RootPanel.get("simpleWidget").add(simpleWidget);
}
}

Now we have to create our widget, we can do this with the wizard plugin doing the following actions :

from the eclipse's prompt do File --> New --> Other --> Google Web Toolkit --> UiBinder --> Next

then digit the name of the java class of the widget, in our case "SimpleWidget" and then click Finish.

We can see now that the wizard has created two files :

- SimpleWidget.java
- SimpleWidget.ui.xml

To obtain our result widget we have to modify both files :

- SimpleWidget.ui.xml


<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<ui:style>
.important {
font-weight: bold;
}
</ui:style>
<g:HTMLPanel ui:field="mainPanel">
<g:VerticalPanel>
<g:Label ui:field="descriptionLabel" ui:text="Put a description of yourself"></g:Label>
<g:TextArea ui:field="textArea" ui:text="Put here your description"></g:TextArea>
<g:Label ui:field="banLabel" ui:text="Select which band you prefer among these"></g:Label>
<g:RadioButton ui:name="band" ui:text="U2" ></g:RadioButton>
<g:RadioButton ui:name="band" ui:text="Radiohead"></g:RadioButton>
<g:RadioButton ui:name="band" ui:text="Pearl Jam"></g:RadioButton>
<g:RadioButton ui:name="band" ui:text="Depeche mode"></g:RadioButton>
</g:VerticalPanel>
<g:Button styleName="{style.important}" ui:field="button" ui:text="Confirm" />
</g:HTMLPanel>
</ui:UiBinder>


- SimpleWidget.java


import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

public class SimpleWidget extends Composite {

private static SimpleWidgetUiBinder uiBinder = GWT
.create(SimpleWidgetUiBinder.class);

interface SimpleWidgetUiBinder extends UiBinder {
}

@UiField
Button button;
@UiField
TextArea textArea;

public SimpleWidget() {
initWidget(uiBinder.createAndBindUi(this));
textArea.setSize("300px", "200px");
}

@UiHandler("button")
void onClick(ClickEvent e) {
Window.alert("OK");
}

}

To build the widget we need the following GWT elements :

- VerticalPanel
- Label
- RadioButton
- Button
- TextArea

if we don't use the UiBinder utilities we have to write the entire widget only with java code, but this time into the SimpleWidget java class we have only specified the size of the text area, all the other elements with their values are specified into the XML file.
This is why UiBinder simplifies the construction of GWT widget and simplifies also the collaboration between UI designers, which are more confortable with markup languages, and developers.

June 7, 2010

Binding improvement

Since Flex 2, the Adobe Flex sdk's contain a class named BindingManager, unfortunately it's not documented in the released ASDoc, but this class it's really helpful to us to manage and debug all kind of binding inside our applications.


BindingManager.debugBinding:
Using the static method provided by the manager you will enable the debug for the property passed as parameter for the method like this:

BindingManager.debugBinding( "myComponent.propertyToDebug" )

Now when you lunch your application in debug mode, you can see in the console something like this:
Binding: destString = myComponent.prpertyToDebug, srcFunc result = First value
Binding: destString = myComponent.prpertyToDebug, error = TypeError: Error #1009: Cannot access a property or method of a null object reference.
Binding: destString = myComponent.propertyToDebug, srcFunc result = Changed value

BindingManager.setEnabled:
Another very handy method can be the setEnabled. By using this static method you will enable or disable all bindings for a specified component or document:

BindingManager.setEnabled( yourComponent, true );


Discover all bindinded properties of a component:
From Flex 2 all documents property of the displayObject components have a non-null public _bindingsByDestination variable, containing the binding instances currently executed for the specified component.
So if you iterate inside the document._bindingsByDestination by String you will access to the "myComponent.bindedProperty":


use namespace mx_internal;

for (var binding:String in myComponent.document._bindingsByDestination)
{
trace( binding );

//And to access the to the binding instance use this:
var myBinding:Binding = myComponent.document._bindingsByDestination[ binding ];
}

This can be accessible only if you specify the use namespace mx_internal.

May 31, 2010

Swiz framework - Custom Metadata Processor

In my last post I briefly introduced Swiz framework and uncovered part of its great potential. This post will be about Swiz's custom metadata processor, a powerful tool available with the 1.0 release. The metadata processors were available in previous versions also, but now their API is open and allows developers to create their own ActionScript metadata and handle them rather easily.

As an example shows on their site, one has to choose a new metadata name and extend org.swizframework.processors.BaseMetadataProcessor (this class was called MetadataProcessor in the alpha release). In the example, a Random metadata was created, that assigns a random numeric value to any variable it decorates:


[Random]
public var randomNumber:Number;

Such custom metadata are is extremely easy to use: once the processor class is created, it can simply be added to Swiz's custom processors:


<swiz:customProcessors>
<processors:RandomProcessor />
</swiz:customProcessors>

Obviously one should remember to edit the compiler parameters in order to add support for the newly created metadata: -keep-as3-metadata+=Random.

Since it came out, many useful custom metadata processors have been developed and released. Some of them, in no particular order, are:


  • Log processor: just add a [Log] decoration to an instance of ILogger, to enable fast access to Flex logging API.

  • Geocode Processor: automatizes parts of the ESRI geolocation features.

  • Yahoo Finance: proof of concept that uses live data from Yahoo to populate a list decorated with custom metadata.

  • Foomonger: metadata processor that simplifies the use of Swiz with AS3signals

ActionScript metadata are customizable by themselves, but using Swiz framework makes the task more easy and fun. Looking forward to see a [WrittenWhile] metadata!

May 23, 2010

Using an editable Combobox as itemrenderer

Flex editable combobox can be really useful if you need to let the user select either one of the predefined values or a custom input. The same result can be achieved using a TextInput for custom text and a button that shows a non editable Combobox, but this solution looks less user friendly.
In this post I will show how to use an editable Combobox as itemrenderer in a List. This approach can be not the best (for example you can use an itemEditor) but maybe you will find the same issues using alternative solutions.
Let’s start creating a simple List with an ArrayCollection of CustomObject as dataProvider and using a custom itemRenderer:

Application.mxml


<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;

private var optionsAC:ArrayCollection = new ArrayCollection([
"option1","option2","option3"
]);
[Bindable]
private var myAC:ArrayCollection = new ArrayCollection([
new CustomObject(false,"",optionsAC),
new CustomObject(true,"custom Test",optionsAC),
new CustomObject(false,"",optionsAC,2),
]);
]]>
</mx:Script>
<mx:List dataProvider="{myAC}" width="300"
itemRenderer="customItemRenderer" />

CustomObject.as

package
{
import mx.collections.ArrayCollection;

public class CustomObject
{
public var custom:Boolean;
public var customString:String;
public var options:ArrayCollection;
public var optionIndex:int;

public function CustomObject(c:Boolean = false,s:String = "",o:ArrayCollection = null ,oInd:int = 0)
{
custom = c;
customString = s;
options = o;
optionIndex = oInd;
}
}
}

customItemRenderer.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%">

<mx:Script>
<![CDATA[

import mx.events.FlexEvent;

override public function set data(value:Object):void {
super.data = value;
if(!data)
return;
if(data.custom) {
combo.selectedIndex = -1;
combo.text = data.customString;
}
else
combo.selectedIndex = data.optionIndex;
}

private function onComboChange():void {
if(combo.selectedItem) {
data.optionIndex = combo.selectedIndex;
data.custom = false;
} else {
data.customString = combo.text;
data.custom = true;
}
}

]]>
</mx:Script>
<mx:ComboBox width="100%" id="combo" editable="true" dataProvider="{data.options}" change="onComboChange()" />
</mx:HBox>

The customItemRenderer sets the data in the Combobox checking if there is a custom string or a predefined option. onComboChange saves the modified data into the custom objects whenever the user type into the Combobox or select one option from the dropdown list.
This example is straightforward and it could be useful most of the time you need something similar. But what happens if your CustomObject class is bindable?
Let’s modify CustomObject.as adding the Bindable Meta Tag:

[Bindable]
public class CustomObject
{

Now, when onComboChange modify one of the attribute of CustomObject, a change event is dispatched, that brings to an update of the itemRenderer with a call to the set data function. Here the Combobox calls its updateDisplayList that select all the text inside its TextInput. So, if the user is typing, after the first keystroke the text will be selected and a second keystroke will eventually delete the previous inserted text.

Here’s a solution, extend the Combobox component and override its updateDisplayList:


package
{
import mx.controls.ComboBox;

public class CustomCombobox extends ComboBox
{
public function CustomCombobox()
{
super();
}

override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
if(editable) {
var begin:int = textInput.selectionBeginIndex;
var end:int = textInput.selectionEndIndex;
}
super.updateDisplayList(unscaledWidth, unscaledHeight);

if (editable)
{
textInput.setSelection(begin, end);
}
}
}
}

The idea is simple, just save the previous selection indexes, than after the Combobox updateDisplayList restore them.
Don’t forget to change the Combobox component used in the itemRenderer with the new custom component.
I think there are many alternative solutions to obtain such interaction but I hope this could be useful to someone to save some time trying to understand why its combobox continue to select its text

This example works in Flex 3.5.

May 11, 2010

Mate Framework - an example

In my last post I showed you how Mate framework works. Now I would like to deepen the study on this framework with a short example, and I'd like to show one of best practice ways to use it. For this project I used Flex 4 and Mate_08_9.swc library.

In respect of the Model View Control Pattern I create a project with six packages: business, component, controls,maps, model and view.

MateProject.JPG

In the business package I create all the classes that can communicate with remote services (like http services or wsdl services ), in fact you can find there a ServiceLocator class as an MXML file, that extends the Object class, where I put an httpService tag, from which I would like to obtain an XML File.

 <?xml version="1.0" encoding="UTF-8"?>
<DataPerson>
	<Person>
		<name>Name</name>
		<surname>Surname</surname>
		<phone>12345678</phone>
	</Person>
	<Person>
		<name>Name 1</name>
		<surname>Surname 1</surname>
		<phone>123456789</phone>
	</Person>
</DataPerson>

In the Component package I create the components of my application (in this example only MyDataGrid.mxml) that I use into my View.
In the controls package I put my Event class, in the maps package My Mate EventMap, and in the model package I create a singleton call MateExampleModel where I manage all the data structure used by my view components that are in View package.

Hope that the project structure is easy to understand, I would like to analize the core of the project in particular how I follow the MVC Pattern with Mate Framework.

First of all we can see into the Application tag (view.MateExample.xml) all the View components present in my project, and it's easy to see that there are only an event dispatcher, a data binding with a property of the model, and the build of the EventMap component (component.MyEntityMap).

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:component="component.*" xmlns:maps="maps.*">
	<mx:Script>
		<![CDATA[
			import controls.XMLLoadMateEvent;
			import model.ModelMateExample;
 
			public var evt:XMLLoadMateEvent = new XMLLoadMateEvent(XMLLoadMateEvent.XML_LOAD);
		]]>
	</mx:Script>
 
	<mx:HBox width="100%" height="100%">
		<mx:VBox width="30%">
			<s:Button label="Fill the Datagrid" click="{dispatchEvent(evt)}" />
			<component:MyDataGrid width="100%" height="100%" dataProvider="{ModelMateExample.instance().gridDB}"/>
		</mx:VBox>
	</mx:HBox>
	<maps:MyEntityMap />	
</mx:Application>

The Control components are the Event Class, dispatched by the view, and the HttpServiceManage Class that contains all the methods for manage the resultObject coming from the HttpService (result and fault methods).

The Mate Entity Map is separated by the other Control classes, and it contains all the tags that we analized in my last post... but I think is a good idea to deepen how I used that tags. First we can see how I manage the httpService: on the bottom of the file MyEventMap.mxml I build an object from my ServiceLocator and I used it to generate an instance of an httpService into the HttpServiveInvoker tag, and, inside it, I manage the resultObject and the fault with the methods of an instance of the HttpServiceManage Class (view the code below).

<?xml version="1.0" encoding="utf-8"?>
<mate:EventMap xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:mate="http://mate.asfusion.com/" xmlns:business="business.*">
	<mx:Script>
		<![CDATA[
			import controls.HttpServiceManage;
			import controls.XMLLoadMateEvent;
		]]>
	</mx:Script>
  
	<!-- enable debugger -->
	<mate:Debugger level="{Debugger.ALL}"/>
  
	<!-- handler of the XMLLoadMateEvent -->
	<mate:EventHandlers type="{XMLLoadMateEvent.XML_LOAD}" debug="true">
		<!-- HTTP Service -->
		<mate:HTTPServiceInvoker instance="{service.httpService}" debug="true" >
			<!-- result handlers -->
			<mate:resultHandlers >
				<mate:MethodInvoker generator="{HttpServiceManage}" method="result" arguments="{resultObject}" >
				</mate:MethodInvoker>
			</mate:resultHandlers>
 
			<!-- fault handlers -->
			<mate:faultHandlers>
				<mate:MethodInvoker generator="{HttpServiceManage}" method="fault" arguments="{fault}" >
				</mate:MethodInvoker>
			</mate:faultHandlers>
		</mate:HTTPServiceInvoker>		
	</mate:EventHandlers>
 
	<!-- Service Locator -->
	<business:ServiceLocator id="service"/>
</mate:EventMap>

It's very import to see that I manage the model of my application without the PropertyInjector tag . In fact, if you see the code of the HttpServiceManageClass, you can observe that I use the model's objects inside the result method of my httpService.

package controls
{
	import model.ModelMateExample;	
	import mx.controls.Alert;
	import mx.rpc.Fault;
  
	public class HttpServiceManage
	{
		public function HttpServiceManage()
		{
		}
		public function result(obj:Object):void{
			ModelMateExample.instance().gridDB = obj.DataPerson.Person;
		}
		public function fault(faultObj:Fault):void{
			Alert.show("Error: "+faultObj.message);
		}
	}
}

Generally I prefer to use this kind of solution because I think it could be clearer for whom want to analize my code to understand the funcionalities and the model's properties managed by the methods.
This approach is not the only one that you can use in your Mate Project, in fact it would like to be only an example of the flexibility of this framework.I think that Mate could be a very simple and power solution for create Flex Project with a solid structure that guarantees good quality for our projects.

Download example source code

Regards