Wednesday, July 7, 2010

Swiz it!


Lets start with a quick video! Then here's a great read on Swiz! Here's still another one! Then a few examples are here 

BTW Swiz is a brain child of  Chris Scott

And of course here's the nice official documentation!

The BIG three offerings of Swiz -
         a) Dependency Injection
         b) Event Handling
         c) Server Interaction!

It does not impose any boilerplate code. It also does not impose J2EE patterns on your code - which may not be so good in my opinion!

Steps in creating a swiz based flex app

1) Swiz Configuration: In the main application file [under declaration section for FB4], define a <swiz:Swiz> metadata tag.

    a) Define your non-visual objects that Swiz should process for dependency injection & event mediation in <swiz:BeanProviders> tag.
 

    b) Define event & view packages in <swiz:config> tag.

     <xml id=simple>

        <swiz:Swiz>
           
            <!-- BeanProviders simply contain the non-display objects that Swiz  should process. -->
            <swiz:beanProviders>
                <config:Beans />
            </swiz:beanProviders>
           
            <swiz:config>
                <!-- The eventPackages value tells Swiz the path to your Event classes,
                and viewPackages is an optional value that speeds up the processing of display classes. -->
                <swiz:SwizConfig
                    eventPackages="org.swizframework.quickswiz.event.*"
                    viewPackages="org.swizframework.quickswiz.view.*" />
            </swiz:config>
           
        </swiz:Swiz>
    </xml>

2) Dependencies Declaration (Services, Controllers, Helpers): In the config package, Define 'Beans.mxml' extending <swiz:BeanProvider>, declare

Service & Controller [& Service Helper]

A Swiz BeanProvider is an MXML file that acts similar to an object registry.
It is the IoC Container of Swiz framework i.e. takes over the task of managing the dependencies from your application.


When you create a bean loader, you’re extending the Swiz BeanProvider class, which registers the objects that you want Swiz to manage for Dependency Injection and Event Mediation.
 

Here you declare objects that will be used in the application and assign IDs to them so that they can be referenced by ID tags at various places where they are needed to be injected(auto-wired).


3) Controller [You define Event handlers for events to be mediated by Flex, declare Service objects to be injected, and make use of service objects in event handlers]: In Controller package, Define a 'Controller.as' class.

    a) Make use of the Service, & ServiceHelper classes here
    b) Declare events which Flex will mediate - using [Mediate(event="EventType", properties="parameter names to be passed to event handling method")] tag

        [Mediate( event="UserEvent.SAVE_USER_REQUESTED", properties="user" )]
        /**
         * Perform a server request to save the user
         */
        public function saveUser( user : User ) : void
        {
            serviceHelper.executeServiceCall( userService.saveUser( user ), handleSaveUserResult );
        }


    c) Execute the Service call using service helper, pass it a result handler.

            serviceHelper.executeServiceCall( userService.saveUser( user ), handleSaveUserResult );
   



4) View - makes use of the model and dispatches custom events that do CRUD on the Model. To achieve this as part of the View definition file, we ask Swiz to inject the model, and we bind model to UI fields


        [Bindable]
        [Inject( source="userController.currentUser", bind="true" )]
        /**
           * We could inject the whole controller instance, but we only need
          * one property from the controller, the current user, so we just
          * inject that property.
          */
   


        /**
          * Handle the user hitting the save button. We capture the form data
          * and dispatch a standard Flex event. No Swiz-specific events or
          * special central dispatcher needed!
          */

        private function saveUser() : void
        {
            user.firstName = firstName.text;
            user.lastName = lastName.text;
            user.email = email.text;
            var event : UserEvent = new UserEvent( UserEvent.SAVE_USER_REQUESTED );
            event.user = user;
            dispatchEvent( event );
        }

5) Model [is a Place holder for application data]- is a Standard Bindable class


        [Bindable]
        public class User
        {
            public var id : int;
            public var firstName : String;
            public var lastName : String;
            public var email : String;       
        }


6) Event Class [extends standard flash.events.Event class] - we need to ensure that event bubbles up by passing the bubble parameter value as true in the call to super()


    public class UserEvent extends Event
    {
        public static const SAVE_USER_REQUESTED : String = "saveUser";
        public var user : User;
       
        /**
         * This is just a normal Flex event. The only thing to note is that we set 'bubbles' to true,
         * so that the event will bubble up the display list, allowing Swiz to listen for your events.
         */
        public function UserEvent( type:String )
        {
            super( type, true );
        }
    }

7) Service Class [handles the remote communication]


    Declare public methods which make Service.send() call and return asyncToken object returned by the send() call. 



The standard ServiceHelper can attach the Result Handler & Fault Handler to this async token which will be invoked when the response is available.


This is how the service class is typically used in Controller. The serviceHelper object below is standard swiz Framework Service Helper


            serviceHelper.executeServiceCall( userService.saveUser( user ), handleSaveUserResult, handleSaveUserFault ); 

Friday, June 25, 2010

Determining Flash Player version in Flex

Flash.system.Capabilities.version and Flash.system.Capabilities.isDebugger are the properties to determine the flash player version

Tuesday, June 22, 2010

Flex name spaces

Controlling method access with name spaces


You could call a different version of calcTax method using the name space soprano with a double colon as shown

tax = Tax.soprano::calcTax();

package com.enron.namespaces {
public namespace soprano=”http://www.enron.com/namespaces”;
}

package com.enron.namespaces {
public namespace regular;
}


package com.enron.tax{
import com.enron.namespaces.*;
public class Tax
{
regular static function calcTax():Number{
return 3500;
}
soprano static function calcTax():Number{
return 1750;
}
}
}

Flex Stage Object

The Stage class represents the main drawing area.

For SWF content running in the browser (in Flash® Player), the Stage represents the entire area where Flash content is shown.

For content running in AIR, each NativeWindow object has a corresponding Stage object.

Reference to Stage object is null until applicationComplete() event - thats where you typically should add any listeners to the stage object

Flex 3 to Flex 4

Features & Migration Guide from Adobe lists them all - pretty useful. Wonder why did not see this earlier

Flash Player 10 in Flex Builder 3.0.2

This is a good post which highlights the steps

 What we essentially gotta do
       a) Install sdk 3.2 & configure it
       b) Remove playerglobal.swc from the existing project build path libraries list and point to  Flash Player 10 playerglobal.swc file as a merged link.

      This file is is in C:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0.3794\frameworks\libs\player\10

Thursday, June 17, 2010

Flex Custom Components

A Great Tutorial  

Singleton in ActionScript!

This is how you'd go about creating a Singleton in ActionScript! Create another class within the same file but outside the package declaration - so that it can only be accessed internally:


package{
    public class Singleton{
        private static var _instance:Singleton=null;
        public function Singleton(e:SingletonEnforcer){
            trace(‘new instance of singleton created’);
        }
        public static function getInstance():Singleton{
            if(_instance==null){
                _instance=new Singleton(new SingletonEnforcer());
            }
            return _instance;
        }
    }
}
//I’m outside the package so I can only be accessed internally
class SingletonEnforcer{
//nothing else required here
}

Wednesday, June 16, 2010

Flex Javascript Integration

Flex Javascript Integration

ExternalInterface defines two especially important static functions:
  • call( functionName:String, ... arguments ) - call a container function
  • addCallback( functionName:String, closure:Function ) - expose a Flex function to the container 
 

Call Browser/JavaScript from ActionScript

// call a JavaScript function defined in the container page
   var result:String = 
      ExternalInterface.call( "doSomethingInJavaScript", arg1, arg2 );
The above ActionScript code could call the below JavaScript code in  the container HTML page:
 
// a JavaScript function in the container HTML page
function doSomethingInJavaScript( arg1, arg2 )
   {
      // do something
      return "results for " + arg1 + " and " + arg2;
   }

Call ActionScript from JavaScript/Browser

public function init():void
   {
      // expose an ActionScript function to the container
      ExternalInterface.addCallback( "doSomethingInActionScript", doSomethingInActionScript );
   }
   
   // function now callable from JavaScript
   public function doSomethingInActionScript( arg1:String, arg2:Number ):String
   {
      return "result";
   }
 
The below JavaScript code can be used to call the exposed ActionScript 
function:
 
// get the Flex application (Flash object)
   var isIE = navigator.appName.indexOf("Microsoft") != -1;
   var flashName = "flashObjectName";
   var flashObject = (isIE) ? parent.Main.window[flashName] : document[flashName];
   
   if( flashObject )
   {
      // call the Flex application (Flash object)
      flashObject.doSomethingInActionScript( "arg1", 2 );
   }
 

 

 


Tuesday, June 15, 2010

Flex Gotchas

1) Construtors cannot be private / protected / internal - They can only be public - use of public keyword is optional.

      a) Create a javascript function which makes use of xmlHTTPRequest object


             xmlHttpRequest.open("GET","http://serverName/URL",true); //true = sync, false = async

      b) Make the javascript function call which will invoke  this javascript function from within Flex using ExternalInterface class

               ExternalInterfac.call(javaScriptFunctionDefinitionStringWhichMakesTheXmlHTTPRequestCall); 

3) When should you use state change[ and transition] vs when should you replace the UI

You use state change when you have to just add or remove a few components in the view and controls pretty much remain the same.

You replace the UI when you have a completely new set of controls 

4) What happens when you removeChild() - parent reference is set to null

5)  When you set a specific height and width of a component, Flex does not call the measure() method, even if you explicitly call the invalidateSize() method. Flex calls the measure() method only if the explicitWidth property or the explicitHeight property of the component is NaN.



 



.

Wednesday, May 5, 2010

Flex Instantiation Lifecycle & Event Flow

The following steps show what occurs when you execute a sample ActionScript code to create the Button control, and add it to a Box container.:


                    container.addChild(component);

                    To Process the addChild call


  1.     set parent reference
  2.     compute style
  3.     dispatch add from the component to let everyone know that its getting added
  4.     dispatch childAdd from the container
  5.     dispatch pre-initialize on component - internal children are about to be added through createChildren() call so developer's get a last chance to affect the component - implement the listener and affect the component's internal structure
  6.     dispatch initialize on component - children get initialized through createChildren() call but layout n sizing of component is not determined yet - you do not have to override this if you are creating your own custom component
  7.     Later render event gets triggered to display the application

   
  1.                     determine the sizing n layout
  2.                     set visible = true
  3.                     creationComplete on component
  4.                     updateComplete

When you create the component in MXML as shown above, Flex SDK generates folllowing equivalent code which is similar to following 3 steps in ActionScript:


1) You call the component's constructor, as the following code shows:
 
// Create a Button control. 
var button1:Button = new Button()

 2) You configure the component by setting its properties, as the following code show:

// Configure the button control.
button1.label = "Submit";

3) You call the addChild() method to add the component to its parent, as the following code shows:
// Add the Button control to the Box container.
box1.addChild(button1);


Flex performs the following actions to process the box1.addChild(button1) call:

4. Flex sets the parent property for the component to reference its parent container.

5. Flex computes the style settings for the component.

6. Flex dispatches the add event from the component, button1 to let the interested folks know that a component button1 got added to parent.

7. Flex dispatches the childAdd event from the parent container box1 to let the interested folks know that a box1 got a child added.

8. Flex dispatches the preinitialize event on the component, button1

The component is in a very raw state when this event is dispatched. Many components, such as the Button control, create internal child components to implement th functionality; for example, the Button control creates an internal UITextField component to represent its label text. 

At the time when Flex dispatches the preinitialize event, the children (including the internal children, of a component) have not yet been created. They get created in this call.

9. Flex creates and initializes the component's children, including the component's internal children.

10. Flex dispatches the initialize event on the component. At this time, all of the component's children have been initialized, but the component has not been fully processed. In particular, it has not been sized for layout.

11. Later, to display the application, a render event gets triggered, and Flex does the following:

1. Flex completes all processing required to display the component, including laying out the component.

2. Flex makes the component visible by setting the visible property to true.

3. Flex dispatches the creationComplete event on the component. The component has been sized and processed for layout and all properties are set. This event is dispatched only once when the component is created.

4. Flex dispatches the updateComplete event on the component. Flex dispatches additional updateComplete events whenever the position, size, or other visual characteristic of the component changes and the component has been updated for display.

Spark Architecture Overview

Here's a very nice post on Spark Architecture

Here's another great piece on Spark
Flex 4's new MXML subset for skins, FGX, is valid XML code, and can be specified either inside an MXML file defining a component or, more often, in a separate file.

The advantage of using a separate file is that designer tools can read and write that file directly.

Adobe, for instance, enhanced its designer tools to comprehend such FGX files, and even provided a specialized designer tool, Catalyst, for the purpose of working with FGX content.

FGX files can declare any visual aspect of a component. An FGX file, for instance, can define runtime graphics classes that draw shapes, specify containment of sub-components, define component effects, transitions, and even specify layout inside the component. In Flex 4, the runtime graphics primitives directly map to graphics classes in Flash Player 10.

Separating out visual concerns into a separate file allows a Flex component's core class to focus on component logic, such as responding to user gestures and data events.

A new component lifecycle ensures that the component's core behavior is associated with the right skin file at runtime.

Wednesday, April 28, 2010

Skin Swapping Example

This is a good skin swapping example

Tuesday, March 9, 2010

Flex application optimization

Here are some good basic steps!

Tuesday, March 2, 2010

Event Bubbling!

Excerpts from the LiveDocs!


When events are triggered, there are three phases in which Flex checks whether there are event listeners. These phases occur in the following order:

* Capturing Phase - Check for listeners "starting from the root until the immediate parent container" in the displayList[by default a) this phase is disabled unless you pass useCapture = true while adding the event listener b) Only a DisplayObject can participate in this phase]

* Targeting - trigger the event listeners of the "target object" - the event originating object.

* Bubbling - Check for listeners "starting from the immediate parent to the root"

During each of these phases, the nodes have a chance to react to the event. For example, assume the user clicks a Button control that is inside a VBox container.



During the capturing phase, Flex checks the Application object and the VBox for listeners to handle the event. Flex then triggers the Button's listeners in the target phase, no other nodes on the display list are examined for event listeners. [The values of the currentTarget and the target properties on the Event object during the targeting phase are the same.]. In the bubbling phase, the VBox and then the Application are again given a chance to handle the event but now in the reverse order from the order in which they were checked in the capturing phase.

- Event object moves from node to node in the display list,

- Only DisplayObject objects (visual objects such as containers and controls) can have a capturing phase and a bubbling phase in addition to the targeting phase.

- Any event can be captured, but no DisplayObject objects listen during the capturing phase unless you explicitly instruct them to do so.In other words, capturing is disabled by default.

- When a faceless event dispatcher, such as a Validator, dispatches an event, there is only a targeting phase, because there is no visual display list for the Event object to capture or bubble through.

Monday, March 1, 2010

Associative Array, Dictionary and Object!

Sourced from Adobe Livedocs:

An associative array, sometimes called a hash or map, uses keys instead of a numeric index to organize stored values. Each key in an associative array is a unique string that is used to access a stored value.

Unlike other classes, the Object class is dynamic - meaning arbitrary properties can be added to serve as keys.


The following example creates an associative array named monitorInfo, using an object literal to initialize the array with two key and value pairs:

var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"};
trace(monitorInfo["type"], monitorInfo["resolution"]);
// output: Flat Panel 1600 x 1200

If you do not need to initialize the array at declaration time, you can use the Object constructor to create the array, as follows:

var monitorInfo:Object = new Object();

monitorInfo["aspect ratio"] = "16:10"; // bad form, do not use spaces
monitorInfo.colors = "16.7 million";
trace(monitorInfo["aspect ratio"], monitorInfo.colors);
// output: 16:10 16.7 million

The Dictionary class lets you create a dynamic collection of properties, which uses strict equality (===) for key comparison.

var dict:Dictionary = new Dictionary();
dict[key] == "Letters";

Iterating with object keys

You can iterate through the contents of a Dictionary object with either a for..in loop or a for each..in loop. A for..in loop allows you to iterate based on the keys, whereas a for each..in loop allows you to iterate based on the values associated with each key.

for (var key:Object in groupMap)
{
trace(key, groupMap[key]);
}
/* output:
[object Sprite] [object Object]
[object Sprite] [object Object]
[object Sprite] [object Object]
*/

for each (var item:Object in groupMap)
{
trace(item);
}
/* output:
[object Object]
[object Object]
[object Object]
*/

Saturday, February 27, 2010

Cairngorm. In a brief!

Here's a link straight from the horse's mouth as they say!

The Cairngorm - micro-architecture as a composition of design patterns, addresses three key areas that Adobe Consulting has long recommended as best-practices for their customers and partners:

- Handling user gestures on the client
- Encapsulating business logic and server interactions
- Managing state on the client and representing this state to the user interface

There are four key benefits that Cairngorm provides:

- Maintaining state on the client
- Architecting the user experience
- Implementing feature-driven development
- Invoking server-side services

Important Components

Following are the important components of Cairngorm:

A) Model - holds the data and the state.

Generally we create a ModelLocator as a composition class consisting of public static getInstance method returning a static singleton reference to itself. all the model objects are stored and refered to from this ModelLocator handle.

B) View - render data and watch the data changes with bindings. Views talk to controller with events.

C) Control - Control layer is implemented as following sub parts

a) Commands - implement execute method that crunches business logic and make use of the model. Create Responder by passing Remote Service Result Handlers and pass the responder to appropriate delegate in constructors. Then invoke asynchronous remote service operations on delegates.(implements com.adobe.cairngorm.control.ICommand).

Register the commands to Cairngorm framework in Front Controller by using addCommand(eventType, commandClass) method.

b) Delegates - Are like proxies for business service APIs. E.g. UserDelegate provides routing to Login, Logout, Registration. OrderDelegate provides Create, Update or Delete order.

To implement a delegate's service method, make use of ServiceLocator. Invoke the appropriate service and attach the responder to the async token of the service operation called.

c) Events - Make use of business events to trigger commands. Typically create one event for each command. Extend com.adobe.cairngorm.events.Event class.

d) Front Controller - Registry of Event to Command mapping. Intercepts dispatched business events and routes them to appropriate commands extends com.adobe.cairngorm.control.FrontController

e) Service Locator - Base your service locator mxml component on Cairngorm ServiceLocator (extend the com.adobe.cairngorm.business.ServiceLocator). Add service tags with id. In your delegate obtain reference as follows

var service:HTTPService=__locator.getHTTPService("UserService");
var token: AsyncToken = service.operation();
token.addResponder(responder);

General Benefits

- maintenance is easier
- debugging is easier
- feature additions and/or changes are easier
- automated testing of business logic and data access is easier
- using mock data-services is easier

Monday, February 22, 2010

SQLite Quick Reference!

:) Here's a quick 10 minute refresher overview on SQLite.

Thursday, February 18, 2010

Making a RESTful Web Service call!

Another name for HTTP Service is REST style web service. To make a successful web service call we gotta take care of steps as below. Similar steps apply for HTTP Object instantiated via HTTP service tag.

1) Instantiate the HTTPService Object.
var httpService: HTTPService = new HTTPService();

2) Set the URL
httpService.url = "serviceURL"; //Mention the service URL

3) Set the method type [GET/POST/PUT/DELETE], default is GET
httpService.method = HTTPService.POST;

4) Set the resultFormat to XML [for true REST], default is Object

httpService.resultFormat = "xml"; //Values possible are object, xml, e4x, text, array, flashvars

5) Add result and fault event listeners

httpService.addEventListener("result", httpResultHandler);
httpService.addEventListener("fault", httpFaultHandler);

6) Construct the parameters to be passed if any, default is null. For example if
your service expects two parameters "userID" & "userName", the values of which you wanna pass as userIDValue and userNameValue, construct an object:

var serviceParameters: Object = {};
serviceParameters["userID"] = userIDValue;
serviceParameters["userName"] = userNameValue;

7) Make the call
httpService.send(serviceParameters);

Bingo! Have Fun! :)

Monday, February 15, 2010

REST vs. SOAP

Among all the rest that are there - here's a good link which exemplifies the differences between the two philosophies and lists out the Pros n Cons.

The fundamental difference between REST Web services and document-style Web services is how the service consumer knows what to expect out of the service. Web services have contracts, defined in WSDL. Since Web services focus on the service, rather than on the resource, the consumer has clear visibility into the behavior of the various operations of the service, whereas in REST's resource-oriented perspective, we have visibility into the resources, but the behavior is implicit, since there is no contract that governs the behavior of each URI-identified resource

Points to take home:

1) SOAP is a protocol for distributed XML based computing. REST is for simple point to point communication using plain old XML.

2) SOAP Envelope( optional header + mandatory body) is often bulkier for following reasons:
  • a) Attributes: Since is designed to be used in a distributed environment with multiple nodes processing a SOAP envelope, its gonna contain role and relay attributes.
  • b) Encoding [Rules on how a data value should be encoded in an XML format]
  • c) Extensions and Versions
3) REST on the other hand is simple & concise -and it makes use of GET PUT POST DELETE methods of HTTP protocols to support CRUD communication over the network. REST using Flex Find it all here. But the bottom line is another name for Flex HTTPService class is REST style web service. For REST-style services, you use a server resource such as a PHP page, JavaServer Page (JSP) or servlet, or ColdFusion page that receives a POST or GET (or a PUT or a DELETE) request from a Flex application using the HTTPService component. That server resource then accesses a database using whatever means are traditional to the particular server technology.

The results of data access can be formatted as XML instead of HTML, as might be typical with the server technology, and returned as the response to the Flex application. Flex, Adobe® Flash® Player, and Adobe AIR™ have excellent XML- handling capabilities that let you manipulate the data for display in the Flex application user interface. REST-style services provide an easy way to access a server resource without a more formalized API such as those provided by web services or remote object services. These services can be implemented using any number of server technologies that can get an HTTP request and return XML as the response

Saturday, February 13, 2010

Comparing LCDS ES 2 & BlazeDS

I did take a while to go back and find out the in detail differences between Adobe LCDS and BlazeDS offering - while Sujith Reddy G had it noted down here - It is available officially on Adobe's website here

In plain words, both BlazeDS and Adobe LCDS ES2 offer server side Remoting services(HTTPService, WebService, RemoteObject class), and Servlet based Messaging (MessageBrokerServlet class). LCDS additionally offers sophisticated Data Management services & Messaging services.

LCDS Data Management features are Real Time Data Synchronization & Change Management across clients, SQL Server & Hibernate Adapters and Data Paging & Lazy Loading.

LCDS Messaging features additionally include Real Time Push & NIO based Messaging.

The high level feature differences can be found on Flex Data Access section of Tour De Flex.