Requirements      
Prerequisite knowledge Required products
Sample files User level
A basic understanding of creating applications in Flash Builder 4 and Flex is recommended.
Flash Builder (Download trial)
 
Beginning
       

 

The Flex SDK includes three Remote Procedure Call (RPC) components that allow you to integrate your Flex applications with common application server products. Of these, the HTTPService component has the most flexibility in terms of the format of messages that are exchanged between the client and server at runtime. Unlike the other RPC components (WebService and RemoteObject), you can use the HTTPService component with any application server because it exchanges data in the form of simple HTTP parameters and XML of any flavor.
 
Flash Builder 4 adds a new set of code generation features. The data-centric development tools enable you to quickly build data-centric applications that trade data at runtime with multiple application servers using any of the RPC architectures.
 
In this tutorial, I’ll describe how to use the new Flash Builder 4 features to define a data connection—a set of ActionScript classes that enable requests to and retrieval of data from an application server.
 

 
Defining data connections

Flash Builder 4 adds a new set of data-centric development features that make it easy to generate code for the following application tasks:
 
  • Connecting to services hosted by remote application servers
  • Converting returned data to strongly typed value object classes
  • Binding returned data to visual controls such as List and DataGrid controls
  • Presenting data entry forms with returned data already filled into the form’s data entry controls
These features are available for use with the following servers and remote applications or data sources:
 
  • Adobe ColdFusion
  • Adobe LiveCycle Data Services
  • BlazeDS
  • PHP
  • SOAP-based web service providers
  • RESTful data providers returning data as well-formed XML
  • Raw XML files
 
Importing the project
To get started, download the HTTPServiceTutorial.zip sample file and extract it anywhere on your hard disk. The ZIP file contains a Flash Builder 4 project in the new FXP project archive format named HTTPServiceTutorial.fxp.
 
Import the project into Flash Builder:
 
  1. Start Flash Builder 4.
  2. Choose File > Import Flex Project (FXP).
  3. Select HTTPServiceTutorial.fxp (see Figure 1) and click Finish.
Importing an FXP file creates a new project of the same name.

Figure 1 . Importing an FXP file creates a new project of the same name.

  1. When the project has been imported, expand it in the Package Explorer view and locate the src/data folder.
  2. Open contacts.xml from the src/data folder.
The contacts.xml file contains a set of fictitious contact information in XML format. The XML file’s root element is named <contacts>, and it contains repeating data elements named <row>:
 
<?xml version="1.0"?> <contacts> <row> <contactid>1</contactid> <firstname>Brad</firstname> <lastname>Lang</lastname> <streetaddress>3004 Buckhannan Avenue</streetaddress> <city>Syracuse</city> <state>NY</state> <email>Brad.C.Lang@trashymail.com</email> <phone>315-449-9420</phone> </row> <row> <contactid>2</contactid> <firstname>Kevin</firstname> <lastname>Mount</lastname> <streetaddress>341 Private Lane</streetaddress> <city>Montgomery</city> <state>GA</state> <email>Kevin.J.Mount@trashymail.com</email> <phone>229-329-4001</phone> </row> ... more data ... </contacts>
 
Creating a data connection
You can define a remote HTTP service in any Flex project. (When working with certain specific application servers such as ColdFusion, you must first associate the Flex project with that server.)
 
You’ll need the following information before you get started:
 
  • The URL or relative address of the XML file or server page that provides the data
  • Any named parameters that are required if you’re making a call to a dynamic remote server page
For this tutorial, you’ll use a static XML file that’s stored within the deployed application’s directory structure.
 
  1. Open the MXML application HTTPServiceTutorial.mxml.
  2. If the file opened in Source mode, click the Design button above the design area to switch to Design mode.
  3. In the Properties view, set Layout to spark.layouts.VerticalLayout (see Figure 2).
Setting the application’s Layout property to an instance of the VerticalLayout class.

Figure 2. Setting the application’s Layout property to an instance of the VerticalLayout class.

  1. Set Align to center and Top Padding to 20.
  2. Switch to Source mode. The layout property should look like this:
<s:layout> <s:VerticalLayout horizontalAlign="center" paddingTop="20"/> </s:layout>
  1. Choose Data > Connect to HTTP from the Flash Builder 4 menu.
  2. In the Connect to Data/Service dialog box, click into the Operation column of the Operations grid and type getContacts (see Figure 3).
Configuring the HTTP Service to retrieve and parse an XML file.

Figure 3. Configuring the HTTP Service to retrieve and parse an XML file.

  1. Click into the URL column and type data/contacts.xml.
  2. In the Service details section, for the Service Name type ContactService. Notice that the Service Package defaults to services.contactservice and the Data Type Package defaults to valueObjects.
  3. Click Finish to complete the code generation operation.
Note: The dialog box displays a warning that the contacts.xml file should be relative to the output folder. When you build the project, the application’s non-embedded assets, including the contacts.xml file, are copied to the output folder, so the data will be available to the application at runtime.
 
It takes a few seconds to create everything you need to request the XML file from the server and parse it. The resulting code is created in the service package, which defaults to services.[service name]. Two ActionScript class are generated there; for example, the preceding steps create a new class named ContactService. This class is derived from a superclass, in this case named _Super_ContactService.
 
You can customize the subclass, which you’ll call directly in your application, adding custom properties and methods as needed. If you change the properties of the data connection in Flash Builder 4, the super class will be regenerated, but the subclass will be left intact with changes you might have made.
 
 
Modifying the connection’s properties
Data connections are managed in the new Flash Builder 4 Data/Services view. From this view, you can select a service and modify its properties, configure the return data types of any service class operations, and start the process of binding an operation’s data to a visual control.
 
Follow these steps to modify a service’s properties:
 
  1. Open the Data/Services view (see Figure 4). If it isn’t currently visible, choose Window > Data/Services.
The getContacts() operation currently returns an ActionScript Object.

Figure 4. The getContacts() operation currently returns an ActionScript Object.

  1. Right-click on the service name in the Data/Services view.
  2. Choose Properties from the context menu.
  3. When the Properties dialog appears, you can add, delete, or modify any of the data connection’s operations.
  4. If you make any changes to the data connection’s properties, you can click Finish to regenerate the data connection’s superclass.
 
Reviewing the generated code
The connection is represented in the Flash Builder 4 interface in the Data/Services view, which in turn points to the set of classes previously described. Follow these steps to explore the generated code:
 
  1. Open the generated package in the Package Explorer view. If you followed the previous instructions to create the data connection, the package is named services.contactservice.
  2. Open ContactService.as.
The code for this class is very simple; it extends another class named _Super_ContactService:
 
/** * This is a generated sub-class of _ContactService.as * and is intended for behavior customization. This class * is only generated when there is no file already present * at its target location. Thus custom behavior that you * add here will survive regeneration of the super-class. **/ package services.contactservice { public class ContactService extends _Super_ContactService { } }
Note: The code in the generated class might not be as clean as the preceding example. I’ve added indentation and eliminated some of the white space in the generated code to make it more readable. But the comments tell you what you need to know: this class can be customized, and won’t be overwritten if you generate the data connection again.
 
The generated superclass code in _Super_ContactService.as, cleaned up for readability, looks like this:
 
/** * This is a generated class and is not intended for modification. To * customize behavior of this service wrapper you may modify the generated * sub-class of this class - ContactService.as. */ package services.contactservice { import com.adobe.fiber.core.model_internal; import com.adobe.fiber.services.wrapper.HTTPServiceWrapper; import mx.rpc.AbstractOperation; import mx.rpc.AsyncToken; import mx.rpc.http.HTTPMultiService; import mx.rpc.http.Operation; [ExcludeClass] internal class _Super_ContactService extends com.adobe.fiber.services.wrapper.HTTPServiceWrapper { // Constructor public function _Super_ContactService() { // initialize service control _serviceControl = new mx.rpc.http.HTTPMultiService(); var operations:Array = new Array(); var operation:mx.rpc.http.Operation; var argsArray:Array; operation = new mx.rpc.http.Operation(null, "getContacts"); operation.url = "data/contacts.xml"; operation.method = "GET"; operation.resultType = Object; operations.push(operation); _serviceControl.operationList = operations; model_internal::initialize(); } /** * This method is a generated wrapper used to call the 'getContacts' operation. * It returns an mx.rpc.AsyncToken whose result property will be populated with the * result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign * its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the * CallResponder.result or fault events. * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the * result of the operation when the server response is received. */ public function getContacts() : mx.rpc.AsyncToken { var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation("getContacts"); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send() ; return _internal_token; } } }
After working through the remainder of this tutorial, you might want to return to this page and review the generated code. You’ll see that it mimics what you can do manually with the HTTPService component: request and parse data in XML format.
 
Note: Notice that the generated code uses a class named HTTPMultiService to send requests to the server. HTTPMultiService allows you to manage multiple related server locations, but shares most of the features of the HTTPService component.
 

 
Defining a return data type

When data is returned from the HTTPService component, it’s defined by default as an ActionScript Object. Flex applications can realize enormous benefits from using strongly typed value object classes instead of generic instances of Object. Flash Builder 4 can parse your returned XML data and automatically generate the required value object class. When the data is then returned from the server, it will appear in the application as the class you’ve selected.
 
 
Generating the code
Flash Builder 4 can dynamically generate value object code based on the XML data that will be received from the server. If you’re working with an application server, you can provide the page location’s URL and Flash Builder 4 will retrieve and parse the returned XML. If you’re working with a static XML file that you’ve included in your Flex project, you’ll need to open the XML file in Flash Builder 4 or another text editor and copy its contents to the system clipboard.
 
  1. Open contacts.xml from the Flex project’s src/data folder.
  2. Select all of the file’s contents and copy it to the clipboard.
  3. In the Data/Services view, right-click (or Ctrl-click on Mac) the getContacts() operation and choose Configure Return Type from the context menu (see Figure 5).
Configuring the return type from the Data/Services view.

Figure 5. Configuring the return type from the Data/Services view.

In the first screen of the Configure Return Type wizard, you can select either auto-detection of the XML data structure, or select an existing ActionScript class to use as a value object.
 
Choosing auto-detection of the XML data structure

Figure 6. Choosing auto-detection of the XML data structure

  1. Leave the default (auto-detection) and click Next (see Figure 6).
  2. In the next screen, if the sample XML data from contacts.xml is not already in the Sample XML/JSON Response text area, then click in the area and paste the contents of the clipboard (the XML file) into it (see Figure 7).
Sample getContacts return data.

Figure 7. Sample getContacts return data.

  1. Click Next.
Configuring the return type’s properties.

Figure 8. Configuring the return type’s properties.

Note: You typically assign the return type a name that is singular, as in Contact, rather than plural as in Contacts. You’re defining a value object ActionScript class that will represent a single instance of the data object.
 
  1. In the next screen, select row as the root; this is the name of the repeating data element in the XML file (see Figure 8).
    The option Is array? is selected automatically.
     
  2. Change the Data type name to Contact.
  3. Click into the Type column next to contactid (the name of the data object’s unique identifier property).
  4. Set the contactid property’s Type to int.
  5. Click Finish to complete the operation and generate the value object class.
In the Data/Services view, the getContacts() operation now shows a return type of Contact[] (see Figure 9). The [] characters indicate that the returned data will be in the form of an Array of instances of the Contact class.
 
The Data/Services panel after setting the return data type.

Figure 9. The Data/Services panel after setting the return data type.

 
Reviewing the generated code
You’ll find three new ActionScript classes in the Flex project’s valueObjects folder:
 
  • Contact.as: the value object class you’ll use in your application. As with the generated ContactService class, this is a subclass that can be customized and won’t be overwritten if you regenerate the return data type at a later time.
  • _Super_Contact.as: the superclass that defines the names and data types of the value object class properties
  • _ContactEntityMetadata.as: a class that manages object bindings, collections that contain the class, and other runtime tasks
The Contact.as file contains the subclass declaration and a call to a static initializer method:
 
package valueObjects { import com.adobe.fiber.core.model_internal; public class Contact extends _Super_Contact { public static function _initRemoteClassAlias() : void { _Super_Contact.model_internal::initRemoteClassAliasSingle(valueObjects.Contact); _Super_Contact.model_internal::initRemoteClassAliasAllRelated(); } model_internal static function initRemoteClassAliasSingleChild() : void { _Super_Contact.model_internal::initRemoteClassAliasSingle(valueObjects.Contact); } { _Super_Contact.model_internal::initRemoteClassAliasSingle(valueObjects.Contact); } } }
The superclass (_Super_Contact.as) defines the class’s private properties and implements matching getter/setter accessor methods for each:
 
[ExcludeClass] public class _Super_Contact extends EventDispatcher implements IValueObject { model_internal var _internal_model : _ContactEntityMetadata; private var _internal_contactid : int; private var _internal_firstname : String; private var _internal_lastname : String; ... more private properties ... [Bindable(event="propertyChange")] public function get contactid() : int { return _internal_contactid; } [Bindable(event="propertyChange")] public function get firstname() : String { return _internal_firstname; } ... more setters and getters ... }
If you’re interested, you can open these generated classes on your system and explore them in depth; or you can move on to the next step, binding the returned data to a visual control.
 

 
Binding data to visual controls

After defining an HTTP connection and its operations, and then configuring an operation’s return type, the next step is to display the returned data in a visual control.
 
  1. Open the HTTPServiceTutorial application in Design mode.
  2. Go to the Data Controls section of the Components view, and drag a DataGrid into the application. The DataGrid initially shows three columns.
Right-click the visual control that will display the data.

Figure 10. Right-click the visual control that will display the data.

  1. Right-click (or Ctrl-click on Mac) on the DataGrid and select Bind to data (see Figure 10).
    Note: You can also start the binding operation by choosing Data > Bind to Data.
     
  2. In the Bind To Data dialog box, select the Service and Operation that you want to bind to (see Figure 11). In this case, simply accept the defaults, ContactService and getContacts():Contact[].
Binding data to a visual control

Figure 11. Binding data to a visual control

  1. Click OK.
    You should see that the DataGrid displays all of the data properties returned from the operation as column headers.
     
  2. With the DataGrid still selected, click Configure Columns in the Properties view.
  3. In the Configure Columns dialog box, you can delete columns that you don’t want to display.
  4. Click the contactid column, and then click Delete.
  5. Also delete the streetaddress, city, and state columns. There should be just four columns left: firstname, lastname, email, and phone (see Figure 12).
This dialog box makes it easy to configure a DataGrid control.

Figure 12. This dialog box makes it easy to configure a DataGrid control.

  1. Click OK to save your changes.
  2. Save and run the application.
When the application starts, you’ll see that it retrieves and displays the data (see Figure 13).
 
The application loads and displays the XML data on startup.

Figure 13. The application loads and displays the XML data on startup.

In some conditions, you might see a runtime security error as shown in Figure 14.
 
The security error indicates that you can’t load a file from the local hard disk.

Figure 14. The security error indicates that you can’t load a file from the local hard disk.

This error occurs because you’re loading an XML file from the local hard disk, rather than over the network. If you see this error, follow these steps to allow the application to load the XML file locally:
 
  1. Choose Project > Properties.
  2. In the Properties dialog box, click Flex Compiler.
  3. In the Additional Compiler Arguments (see Figure 15) add the following to the existing -locale setting:
-use-network=false
The use-network compiler argument lets you retrieve files from the local hard disk.

Figure 15. The use-network compiler argument lets you retrieve files from the local hard disk.

  1. Click OK to save the project properties.
  2. Run the application again. This time you should see the data successfully displayed in the DataGrid control.

 
Generating a form

Flash Builder 4 also can generate a form based on the structure of the data returned from the XML file. In these steps, you’ll create a read-only form that displays detailed data selected from the DataGrid control.
 
  1. Open HTTPServiceTutorial.mxml in Design mode.
  2. Choose Data > Generate Form.
    The Generate Form dialog box shows that the form will show the data returned from the getContacts() operation (see Figure 16).
  3. Change the selection for Generate form for to Data type.
The Generate Form dialog box.

Figure 16. The Generate Form dialog box.

  1. Uncheck the option Make Form Editable.
  2. Click Finish to generate the form.
    The form will appear just below the DataGrid control (see Figure 17).
     
The application in Design mode after generating the form.

Figure 17. The application in Design mode after generating the form.

Next, you’ll add a line of ActionScript code that causes the form to display the row of data that the user selects in the DataGrid.
 
  1. Click the DataGrid control.
  2. In the Properties view, click the lightning bolt icon next to the On Change property (see Figure 18).
You can generate an event handler function from Source or Design mode.

Figure 18. You can generate an event handler function from Source or Design mode.

  1. Choose Generate Event Handler from the menu that appears.
    Flash Builder 4 switches to Source mode and generates a new ActionScript function named dataGrid_changeHandler().
     
  2. Delete the comment inside the new function.
  3. Add the following line of code to the function:
contact = event.target.selectedItem as Contact
The complete function should look like this:
 
protected function dataGrid_changeHandler(event:ListEvent):void { contact = event.target.selectedItem as Contact; }
  1. Save and run the application.
  2. When the data is displayed, click any row in the DataGrid. The form below the DataGrid will display the details of the selected row (see Figure 19).
The completed application displaying detail data in the generated form.

Figure 19. The completed application displaying detail data in the generated form.

 
Where to go from here

You can learn more the HTTPService component and other RPC tools in the Flex SDK from the Flex 4 documentation:
 
Also, be sure to visit the Flex Developer Center for more helpful tips and tutorials.