Requirements

   
Prerequisite knowledge
Familiarity with Flex 3 and some exposure to the Flex 4 framework is recommended.
 
User level
Intermediate
 
Required products
Flash Builder (Download trial)
Adobe ColdFusion Enterprise Edition (2016 release) (Download trial)
Sample files

Requirements

Prerequisite knowledge

Familiarity with Flex 3 and some exposure to the Flex 4 framework is recommended.

User level

Intermediate

This article highlights some of the new features in Flex 4 and Flash Builder 4 by walking through an intranet application for a fictitious company named Spark Intranet Sample App. (see Figure 1).
 
This article is intended for developers with knowledge of Flex 2 or Flex 3, and preferably at least some exposure to the Flex 4 framework. One of the best ways to understand the differences between Flex 4 and earlier versions is via a working application. To give you a better idea of the benefits of the new Spark framework Flash Builder 4, this article will highlight numerous features.
 
Flash Builder 4 features covered:
 
  • Data/Services connectivity
  • Network Monitor view
  • Test Operation view
  • Getter/Setter auto-generation
  • Design view features
Flex 4 SDK and Spark features covered:
 
  • Layouts
  • Skins and components
  • Effects
  • States
  • Transitions
  • CSS styles syntax
  • Text Layout Framework

 
Setting up the project

Before diving into the code for the application, you’ll need to install Flash Builder 4 (if you haven’t already) and download the sample files.
 
ColdFusion 9 is not absolutely necessary for this article. Without it, however, you won’t be able to fully experience the new Data/Services features in Flash Builder 4. By default, all code pertaining to connectivity with the server via RemoteObjects is within a separate component in the application or commented out. In this state, you can run the application without relying on the ColdFusion Components (CFCs) running on ColdFusion 9 server. By default, the code uses an HTTPService component to acquire the XML data for the application, and there are a few other methods that use dummy data to make the application work. If you choose, you can use the code as is and skip the next section on setting up ColdFusion 9.
 
 
Set up ColdFusion 9
If you want to use the full server-side functionality for this article, you’ll need ColdFusion 9 server installed locally. To download and install the Developer edition, visit http://www.adobe.com/products/coldfusion/.
 
When installing ColdFusion, remember to make note of your RDS (Remote Development Services) username and password, as you’ll need them later.
 
Once you install ColdFusion server, place a copy of the Users.cfc file from the sample filesin the wwwroot/com/sparkintranet/ folder of your ColdFusion 9 install. The default folder on Windows is C:\ColdFusion9\wwwroot\com\sparkintranet and on Mac OS X it is /Applications/ColdFusion9/wwwroot/com/sparkintranet. The Users.cfc includes methods that provide services for the Flex intranet application. The EmployeeVO.cfc is a server-side object for use in a later call for the Employee Directory section in the sample application.
 
 
Set up the project in Flash Builder 4
Follow these steps to set up the project:
 
  1. Download the sample files and unzip them to a directory on your computer.
  2. Start Flash Builder 4.
  3. To import the project, choose File > Import Flex Project (FXP) and select the Spark Intranet Sample App.fxp file from the ZIP file.
The project should be up and running at this point and you can take a look at the Flex 4 directory structure with the new Package Explorer view in Flash Builder 4 (see Figure 2).
 

 
The Spark Intranet Sample App application

The Spark Intranet Sample App application is made up of a few custom components and skins located in the default package and the components package. Skins and item renderers are also located in the same package to keep things simple.
 
 
Main.mxml
In the Main.mxml file, you’ll find the HomeView, LoginView, EmployeeDirectoryView, and TimesheetView components, as well as some transitions, effects, and the components used for navigation. The first piece I’ll go over is HomeView. You’ll notice its visible property relies on a Boolean variable set earlier. This is to ensure the transitions look right when changing states between normal and timesheet.
 
<local:HomeView id="homeView" x="10" y="257" visible="{!vis}"/>
At the top of Main.mxml, there are four states declared: normal, disabled, timesheet, and employeeDirectory. The HomeView component consists of the main content you see on screen when the application first starts. Open HomeView, and in the center VGroup container you’ll see there are two more components: NewsView and ExpandedNewsView.
 
The other components and code are related to the overall template of the application and not specific to any particular view. For example, the top navigation buttons make use of the new SparkSkin class to specify two images that represent the up and hovered states. In this particular instance, the SparkSkin for the TimesheetButton is set via CSS styles. The TimesheetButtonSkin is referenced with the styleName property on the button itself.
 
In the Styles.css file you’ll see the classReference for the TimeSheetBtn class as follows:
 
s|Button.TimeSheetBtn { skinClass:ClassReference("components.TimesheetButtonSkin"); }
To make use of the styles for each tree (Spark vs. Halo components packages) the namespaces for each are necessary. At the top of the CSS file, the two namespaces are declared:
 
@namespace s "library://ns.adobe.com/flex/spark"; @namespace mx "library://ns.adobe.com/flex/mx";
The rest of the styles in this file fall into one of the two namespaces, mx|Button or s|Button depending on which Button component they’re referencing. This is one way to reference a skin for a Spark component; the other is to use the skinClass property. You’ll notice the Application tag references skinClass="components.AppBackgroundSkin" for its skin.
 
 
NewsView.mxml
In NewsView.mxml, you’ll see the component consists of a data provider and a Spark List. It also uses the skinClass property of the List to reference its skin. Open the components.NewsList skin class and you’ll start to delve deeper into the code that gives this List its look and behavior.
 
At the top of the skin class is the HostComponent Metadata tag:
 
<fx:Metadata>[HostComponent("spark.components.List")]</fx:Metadata>
This Metadata tag explicitly declares that NewsList is actually a Spark List component and can be expected to behave like one.
 
The NewsList has Image and Label components that make up part of its look and feel, and further down you’ll see the DataGroup and HScrollBar for the actual list functionality. If you instantiated a DataGrid in Flex 3, you got the Halo skins along with it and it was harder to create a custom look and feel. With the Spark framework, you make use of each component’s functionality and have complete control over the look and feel.
 
Take a look at the item renderer for the DataGroup in NewsList to get a better idea of this concept. Open the components.NewsListItemRenderer component and you’ll recognize a familiar pattern. This component inherits from the Spark ItemRenderer, so obviously it has different functionality than the List itself. Other than functionality, the MXML class only defines how the component looks and reacts to user input. There are four states in this class: normal, hovered, selected, and disabled. How components are affected in each state is defined in the components themselves. For example, the Rect object serves as the background for the item renderer:
 
<s:Rect width="100" height="100" y="80" y.hovered="20" id="rect1">
Notice the y property is set to 80 for all states except for hovered, in which it is set to 20. When a user rolls over each item in the List and the hovered state takes effect, the Rect moves the y position to 20 pixels from the top. The image is also slightly skewed with the 3DRotate for added effect. In Flex 3, making changes to components that result from state changes was a more complicated task. The Spark architecture makes things more intuitive. You just check the components themselves to see which properties are affected by state changes, and simply declare your states separately.
 
The actual data for the item renderer is handled the same as it was with Flex 3. The Label receives its text by referring to the data property set for the item renderer:
 
<s:Label text="{data.title}" styleName="blackTitle" x="2" y="83" excludeFrom="hovered"/>
To demonstrate a bit more of the versatility of the new Spark framework and what it means for Flex developers when creating truly custom components and effects, take a look at NewsList again. As a developer, if you receive a change request for a vertical List instead of horizontal, making the change is as easy as swapping the HorizontalLayout tag with a VerticalLayout tag, otherwise the component behaves exactly the same as before.
 
 
ExpandedNewsView.mxml
The ExpandedNewsView component consists of the cross-fading picture and brief articles in the first view of the application. There are a few areas of interest here. You’ll see two strings inside the <fx:Declarations> that contain formatted HTML. These strings make up the content for the articles, and although they could be loaded externally, for simplicity they’re added here in MXML form.
 
Introduced prior to Flex 4, the TextLayout Framework (TLF) is now included with the SDK. This example shows a very simplistic use of the TLF, but there are many more elaborate features available and I encourage you to explore them in more depth.
 
In the ExpandedNewsView, the component uses the static TextConverter.importToFlow method of the TLF to translate formatted HTML content into equivalent TLF classes for use in the RichText component. For example, a <p> tag in HTML is mapped to a ParagraphElement object in the text object model for use in the RichText component.
 
The two states listed in the ExpandedNewsView change based on a Timer set to fire every 10 seconds. At that time, the picture that accompanies the text is cross-faded with another image for the second article via the new CrossFade Spark effect. CrossFade performs a bitmap transition between two images on a per pixel basis over the duration of the effect. In this view, the text content is also swapped out to accompany the image that was just faded in during the state change.
 
TLF allows you to select, edit, and flow text across multiple columns and linked containers and around inline images; perform animations on text without having to embed fonts; and create custom text components. With the Spark effects classes, you have access to three dimensions and you can create completely custom effects with motion paths and keyframes, as well as custom pixel-shader effects for any component. I recommend spending some time with these new additions to the Flex SDK so you can see first-hand what can be done with them.
 
 
TimeSheetView.mxml
For demonstration purposes, the Spark Intranet Sample App application doesn’t make use of any particular architecture framework, such as Cairngorm, but rather uses inline examples that are easier to understand.
 
With that in mind, you can see there is another List component with its own skin and item renderer for use as the timesheet itself, and the rest of the MXML is pretty straightforward, with buttons and labels for the UI. The timesheet is a DataGrid-like component, but an actual DataGrid component was more than what the application called for. A custom Spark List component was the better answer in this case as the application gets all the functionality required, but without the extra padding of skins and features that aren’t necessary.
 

 
EmployeeDirectoryView.mxml

The EmployeeDirectoryView.mxml uses a simple HTTPService component by default to load a list of employees. If you have deployed the CFCs earlier, you also have the option of loading the actual ColdFusion server-side objects directly into Flash Builder. You’ll read more on how to do this further along in the article. For now, you can see that the EmployeesDirectoryView consists of a list of employees with an optional layout scheme. By choosing a layout from the DropDownList, you can choose to view the employeesList horizontally, vertically, or in a tile layout.
 
The DropDownList triggers a state change in the EmployeeDirectoryView component, which directs the employeesList, and expandedEmployeesView to move positions via the transitions set above in the code. Both the employeesList and expandedEmployeesView specifiy a width, height, x, and y position for the normal, and horizontal states. The resize and move effects within the transitions are set to animate the components with the same ending sizes and coordinates that are specified within the components themselves. This ensures a smooth transition during state changes.
 
<s:List x="10" y="66" width="500" width.horizontal="1000" height="300" height.horizontal="100" id="employeesList"
The components.EmployeeItemRenderer being used for the employeesList handles its own animations by making use of states and transitions. When a user rolls over the list items, the itemRender increases the alpha property of each item and includes a DropShadowFilter in the rollOver state to give a clean, subtle roll-over behavior for the employeesList. Later in this article, you will see more of the Flash Builder features which made the creation of the EmployeesItemRenderer a quick and easy process.
 

 
Data/Services view, Test Operation view, and Getter/Setter auto-generation

Now that you understand the components of the application better, you can delve into some more specifics on how they were created with the new Flash Builder features. Take a look at the <fx:Declarations> section of TimeSheetView is an HTTPService component that loads a local XML file. If you’ve installed ColdFusion server, you can use the TimeSheetView_CF instead to connect to the CFC provided with the sample code. By using the provided ColdFusion component, you can get a more in-depth look at the new Data/Services feature inFlash Builder 4 to inspect if the CFC is available. To use TimeSheetView_CF, open the Main.mxml file and uncomment the component. Be sure to comment out the TimeSheetView right above it before you run the application.
 
If you’re using the CFC, follow these steps to explore it in the Data/Services view:
 
  1. If the Data/Services view is not showing already, choose Window > Data/Services.
  2. Click the Connect To Data/Service button on the top right (see Figure 3).
Find Users.cfc in the Flash Builder 4 Data/Services view.
  1. Select the ColdFusion option (see Figure 4) and click Next.
Choose the ColdFusion option in the Data/Services window.
  1. A dialog box appears asking if you want to set the project’s server type to ColdFusion; click Yes.
  2. In the Flex Server settings of the Properties for Spark Intranet dialog box, select ColdFusion as the Application Server, then deselect Use Default Location For Local ColdFusion Server.
  3. Ensure your ColdFusion Root Folder is correct, and click Validate Configuration.
  4. When your configuration is validated, click OK.
  5. Browse to the Users.cfc that you deployed to your wwwroot/com/sparkintranet/ folder earlier (see Figure 5).
  1. Click Finish.
  2. Enter your RDS user name and password if required and click OK.
  3. When an item named Users appears in the window, expand it. This is the CFC you deployed earlier.
You can now inspect all the ColdFusion methods available to Flex from within this CFC.
 
 
Test Operation view
The Test Operation feature allows developers to further inspect the services available in the CFC and to actually perform a call to the server with dummy data. Follow these steps to try it out:
 
  1. Right-click the checkLogin() method and select Test Operation.
  2. Type user for the userName and password for the password.
  3. Click Test (see Figure 6).
You should see a return Boolean value of true. Likewise, if you send incorrect information to the server, you’ll receive a false Boolean in return.
 
Note: The code within the CFC is hardcoded just for this sample; there is no database connectivity.
 
Use the Test Operation feature to perform live tests on the CFC methods.
The same procedures can be performed for ColdFusion, HTTPServices, web services, and PHP via the Data/Services feature of Flash Builder 4. This is a simple example to get you started, but there are many more time saving features you can access with the Data/Services functionality. You can browse a table in a database and have Flash Builder 4 auto-generate typical CRUD (create, read, update, and delete) capabilities in a ColdFusion component or PHP class. The feature also allows drag/drop simplicity when browsing services and binding to components in Design view.
 
 
Getter/Setter auto-generation
If you open the valueObjects.CustomerData class, you’ll find it’s a typical looking value object. Another useful feature of Flash Builder 4 when creating standard value objects is the Getter/Setter auto-generation. Just set the variables at the top of your class, click one of them, and choose Source > Generate Getter/Setter. The Generate Getter/Setter dialog box will appear and ask how you’d like to handle the formatting.
 
The best practices standard is naming private variables at the top of the class with underscores (for example, private var _customers:ArrayCollection) and making the getter/setter pair publicly accessible. The Generate Getter/Setter feature will handle this for you, saving you time you’d otherwise spend on a tedious, repetitive task.
 

 
Using the Network Monitor

Whether you’re using the HTTPService currently in the code, or if you’ve tried the ColdFusion component for Spark Intranet, another great Flash Builder 4 feature to check out is the Network Monitor.
Follow these steps to trace network traffic on the project:
 
  1. Choose Window > Network Monitor.
  2. Make sure it’s enabled by checking the Enable Monitor icon in the upper right corner of Network Monitor view.
The Network Monitor shows the request and response after a successful login to the Spark Intranet Sample App back-end.
  1. Run the application, click on the Timesheet button, and login.
  2. Return to the Network Monitor view in Flash Builder 4.
You’ll see that the HTTPService calls (or the remoting calls with ColdFusion server) and responses have been recorded in the window. Take a minute to expand and inspect the results (see Figure 7). There are excellent third-party tools available that make it possible to inspect client-server traffic, but having that ability right within Flash Builder 4 is a big benefit for developers. Whether you’re using a local or remote server, you can see the real-time traffic between your application and the server.
 

 
Design view features in Flash Builder

Back in the EmployeesDirectory.mxml component, click the Design button to enter Design view and make sure the Data/Services window is open. A new feature of Flash Builder is the simple drag/drop operations to bind components to the results of a service call. In the creation of the employeesList, simple drag and drop gestures from the getEmployees() method in the Data/Services window to the List created a few new lines of code in the component (see Figure 8). 
 
Upon dropping the dragged method name, the Bind to Data window appears. You don’t need to make any selections now because as you can see in Figure 8, the getEmployees() method already returns an array of EmployeeVO objects from ColdFusion. Behind the scenes, Flash Builder has created this value object for you with matching properties from the ColdFusion object EmployeeVO.cfc. If you right click the getEmployees() method in the Data/Services window, and select Congfigure Return Type, you’ll see two options: “Auto-detect the return type from sample data” and “Use an existing data type”. For future reference, if you select “Use an existing data type” you can scroll through the list and choose a predefined type or object to use for the result of the service call. In this case, the call is returning an array of EmployeeVOs, which can be seen in Figure 9 (EmployeeVO[] means an array of the objects is returned, as opposed to just one EmployeeVO).
 
Go back to the code view by clicking the Source button above in the EmployeeDirectoryView file. Inside the employeesList, you’ll notice Flash Builder added a new dataProvider mxml tag with a AsynchListView component.
 
<s:dataProvider.normal> <s:AsyncListView list="{getEmployeesResult.lastResult}"/> </s:dataProvider.normal>
Above, in the Declarations mxml tags, you’ll see that Flash Builder also instantiated a CallResponder object named appropriately getEmployeesResult.
 
<s:CallResponder id="getEmployeesResult"/>
In its simplest form, the list is now bound to the response from the server call, in this case, the getEmployees() method of the Users.cfc deployed earlier.
 
Back in Design view, there is another feature of Flash Builder that saves time and makes life easier. Right click the employeesList and select Create Item Renderer. In the New MXML Item Renderer window that appears, you can choose the package and name of the class you’ll use for the employeesList item renderer. Flash Builder creates the MXML file with a simple template and sets it as the item renderer for employeesList when you click Finish (See Figure 10). There are many new time saving shortcuts like this one throughout the Flash Builder IDE.
 
The components.EmployeeItemRenderer now has everything it needs to display each item in the list by simply referring to its data property. These are just some of the new features that allow you to spend more time concentrating on the application’s look and feel and saving time on the tedious tasks by taking advantage of some of the built-in shortcuts. 
 
<s:Label id="nameLabel" text="{data.firstname + ' ' + data.lastname}" styleName.rollOver="empInfoTitle" styleName.selected="empInfoTitle"/>
As is often the case, you may want to do additional formatting or validation to the result of a service call. Take a look at the EmployeeDirectoryView again. For this example, the AsynchListView that Flash Builder added was commented out and a result handler method was created for the call responder. You’ll see the dataProvider property of the employeesList was set to an ArrayCollection named empDP, which is populated inside the getEmployeesResult_resultHandler() method set on the getEmployeesResult CallResponder.
 
protected function getEmployeesResult_resultHandler(event:ResultEvent):void { empDP = event.result as ArrayCollection; }
As a result of dragging and dropping the method call in Design view, Flash Builder added the AsynchListView component to bind the result data to the employeeList. By creating a result handler method on the CallResponder and setting the dataProvider property in the List, you can perform the extra steps like validating the server’s results, or handling any formatting your application might need.
 
When you run the application, click “Log in” on the top-right of the screen, then click the Employees Directory button, you’ll see the resulting employees data populated in the list. By selecting an employee from the list, the ExpandedEmployeesView comes into play with a simple fade and gives a more complete set of the data to the end user.
 

 
Where to go from here

By stepping through this sample application, hopefully you’ve gotten a good feel for what the new Spark components and Flash Builder 4 features can help you achieve with your Flex development. The productivity gains, easier workflow between designer and developer, and new Spark framework offer many new possibilities for creating great rich Internet applications.
 
If you’d like to delve deeper into the topics you touched on in this sample application, check out the following resources to learn more about Flex 4 and Flash Builder 4: