Import a service and bind data to application components
The relationship between client code and server code in
Flex differs from the traditional relationship in a server template.
In a traditional relationship, a server template mixes server
code with client code. When the client queries a database, it dynamically
embeds HTML code with returned data.
Flex, however, separates client code from server code. The remote
service returns only data. Flex binds the returned data to user
interface components in the client application.
This tutorial shows how to create a client application that imports
a ColdFusion service. You first create a Label item that displays
static text. Next, you create a ColdFusion service that returns
a localized text string. Then, you bind the data returned from the
ColdFusion service to the Label item. Finally, you examine the generated
code to see how Flex accesses the data returned from the service.
Create the applicationIn Flash Builder, select File > New > Flex
Project.
Specify HelloCF for the project name, set Application Server
Type to ColdFusion, and specify ColdFusion Flash Remoting.
Click Next. Verify your ColdFusion server configuration and
click Validate Configuration.
Click Finish.
The Flash builder source editor opens
to Hello.mxml.
If Design mode is not selected, select Design to switch to
Design mode of the editor.
In the Components View, make sure that the Controls folder
is open. Scroll the controls to find the Label control.
 Label control in the Controls folder
Drag a Label component from the Components View to the design
area.
Double-click the Label component. Replace the default text
with Hello.
In the Properties view, modify the appearance of the text.
With the Label component selected, specify the following:
Font Size
|
24
|
Font Attribute
|
Bold
|
Font Attribute
|
Italic
|
 Select the font attributes
Click the Font Color box and specify #ff0000 to
change the text to Red.
Save the file. Click the Run button to run the application.
The application
runs in a web browser.
Create a ColdFusion service that returns localized stringsCreate a ColdFusion component (CFC) that can be accessed
as a service by Flex over the Internet.
Code the following CFC:
<cfcomponent>
<cffunction name="getMessage" access="remote" returntype="string">
<cfset message = "Hello from CF!">
<cfreturn message>
</cffunction>
<cffunction name="getLocalizedMessage" returnType="string" access="remote">
<cfargument name="locale" required="yes"/>
<cfswitch expression="#locale#">
<cfcase value="en">
<cfset message = "Hello from CF!"/>
</cfcase>
<cfcase value="es">
<cfset message = "Hola de CF!"/>
</cfcase>
<cfcase value="ne">
<cfset message = "Namaskar CF bata!"/>
</cfcase>
<cfdefaultcase>
<cfthrow message="Unknown locale code"/>
</cfdefaultcase>
</cfswitch>
<cfreturn message>
</cffunction>
<cffunction name="getLocales" returnType="array" access="remote">
<cfset codes = listToArray("en,es,ne")/>
<cfreturn codes>
</cffunction>
</cfcomponent>
The function getMessage() is
a service operation that client applications access.
Make
sure to specify remote as the access type for the function.
Save the CFC as HelloService.cfc in your
web root. Place it in a folder named HelloCF. <CF Web Root>/HelloCF/HelloService.cfc
(Optional) Test the ColdFusion serviceThere are various ways to test the service before you access
it from an application.
Create a ColdFusion script file, helloservicetest.cfm,
that calls the service and displays the returned data in HTML.
Use
the cfinvoke tag to call the service.
Use
the cfdump tag to view the results.
Testing getLocales()...
<cfinvoke component="HelloService" method="getLocales" returnvariable="locales"/>
<p> Result: <cfdump var="#locales#"/> </p>
Testing getLocalizedMessage("es")...
<cfinvoke component="HelloService" method="getLocalizedMessage" locale="es" returnvariable="message"/>
<p> Result: <cfdump var="#message#"/> </p>
Save helloservicetest.cfm in the same folder
as HelloService.cfc, and call the script from a
web browser:
http://localhost:8500/HelloCF/helloservicetest.cfm
If there
is an error in the service, ColdFusion displays detailed information about
the error.
You
can also enable Robust Exception Information for the ColdFusion
server to get detailed debugging output.
Add trace statements to the service.
In the ColdFusion
Administrator, enable debugging and logging.
Add ColdFusion
trace statements as necessary to debug your service. For example,
add the following line in helloservicetest.cfm:
Testing getLocalizedMessage()...
<cfinvoke component="HelloService" method="getLocalizedMessage" returnvariable="message"/>
<cftrace category="getLocalizedMessage End" inline="yes" var="message" text="GetLocalizedMessage call has completed">
. . .
Call the script from a web browser to view the
debugging output. You can also inspect the ColdFusion log files.
Call a function in the service directly from a URL.
For
example, call getLocalizedMessage() with the parameter es: http://localhost:8500/HelloCF/HelloService.cfc?method=getLocalizedMessage&locale=es
Connect to the ColdFusion serviceIn Flash Builder, connect to the ColdFusion service and
bind the data returned from the service to the Label component.
In Design mode of the MXML editor, make sure Hello.mxml is
open. From the Flash Builder Data menu, select Connect To Service.
Select ColdFusion as the service type. Click Next.
Click Browse and navigate to the HelloService.cfc you
previously created. Flash Builder names the service HelloService.
Click Finish. Provide your credentials to log in to the ColdFusion
database.
The Data Services View now displays your ColdFusion
service.
 Data Services View  The Data Service View provides a picture of remote
services. This view becomes useful when you configure types for
data returned by a service call.
Select the Label component in the design area. From the context
menu, select the Bind to Data button for the Label component.
Select OK to replace the current text with the text returned
from a service operation.
 Flash Builder provides
various ways to bind data to a selected component. In addition to
the Properties view, you can bind to data from the context menu.
You can also select Bind to Data from the Flash Builder Data menu.
In the Bind to Data dialog, make sure that New Service Call
is selected. For Operation select getLocalizedMessage.
Click OK.
 Select the operation for binding data Flash
Builder switches the editor to Source mode, highlighting the parameter to getLocalizedMessage().
Type "es" for the parameter value
for getLocalizedMessage(). Switch to Design mode of the editor.
 Design mode showing data binding
Save and run the application.
The Label component displays
the message retrieved from the HelloService.
Examine the generated codeWhen you imported the ColdFusion service into a client
application, Flex generated client code that accessed the ColdFusion
service. Flex also generates code when you bind operations to application
components.
There are three parts to the generated code:
This part of the tutorial walks
you through the Flex code generated in the previous tutorial. There
are no “steps” to this part of the tutorial. Just a description of
the code generation.
Event handlersFlex uses event handlers to trigger a service call.
Flex code is not processed “top to bottom,” as in server templates.
Instead, applications built with Flex listen for events to trigger
responses.
By default, Flex uses the creationComplete event
on a component to trigger a service call.
Examine the Label component in the HelloCF.mxml source
code:
<s:Label x="70" y="60"
text="{getLocalizedMessageResult.lastResult}"
fontWeight="bold" fontSize="24" fontStyle="italic"
color="#FF0000" id="label"
creationComplete="label_creationCompleteHandler(event)"/>
The creationComplete event fires after the application
creates the component. For this Label component, creationComplete calls
an event handler that Flash Builder generated for the event. Examine
the code for the event handler, which is placed inside a Script
block:
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.controls.Alert;
protected function label_creationCompleteHandler(event:FlexEvent):void
{
getLocalizedMessageResult.token = helloService.getLocalizedMessage("es");
}
]]>
</fx:Script>
The creationComplete event handler calls the getLocalizedMessage() operation
from the ColdFusion service. It passes the parameter "es",
which you specified earlier in the source code.
You can use other events, such as a Click event
on a button or a selectionChange event of a list,
to trigger service calls.
Service calls and respondersWhen you add a service, Flex creates a component containing
methods that call the service operations. When you call one of the
methods, the component calls the corresponding service operation
over the network using the appropriate protocol.
Service calls are associated with CallResponders. Data returned
from a service call is placed in the lastResult attribute
of the CallResponder. CallResponders allow service calls to operate
asynchronously. The client application can continue to be responsive
while the service call is being processed.
Examine the generated service call and responder:
<fx:Declarations>
<s:CallResponder id="getLocalizedMessageResult"/>
<helloservice:HelloService id="helloService"
fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)"
showBusyCursor="true"/>
</fx:Declarations>
When you imported the HelloService service, Flex created the
HelloService class. This class contains methods to call the getLocales(),
and getLocalizedMessage operations of the service.
The CallResponder, identified by the getLocalizedMessageResult id, provides
access to the returned data.
Data bindingFlex data binding allows you to assign the value of the lastResult attribute
of a CallResponder to a user interface component. When the last
result updates, Flex automatically updates the component.
Flex uses curly braces {} to bind data to an
attribute of a component. In this example, Flex binds the lastResult value
to the text attribute of the Label component.
Examine the data binding for the Label component:
<s:Label x="70" y="60"
text="{getLocalizedMessageResult.lastResult}"
fontWeight="bold" fontSize="24" fontStyle="italic"
color="red" id="richEditableText"
creationComplete="label_creationCompleteHandler(event)"/>
The data returned to the CallResponder, getLocalizedMessageResult.lastResult,
is automatically assigned as the text attribute for the Label component.
Code generation summaryIn summary, Flash Builder generates code to access the
imported service in the client application:
After Flex creates the Label component in the running
application, the creationComplete event fires,
calling a service operation.
The data returned from the service call is placed in the lastResult attribute of
the associated CallResponder.
The text attribute of the Label component,
which is bound to the lastResult attribute, updates
with the returned data.
|