« June 2007 | Main | August 2007 »

July 2007 Archives

July 3, 2007

The advantages of going open source with Flex 3

As you probably know, Flex 3 is gonna be open source. But many developers are asking what that means.
There is a great interview by HowSoftwareisbuilt to Phil Costa who is the Director of Product Management for Flex and ColdFusion at Adobe, with responsibility for product definition and strategy of the Flex product line.

This is the answer Phil gave to the question : What are the advantages of going with more of an open source model — what are the advantages of taking something that hasn’t been open source and open sourcing it?

There are a few different elements to it. First, there’s the nature of the product itself. The core part of the product is try hard to internally test, and get all the bugs out, because it’s a development framework. By its nature, it gets used in a million different ways. It’s very hard to actually set up tests for all those ways and to chase down all the bugs.

So having an open source model will actually help us by having more people looking at the code and suggest changes based on their particular use-case. In one respect, we view it as a way of magnifying the QA resources we have, and also magnifying some of the bug-fixing resources. So, that’s a very tactical thing, but that is a proven advantage of an open source project.

The second element refers more to the evolution of the product. We’ve always tried to be very customer-centric in terms of designing the product, working with early adopters, niche users, and new users, to determine what things we should be adding to the product, to make sure that it fits their needs, both on the learning-curve side as well as the power-user side.

We decided that having a group of people who can directly influence that — or at least feel more deeply invested in it — was a good way to continue to evolve the product. With a developer product, the people who develop the product are also the users of the product, and there’s a very efficient feedback loop.

The third piece is more PR and marketing focused. Because people have to make a substantial investment in Flex — in terms of spending a lot of time developing an application and then making their application dependent on the Flex framework — they’re looking for an open source project or a set of standards. In the rich-ended application space, there aren’t really any standards, per se. They’re mostly looking for open source or de facto standards.

It’s become increasingly apparent, as the market has grown up, that to be successful as a platform you need to be an open source project, so that people view the product as being bigger than one individual company, or in some cases one individual product team. In a lot of ways, that was another requirement that more and more customers were raising; they love Flex but they wanted it to be bigger than just Adobe.

July 6, 2007

Creating an ObjectManager for improving the Flex interaction with Ajax or Javascript

In the latest years the growing demand for Rich Internet Applications submitted the following question to the developers' community: which to choose between the Ajax + JavaScript solution on one hand, and the Flash player based Adobe Flex technology on the other hand? The choice is definitely hard, as in most cases both solutions are suitable without particular indications or limitations, and we can insert both Ajax and Flex with no difficulty in the same web pages and applications in case of particular requirements.

What if we want that Flex interacts with Ajax/JavaScript in the same application to render a virtually unlimited user experience? What if we need our Flex application interacts with third parties' applications (e.g. Google Maps)?

Flex Ajax Bridge is a free small library which in such circumstances allows the developer to save many lines of code. Through Flex Ajax Bridge , which is now included in Adobe LiveCycle Data Services 2.5, you can make your ActionScript classes available to JavaScript without any additional coding. After you insert the library, essentially anything you can do with ActionScript, you can do with JavaScript.

While the functionalities offered by the External Interface class of the Flash Player can solve the easiest cases of ActionScript/JavaScript interaction, it is advisable to use the FABridge (Flex Ajax Bridge) in the most complex situations, in presence of user-defined classes or when we should define an interface to make JavaScript dialog with ActionScript and vice-versa.

In both cases we would face a little limit: it causes a problem trying to access Flex component just after html loads using body tags onload attributes while the swf files is not loaded yet.

It seems a marginal issue, but quite often it happens that our Flex movie will be initialized after the onload event is launched.

A possible solution could be the one of waiting a few seconds by using the Javascript function setTimeout(code,millisec,lang) , however what assures the movie will be ready in that time? If the movie were not ready, either an error is generated or the input to the Flex component goes lost.

The solution on the Flex 3 side is to make our Flex application disabled by using JavaScript :

To get the DOM object of our SWF file we'll use the ExternalInterface class standard function:

function thisMovie(movieName) {

if (navigator.appName.indexOf("Microsoft") != -1) {

return window[movieName];

} else {

return document[movieName];

}

}

In Flex we register the ActionScript method we want to call from the JavaScript side with the addCallback method :

ExternalInterface.addCallback("disableApplication", disableFunction);

We could call the method registering it on the creationComplete Flex event or any other system event.

Then we invoke the function that will call the method exposed by the ExternalInterface class, disableApplication in our case :

function disableMovie(movieName) {

var myMovie = thisMovie(movieName);

if(myMovie == null || myMovie.disableApplication == null)

{

setTimeout("disableFilter("+movieName+")", 100);

}

else

{

myMovie.disableApplication();

}

}

If the SWF file has not been loaded yet or the ExternalInterface.addCallback function has not been invoked on the Flex side, the movie will wait 100 milliseconds to disable the application again.

This method is known as busy waiting, and it's not a CPU intensive processing method, but it continuously calls the JavaScript function until it gets the value.
It's easy to implement this solution for small applications but it has several problems as soon as more and more applications run concurrently or there are race conditions. A more complicated solution to solve some of these problems can be to use some global variables to hold the objects returned by setTimeout() function, so we could call a clearTimeout() when needed.
As you can note, this method could generate unwanted effects when there are several functions and a medium size application.

This example is based on the ExternalInterface class but such a problem comes in also when using Flex Ajax Bridge, as mentioned in the Adobe Labs Wiki.

In the next part of the post we'll create an ObjectManager in JavaScript to handle this issue.

July 12, 2007

Building a Rest Server with Zend and retrieve data with Flex and the HTTPService

Representational State Transfer (REST) architectural style for distributed hypermedia systems can be a new model for web services construction. REST is not a standard, because REST is just an architectural style, you can't bottle up that style, you can only understand it, and design your Web services in that style.
The REST web services architecture is related to the Service Oriented Architecture. This limits the interface to HTTP with the four well-defined verbs: GET, POST, PUT, and DELETE. REST web services also tend to use XML as the main messaging format.

In this post we want to illustrate how simple and efficient are an implemantation of a web service using Zend Framework and Flex to represent the data retrieved.

The Zend Framework provides both REST Client and Server capabilities. The Server component features automatic exposition of functions and classes using a meaningful and simple XML format. When accessing these services using Flex, it is possible to easily retrieve the return data from the remote call and will still provide easier data access.

You must have installed the Zend Framework and configured for your web server, you can find instrunctions on the Zend website.

On the server side you must provide a php function to call from Flex like this, in this example we provide the sayHello function:


<?php>
require_once 'Zend/Rest/Server.php';

/**
* Say Hello
*
* @param string $who
* @param string $when
* @return SimpleXMLElement
*/
function sayHello($who, $when)
{
    $xml ='<?xml version="1.0" encoding="ISO-8859-1"?>
    <mysite>
        <value>Hey $who! Hope you're having a good $when</value>
        <code>200</code>
    </mysite>';

    $xml = simplexml_load_string($xml);
    return $xml;
}

$server = new Zend_Rest_Server();
$server->addFunction('sayHello);

$server->handle();
</php>


On the Flex side we must provide an HTTPService that point to the http://yourSite/restClass.php, and providing the necessary parameter for sayHello function, who and when, and also we must provide the method parameter that represent the function to invoke.


<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
creationComplete="{myRestService.send()}">

<mx:HTTPService
id="myRestService"
url="http://yourSite/restClass.php"
result="myResult(event)">
        <mx:request>
            <method>sayHello</method>
            <who>Boy</who>
            <when>day</when>
        </mx:request>
    </mx:HTTPService>
    
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
private function myResult(event:ResultEvent):void {

Alert.show( String ( event.result.mysite.value ) );

}
]]>
</mx:Script>
    
</mx:Application>


This is the simple step to implement a REST web services using the Zend Framework.
Zend Framework also provide a lot of features like a cache system to improve performance of your query.

July 20, 2007

Conditional visualization in Cairngorm 2.x using the ChangeWatcher class

Data Binding is one of the most important and powerful flex features and the Cairngorm framework makes a full use of it in its Model View Controller design pattern.
In a standard and simple use of Cairngorm we have a view with some controls with dataProviders directly bound to the ModelLocator, if you don't have a clear view of how these things work you'll have a better outlook viewing the diagram on cairngormdocs.org

Sometimes we want to have in a view only some data that satisfies certain conditions, we have to filter the collection before passing it to the view. Flex gives the possibility to use a filter function associated to the collection; if you are considering a small application this is a viable solution but in an Enterprise RIA application probably we cannot apply a filter function, because that data source can be a data provider for different views that need the complete collection.
The flex ChangeWatcher class provides a complete different solution. From the flex 2 api: “
The ChangeWatcher class defines utility methods that you can use with bindable Flex properties. These methods let you define an event handler that is executed whenever a bindable property is updated.”

Let'see a tipical view in Cairngorm:

<MyView ... >

 <mx:DataGrid dataProvider=”{MyModelLocator.getInstance().myDataSource}”
itemRenderer=”MyItemRenderer” />

</MyView>

seq1.png


We have no way to intercept changes in the data source because the data binding will make changes effective in the view instantaneously.
Using the ChangeWatcher and the view helper we interpose a layer that prepares the data before sending them to the view.


The new View:


<MyView ... >

 <MyViewHelper id="myViewHelper" />

 <mx:ArrayCollection id=”myDataProvider” />

 <mx:DataGrid dataProvider=”{myDataProvider}”
itemRenderer=”MyItemRenderer” />

</MyView>


The ViewHelper:

package ...
{
...

 public class MyViewHelper extends ViewHelper
 {
   private var myChangeWatcher:ChangeWatcher;

   public function MyViewHelper() {

    myChangeWatcher = ChangeWatcher.watch(MyModelLocator.getInstance(), “myDataSource”, prepareDataProvider);
   }


   private function prepareDataProvider(event:Event) {

    var myAC:ArrayCollection = new ArrayCollection();
    for each(var item:Object in MyModelLocator.getInstance().myDataSource) {
     //if item satisfies certain conditions
     myAC.addItem(item);
    }
    view.myDataProvider = myAC;
   }

  }
}
seq2.png


Every time the data source is updated, the handler is called and the collection is filtered. It is convenient that the responder updates the entire collection at once and not adding items one by one, because the handler would be called every time. To stop watching the data source you can call the unwatch() function on the changeWancher instance in the ViewHelper.
This is only one of the possible solutions we can use thanks to the flexibility of data binding.

July 26, 2007

LiveCycle Data Services and Hibernate integration in Flex RIA applications

RIA applications allow client applications to absolve the back-end server from part of its activities, allowing a more equal balance between them. Using Flex, clients grow to become standalone applications, that connect to a server and perform the required operations. LiveCycle Data Services is a remarkable Adobe product as it allows Flex clients to easily connect to JavaEE based servers and manipulate data in many easy ways. In this post we will see how to use LiveCycle Data Services as an intermediary between a Flex client and a Hibernate server layer; the application domain will contain only a domain class, that will be persisted by Hibernate; we will define a named query in the Java layer and use the named query directly from a Flex client.
In the example we have a domain class Contact, with information such as name, surname, email, birth date. The Java server will have a Java bean class domain.Contact and also a Hibernate mapping file that defines how the domain class is persisted on a database.
The mapping file will also contain a named query, in HQL (Hibernate Query Language) for simplicity, that will return all the contacts.
Contact.hbm.xml:

<hibernate-mapping>
 <class name=\"domain.Contact\" table=\"contact\">
  <id name=\"id\"><generator class=\"native\" /></id>
  <property name=\"name\" />
  <property name=\"surname\" />
  <property name=\"email\" />
  <property name=\"birthDate\" column=\"birthDate\" type=”date” />
 </class>
 <query name=\"contact.all\">
  <![CDATA[
   FROM Contact
  ]]>
 </query>
</hibernate-mapping>

The generated JAR archive will have to be deployed within a LiveCycle Data Services context, that is a LCDS web application deployed in the Tomcat webapps/ folder, configured for use with Hibernate. The JAR file will be part of the web application libraries and, on deploy, if well configured, will take care of connecting to the database and create or update the required tables.

For the client we have to create a Flex Data Services Project that points to the previously created LCDS web application and, before developing the Flex client, edit the LiveCycle Data Services configuration files to reflect the services we want to export from our LCDS enabled JavaEE server.
To use the data capabilities we need to add a data destination to data-management-config.xml, that will allow LiveCycle Data Services to handle our domain classes in a transparent and efficient way.
The destination added to data-management-config.xml:

<destination id=\"hibernateContact\">
 <adapter ref=\"java-dao\" />
 <properties>
  <source>flex.data.assemblers.HibernateAssembler</source>
  <scope>application</scope>
  <metadata>
   <identity property=\"id\"/>
  </metadata>
  <network>
   <paging enabled=\"true\" pageSize=\"10\" />
   <throttle-inbound policy=\"ERROR\" max-frequency=\"500\"/>
   <throttle-outbound policy=\"REPLACE\" max-frequency=\"500\"/>
  </network>
  <server>
   <hibernate-entity>domain.Contact</hibernate-entity>
   <update-conflict-mode>PROPERTY</update-conflict-mode>
   <delete-conflict-mode>OBJECT</delete-conflict-mode>
   <fill-configuration>
    <use-query-cache>false</use-query-cache>
    <allow-hql-queries>true</allow-hql-queries>
   </fill-configuration>
  </server>
 </properties>
</destination>

We can see in this last configuration sample part of what’s behind the curtains; for start, hibernate-entity holds the full name of the Java domain class and identity property is the property that is the unique id of the Java domain class. By providing flex.data.assemblers.HibernateAssembler as destination source we basically let LCDS handle almost everything about the domain classes, as long as related to data management. The HibernateAssembler provides full support for Hibernate entities as Flex data destinations. It can, of course, be extended to get a better control, but it can be used as is, allowing to forget about any persistence problems and head straight to the Flex client development.
The fill-configuration section contains configuration that defines how data fill is handled from server on client request. Additionally, the allow-hql-queries attribute allows to decide if the Flex client can have direct access to HQL queries related to the current destination. The client can send query strings or call named queries and then directly receive data, while the HibernateAssembler and LiveCycle Data Services deal internally with all other operations.

A Flex value object class needs to be defined, that reflects the Java domain class, with all of its properties:

package client.domain
{
 [RemoteClass (alias="domain.Contact")]
 public class ContactVO {
  â€¦
 }
}

We can define an array collection, that will hold incoming data, as an array of ContactVO:

[Bindable]
var:ArrayCollection = new ArrayCollection();

a data service that will connect to the remote server, through LiveCycle DS:

var = new DataService("hibernateContact");
dataService.autoCommit = false;
dataService.autoMerge = false;
dataService.autoSyncEnabled = false;

The data service is created to connect to the specified destination, the one configured in the data-management-config.xml file.

Finally a data grid will display the data from the server:

<mx:DataGrid id=\"dg\" dataProvider=\"{arrayCollection}\" />

And to get all together and working, one line of code will connect the data service to the remote destination, call a remote named query and get the data into a local array collection:

dataService.fill(arrayCollection, "contact.all", []);

Calling fill() on the data service will use the fill configuration defined in the data management file, that permits the use of named queries, and ask for all Java Contact objects, that will arrive as Flex ContactVO objects and will be placed into the array collection.
If the named query would have required a parameter, for example it would be provided as third parameter of the fill() function, just inside the array that now is empty [].
LiveCycle Data Services and Hibernate can work together very well, after some configuration procedures, together they cover up everything from data persistence to data management in Flex clients.

Obviously, in order to hide server side logic and structure, it is better to use named queries instead of plain queries, just like the one defined in the hibernate-mapping snippet above. The Flex DataService class, like any AbstractService class, has the setRemoteCredentials() method that provides means to authenticate a request to a LiveCycle DS remote server, but this is subject for another blog entry.

About July 2007

This page contains all entries posted to Comtaste Consulting | Enterprise RIA consulting and development in July 2007. They are listed from oldest to newest.

June 2007 is the previous archive.

August 2007 is the next archive.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33