Wednesday, October 13, 2010

Flex 4

  1. The Flex 4 SDK requires Flash Player 10 support.
  2. Adobe® Flex® 4 introduces many features including a new skinning and component architecture, a new animations engine, an extended layout mechanism, a new text engine, and a new graphics library.
  3. Flex 4 contains several major features added to the Flex architecture:

  4. The biggest change to Flex 4 is the introduction of a new skinning and component architecture called Spark.
  5. The Spark component architecture has several goals:
  • Define a clean separation between the functional logic of the component and its appearance. Spark components consists of two classes to support the separation of logic and appearance: an ActionScript class that defines a component's logic and an MXML skin class that defines its visual appearance. To change the component's logic, subclass the component class and add your own behavior. To change the component's appearance but not its logic, customize the skin. Flex 4 has also simplified the process of skinning a component. Instead of defining skins in ActionScript, the Spark architecture lets you define skins in MXML.
  • Create a small set of basic components that are easily customized by developers.

    • Spark containers use a swappable layout algorithm that lets you select the layout from a set of predefined layouts. Or, you can define your own custom layout without creating an entire custom container.

    • Implement the Spark components on the same base classes as the components in the previous versions of Flex.

      The new Spark component architecture is based on existing Flex classes, such as mx.core.UIComponent and mx.effects.Effect. Developers upgrading from previous versions of Flex are already familiar with these base classes, which makes the upgrade process simple. This means that you can mix components built with prior versions of Flex with the new Spark components in the same application.

Monday, October 11, 2010

BlazeDS Basics

BlazeDS provides a set of services that lets you connect a client-side application to server-side data, and pass data among multiple clients connected to the server.BlazeDS implements real-time messaging between clients.

A BlazeDS application consists of two parts:
a client-side application
and a server-side J2EE web application.

A BlazeDS client application is typically an Adobe Flex or AIR application. Flex and AIR applications use Flex components to communicate with the BlazeDS server, including the RemoteObject, HTTPService, WebService, Producer, and Consumer components. The HTTPService, WebService, Producer, and Consumer components are part of the Flex Software Development Kit (SDK).


The BlazeDS server runs in a web application on a J2EE application server.

The main features of BlazeDS:
the RPC services and the Messaging Service.

RPC services

The Remote Procedure Call (RPC) services are designed for applications in which a call and response model is a good choice for accessing external data. RPC services let a client application make asynchronous requests to remote services that process the requests and then return data directly to the client. You can access data through client-side RPC components that include HTTP GET or POST (HTTP services), SOAP (web services), or Java objects (remote object services).

Use RPC components when you want to provide enterprise functionality, such as proxying of service traffic from different domains, client authentication, whitelists of permitted RPC service URLs, server-side logging, localization support, and centralized management of RPC services.


A client-side RPC component calls a remote service. The component then stores the response data from the service in an ActionScript object from which you can easily obtain the data. The client-side RPC components are the HTTPService, WebService, and RemoteObject components.


Messaging Service

The Messaging Service lets client applications communicate asynchronously by passing messages back and forth through the server. A message defines properties such as a unique identifier, BlazeDS headers, any custom headers, and a message body.

Client applications that send messages are called message producers. You define a producer in a Flex application by using the Producer component. Client applications that receive messages are called message consumers. You define a consumer in a Flex application by using the Consumer component. A Consumer component subscribes to a server-side destination and receives messages that a Producer component sends to that destination.

Service adapters

BlazeDS lets you access many different persistent data stores and databases including JMS, and other data persistence mechanisms. A service adapter is responsible for updating the persistent data store on the server in a manner appropriate to the specific data store type.

When to use RPC / Messaging Services

BlazeDS uses a message-based framework to send data back and forth between the client and server. BlazeDS uses two primary exchange patterns between server and client. In the first pattern, the request-response pattern, the client sends a request to the server to be processed. The server returns a response to the client containing the processing outcome. The RPC services use this pattern.

The second pattern is the publish-subscribe pattern where the server routes published messages to the set of clients that have subscribed to receive them. The Messaging Service uses this pattern to push data to interested clients. The Messaging Service also uses the request-response pattern to issue commands, publish messages, and interact with data on the server.

To send messages across the network, the client uses channels. A channel encapsulates message formats, network protocols, and network behaviors to decouple them from services, destinations, and application code. A channel formats and translates messages into a network-specific form and delivers them to an endpoint on the server.

Channels also impose an order to the flow of messages sent to the server and the order of corresponding responses. Order is important to ensure that interactions between the client and server occur in a consistent, predictable fashion.

Channels communicate with Java-based endpoints on the server. An endpoint unmarshals messages in a protocol-specific manner and then passes the messages in generic Java form to the message broker. The message broker determines where to send messages, and routes them to the appropriate service destination.

Channel types

BlazeDS includes several types of channels, including standard and secure Action Message Format (AMF) channels and HTTP (AMFX) channels. AMF and HTTP channels support non-polling request-response patterns and client polling patterns to simulate real-time messaging. The streaming AMF and HTTP channels provide true data streaming for real-time messaging.

The main features of BlazeDS:

1> Proxy service : Enables communication between clients and domains that they cannot access directly, due to security restrictions, allowing you to integrate multiple services with a single application. By using the Proxy Service, you do not have to configure a separate web application to work with web services or HTTP services

2> Publish and subscribe messaging

Provides a messaging infrastructure that integrates with existing messaging systems such as JMS. This service enables messages to be exchanged in real time between browser clients and the server. It allows Flex clients to publish and subscribe to message topics with the same reliability, scalability, and overall quality of service as traditional thick client applications.


3> Software clustering

Handles failover when using stateful services to ensure that Flex applications continue running in the event of server failure. The more common form of clustering using load balancers, usually in the form of hardware, is supported without any feature implementation.

A destination is the server-side code that you connect to from the client.

services-config.xml configuration file defines the destinations and channels that the client application uses to communicate with the server.

The Remoting Service is one of the RPC services included with BlazeDS. The Remoting Service lets clients access methods of Plain Old Java Objects (POJOs) on the server.

Ex: Create a Java Class that sends output to client .Compile the java class and place it under WEB-INF/classes/ directoryName.

Define a destination, and reference one or more channels that transport the data. Configure JavaClassName.class as a remoting destination by editing the WEB-INF/flex/remoting-config.xml file.


<destination id="javaDestination" channels="my-amf">

<properties>

<source>DirectoryName.JavaClassName</source>

</properties>

</destination>




The source element references the Java class, and the channels attribute references a channel called my-amf.

Define the my-amf channel in WEB-INF/flex/services-config.xml, The channel definition specifies that the Flex client uses a non-polling AMFChannel to communicate with the AMFEndpoint on the server.


<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">

<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf"

class="flex.messaging.endpoints.AMFEndpoint"/>

<properties>

<polling-enabled>false</polling-enabled>

</properties>

</channel-definition>


The Flex client application uses the RemoteObject component to access JAVACLASSNAME. The RemoteObject component uses the destination property to specify the destination.


// Send the message in response to a Button click.

private function echo():void {

var text:String = ti.text;

remoteObject.javaMethodName(parameters);

}


<mx:RemoteObject id="remoteObject"

destination="javaDestination"

result="resultHandler(event);"

fault="faultHandler(event);"/>




Compile the client application into a SWF file by using Flex Builder or the mxmlc compiler, and then deploy it to your web application.

Messaging Service example

The Messaging Service lets client applications send and receive messages from other clients. In this example, create a Flex application that sends and receives messages from the same BlazeDS destination.

Define the messaging destination in WEB-INF/flex/messaging-config.xml, as the following example shows:


<destination id="MessagingDestination" channels="my-amf-poll"/>






Define the my-amf-poll channel in WEB-INF/flex/services-config.xml, as the following example shows:


<channel-definition id="my-amf-poll" class="mx.messaging.channels.AMFChannel">

<endpoint

url="http://{server.name}:{server.port}/{context.root}/messagebroker/amfpoll"

class="flex.messaging.endpoints.AMFEndpoint"/>

<properties>

<polling-enabled>true</polling-enabled>

<polling-interval-seconds>1</polling-interval-seconds>

</properties>

</channel-definition>







This channel definition creates a polling channel with a polling interval of 1 second. Therefore, the client sends a poll message to the server every second to request new messages. Use a polling channel because it is the easiest way for the client to receive updates. Other options include polling with piggybacking, long-polling, and streaming.

The following Flex client application uses the Producer component to send a message to the destination, and the Consumer component to receive messages sent to the destination. To send the message, the Producer first creates an instance of the AsyncMessage class and then sets its body property to the message. Then, it calls the Producer.send() method to send it. To receive messages, the Consumer first calls the Consumer.subscribe() method to subscribe to messages sent to a specific destination.


<?xml version="1.0"?>

<!-- intro\intro_messaging.mxml -->

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

width="100%" height="100%"

creationComplete="consumer.subscribe();">



<mx:Script>

<![CDATA[

import mx.messaging.events.MessageFaultEvent;

import mx.messaging.events.MessageEvent;

import mx.messaging.messages.AsyncMessage;

import mx.messaging.Producer;

import mx.messaging.Consumer;



// Send the message in response to a Button click.

private function sendMessage():void {

var msg:AsyncMessage = new AsyncMessage();

msg.body = "Foo";

producer.send(msg);

}



// Handle the received message.

private function messageHandler(event:MessageEvent):void {

ta.text += "Consumer received message: "+ event.message.body + "\n";

}



// Handle a message fault.

private function faultHandler(event:MessageFaultEvent):void {

ta.text += "Received fault: " + event.faultString + "\n";

}

]]>

</mx:Script>



<mx:Producer id="producer"

destination="MessagingDestination"

fault="faultHandler(event);"/>



<mx:Consumer id="consumer"

destination="MessagingDestination"

fault="faultHandler(event);"

message="messageHandler(event);"/>



<mx:Button label="Send" click="sendMessage();"/>

<mx:TextArea id="ta" width="100%" height="100%"/>

</mx:Application>



Compile the client application into a SWF file by using Flex Builder or the mxmlc compiler, and then deploy it to your web application.



















Tuesday, April 28, 2009

Loading a web page from Flex

ActionScript 3.0. Developers now have to use the new navigateToURL method to load a web page from a Flex application.The navigateToURL method loads a document from a specified URL. You can use it to load the document in the same or a new browser window, and you can optionally pass variables with the URL.you can also use the method to call a JavaScript function on the web page hosting the SWF file. You can use the navigateToURL method in the following way:

navigateToURL(request, window);

The first argument, request, is a URLRequest object that specifies which web page to load. The
window argument determines how the page loads, and it can be one of the following string values:
_self, _blank, _parent, or _top.

To open the google web site in a new web browser window from a Flex application, you could
use the following lines of ActionScript:

var site:URLRequest = new URLRequest("http://www.google.com");
navigateToURL(site, "_blank");

Sending variables when calling a web page

Some Flex applications need to send variables to the web page that hosts the SWF file.
Whatever your need, one approach is to use the navigateToURL method to pass the values. There are two ways to do this:
1. Append variables to the URL, as in a GET operation.
2. Use a URLVariables object with POST.

You can add querystring variables from Flex by referring to the variable name at the end of the URL, as shown here:

var isbn:String = "1590597338";
var request:URLRequest =
new URLRequest("http://www.friendsofed.com/book.html?isbn=" + isbn);

This has the same effect as using HTTP GET to send form variables.

You can also create a new URLVariables object and pass the variables from Flex that way. The following example shows how to POST username and password variables with a URLRequest:

var site:URLRequest = new URLRequest("http://www.friendsofed.com");
var urlVars:URLVariables = new URLVariables();
site.method = "POST";
urlVars.username = "sas";
urlVars.password= "1234";
site.data = urlVars;
navigateToURL(site);

you’ll need to import the relevant classes, including the following:

import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLVariables;

You can also use the URLVariables class to send values to a server-side script.

Calling JavaScript with navigateToURL

Instead of loading a web page, you can call a JavaScript function with the navigateToURL method. To do this, don’t specify a URL. Use navigateToURL to reference a javascript command or function on the page containing the SWF file:

var jsRequest:URLRequest = new URLRequest("javascript: doWork();");

The preceding line calls the doWork JavaScript function in the web page that hosts the SWF file. Be aware that this approach might not work in all browsers, and security settings might prevent the JavaScript code from executing. A more robust approach is to use the External API.

Sending variables into a SWF file

In some cases, the hosting web page needs to send values into a Flex application. You might do this if you used server-side code to log in and you want to indicate to the Flex application that the user has logged in privileges. You could also use values from the web page to load a specific Flex application state.

there are two main approaches to sending variables into a SWF file so they can be used in your application:

Using querystring parameters when loading the SWF file
Using flashVars

Using querystring parameters
Querystring parameters are name-value variable pairs that are added at the end of a URL or file name;
for example:

mySWF.swf?userID=1234&admin=true

Once you add these parameters to the end of the SWF file name, they are accessible as variables in your Flex application.

Manually adding drag-and-drop support

To support drag-and-drop operations with non-list-based components, or to explicitly control drag and drop with list-based controls, you must handle the drag and drop events.

Classes used in drag-and-drop operations

You use the following classes to implement the drag-and-drop operation:

Class

Function

DragManager

Manages the drag-and-drop operations; for example, its doDrag() method starts the drag operation.

DragSource

Contains the data being dragged. It also provides additional drag management features, such as the ability to add a handler that is called when data is requested.

DragEvent

Represents the event object for all drag-and-drop events.



A component that acts as a drag initiator handles the following events to manage the drag-and-drop operation:

mouseDown and mouseMove,

dragStart

dragComplete.

The mouseDown event is dispatched when the user selects a control with the mouse and holds down the mouse button. The mouseMove event is dispatched when the mouse moves.

dragStart event is Dispatched by a list-based component when a drag operation starts. This event is used internally by the list-based controls; you do not handle it when implementing drag and drop.

dragComplete event is dispatched when a drag operation completes, either when the drag data drops onto a drop target, or when the drag-and-drop operation ends without performing a drop operation.

You can use this event to perform any final cleanup of the drag-and-drop operation.

When adding drag-and-drop support to a component, you must implement an event handler for either the mouseDown or mouseMove event, and optionally for the dragComplete event. When you set the dragEnabled property to true for a list-based control, Flex automatically adds event handlers for the dragStart and dragComplete events.

Drag-and-drop events for a drop target

To use a component as a drop target, you handle the following events:

dragEnter event :

Dispatched when a drag proxy moves over the drop target from outside the drop target.

A component must define an event handler for this event to be a drop target. The event handler determines whether the data being dragged is in an accepted format. To accept the drop, the event handler calls the DragManager.acceptDragDrop() method. You must call the DragManager.acceptDragDrop() method for the drop target to receive the dragOver, dragExit, and dragDrop events.

In the handler, you can change the appearance of the drop target to provide visual feedback to the user that the component can accept the drag operation. For example, you can draw a border around the drop target, or give focus to the drop target.

dragOver event is :

Dispatched while the user moves the mouse over the target, after the dragEnter event.

You can handle this event to perform additional logic before allowing the drop operation, such as dropping data to various locations within the drop target, reading keyboard input to determine if the drag-and-drop operation is a move or copy of the drag data, or providing different types of visual feedback based on the type of drag-and-drop operation.

dragDrop event is dispatched when the user releases the mouse over the drop target.

dragExit event is dispatched

when the user moves the drag proxy off of the drop target, but does not drop the data onto the target.

You can use this event to restore the drop target to its normal appearance if you modified its appearance in response to a dragEnter event or other event.

When adding drag-and-drop support to a nonlist-based component, you must implement an event handler for the dragEnter and dragDrop events, and optionally for the other events.

drag and drop

The drag-and-drop operation lets you move data from one place in an Adobe® Flex™ application to another. It is especially useful in a visual application where you can drag data between two lists, drag controls in a container to reposition them, or drag Flex components between containers.

You can add support for drag and drop to all Flex components. Flex also includes built-in support for the drag-and-drop operation for certain controls such as List, Tree, and DataGrid, that automate much of the processing required to support drag and drop.

The drag-and-drop operation has three main stages: initiation, dragging, and dropping:

Initiation

User initiates a drag-and-drop operation by using the mouse to select a Flex component, or an item in a Flex component, and then moving the component or item while holding down the mouse button. For example, a user selects an item in a List control with the mouse and, while holding down the mouse button, moves the mouse several pixels. The selected component, the List control in this example, is the drag initiator.

Dragging

While still holding down the mouse button, the user moves the mouse around the Flex application. Flex displays an image during the drag, called the drag proxy. A drag source object (an object of type DragSource) contains the data being dragged.

Dropping

When the user moves the drag proxy over another Flex component, that component becomes a possible drop target. The drop target inspects the drag source object to determine whether the data is in a format that the target accepts and, if so, allows the user to drop the data onto it. If the drop target determines that the data is not in an acceptable format, the drop target disallows the drop.

A drag-and-drop operation either copies or moves data from the drag initiator to the drop target. Upon a successful drop, Flex adds the data to the drop target and, optionally, deletes it from the drag initiator in the case of a move.

A single Flex component can function as both the drag initiator and the drop target. This lets you move the data within the component.

You can specify the List control as both the drag initiator and the drop target, you can use drag and drop to rearrange the items in the control. For example, if you use a Canvas container as the drag initiator and the drop target, you can then use drag and drop to move controls in the Canvas container to rearrange them.

Drag and drop is event driven. To configure a component as a drag initiator or as a drop target, you have to write event handlers for specific events, such as the dragDrop and dragEnter events.

The following controls include built-in support for the drag-and-drop operation:

The built-in support for these controls lets you move items by dragging them from a drag-enabled control to a drop-enabled control. However, to copy items, you must add additional logic.

For all list classes except the Tree control, the default value of the dragMoveEnabled property is false, so you can only copy elements from one control to the other. By setting the dragMoveEnabled to true in the first List control, you can move and copy data. For the Tree control, the default value of the dragMoveEnabled property is true.

When the dragMoveEnabled property is set to true, the default drag-and-drop action is to move the drag data. To perform a copy, hold down the Control key during the drag-and-drop operation.

The only requirement on the drag and drop operation is that the structure of the data providers must match for the two controls. In this example, the data provider for srclist is an Array of Strings, and the data provider for the destination List control is an empty Array. If the data provider for destlist is an Array of some other type of data, destlist might not display the dragged data correctly.

You can modify the dragged data as part of a drag-and-drop operation to make the dragged data compatible with the destination.


You can use drag and drop to copy data between two different types of controls, or between controls that use different data formats. To handle this situation, you write an event handler for the dragDrop event that converts the data from the format of the drag initiator to the format required by the drop target.


Drag and drop properties for list-based controls

List-based controls provide properties and methods for managing the drag-and-drop operation. The following table lists these properties and methods:

Property/Method

Description

dropIndicatorSkin

Specifies the name of the skin to use for the drop-insert indicator which shows where the dragged data will be inserted.

The default value is ListDropIndicator.

dragEnabled

A Boolean value that specifies whether the control is a drag initiator. The default value is false. When true, users can drag selected items from the control. When a user drags items from the control, Flex creates a DragSource object that contains the following data objects:

  • A copy of the selected item or items in the control.
    For all controls except for Tree, the format string is "items" and the items implement the IDataProvider interface.
    For Tree controls the format string is "treeItems" and the items implement the ITreeDataProvider API interface.
  • A copy of the initiator, with a format String of "source".
dropEnabled

A Boolean value that specifies whether the control can be a drop target that uses default values for handling items dropped onto it. The default value is false, which means that you must write event handlers for the drag events. When the value is true, you can drop items onto the control by using the default drop behavior.

When you set dropEnabled to true, Flex automatically calls the showDropFeedback() and hideDropFeedback() methods to display the drop indicator.

dragMoveEnabled

If the value is true, and the dragEnabled property is true, specifies that you can move or copy items from the drag initiator to the drop target. When you move an item, the item is deleted from the drag initiator when you add it to the drop target.

If the value is false, you can only copy an item to the drop target. For a copy, the item in the drag initiator is not affected by the drop.

When the dragMoveEnabled property is true, you must hold down the Control key during the drop operation to perform a copy.

The default value is false for all list controls except the Tree control, and true for the Tree control.

calculateDropIndex

Returns the item index in the drop target where the item will be dropped. Used by the dragDrop event handler to add the items in the correct location.

Not available in the TileList or HorizontalList controls.

hideDropFeedback()

Hides drop target feedback and removes the focus rectangle from the target. You typically call this method from within the handler for the dragExit and dragDrop events.

showDropFeedback()

Specifies to display the focus rectangle around the target control and positions the drop indicator where the drop operation should occur. If the control has active scroll bars, hovering the mouse pointer over the control's top or bottom scrolls the contents.

You typically call this method from within the handler for the dragOver event.



Monday, April 27, 2009

AdvancedDataGrid control

The AdvancedDataGrid control expands on the functionality of the standard DataGrid control to add data visualization capabilities to your Adobe® Flex™ application.

The following table describes the main data visualization capabilities of the AdvancedDataGrid control:

Capability

Description

Sorting by multiple columns

Sort by multiple columns when you click in the column header. For more information, see Sorting by multiple columns.

Styling rows and columns

Use the styleFunction property to specify a function to apply styles to rows and columns of the control. For more information, see Styling rows and columns.

Displaying hierarchical and grouped data

Use an expandable navigation tree in a column to control the visible rows of the control. For more information, see Hierarchical and grouped data display.

Creating column groups

Collect multiple columns under a single column heading. For more information, see Creating column groups.

Using item renderers

Span multiple columns with an item renderer and use multiple item renderers in the same column. For more information, see Using item renderers with the AdvancedDataGrid control.



To disable sorting for an entire AdvancedDataGrid control, set the AdvancedDataGrid.sortableColumns property to false. To disable sorting for an individual column, set the AdvancedDataGridColumn.sortable property to false.

The way that you sort multiple columns is based on the setting of the sortExpertMode property. By default, the sortExpertMode property is set to false. This setting means that you click in the header area of a column to sort the rows of the AdvancedDataGrid control by that column. Then you click in the multiple column sort area of the header to sort by additional columns. To use the Control key to select every column after the first column to perform sort, set the sortExpertMode property to true.

DataGrid control

The DataGrid control is like a List except that it can show more than one column of data making it suited for showing objects with multiple properties.

The DataGrid control provides the following features:

  • Columns of different widths or identical fixed widths
  • Columns that the user can resize at runtime
  • Columns that the user can reorder at runtime
  • Optional customizable column headers
  • Ability to use a custom item renderer for any column to display data other than text
  • Support for sorting the data by clicking on a column
The DataGrid control is intended for viewing data.