Flash Builder 4 and Flex 4 Bible- P19

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:50

lượt xem

Flash Builder 4 and Flex 4 Bible- P19

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Flash Builder 4 and Flex 4 Bible- P19: When Macromedia first released Flash MX in 2002, the product was branded as the new way to build Rich Internet Applications (known by the acronym RIA). The term was invented at Macromedia to describe a new class of applications that would offer the benefits of being connected to the Internet, including access to various types of Web-based services, but would solve many of the nagging issues that had been inherent in browser-based applications since the mid-1990s....

Chủ đề:

Nội dung Text: Flash Builder 4 and Flex 4 Bible- P19

  1. Chapter 27: Using the Message Service with BlazeDS FIGURE 27.4 An application sending and receiving filtered messages using subtopics Tracing Messaging Traffic As with all network communications between Flex clients and application servers, you can use the TraceTarget component to enable tracing of messaging traffic. Follow these steps to trace messaging: 1. Open any Flex application that uses the Message Service. 2. Add an tag as a child of the application’s element. 3. Set any optional values that determine what metadata is included with each tracing message. For example, this declaration of the TraceTarget object would cause tracing messages to display date and time information: 4. Run the application in debug mode. 5. Watch Flash Builder’s Console view to see the tracing output. Figure 27.5 shows the resulting output in Flash Builder’s Console view. 871
  2. Part IV: Integrating Flex Applications with Application Servers FIGURE 27.5 Tracing output from a messaging application Summary In this chapter, I described how to create and deploy Flex client applications that use the Message Service with BlazeDS. You learned the following: l The Message Service is implemented in both LiveCycle Data Services and BlazeDS. l The Message Service enables you to share data between multiple connected Flex applica- tions in real time or “almost real time.” l Flex applications that use the Message Service can be integrated with other applications that are built in Java and ColdFusion. l A Flex application sends messages using the Flex framework’s Producer component. l A Flex application receives and processes messages using the Flex framework’s Consumer component. l You can send and receive both simple and complex data. l Messages can be filtered at the server with the Consumer component’s selector prop- erty or with subtopics. l You can use the TraceTarget logger target to turn on tracing of message traffic during debugging sessions. 872
  3. CHAPTER Integrating Flex Applications with ColdFusion F lash Remoting, the technology that enables Flash-based documents to communicate with Web-based resources over a high-speed, binary IN THIS CHAPTER protocol, was first introduced with ColdFusion MX (also known as Understanding Flash Remoting ColdFusion version 6). In the early days of the technology, before the intro- and ColdFusion duction of Flex, applications built in Flash MX and subsequent releases had the ability to make remote procedure calls to functions of ColdFusion Creating a Flex project for use Components (CFCs) over a standard Web connection. with ColdFusion Configuring Flash Remoting When Flex 1.0 was released, Flash Remoting was adapted for use with on the server Java-based application servers that hosted Java-based classes. Flex client applications could make calls to Java-based methods just as easily as with Creating CFCs for Flex ColdFusion using the feature first known as Remote Object Services, now known as the Remoting Service. Calling CFC functions and handling CFC function results Cross-Reference The Java-based Remoting Service is described in Chapter 26. n Passing arguments to CFC functions Adobe ColdFusion 9 (the most recent version at the time that Flash Builder 4 Using value object classes and Flex 4 were released) continues to offer built-in support for Flash Remoting with Flex-based and Flash-based client applications, and it adds Using ColdFusion data the capability to integrate tightly with features that are unique to LiveCycle connections in Flash Builder Data Services or BlazeDS. When ColdFusion is integrated with these Adobe Working with ColdFusion 9 products, you can build and deploy Flex applications that share messages in Services real time or near real time with ColdFusion-based resources using the Message Service, and you can use LiveCycle Data Services’ Data Management Service to create applications that synchronize data between multiple con- nected clients and servers. 873
  4. Part IV: Integrating Flex Applications with Application Servers New Feature BlazeDS is automatically installed with ColdFusion 9, so the features described in Chapters 26 and 27, such as the Message Service, are also available to ColdFusion 9 developers. n Note All of the currently available ColdFusion features that support integration with Flex client applications were first introduced in ColdFusion version 7.02. With the exception of the event gateway used to integrate Flex applications with the Message Service, all of the features described in this chapter work equally well with ColdFusion 7.02 or later. n In this chapter, I describe how to use Flash Remoting to call ColdFusion component functions from Flex applications. On the Web To use the sample code for this chapter, download chapter28.zip from the Web site. Follow the instruc- tions later in this chapter to create a Flex project for use with ColdFusion and install the various project com- ponents to the client and server. n Understanding Flash Remoting and ColdFusion The feature known as the Remoting Service in LiveCycle Data Services and BlazeDS is known as Flash Remoting in ColdFusion. Flash Remoting enables you to directly make calls to functions of ColdFusion Components using the Flex SDK’s RemoteObject component. Calls from a Flex client application are sent directly to the ColdFusion server as HTTP requests encoded in Action Message Format (AMF), and responses are returned from ColdFusion to the Flex application without any intermediate proxy or additional software. As shown in Figure 28.1, when using the RemoteObject component to call CFC methods, you don’t need to install or integrate LiveCycle Data Services or BlazeDS. FIGURE 28.1 Flash Remoting requests and responses travel directly from the Flex application to ColdFusion and back again. HTTP requests and responses Flex application ColdFusion 874
  5. Chapter 28: Integrating Flex Applications with ColdFusion To call CFC functions from a Flex application, follow these steps: 1. Install Adobe ColdFusion or obtain access to a ColdFusion server. You can use either the Standard or Enterprise edition, or, if you don’t have a license, you can install ColdFusion locally as the Developer edition. This edition is free for development and testing and has some limitations, including allowing connections from only two browser clients during any particular session. 2. Create ColdFusion Components on the server with code you can call from a Flex application. 3. If using Flash Builder, create a Flex project that’s integrated with your ColdFusion server installation. 4. Create and test Flex client code to call the CFC functions. Note The sample code and instructions in this chapter assume that ColdFusion 9 has been installed on a Windows- based development system using the development Web server running on port 8500. If your ColdFusion instal- lation differs, adapt the instructions as needed. n Creating a Flex project for use with ColdFusion When you create a new Flex project, you can add project properties that enable you to easily test your Flex application with the ColdFusion server. Follow these steps to create a new Flex project: 1. Choose File ➪ New ➪ Flex Project from the Flex Builder menu. 2. On the first screen, set these properties, as shown in Figure 28.2: l Project name: chapter28 l Use default location: selected l Application type: Web application l Application server type: ColdFusion l Use remote object access service: selected l ColdFusion Flash Remoting: selected 3. Click Next. 4. On the Configure ColdFusion Server screen, shown in Figure 28.3, set the ColdFusion installation type and location. If you installed the server configuration to the default location in Windows, for the ColdFusion installation type, select Standalone. 5. Set the ColdFusion root folder to the installation folder. For example, if you are using the default stand-alone installation on Windows, the root folder is C:\ColdFusion9. 6. Set the Web server root folder and URL. If you are using the default stand-alone instal- lation on Windows, the root folder is C:\ColdFusion9\wwwroot, and the Root URL is http://localhost:8500. 875
  6. Part IV: Integrating Flex Applications with Application Servers FIGURE 28.2 Creating a new Flex project 7. Click Validate Configuration to verify that your ColdFusion configuration settings are accurate. Note ColdFusion must be running in order to validate the configuration at this point. Flex Builder sends a test request to the ColdFusion server’s Root URL to ensure that the server is reachable. n 8. Click Next. 9. Accept the Main application filename of chapter28.mxml. 10. Set the Output folder to a location under the ColdFusion Root URL. This is the folder where the application’s debug output files will be generated during the compilation process and from which you retrieve documents in the browser during testing. The default setting is a subfolder under the ColdFusion Web root whose name starts with the project name and ends with -debug. 11. Click Finish to create the project and application. 12. Run the application. You should see that the application is retrieved from the folder on the ColdFusion server using the server’s root URL and the subfolder in which the output files are generated. 876
  7. Chapter 28: Integrating Flex Applications with ColdFusion FIGURE 28.3 Configuring the ColdFusion server location On the Web If you want to use the sample applications for this chapter from the Web site, follow these instructions: Extract the contents of chapter28.zip to the new project’s root folder, locate ColdFusionFiles folder in the project files, and copy its files to the ColdFusion server’s Web root folder, such as C:\ ColdFusion9\www root. This creates a new subfolder named flex4bible/chapter28 under the ColdFusion Web root. n Configuring Flash Remoting on the server Just as with the Remoting Service on LiveCycle Data Services or BlazeDS, to use Flash Remoting from a Flex application, it must be configured on the server. When you install ColdFusion, a folder named WEB-INF/flex is created that contains a default set of configuration files. Note The WEB-INF folder is located under the ColdFusion Web root, as defined during the ColdFusion installation process. The actual location differs depending on ColdFusion’s configuration. The “server” configuration that includes a limited JRun server places WEB-INF under the installation folder’s wwwroot subfolder. When the server configuration of ColdFusion is installed on Windows with the default location, the Flex configuration files are stored in C:\ColdFusion9\wwwroot\WEB-INF\flex. For the J2EE or multi-server configurations, WEB-INF is located under the ColdFusion “context root” folder. For example, when installed with the default location on Windows, the Flex configuration files are stored in C:\JRun4\servers\cfusion\cfusion-ear\cfusion-war\WEB-INF\flex. n 877
  8. Part IV: Integrating Flex Applications with Application Servers Flash Remoting access is configured in the primary services configuration file, services- config.xml, which includes a file named remoting-config.xml that declares Flash Remoting configuration options. ColdFusion 9 includes a predefined Flash Remoting destination with an id of ColdFusion in remoting-config.xml that looks like this: * The following key destination properties are worth a detailed description: l The is set to my-cfamf. This channel is defined in services.config. xml and uses the AMFChannel class on the server to serialize and deserialize AMF- formatted messages between client and server. The services configuration file also defines a channel named my-cfamf-secure that can be used for encrypted communications over SSL. l The property is set to a wildcard value of *, meaning that the predefined ColdFusion destination can be used to call any CFC on the server. This is in contrast to the use of the Java-based Remoting Service with LCDS and BlazeDS, where each Java class must be configured with its own unique destination. The default ColdFusion destination is designed to be usable with its default property settings. In most cases, you can start calling CFC functions from a Flex client application without changing any of the server-side configuration options. Creating ColdFusion Components for Flex The rules for creating ColdFusion components for use with a Flex application are very similar to those CFCs used as SOAP-based Web services: l CFCs should be placed in a folder under the Web root. With additional configuration, you also can place CFCs in folders that are mapped through the ColdFusion administrator. l CFC functions should have their access attribute set to remote. With additional configuration, you also can expose functions with their access set to public. l Functions should return values with data types that are compatible with Flex applications. 878
  9. Chapter 28: Integrating Flex Applications with ColdFusion Web Resource A complete description of how to create and deploy ColdFusion components is beyond the scope of this chapter. For a good starting tutorial on this subject, see Ben Forta’s article on the Adobe Developer Center Web site at: www.adobe.com/devnet/coldfusion/articles/intro_cfcs.html. n Table 26.1 describes the data types that can be returned from a CFC to a Flex application and how each value is translated into an ActionScript variable when it’s returned from a CFC function to a Flex client application. TABLE 26.1 Data Conversion from ColdFusion to ActionScript ColdFusion Data Type ActionScript Data Type String String Array Array Query ArrayCollection Struct Object CFC instance Strongly typed value object Date Date Numeric Number XML object XML object The returned data type is determined in a ColdFusion function by its returntype property. The CFC in Listing 28.1 shows a ColdFusion component with a helloWorld() function that declares a returntype of string: LISTING 28.1 A simple ColdFusion component On the Web The code in Listing 28.1 is available in the Web site files as HelloService.cfc in the ColdFusion files of the chapter28 project. n 879
  10. Part IV: Integrating Flex Applications with Application Servers Note Unlike the worlds of Java and ActionScript, ColdFusion Markup Language is mostly case-insensitive. As a result, returntype values of string and String mean the same thing. n The returntype attribute is also used by ColdFusion to verify that data being returned by a function is of the correct type. ColdFusion Markup Language (CFML) is a very loosely typed language, where simple values are generally stored as String values until being cast appropriately at runtime (a process sometimes known as “lazy evaluation”). But at runtime, ColdFusion can detect discrepancies between a declared returntype and the actual value being returned. This function, for example, would generate a server-side runtime error, because the value being returned can’t be parsed as a number: This resulting server-side error would be exposed in the Flex client application as a fault event dispatched by the RemoteObject that made the remote call to the function. New Feature In ColdFusion 9, you can write CFCs with the pure scripting style known as CFScript. Using the new scripting syntax, the CFC in Listing 28.1 would look like this: component hint=”A CFC written in script” output=”false” { remote string function helloWorld() { return “Hello from a ColdFusion Component!”; } } You can choose either tag- or scripting-based syntax in ColdFusion 9; in either case, the CFC is available to the Flex application using either Flash Remoting or SOAP-based Web services. n Using CFCs with the RemoteObject Component To call a CFC function from a Flex client application, you start by creating an instance of the RemoteObject component. This is the same RPC component that’s used to integrate Flex appli- cations with LiveCycle Data Services and BlazeDS, and the client-side code that’s used to commu- nicate with ColdFusion is almost exactly the same. If the source of the component is set to a wildcard in the server-side destination, you set the component’s source property in the client-side RemoteObject declaration. 880
  11. Chapter 28: Integrating Flex Applications with ColdFusion Setting the source property The CFC is known to the Flex client application by its fully qualified name and location, declared with dot notation. This String value is passed to the RemoteObject component’s source property to determine which component will be called on the server. ColdFusion uses a naming pattern whereby CFCs are known by the name of the file in which the component is defined (without the file extension), prefixed with the names of the folders in which it’s stored, starting at the Web root folder. Folder and component names are separated with dot characters, just like packages in Java. So, for example, a CFC that’s defined in a file named MyComponent.cfc and stored in a subfolder under the ColdFusion Web root named flex4bible/cfc would be referred to from Flex as: flex4bible.cfc.MyComponent If you’re working on a development server that has RDS enabled, you can generate a CFC’s documentation by navigating to the component from a Web browser. The documentation includes the exact string you need to set the component’s source accurately in Flex. For example, you can browse to the HelloService.cfc file stored in the Web root folder’s flex3bible/ chapter28 folder with this URL: http://localhost:8500/flex4bible/chapter28/HelloService.cfc Tip If you have RDS security turned on in ColdFusion Administrator, you’ll need to enter your RDS password to view the CFC’s documentation. n Figure 28.4 shows the resulting CFC documentation. The string value you use as the source attribute in Flex is displayed twice: once at the top of the documentation page and again in the hierarchy section. Creating a RemoteObject instance You can create an instance of the RemoteObject component that works with the ColdFusion destination in either MXML or ActionScript. In addition to the object’s unique id, you set object’s destination to the id of the destination on the server, named by default ColdFusion. The object’s source attribute is set to the fully qualified name and location of the CFC in dot notation, as described in the preceding section. The code to create a RemoteObject and set its required properties in MXML looks like this: 881
  12. Part IV: Integrating Flex Applications with Application Servers The code to create the same object in ActionScript looks like this: import mx.rpc.remoting.RemoteObject; var helloService:RemoteObject = new RemoteObject(“ColdFusion”); helloService.source = “flex4bible.chapter28.HelloService”; After you’ve declared the RemoteObject and set its source and destination properties, you’re ready to make runtime calls to remote CFC functions. FIGURE 28.4 Automatically generated CFC documentation, including the component’s fully qualified name and location Calling CFC functions You call CFC functions as though they were local methods of the RemoteObject. For example, the CFC in Listing 28.1 has a public method named helloWorld() that returns a simple String. As with local functions, you can call the remote method upon any application event. For example, the following code calls the server-side helloWorld() method upon a Button com- ponent’s click event: You also can call a CFC function by calling the RemoteObject component’s getOperation() method to create an instance of the Operation class. The following code creates the Operation object and then calls its send() method to call the remote method: 882
  13. Chapter 28: Integrating Flex Applications with ColdFusion import mx.rpc.remoting.mxml.Operation; private function callIt():void { var op:Operation = helloService.getOperation(“helloWorld”) as Operation; op.send(); } This technique enables you to determine which remote method will be called at runtime, instead of having to hard code the method name. Handling CFC Function Results Calls to remote CFC functions are made asynchronously in Flex, so a call to a CFC function doesn’t return data directly. Instead, as with the other RPC components, you handle the response with binding expressions or event handlers. Binding expressions require less code and are easy to create, while event handlers offer much more power and flexibility in how you receive, process, and save data to application memory. Using binding expressions A binding expression used to pass returned data to application components consists of three parts, separated with dots: l The RemoteObject instance’s id l The CFC function name l The lastResult property At runtime, the method is created as an Operation object that’s a member of the RemoteObject instance. The Operation object’s lastResult property is populated with data when it’s received from the server. The lastResult property is explicitly typed as an ActionScript Object, but at runtime its native type is determined by the type of data that’s returned from the server. A String returned from ColdFusion is translated into an ActionScript String value, so a binding expression that han- dles the value returned from the simple helloWorld() method can be used to pass the returned value to a Label or other text display control. The application in Listing 28.2 calls the remote helloWorld() CFC function and displays its returned data in a Label control with a binding expression in its text property. 883
  14. Part IV: Integrating Flex Applications with Application Servers LISTING 28.2 Handling returned data with a binding expression On the Web The code in Listing 28.2 is available in the Web site files as ROWithBinding.mxml in the src folder of the chapter28 project. n Using the result event As with other RPC components, you can handle results of a call to a CFC function with the RemoteObject component’s result event. This event dispatches an event object typed as mx.rpc.events.ResultEvent, the same event object that’s used by the other RPC compo- nents HTTPService and RemoteObject. The event object’s result property references the returned data. To handle and save data using the result event, follow these steps: 1. Declare a bindable variable outside of any function that acts as a persistent refer- ence to the returned data. Cast the variable’s type depending on what you expect to be returned by the remote method. For example, if the data returned by the CFC function is typed as a query object, the RemoteObject component casts the returned data as an ArrayCollection. The following code declares a bindable ArrayCollection variable: import mx.collections.ArrayCollection; [Bindable] private var myData:ArrayCollection 884
  15. Chapter 28: Integrating Flex Applications with ColdFusion 2. Create an event handler function that will be called when the event is dispatched. The function should receive a single event argument typed as ResultEvent and return void: private function resultHandler(event:ResultEvent):void { } 3. Within the event handler function, use the event.result expression to refer to the data that’s returned from the server. Just as with the WebService component, ResultEvent.result is typed as an Object. Because the expression’s native type differs depending on what’s returned by the CFC function, you typically have to explic- itly cast the returned data. This code expects the CFC function to return an ArrayCollection: myData = event.result as ArrayCollection; You can listen for the result event with either an MXML attribute-based event listener or a call to the ActionScript addEventListener() method. The attribute-based event listener looks like this: When using addEventListener() to create an event listener, you can designate the event name with the String value result, or with the ResultEvent class’s RESULT static constant: var contactService:RemoteObject = new RemoteObject(“ColdFusion”); contactService.source = “flex4bible.chapter28.ContactService”; contactService.addEventListener(ResultEvent.RESULT, resultHandler); contactService.getAllContacts(); Listing 28.3 uses a result event handler function to capture and present data that’s been returned from a CFC function. LISTING 28.3 Handling results from a CFC function with a result event handler
  16. Part IV: Integrating Flex Applications with Application Servers LISTING 28.3 (continued) [Bindable] private var contactData:ArrayCollection; private var contactService:RemoteObject; private function app_creationCompleteHandler():void { contactService = new RemoteObject(“ColdFusion”); contactService.source = “flex4bible.chapter28.ContactService”; contactService.addEventListener(ResultEvent.RESULT, resultHandler); } private function resultHandler(event:ResultEvent):void { contactData = event.result as ArrayCollection; } ]]> On the Web The code in Listing 28.3 is available in the Web site files as ROResultHandler.mxml in the src folder of the chapter28 project. n Listing 28.4 shows the code for the CFC that’s called by this and other applications in this section. Notice that the query object is created manually in ColdFusion code, rather than being generated with a command. As a result, the case of the column names is controlled by this call to the ColdFusion QueryNew() function, rather than being derived from a database query’s metadata: LISTING 28.4 A CFC returning a Query object 886
  17. Chapter 28: Integrating Flex Applications with ColdFusion SELECT * FROM session.qContacts WHERE 0=0 AND firstname LIKE ‘%#trim(arguments.firstname)#%’ AND lastname LIKE ‘%#trim(arguments.lastname)#%’ continued 887
  18. Part IV: Integrating Flex Applications with Application Servers LISTING 28.4 (continued) On the Web The code in Listing 28.4 is available in the Web site files as ContactService.cfc in the ColdFusion files of the chapter28 project. n Handling results from multiple CFC functions When you need to call more than one function from a CFC, you have to distinguish which event handler function should be called for each one. You do this in MXML with the compiler tag, which is nested within a tag set. Each tag represents a CFC function and can declare its own distinct result and fault event handlers. The CFC in Listing 28.4, for example, has a function named getContactCount() that returns a numeric value and a function named getAllContacts() that returns a Query object (translated 888
  19. Chapter 28: Integrating Flex Applications with ColdFusion to an ArrayCollection in the Flex application). To handle each function’s result event with its own distinct event handler function, you create the functions and then declare the tags as follows: The application in Listing 28.5 calls getContactCount() upon application startup to inform the user how many data items are available on the server. The call to getAllContacts() to actually retrieve the data is made only when the user clicks Get Contact Data. LISTING 28.5 Handling result events from multiple CFC functions continued 889
  20. Part IV: Integrating Flex Applications with Application Servers LISTING 28.5 (continued) On the Web The code in Listing 28.5 is available in the Web site files as ROMultipleFunctions.mxml in the src folder of the chapter28 project. n Figure 28.5 shows the resulting application. The Label at the top of the application displays the getContactCount() results immediately upon application startup, while the actual data is displayed only when the user requests it from the server. FIGURE 28.5 An application using two different functions of a single CFC 890
Đồng bộ tài khoản