Posts Tagged Flex

Updating server after DataGrid edits – Dealing with event handler priorities

In this example we’re looking at sending a server request to update data from a Flex DataGrid after a user has edited a field. What we want to do is automatically save the data to the backend when a user leaves an editable field.

The datagrid fires off an event when the user is done editing. Setting up a handler for  DataGridEvent.ITEM_EDIT_END can be done right on the MXML or in ActionScript. The MXML version is very straight forward.

<mx:DataGrid 
id=”dg”
dataProvider="{dgCollection}" 
itemEditEnd="endHandler(event)"
editable="true">

 

The problem here is that this fires before the datagrid updates the data provider with the edits. In this case the endHandler function only has access to the original values.

As Paul Robertson notes in his article on this the DataGrid registers its own handler for this event. When adding event handlers you can optionally add a priority, and in this case the DataGrid handler is –50 in priority and our endHandler is using the default 0. Which means our function fires before the datagrid’s function.

In order to gain access to the updated results on the dataprovider we need to register our handler AFTER the datagrid updates the provider. To do this we need to switch over and user the ActionScript moethod of handler registration instead of the MXML style.

We register our handler in ActionScript with a priority less than –50

dg.addEventListener(
    DataGridEvent.ITEM_EDIT_END, 
    endHandler,
    false,
    -100);

Now when endHandler fires it will be accessing the updated values

 

Here is the complete code

 

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768"
              creationComplete="creationCompleteHandler(event);">
    <fx:Declarations>
        <mx:RemoteObject id="ro" destination="DGSource" result="resultAllEvents" />
    </fx:Declarations>
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.events.FlexEvent;
            import mx.rpc.events.ResultEvent;
            import mx.events.DataGridEvent;
            [Bindable]
            private var dgCollection:ArrayCollection;
           private function creationCompleteHandler(event:FlexEvent):void
            {
                dg.addEventListener(DataGridEvent.ITEM_EDIT_END, endHandler,false,-100);
            }
            private function resultAllEvents(evt:ResultEvent):void
            {
                var e:ArrayCollection = evt.result as ArrayCollection;
                dgCollection=e;
            }
            public function endHandler(event:DataGridEvent):void
            {
                ro.saveOrUpdateEvent(dg.selectedItem);
            }

        ]]>
    </fx:Script>
    <mx:Button x="168" y="10" label="Get Events" width="343" click="ro.getOperation(‘findAll’).send();" height="21"/>
    <mx:DataGrid
        dataProvider="{dgCollection}" 
       id="dg" editable="true"
        >
        <mx:columns>
            <mx:DataGridColumn headerText="Date" dataField="date"/>
            <mx:DataGridColumn headerText="Title" dataField="title"/>           
        </mx:columns>
    </mx:DataGrid>
</s:Application>

, , , , , , ,

Leave a Comment

Flex development on the cheap (free)

imageWhen introducing Flex in my organization there was a bit of pushback on the Flex Builder licenses. Being the Java shop the we are, free is just the way it works. We’re so used to using free tools like Eclipse that we question paying for anything. This reminded me of when I was trying to learn ActionScript way back and had to have a copy of Flash to work through things.

 

So here you are, don’t want to buy Flex Builder but you do want to learn flex. Sure there is a 30day trial but what will you do after that?

There are a few tools available that allow you to code in ActionScript / Flex for free. One of the popular ones is FlashDevelop is imagea free IDE for developing apps for the Flash Platform. FlashDevelop is a basic IDE that provides code insight, project management, and integrated compilation. There are a few steps to install,such as pointing to the Flex3 SDK and the location of your Flash Player, but that’s it.

Create a new project, write some code and you’re good to go. Flex development with no strings attached.

Check out FlashDevelop, it’s a great tool for Flex development.

, , ,

Leave a Comment

Connecting Flex to Java with BlazeDS

BlazeDS offers a great mechanism to attach your flex application to backend services. In this brief overview we’ll configure flex to call a Java Class and return results. This overview assumes you’ve already setup your IDE with a basic Flex / BlazeDS project.

Main points we’ll cover

  • Build the Java Class
  • Expose the Class with Blaze on the server
  • Configure Flex to find the Blaze service
  • Build the Flex components to make the call

Build the Java Class

In your IDE switch to the Java view and create a new Java class. We’ll call it HelloFlex. Create a private variable called message. Set an initial value for this variable in the constructor. Finally create a getter method that returns the message string.

package com.grant;

public class HelloFlex {
private String message;
public HelloFlex(){
message=”HI Flex. this is Java. How are you?”;
}
public String getMessage(){
return message;
}
}

 

Expose the class with BlazeDS on the server

Under your web-inf directory you’ll fine a subdirectory called flex. Within there you’ll see the main config files blaze uses to set up the services. services-config.xml is the main file and has statements to include the others. For this example we’re creating a simple remoting service, so go ahead and open up the  remoting-config.xml. Here’s where we’ll set up the configuration for our reomting service.

Blaze calls exposed services destinations. In this remoting-config.xml we’ll set up a destination that points to our HelloFlex class.

Under the default-channels create a new destination as follows.

<?xml version=”1.0″ encoding=”UTF-8″?>
<service id=”remoting-service”
class=”flex.messaging.services.RemotingService”>

<adapters>
<adapter-definition id=”java-object” class=”flex.messaging.services.remoting.adapters.JavaAdapter” default=”true”/>
</adapters>

<default-channels>
<channel ref=”my-amf”/>
</default-channels>

<destination id=”helloflex”>
<properties>
<source>com.grant.HelloFlex</source>
</properties>
<adapter ref=”java-object” />
<channels>
<channel ref=”my-amf” />
</channels>
</destination>
</service>

 

Configure Flex to find the BlazeDS Service

Depending how you set up your workspace that set may already be done for you. In order for flex to know what channels and destinations are available, our application needs to know where these config files are. In Java, these files are in the class path and are included in the build process. In Flex we need to explicitly tell the compiler where these files are.

Right click on the project and choose properties. Under flex compiler you’ll see a textbox for additional compiler arguments. To configure the file location you’ll need an argument here called services which points to the location of your xml files.

You have two options now.

image1) If the folder is part of your flex build path you can make a relative reference to the file using the –services=<file> format as follows. Notice the web-inf directory is not included in the definition. In this the folder containing the flex subfolder is on my build path.

2) If the folder is NOT on your build path you can point to the file location. This is the default method that FlashBuilder implements. We’ll use it for this example, however I suggest imageyou move to a relative location style as soon as you can.

For an explicit file system location the flex option is slightly different. Here we use the –services “<file Location>” format. On my drive the option reads –services “C:\FlashBuilder\dev\MyProject\WebContent\WEB-INF\flex\services-config.xml”

 

Build the Flex components to make the call

Now we can get back to our flex components and make the actual call. First flip back over to your Flex Perspective and open your main mxml file.

First we’ll define the service:

<mx:RemoteObject id=”myService”  destination=”helloflex” />

The id is the name you’ll reference this service elswhere in your flex app. The destination of helloflex needs to match the destination name you entered in your remoting-config.xml

Next we’ll move to some visual components. First lets add a panel to hold our controls.

<s:Panel width=”100%” height=”100%”>
<s:layout>
<s:VerticalLayout/>
</s:layout>

</s:Panel>

And add a text box to display some results

<s:Panel width=”100%” height=”100%”>
<s:layout>
<s:VerticalLayout/>
</s:layout>

<mx:TextArea id=”result_text”/>

</s:Panel>

Now we’ll add a button on the page to use the service

<s:Panel width=”100%” height=”100%”>
<s:layout>
<s:VerticalLayout/>
</s:layout>

<mx:TextArea id=”result_text”/>
<mx:Button label=”Call Java” click=”myService.getOperation(‘getMessage’).send();”/>

</s:Panel>

This is a direct use of the RemoteObject myService. This is not a best practice. Typically you would have a function managing your calls and the button would utilize that function. For simplicity sake I’ve included the direct call for this demonstration. In this example you’ll notice we use the getOperation function and pass in the java method name we want to call.

If you were to run this now you would see no results. We have yet to define what happens when the service gets called. Lets do that now.

Create a script block to hold our action script and add a simple method that puts the response of our service in our textbox.

<fx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
private function resultHandler(evt:ResultEvent):void
{
result_text.text = evt.message.body.toString();
}
]]>
</fx:Script>

To use this function we’ll go back to the service and add a handler to manage all responses.

<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
<!– DEFINE REMOTE SERVICES WE’LL USE –>
<mx:RemoteObject
id=”myService”
destination=”helloflex”
result=”resultHandler(event)” />
</fx:Declarations>

 

Your completed code should look like this

 

<?xml version=”1.0″ encoding=”utf-8″?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/halo” minWidth=”1024″ minHeight=”768″>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
<!– DEFINE REMOTE SERVICES WE’LL USE –>
<mx:RemoteObject
id=”myService”
destination=”helloflex”
result=”resultHandler(event)” />
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
private function resultHandler(evt:ResultEvent):void
{
result_text.text = evt.message.body.toString();
}
]]>
</fx:Script>
<s:Panel width=”100%” height=”100%”>
<s:layout>
<s:VerticalLayout/>
</s:layout>
<mx:TextArea id=”result_text”/>
<mx:Button label=”Call Java” click=”myService.getOperation(‘getMessage’).send();”/>
</s:Panel>

</s:Application>

 

That’s it! Run the application and pat yourself on the back. Congratulations! Your first end to end Flex-Java app.

 

image

, , , , , , , ,

1 Comment

Setting up Flex BlazeDS in FlashBuilder

One of the most compelling aspects of Flex is its ability to integrate with a wide variety of data sources. Many of the introductory tutorials online teach how to connect to http services to pull data. The result is typically an XML response. Flex makes it easy to manage XML but there are better ways. using XML requires an object on the server to be serialized to a text format which adds processing time. The response is also larger due to the variety of XML tags that need to be added in order to properly represent the object’s structure. Yes I hear you in the back telling me that JSON is a lighter weight response that doesn’t require all the tags. Regardless the response still needs to be parse out in the client. Finally the contract between client and server is not well defined with straight XML or JSON. Web services do provide a strict contract for the interface that the client can rely on but  the objects are still serialized with extraneous tags used to define the structure.

BlazeDS utilizes AMF to provide direct links between client and server objects. AMF provides access to objects through a binary protocol and eliminates the need to add additional tags that identify the object structure. It also reduces the work in flex to get the data back into a usable flex object.

Lets start working through an example by getting our workspace setup.

 

Initial Setup

Flex and Java both need to know about BlazeDS and where to look for the libraries and configuration files. FlashBuilder lends a hand with this by automating some of the process.

First things first, you’ll need to have FlashBuilder installed. The beta version can be downloaded at http://labs.adobe.com/technologies/flashbuilder4/.  Also check to make sure you have the WTP extensions installed in eclipse so you can automate creating the web application structure.

Finally for this IDE example we’re going to download the BlazeDS war from adobe at: http://opensource.adobe.com/wiki/display/blazeds/Release+Builds Just download the binary version, we don’t need the full turnkey for this. Once you have it downloaded, extract it to your drive, you should see the blazeds.war when you’re done.

In FlashBuilder create a new Flash project. Select J2EE Application server type. Select Remote object access with BlazeDS and the type. Select create combined Java/Flex using WTP. Click next.

image

 

On the next page, for the BlazeDS WAR file, point to the location where you extracted the files from Adobe. The system will pull all the jar files and configs from this war and add them to your project. Click finish.

image

You’ll notice that FlashBuilder loaded all the Jars and Config files as well as setting up the web.xml.image

The web.xml tells java where to find the config files that BlazeDS needs. Remembering that Flex and Java are compiled separately and both need to know where configuration files are, lets find out where the IDE tells Flex about the config files.

Looking under the project properties under flex compiler you’ll see a compiler option is added for services.

image

NOTE: Without this compiler option Flex would not be able to find the BlazeDS services. When setting up blazeDS manually this flag will needed to be added by hand.

Java vs Flex: In Java the config files are loaded at run time. To change a value in the property file you simply need to restart the server to make it take effect. In Flex however this is a compile time include which means any changes to the files will need to be rebuilt into the application. Just a little note that may save you some headaches later.

 

That’s is for the setup.

Next time we’ll look at the code needed to use BlazeDS.  Stay tuned.

, , , , , , ,

5 Comments

Follow

Get every new post delivered to your Inbox.

Join 473 other followers