ActionScript Convert Array to Tree XML.

23 03 2009

Convert array with DB Design ID and ParentID. I wrote it for my work ^^.

This is table structrure.

convertarrtotreexml1
Hope will useful for anybody.

/**
* Convert array data to tree xml
* @param arr Datasource array
* @param parent Xml node parent
* @param colFieldName_ID Name of field id (it same and use in parent id)
* @param colFieldName_ParentID Name of field parent id ( it's id other node's id)
* @return XML
*
*/
public static function convertArrayToTreeXML(arr:Array, parent:XML, colFieldName_ID:String, colFieldName_ParentID:String):XML {
var root:XML ;
if(parent == null){
root = new XML("<root></root>")
}else{
root = parent;
}
var itemNode:XML;
var strXML:String;
var itemChildNodes:XML;
var arrLvln:Array;
if(parent == null){
arrLvln = arr.filter(function(item:*, index:int, array:Array):Boolean
{
return item[colFieldName_ParentID] == null
|| item[colFieldName_ParentID].toString() == "-1"
|| item[colFieldName_ParentID].toString() == "";
});
}else{
arrLvln = arr.filter(function(item:*, index:int, array:Array):Boolean
{
return item[colFieldName_ParentID] == parent["@"+colFieldName_ID];
});
}
if(arrLvln == null || arrLvln.length == 0){
return null;
}
for each(var obj:Object in arrLvln) {
strXML = "<node";
for(var prop:String in obj){
strXML += " " + prop + "='" + obj[prop] +"'";
}
strXML += "></node>";
itemNode = new XML(strXML);
convertArrayToTreeXML(arr,itemNode,colFieldName_ID,colFieldName_ParentID);
root.appendChild(itemNode);
}
return root;
}




Getting Started with Cairngorm – Part 5

14 03 2009

In Part 4 you saw the full Service to Worker pattern demonstrated. However, the method discussed in the last tutorial doesn’t fit every situation. In this tutorial you will learn a few “best-practices” for Cairngorm projects as well as an extension to the Service to Worker pattern for more complex cases.

Delegates, Commands, and Responders

These classes (Delegates, Commands, and Responders) have specific responsibilities. Many developers run into problems when they do not adhere to these responsibilities. The following tips are guidelines for your code.

  • Responders – Responders should deal only in strongly-typed application objects. Responders may set values on the model.
  • Commands – Commands never deal directly with server interaction. Commands may set values on the model.
  • Delegates – Delegates should pass strongly typed strongly-typed application objects to the Responder. If the Delegate doesn’t receive strongly-typed application objects, it must parse and convert the data into that format.

Cairngorm Delegate Data Diagram

Figure 1 – Data Transmission in the Service to Worker Pattern

The goal of this separation of responsibility is that services should be able to be switched out with only a change in the delegate. This may sound a bit unimportant, but if you are working for a large company, the server-side implementation can change drastically from development to production. For this to work properly, the service call will need to have two responders: the Delegate, and the actual Responder. Figure 1 illustrates this separation. The data passed from the service to the delegate can be in virtually any format, but the transfer from the Delegate to the Responder needs to only be application data (VO’s, model classes).

In this case, the Delegate now has an added responsibility, parsing the raw data. To accomplish this, you can create a factory class to parse the data. In the sample below the class DeliciousFactory (because it parses data from a Del.icio.us feed) has a method buildPostArrayFromJSON which handles this responsibility.

Actionscript:

...
package net.davidtucker.deliciousbrowser.business {
import com.adobe.cairngorm.business.ServiceLocator;
import mx.rpc.AsyncToken;
import mx.rpc.IResponder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import net.davidtucker.deliciousbrowser.factories.DeliciousFactory;
public class PostsDelegate {
private var responder:IResponder;
private var service:Object;
public function PostsDelegate( responder:IResponder ) {
this.responder = responder;
this.service = ServiceLocator.getInstance().getHTTPService( "sampleService" );
}
public function getRecentPosts():void {
// Call the Service and Attach that call to an AsyncToken
var token:AsyncToken = service.send(params);
// Create a Responder for the call
var responder:mx.rpc.Responder = new mx.rpc.Responder(onResult, onFault);
// Add the Responder to the AsyncToken
token.addResponder(responder);
}
private function onResult( e:ResultEvent ):void {
// Parse JSON into Array of VO's
var posts:Array = DeliciousFactory.buildPostArrayFromJSON( e.result as String );
// Pass VO Array to Responder
responder.result( new ResultEvent( ResultEvent.RESULT, false, true, posts ) );
}
private function onFault( e:FaultEvent ):void {
}
}
}...

Code Example 1 – A Delegate Parsing Raw Server Data

Parsing the server data is only a part of this extended design pattern. For this to work properly with the traditional Cairngorm flow, the delegate must “intercept” the result of the service call. To accomplish this, you will attach an AsyncToken [Reference] to the service call, create a responder for the call, and then attach the responder to the AsyncToken. This is illustrated in lines 23-30 of Code Example 1.

Now that the delegate has “intercepted” the result of the service call, it need to have methods to parse the data. When you created the responder inside of the delegate (line 27 of Code Example 1), you passed in a result and fault method. In this case it was onResult and onFault. You now need to add these methods to the delegate.

To pass the parsed data to the original responder, you will need to create a new instance of the ResultEvent [Reference] with the parsed data in the result property (line 40 of Code Example 1). This event will be passed as an argument to the original responder’s result method.

Setting ModelLocator Values

Within a Cairngorm application, it can be extremely tempting to set values of ModelLocator variables in your events, delegates, or views, but this should be avoided. These values should be set only in the Command Level (see Figure 1) of the application. This means that you can set these values in a Command or Responder. This keeps every class in tune with its true function.

Sequence Commands

Cairngorm also contains a class, SequenceCommand [Reference] that allows the developer to chain command/events together for sequential execution. Initially this may seems like it breaks the framework’s rule oft having every command triggered by an event, but it doesn’t. Inside of a SequenceCommand you define the nextEvent property (which is an instance of a CairngormEvent). This event is executed when the executeNextCommand method is called. This is the most effective way to attach multiple commands to a single user gesture.

Actionscript:
public class SampleSequenceCommand extends SequenceCommand implements ICommand, IResponder {
public function SampleSequenceCommand() {
this.nextEvent = new GetPostsEvent();
}
override public function execute( e:CairngormEvent ):void {
}
public function result( event:Object ):void {
this.executeNextCommand();
}
public function fault( event:Object):void {
}
}

NOTE: The SequenceCommand class assumes that you are not separating your Command and Responder. You could easily extend the architecture and create a SequenceResponder class to achieve the same effect.

ViewHelper and ViewLocator Classes

Many people have inquired about the ViewHelper [Reference] and ViewLocator [Reference] classes. Both of these classes are now deprecated as of Cairngorm 2.1, and it is considered bad practice to use either of these classes in a new Cairngorm project. Should you be working with an existing project that still uses these classes, I would recommend refactoring your code to meet Cairngorm 2.2 standards.

Summary of Tips

  1. Don’t use ViewHelpers and ViewLocators
  2. Only set ModelLocator variables in the Command Level (Command or Responder).
  3. SequenceCommand can be used to chain multiple commands to a single user gesture.
  4. Delegates deal in raw service data (which could be application data), but Responders only deal in strongly-typed application data.
  5. Commands do not directly communicate with services.

Application Code
Beginning Code Download (9 Kb)
Finished Code Download (12 Kb)

References
AS3CoreLib

Looking Ahead

In the next (and final) tutorial on Cairngorm, you will learn tips to make your Cairngorm development go faster as well as learning more “best practices” for Cairngorm development.





Getting Started with Cairngorm – Part 4

14 03 2009

The basic Cairngorm Event Flow that is handled in Part 3 is essential to any Cairngorm application, but most applications interact with a server. The Service to Worker pattern that was discussed in the previous tutorial is essential to this process. To learn the expanded Cairngorm Flow, you will need to learn a few new Cairngorm elements.

The Server Interaction Elements

There are three new types of classes that you will need to be familiar with to understand the full Service to Worker Pattern.

  • ServiceLocator [Reference] – The ServiceLocator is a singleton that contains references to all of the services that your application will use. It usually includes HTTPService, WebService, or RemoteObject calls.
  • Business Delegate – A Business Delegate has three functions: to locate the service that is needed, to call a method on the service, and to route the result to the specified responder. There is usually one Business Delegate for each service.
  • Value Object – Value Objects are classes that by definition do not require any methods, only properties. They allow for the application to transfer strongly-typed complex data objects to and from the server.

Organizing Your Cairngorm Project (With Server Interaction)

In the last tutorial you saw the standard Cairngorm structure for a project. To complete this structure, you will need to add an additional two folders:

  • /business – This folder typically contains two types of files: the ServiceLocator (named Services.mxml) and Business Delegates.
  • /vo – This folder contains the value objects that are passed to and from the server.

Understanding the Process

Before you begin crafting the server interaction for your project, you need to understand the full Service to Worker pattern. Figure 1 illustrates the entire process.

Full Cairngorm Diagram Final

Figure 1 – Cairngorm Event Flow with Server Interaction

Phase I – Execution Phase

  1. The user is viewing a component that has a login button. When the button is clicked, that component would dispatch an event named LoginEvent that extends CairngormEvent.
  2. The FrontController would receive the LoginEvent and execute the command that is mapped to that event. For this example, it will be named LoginCommand and will implement ICommand.
  3. The Command is executed and received the LoginEvent as an argument. The LoginCommand creates an instance of the Delegate while passing a reference to the Responder. The Command then calls the specified method on the Delegate.
  4. The Delegate gets the service from the ServiceLocator and calls the method on the specific service.
  5. The service defined in the ServiceLocator receives the information that is passed to it from the call in the Delegate.

Phase II – Application Tier Processing

Phase III – Response Phase

  1. The service that is defined in the ServiceLocator returns the result of the server-side processing.
  2. The Delegate receives the result and passes it to the specified responder.
  3. The Responder receives the result indicating a successful login.
  4. The ModelLocator will have a predefined constant for the “Logged in View”. The Responder will change workflowState to this value.
  5. Since the view is bound to workflowState, it will automatically update itself to the new view.

Note: Traditionally the Command and Responder were the same class in a Cairngorm application. If you are working with other developers, the applications will probably be coded in this manner. However, most developers (including Adobe Consulting) are now separating these classes into two different classes. For a less complex project, it might not make sense to separate these items, but in a large application it could prove advantageous in organization and practice to have two different classes.

The ServiceLocator

The ServiceLocator is a singleton that contains references to all of the services that the application will be using. These services can be RemoteObjects, HTTPServices, WebServices, or custom services. Like the FrontController, this class is usually instantiated in your main application file. Unlike many of the other Cairngorm project assets that you have created, this class can be defined in MXML (as well as ActionScript). To properly define this in MXML, there must be a namespace that points to the business folder of the Cairngorm package. In this case the namespace cairngorm is typically used. The ServiceLocator in Code Example 1 has one service defined, loginService.

Actionscript:

  1. <?xml version=“1.0″ encoding=“utf-8″?>
  2. <cairngorm:ServiceLocator
  3. xmlns:cairngorm=“com.adobe.cairngorm.business.*”
  4. xmlns:mx=“http://www.adobe.com/2006/mxml”>
  5. <!– Login Service –>
  6. <mx:RemoteObject id=“loginService”
  7. showBusyCursor=“true”
  8. destination=“ColdFusion”
  9. source=“CairngormTest.CairngormLogin”>
  10. <mx:method name=“login” />
  11. </mx:RemoteObject>
  12. </cairngorm:ServiceLocator>

Code Example 1 – Sample ServiceLocator

The ServiceLocator is typically named Services.mxml and resides in the business folder of your Cairngorm project.

Commands with Server Interaction

In the last tutorial you hard-coded some values into the LoginCommand to check for a specific username and password. Here was the execute method:

Actionscript:

  1. public function execute(event:CairngormEvent):void {
  2. var loginEvent:LoginEvent = event as LoginEvent;
  3. if( (loginEvent.username == “david”) && (loginEvent.password == “password”)) {
  4. modelLocator.workflowState = ViewModelLocator.WELCOME_SCREEN;
  5. }
  6. }

Code Example 2 – Command Without Delegate

This methodology will hold true for any Command that doesn’t have server interaction, but if you do have server interaction, it will need to be modified to include the delegate. First, you will need to make a decision. As stated earlier, you can have separate Commands and Responders, or they can be the same class. For this example, they will be the same class. The Command will now also need to implement the mx.rpc.IResponder class (please note that com.adobe.cairngorm.business.Responder is deprecated and should no longer be used).

The other initial change is that the execute method now instantiates a class named LoginDelegate (which will be created shortly). The LoginDelegate class required one argument in its constructor, the Responder of the service. In this case, the Command will function both as the command and the responder, so you simply need to insert the this keyword inside the parenthesis. If you chose to have a separate responder, you would insert the reference to it here (instead of the this keyword).

Actionscript:

  1. package net.davidtucker.CairngormSample.commands {
  2. import com.adobe.cairngorm.commands.ICommand;
  3. import com.adobe.cairngorm.control.CairngormEvent;
  4. import mx.controls.Alert;
  5. import mx.rpc.IResponder;
  6. import net.davidtucker.CairngormSample.business.LoginDelegate;
  7. import net.davidtucker.CairngormSample.events.LoginEvent;
  8. import net.davidtucker.CairngormSample.model.ViewModelLocator;
  9. public class LoginCommand implements ICommand,IResponder {
  10. public var modelLocator:ViewModelLocator = ViewModelLocator.getInstance();
  11. public function LoginCommand() {
  12. }
  13. public function execute(event:CairngormEvent):void {
  14. var loginEvent:LoginEvent = event as LoginEvent;
  15. var delegate:LoginDelegate = new LoginDelegate( this );
  16. delegate.login(loginEvent.loginAttempt);
  17. }
  18. public function result( event:Object ):void {
  19. if(event.result == true) {
  20. modelLocator.workflowState = ViewModelLocator.WELCOME_SCREEN;
  21. } else {
  22. mx.controls.Alert.show(“Password Incorrect”,“ERROR”);
  23. }
  24. }
  25. public function fault( event:Object ):void {
  26. trace(“Service Error”);
  27. }
  28. }
  29. }

Code Example 3 – Command with Server Interaction Through a Delegate

Value Objects

A Value Object does not extend or implement any Cairngorm class. As stated earlier, it simply is a class that is only required to have properties, but not methods. For example, if you created a Value Object for a Login – it would have a property for username and a property for password.

Actionscript:

  1. package net.davidtucker.CairngormSample.vo {
  2. [RemoteClass(alias="CairngormTest.LoginVO")]
  3. public class LoginVO {
  4. public var username:String;
  5. public var password:String;
  6. public function LoginVO(username:String,password:String) {
  7. this.username = username;
  8. this.password = password;
  9. }
  10. }
  11. }

Code Example 4 – Value Object for Login

The RemoteClass metatag is important to note. This will allow the corresponding server-side object (ColdFusion Component, PHP Class, Java Class, etc…) to be mapped to this Value Object. In this case, it is mapped to a ColdFusion component named LoginVO in the CairngormTest folder.

Business Delegates

The final design pattern in the Cairngorm Micro-Architecture is the Business Delegate. A Business Delegate essentially is the abstraction layer between your services and the rest of your application. As stated earlier, it has three functions. First, the Business Delegate will locate the service that is needed in the ServiceLocator. Second, it will call a method on that service. Finally, it will route the response back to the specified responder (usually either a command or separate responder).

A Delegate class doesn’t extend or implement and Cairngorm classes, but it generally follows the following guidelines.

  • The Delegate has at least two properties: one named service which is a reference to a service in the ServiceLocator and one named responder which is the responder for the service calls.
  • There is a method for each server-side method that you will be calling.
  • Both the responder and the service variables are set in the constructor.
Actionscript:

  1. package net.davidtucker.CairngormSample.business {
  2. import mx.rpc.IResponder;
  3. import net.davidtucker.CairngormSample.vo.LoginVO;
  4. import com.adobe.cairngorm.business.ServiceLocator;
  5. public class LoginDelegate {
  6. private var responder : IResponder;
  7. private var service : Object;
  8. public function LoginDelegate( responder:IResponder ) {
  9. this.responder = responder;
  10. this.service = ServiceLocator.getInstance().getRemoteObject(“loginService”);
  11. }
  12. public function login(login:LoginVO):void {
  13. var call:Object = service.login( login );
  14. call.addResponder( responder );
  15. }
  16. }
  17. }

Code Example 5 – Service Delegate

There are many benefits to having this layer. If coded correctly, you should be able to change out the server interaction (going from PHP to ColdFusion for example) and only have to change the code in your ServiceLocator and your Delegate. You also can easily insert “stub code” to simulate the actual server interaction during the early stages of development.

The Application Tier

In this example, the Application Tier will be handled by a ColdFusion 8 installation. It will contain two Coldfusion components. These components are purposefully simple.

  1. LoginVO.cfc – This component will correspond to the ActionScript class LoginVO that you created earlier.
  2. CairngormLogin.cfc – This component will perform the actual login processing.

In this example, the Flex application will pass a LoginVO ActionScript object to the CairngormLogin.cfc’s login method through a RemoteObject call. This will be mapped to a LoginVO.cfc object. If this LoginVO.cfc object has the username “david” and the password “password” the method will return true. If not, it will return false.

Coldfusion:

  1. <cfcomponent displayname=“LoginVO” hint=“Login VO For CairngormTest” output=“false”>
  2. <cfset this.username = “” />
  3. <cfset this.password = “” />
  4. </cfcomponent>

Code Example 6 – LoginVO.cfc

Coldfusion:

  1. <cfcomponent displayname=“CairngormLogin” hint=“CFC to Test Cairngorm Service Interaction” output=“false”>
  2. <cffunction name=“login” displayname=“login” access=“remote” output=“false” returntype=“boolean”>
  3. <cfargument name=“loginAttempt” type=“LoginVO” required=“true” />
  4. <cfif (loginAttempt.username EQ “david”) AND (loginAttempt.password EQ “password”)>
  5. <cfreturn true />
  6. <cfelse>
  7. <cfreturn false />
  8. </cfif>
  9. </cffunction>
  10. </cfcomponent>

Code Example 7 – CairngormLogin.cfc

Application Code
Download (11 Kb)

Looking Ahead

There are only two tutorials remaining in the Cairngorm series. In the next tutorials you will learn about code generation options for Cairngorm, and you will also build an actual application using Cairngorm.

Reference

The following resouces should assist you in getting Flex connected to your application server.





Getting Started with Cairngorm – Part 3

14 03 2009

Now that you have isolated two specific elements of the Cairngorm Micro-Architecture, you will now create a more complete Cairngorm application. Up to now the tutorials have covered only one design pattern, the ModelLocator, but now you will be introduced to the most crucial element of Cairngorm, the Service to Worker design pattern. The explanation of this pattern will span two tutorials. This tutorial will cover the basic flow inside of a Cairngorm application, and the next tutorial will expand this flow to include server interaction. However, before you can properly implement this design pattern you need to learn about the organization of a Cairngorm project.

Organizing a Cairngorm Project

One of the tasks involved with any project is organization. When working with other developers, this becomes extremely important. Normally a Cairngorm project is organized in the following manner:

  • There is a Main.mxml file that is the main application file for the Cairngorm application.
  • The project files are contained in a folder that uses “reverse-dns” format. For example, if the project was named CairngormSample, I would use the following folders net/davidtucker/CairngormSample .
  • Within the CairngormSample directory, there will be the following folders (there will be additional folders added in the next tutorial).
    • events/ – This directory holds all of the custom events for the application
    • control/ – This directory houses the FrontController for the application
    • commands/ – This directory contains the Commands that are called by the FrontController
    • model/ – The ModelLocator is contained in this folder (and other classes related to the model)
    • view/ – The components of the view are contained in this directory

By following this standard, you can know where to find any class that you may need in your Cairngorm application. Figure 1 illustrates this project structure. It also is a good development process to have a standard organizational structure for your projects – even if you are not using Cairngorm.

Cairngorm Project Folder

Figure 1 – Cairngorm Project Structure

The Service to Worker Pattern

The Service to Worker pattern is the hardest for most people to grasp. It encompasses most of the logic for a Cairngorm application. To understand this pattern, you will need to understand some of the classes that are included with Cairngorm and their respective purposes.

  • CairngormEvent [Reference] – CairngormEvent is central in this pattern. It extends from Event. For your event to be handled properly in Cairngorm, it will need to be of type CairngormEvent.
  • CairngormEventDispatcher [Reference] – CairngormEventDispatcher actually dispatches the CairngormEvents. It is a singleton (just like the ModelLocator). In previous Cairngorm versions, you would call this class regularly, but now CairngormEvents can dispatch themselves (via the method dispatch). This method is simply a wrapper for the CairngormEventDispatcher, so even if you don’t actually import and call the class, it is still central to the Service to Worker pattern in Cairngorm.
  • FrontController [Reference] – The FrontController maps a CairngormEvent to a Command.
  • ICommand [Reference] – For a Command to function properly in Cairngorm, it needs to implement the ICommand interface. This interface requires that a command have a method named execute and that it accept the CairngormEvent that is mapped to it as an argument.

The Cairngorm Event Flow

The way that these classes interact is the Cairngorm Event Flow. Figure 2 illustrates this entire process. While this process seems lengthy, it follows a logical order.

Basic Cairngorm Event Flow

Figure 2 – Cairngorm Basic Event Flow

For example, assume that Figure 2 shows what happens when a user clicks a login button. It would follow the following steps:

  1. The user is viewing a component that has a login button.
  2. When the button is clicked, that component would dispatch an event named LoginEvent that extends CairngormEvent.
  3. The FrontController would receive the LoginEvent and execute the command that is mapped to that event. For this example, it will be named LoginCommand and will implement ICommand.
  4. The Command is executed and received the LoginEvent as an argument. The LoginCommand will change the workflowState value in the ModelLocator.
  5. The ModelLocator will have a predefined constant for the “Logged in View”. The command will change workflowState to this value.
  6. Since the view is bound to workflowState, it will automatically update itself to the new view.

Once these items are understood, the next most important thing to understand about Cairngorm is: Everything Should Be Mapped to an Event. This is a drastic over-simplification, but it holds true in most situations. When a user clicks a login button – it should dispatch a CairngormEvent. When the user selects an option to change the view – it should dispatch a CairngormEvent. When a user submits a form to be stored on in a database – the form should dispatch a CairngormEvent. The dispatching of a CairngormEvent sets everything in motion.

Custom CairngormEvents

The class CairngormEvent can be used inside of your project, but in most situations you will create your own custom events that extend CairngormEvent (as stated previously, for an event to be included in the Cairngorm Event Flow it should extend CairngormEvent). Another reason to create custom events it to create custom properties of the event which contain data that you need to pass to the command. CairngormEvent has a property named data (of type Object) that can contain data, but it is ideal to have a strongly-typed property where you can place the data to pass.

For this example you will create an event that corresponds to the earlier example of a login page. This event will need to meet the following criteria:

  • Extend CairngormEvent
  • Have a property for the username
  • Have a property for the password

Code Example 1 illustrates this completed event. You can see that you will need to import both CairngormEvent and the basic Event class. Also, as with all events, you have to define the Event constant. In this instance, you can use LOGIN. The properties are defined below the constant – and they also are passed into the constructor. The only thing out of the ordinary is that you need to override the public method clone(). This is the the method that the event uses to make a copy of itself. This is key in the Cairngorm Event Flow. Also, for the function to implement ICommand this method will need to have a return type of Event (and not CairngormEvent).

Actionscript:

  1. package net.davidtucker.CairngormSample.events {
  2. import com.adobe.cairngorm.control.CairngormEvent;
  3. import flash.events.Event;
  4. public class LoginEvent extends CairngormEvent {
  5. public static const LOGIN:String = “Login”;
  6. public var username:String;
  7. public var password:String;
  8. public function LoginEvent(submittedUsername:String,submittedPassword:String) {
  9. username = submittedUsername;
  10. password = submittedPassword;
  11. super(LOGIN);
  12. }
  13. override public function clone():Event {
  14. return new LoginEvent(username,password);
  15. }
  16. }
  17. }

Code Example 1 – Custom Event

Commands

The Commands within a Cairngorm application actually “command” the application. Even in the next tutorial where you will be interacting with a server, the command still will do a majority of the work. In this example you will create a component that will receive the username and password from the LoginEvent, check the values against hard-coded values, and then change the workflowState on the ModelLocator if the values are correct. The following example performs these steps (but it doesn’t have the hard-coded values included – that will be covered in the video).

The first thing to notice about the code below in Code Example 2 is that the LoginCommand implements ICommand. To accomplish this the ICommand class is also imported. In addition, you will notice the boilerplate code that you have used in the past to bring in the ModelLocator. To properly implement ICommand, the method execute() is also created. It received an event of type CairngormEvent (it has to be CairngormEvent and not LoginEvent to properly implement ICommand). To properly use the event, you will need to cast this event to the type LoginEvent (the process of casting will be further explained in the video). The actual logic has been left out of this command, but you can see that the ModelLocator updates the view. Once the logic is implemented this line of code would probably be inside of an if statement.

Actionscript:

  1. package net.davidtucker.CairngormSample.commands {
  2. import com.adobe.cairngorm.commands.ICommand;
  3. import com.adobe.cairngorm.control.CairngormEvent;
  4. import net.davidtucker.CairngormSample.events.LoginEvent;
  5. import net.davidtucker.CairngormSample.model.ViewModelLocator;
  6. public class LoginCommand implements ICommand {
  7. public var modelLocator:ViewModelLocator = ViewModelLocator.getInstance();
  8. public function LoginCommand() {
  9. }
  10. public function execute(event:CairngormEvent):void {
  11. var loginEvent:LoginEvent = event as LoginEvent;
  12. // COMMAND LOGIC
  13. modelLocator.workflowState = ViewModelLocator.WELCOME_SCREEN;
  14. }
  15. }
  16. }

Code Example 2 – Cairngorm Command

Front Controller

As stated earlier, the FrontController maps your CairngormEvents to specific commands. Without this, your events would never integrate into the Cairngorm flow. The class extends FrontController and has two methods: the constructor and the initialize method. The initialize method is where you will use the addCommand method to map your events to commands (as you can see with the LoginEvent and LoginCommand).

Actionscript:

  1. package net.davidtucker.CairngormSample.control {
  2. import com.adobe.cairngorm.control.FrontController;
  3. import net.davidtucker.CairngormSample.commands.*;
  4. import net.davidtucker.CairngormSample.events.*;
  5. public class SampleController extends FrontController {
  6. public function SampleController() {
  7. this.initialize();
  8. }
  9. public function initialize():void {
  10. //ADD COMMANDS
  11. this.addCommand(LoginEvent.LOGIN,LoginCommand);
  12. }
  13. }
  14. }

Code Example 3 – The Cairngorm FrontController

Simply creating a FrontController is not enough. Like any class it needs to be instantiated inside of your application. Code Example 4 illustrates how to instantiate your FrontController in the Main.mxml file of your application. You simply need to add the control directory as an XML Namespace and then include the FrontController tag in the file.

mxml:

  1. <?xml version=“1.0″ encoding=“utf-8″?>
  2. <mx:Application xmlns:mx=“http://www.adobe.com/2006/mxml”
  3. xmlns:control=“net.davidtucker.CairngormSample.control.*”
  4. layout=“absolute”>
  5. <control:FrontController id=“controller” />
  6. </mx:Application>

Code Example 4 – Integrating a FrontController

Now that you have seen the basic elements of a Cairngorm project, you can actually build the working sample with the video. As always, the application code is included below.

Application Code
Download (7 Kb)

Looking Ahead

This is the basic Cairngorm flow. You may notice that this flow really does not include any “Services” yet. Server interaction will introduce a few additional steps to the flow (which will be covered in depth in the next tutorial).





Getting Started with Cairngorm – Part 2

14 03 2009

Recap: In Part 1, I discussed the basic implementation and use of the ModelLocator pattern. This pattern is one of many design patterns contained within the Cairngorm micro-architechture. This design pattern will be used in Part 2 as well, so it is assumed that you are familiar with the concepts in Part 1 of the tutorial. At this point, we still are not working with a “complete” Cairngorm application (that will come in Part 3).

Part 2 – Using a ModelLocator to Manage the View

Note: As with all of the tutorials that will come in this series, this lesson has two parts. First, in the article you will learn the theory behind the topic, and then in the video you will do an actual “code-along”. The article will give some instructions in how to set up your project for the “code-along”.

In the previous tutorial you learned the advantages of using a ModelLocator to manage data within an application, however, the advantage of the ModelLocator pattern extends beyond the management of data. It can manage the “view” of an application as well. To see how view management works in Cairngorm, you will first need to create a new project named “ViewManager” and name the main application file “Main.mxml”. For this project, your will also need to add the Cairngorm.swc to your project build path (as described in Part 1). You will also need to create two new folders inside of the “src” folder: view and model. When you are completed, your project should look similar to Figure 1 below.

Cairngorm Project Window
Figure 1 – ViewManager Project

Next, you will need to take the ModelLocator code from the previous tutorial and place it inside your application. I have posted the code below for your convenience.

Actionscript:

  1. package model {
  2. import com.adobe.cairngorm.model.IModelLocator;
  3. [Bindable]
  4. public class ViewModelLocator implements IModelLocator {
  5. // Single Instance of Our ModelLocator
  6. private static var instance:ViewModelLocator;
  7. public function ViewModelLocator(enforcer:SingletonEnforcer) {
  8. if (enforcer == null) {
  9. throw new Error( “You Can Only Have One ViewModelLocator” );
  10. }
  11. }
  12. // Returns the Single Instance
  13. public static function getInstance() : ViewModelLocator {
  14. if (instance == null) {
  15. instance = new ViewModelLocator( new SingletonEnforcer );
  16. }
  17. return instance;
  18. }
  19. //DEFINE YOUR VARIABLES HERE
  20. }
  21. }
  22. // Utility Class to Deny Access to Constructor
  23. class SingletonEnforcer {}

Example 1 – The ModelLocator from Part 1

If you need information about the ModelLocator, please return to Part 1 of the tutorial.

The only item that must be changed in the ModelLocator is the “package” statement. For this project, you will be placing the ModelLocator in the “model” folder, so the package path simply needs to me “model” (it has already been corrected above). You will also need to add one variable to your ModelLocator initially. This variable will be called “workflowState” and it will be of type “uint”. The declaration will look like this:

Actionscript:

  1. public var workflowState:uint = 0;

Example 2 – Defining the workflowState Variable

This variable will be used to “control” the view in your application. The most common way to accomplish this is to use a ViewStack [ Reference ]. If you are not familiar with a ViewStack, feel free to read through this information. A ViewStack has a property named “selectedIndex”. This numeric value defines which “child” is visible in the ViewStack. Consider the following code:

mxml:

  1. <mx:ViewStack id=“myViewStack”>
  2. <mx:HBox id=“box1″>
  3. <mx:Label text=“I am Box 1″ />
  4. </mx:HBox>
  5. <mx:HBox id=“box2″>
  6. <mx:Label text=“I am Box 2″ />
  7. </mx:HBox>
  8. <mx:HBox id=“box3″>
  9. <mx:Label text=“I am Box 3″ />
  10. </mx:HBox>
  11. </mx:ViewStack>

Example 3 – A Basic ViewStack Example

Initially the value of selectedIndex is 0. With this setting “box1″ would be visible. If you issue the following command:

Actionscript:

  1. myViewStack.selectedIndex = 1;

Example 4 – Manually Setting the selectedIndex

then the box named “box2″ would be visible. However, if you apply the ModelLocator to this concept, you could use the workflowState varaible to set the selectedIndex property. By binding the selectedIndex to the workflowState value, you now have complete control over what is displayed in the ViewStack from your ModelLocator.

mxml:

  1. <mx:ViewStack id=“myViewStack” selectedIndex=“{modelLocator.workflowState}”>
  2. </mx:ViewStack>

Example 5 – Binding the selectedIndex to the workflowState

Defining Constants for Better Code

It would be simple to manipulate the view using this method, however, it could lead to potentially confusing code. For example, assume that you have the following:

  • A ViewStack with two children: a Login Screen and a Welcome Screen
  • The ViewStack’s selectedIndex is bound to the workflowState property
  • A login button that performs the action shown in Example 4

This might seem as if it works properly, but it doesn’t account for any changes. If another child is added to the ViewStack, it could throw off the order. There needs to be a better way to manually set the selectedIndex property. To accomplish this you just need to define constants inside of the ModelLocator.

Actionscript:

  1. //DEFINE YOUR VARIABLES HERE
  2. public var workflowState:uint = 0;
  3. // DEFINE VIEW CONSTANTS
  4. public static const LOGIN_SCREEN = 0;
  5. public static const WELCOME_SCREEN = 1;

Example 6 – Defining View Constants in the ModelLocator

By using this method, you only have to change the value in one location if the number of children or the order of the children changes in the ViewStack. Now, you would assign the login button the following action to the click event:

Actionscript:

  1. myViewStack.selectedIndex = ViewModelLocator.WELCOME_SCREEN;

Example 7 – Setting the View with Defined Constants

Not only do you protect against future changes, you also have made your code much more logical. Another developer could easily look at the code and understand the process without having to reference all of the children in the ViewStack.

NOTE: The audio was not that great for this video. I will be using a better system for the next tutorial.

Video Example – Controlling the View with a ModelLocator

Application Code
Download (3 kB)





Getting Started with Cairngorm – Part 1

14 03 2009

I spoke about Cairngorm 2.2 in the Flex Bootcamp at Max this week. Many people were interested in Cairngorm, but I only had about 10 minutes to explain the basics of Cairngorm. I guess the easiest way to assist these people is to do a quick blog series on the benefits of Cairngorm. This series will combine articles with “code-along” videos.

Disclaimer: I do not claim the be “the expert” on Cairngorm – I am far from it. However, I have used Cairngorm on several large projects (both at Georgia Tech and in my own business). I am certainly open to corrections if you see that I have made an error on this project. If you want “the experts” check out: Steven Webster, Alistair McLeod, Alex Uhlmann, and Peter Martin.

Note: The guys at Adobe Consulting (that developed Cairngorm) are currently investigating some new things with the framework as a whole. It is possible (actually probable) that some of these things will change in the future. One of the very specific areas of change is the Model Locator.

Part 1 – Getting Started By Using a Model Locator

The Model Locator pattern is used in Cairngorm, but you don’t have to have a full Cairngorm Implementation to use the pattern. First, let’s cover what benefits that you get from using a Model Locator.

A Model Locator is a centralized repository for all of the data that is needed across your application. Your data will exist inside of a “singleton class”. This “class” can only have one instance of itself. Why is this important? Let me give you an example.

We have great mini-notepads at work that I use to write down data while I work. However, sometimes, I lose a notepad – get a new one, and then find the old one. After both have been heavily used – it is really hard to find out which notepad I used to write down a piece of information from one week ago. That is a simple example – but imagine if I had 20 notepads? This could get crazy.

In the same way you could have a “class” that gets “instantiated” 20 times within your application (even if you don’t mean for it to). The easiest way to eliminate this problem is to use a “singleton”. A singleton is a class that is never “created” in the traditional way. It has one main rule – no more than one of itself can exist at any point in time. How does it do this? I will show you in the Model Locator example.

Actionscript:

  1. package net.davidtucker.CairngormSample.model {
  2. import com.adobe.cairngorm.model.IModelLocator;
  3. [Bindable]
  4. public class ModelLocator implements IModelLocator {
  5. // Single Instance of Our ModelLocator
  6. private static var instance:ModelLocator;
  7. public function ModelLocator(enforcer:SingletonEnforcer) {
  8. if (enforcer == null) {
  9. throw new Error( “You Can Only Have One ModelLocator” );
  10. }
  11. }
  12. // Returns the Single Instance
  13. public static function getInstance() : ModelLocator {
  14. if (instance == null) {
  15. instance = new ModelLocator( new SingletonEnforcer );
  16. }
  17. return instance;
  18. }
  19. //DEFINE YOUR VARIABLES HERE
  20. }
  21. }
  22. // Utility Class to Deny Access to Constructor
  23. class SingletonEnforcer {}

This code may look a bit daunting in the beginning, but trust me that it is not as difficult as it may appear. First, we have our package definition and we import some classes. Right now we know that we will need the IModelLocator interface. To use this you will need the Cairngorm SWC that can be found here: Cairngorm. Also note – you could build a model locator without Cairngorm, and I do this frequently on small projects (you just leave out the ‘implements IModelLocator’ and ‘import com.adobe.cairngorm.model.IModelLocator’ code from the Model Locator).

Actionscript:

  1. [Bindable]
  2. public class ModelLocator implements IModelLocator {
  3. // Single Instance of Our ModelLocator
  4. private static var instance:ModelLocator;

Next we have our class definition. It is important that you use the Bindable metatag directly above your class definition. This will allow all of our variables that we define inside of the Model Locator to be used for binding. We also will go ahead and create one variable. It will be called “instance” and it will be of type ModelLocator. This will be the variable where we will store our one instance of our class. It will also be denoted as a “static” property. If you are not sure what a “static” property is, it’s ok – we will discuss that in our next lesson.

Actionscript:

  1. public function ModelLocator(enforcer:SingletonEnforcer) {
  2. if (enforcer == null) {
  3. throw new Error( “You Can Only Have One ModelLocator” );
  4. }
  5. }

This is followed by the constructor. The constructor takes on argument – “enforcer”. You will notice that this “enforcer” has a type of “SingletonEnforcer” which is defined directly after our class. Here is the logic behind that:

  • When you put a class in an Actionscript file below the main class, it is only available to that class. Many people refer to these as “utility classes” (although many people use that term in a much broader scope).
  • If the constructor requires this argument – then only our main class can create an instance of itself, because we do not have access to the “SingletonEnforcer” class – only the main class has this access.
  • We will not access our class in the normal way by using the “new” statement because we can’t call the constructor (I will show you how we will do it in a bit).

Once we get inside of the constructor, we have a few lines that make sure things work as planned. The “if” statement ensures that we had a valid “enforcer” passed in. If there wasn’t it throws an Error stating that “You Can Have Only One ModelLocator”.

Actionscript:

  1. // Returns the Single Instance
  2. public static function getInstance() : ModelLocator {
  3. if (instance == null) {
  4. instance = new ModelLocator( new SingletonEnforcer );
  5. }
  6. return instance;
  7. }

The “getInstance” function is how we will access our ModelLocator from our application. This function simply passes back the “instance” of the class. If it doesn’t exist yet, it creates it. We can now get the ModelLocator by using the following code:

Actionscript:

  1. var model:ModelLocator = ModelLocator.getInstance();

Video Example – Getting Started and Building a Contact List

Application Code
Download (418 kB)





Convert html on RichTextEditor

11 03 2009

Original on thanksmister.com

I. Use XML to convert html ricktexteditor to xhtml.

         private function richTextEditorToHtml(str:String):String {
                // Create XML document
                var xml:XML = XML("<BODY>"+str+"</BODY>");

                // temporary
                var t1:XML;
                var t2:XML;

                // Remove all TEXTFORMAT
                for( t1 = xml..TEXTFORMAT[0]; t1 != null; t1 = xml..TEXTFORMAT[0] ) {
                    t1.parent().replace( t1.childIndex(), t1.children() );
                }

                // Find all ALIGN
                for each ( t1 in xml..@ALIGN ) {
                    t2 = t1.parent();
                    t2.@STYLE = "text-align: " + t1 + "; " + t2.@STYLE;
                    delete t2.@ALIGN;
                }

                // Find all FACE
                for each ( t1 in xml..@FACE ) {
                    t2 = t1.parent();
                    t2.@STYLE = "font-family: " + t1 + "; " + t2.@STYLE;
                    delete t2.@FACE;
                }

                // Find all SIZE
                for each ( t1 in xml..@SIZE ) {
                    t2 = t1.parent();
                    t2.@STYLE = "font-size: " + t1 + "px; " + t2.@STYLE;
                    delete t2.@SIZE;
                }

                // Find all COLOR
                for each ( t1 in xml..@COLOR ) {
                    t2 = t1.parent();
                    t2.@STYLE = "color: " + t1 + "; " + t2.@STYLE;
                    delete t2.@COLOR;
                }

                // Find all LETTERSPACING
                for each ( t1 in xml..@LETTERSPACING ) {
                    t2 = t1.parent();
                    t2.@STYLE = "letter-spacing: " + t1 + "px; " + t2.@STYLE;
                    delete t2.@LETTERSPACING;
                }

                // Find all KERNING
                for each ( t1 in xml..@KERNING ) {
                    t2 = t1.parent();
                    // ? css
                    delete t2.@KERNING;
                }

                return xml.children().toXMLString();
            }

II. Use RegExp convert between flex-html and xhtml

public function convertFromXHtml(str:String):String
{

var pattern:RegExp;
pattern = /<p style="text-align:left">/g;
str = str.replace(pattern, "<P ALIGN=\"LEFT\">");
pattern = /<p style="text-align:right">/g;
str = str.replace(pattern, "<P ALIGN=\"RIGHT\">");
pattern = /<p style="text-align:justify">/g;
str = str.replace(pattern, "<P ALIGN=\"JUSTIFY\">");
pattern = /<\/p>/g;
str = str.replace(pattern, "</P>");
pattern = /<span style=\"(.*?)\">/g;
str = str.replace(pattern, "<FONT $1>");
pattern = /color:(.*?);/g;
str = str.replace(pattern, "COLOR=\"$1\" ");
pattern = /font-size:(.*?)px;/g;
str = str.replace(pattern, "SIZE=\"$1\" ");
pattern = /font-family:(.*?);/g;
str = str.replace(pattern, "FACE=\"$1\" ");
pattern = /text-align:(.*?);/g;
str = str.replace(pattern, "ALIGN=\"$1\" ");
pattern = /<\/span.*?>/g;
str = str.replace(pattern, "</FONT>");
pattern= /<\/li><li>/g;
str = str.replace(pattern, "</LI><LI>");
pattern= /<\/li><\/ul>/g;
str = str.replace(pattern, "</LI>");
pattern= /<ul><li>/g;
str = str.replace(pattern, "<LI>");
pattern = /<em>/g;
str = str.replace(pattern, "<I>");
pattern = /<\/em>/g;
str = str.replace(pattern, "</I>");
pattern = /<strong>/g;
str = str.replace(pattern, "<B>");
pattern = /<\/strong>/g;
str = str.replace(pattern, "</B>");
pattern = /<u>/g;
str = str.replace(pattern, "<U>");
pattern = /<\/u>/g;
str = str.replace(pattern, "</U>"); 
// Remove extra white space
pattern = /  /g;
str = str.replace(pattern, " ");
return str;
}

public function convertToXHtml(str:String):String
{
var pattern:RegExp;
pattern = /<TEXTFORMAT.*?>/g;
str = str.replace(pattern, "");
pattern = /<\/TEXTFORMAT.*?>/g;
str = str.replace(pattern, "");
pattern = /<P ALIGN="LEFT">/g;
str = str.replace(pattern, "<p style=\"text-align:left\">");
pattern = /<P ALIGN="RIGHT">/g;
str = str.replace(pattern, "<p style=\"text-align:right\">");
pattern = /<P ALIGN="JUSTIFY">/g;
str = str.replace(pattern, "<p style=\"text-align:justify\">");
pattern = /<\/P>/g;
str = str.replace(pattern, "</p>");
pattern = /<FONT (.*?)>/g;
str = str.replace(pattern, "<span style=\"$1\">");
pattern = /COLOR=\"(.*?)\"/g;
str = str.replace(pattern, "color:$1;");
pattern = /SIZE=\"(.*?)\"/g;
str = str.replace(pattern, "font-size:$1px;");
pattern = /FACE=\"(.*?)\"/g;
str = str.replace(pattern, "font-family:$1;");
pattern = /ALIGN=\"(.*?)\"/g;
str = str.replace(pattern, "text-align:$1;");
pattern = /LETTERSPACING=\".*?\"/g;
str = str.replace(pattern, "");
pattern = /KERNING=\".*?\"/g;
str = str.replace(pattern, "");
pattern = /<\/FONT.*?>/g;
str = str.replace(pattern, "</span>");
pattern= /<\/LI><LI>/g;
str = str.replace(pattern, "</li><li>");
pattern= /<\/LI>/g;
str = str.replace(pattern, "</li></ul>");
pattern= /<LI>/g;
str = str.replace(pattern, "<ul><li>");
pattern = /<I>/g;
str = str.replace(pattern, "<em>");
pattern = /<\/I>/g;
str = str.replace(pattern, "</em>");
pattern = /<B>/g;
str = str.replace(pattern, "<strong>");
pattern = /<\/B>/g;
str = str.replace(pattern, "</strong>");
pattern = /<U>/g;
str = str.replace(pattern, "<u>");
pattern = /<\/U>/g;
str = str.replace(pattern, "</u>");
return str;
}