Using Flash Remoting for Flash MX 2004 ActionScript 2.
Trademarks Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware, Authorware Star, Backstage, Bright Tiger, Clustercats, ColdFusion, Contribute, Design In Motion, Director, Dream Templates, Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, Flash Lite, Flex, Fontographer, FreeHand, Generator, HomeSite, JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track, LikeMinds, Lingo, Live Effects, MacRec
CONTENTS INTRODUCTION: About Flash Remoting . ............................... 9 Who should read this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 About Flash Remoting documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 What’s new in Flash Remoting for Flash MX 2004 ActionScript 2.0 . . . . . . . . . . . 10 Developer resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Handling service results and errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Using the RelayResponder object for a service . . . . . . . . . . . . . . . . . . . . . . . . . 44 Using PendingCall and RelayResponder objects for a specific service function . 45 Using the ResultEvent class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Using the FaultEvent class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 5: The NetConnection Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Using the NetConnection Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Enabling debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Disabling debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 NetConnection events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Calling Enterprise JavaBeans (EJBs) from Flash. . . . . . . . . . . . . . . . . . . . . . . . . . 128 Getting a reference to an EJBHome object in ActionScript. . . . . . . . . . . . . . . 128 Invoking EJB methods in ActionScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Looking at a Flash application that calls an EJB . . . . . . . . . . . . . . . . . . . . . . . 129 Calling servlets and JSPs from Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
APPENDIX A: Using NetServices and Connection Classes . . . . . . . . . . . . . . . . 163 Creating a gateway connection using the NetServices object . . . . . . . . . . . . . . . . 163 Specifying the gateway in the NetServices createGatewayConnection() method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Using the NetServices setDefaultGatewayUrl() method . . . . . . . . . . . . . . . . . 164 Authenticating a user to the application server . . . . . . . . . . . . . . . . . . . . . . . .
Contents
INTRODUCTION About Flash Remoting Macromedia Flash Remoting for Flash MX 2004 ActionScript 2.0 provides a communications channel between Macromedia Flash applications and a wide range of business logic and data from ColdFusion, Microsoft® .NET, Java, and Simple Object Access Protocol (SOAP)-based web services. Using Flash Remoting is intended for Macromedia Flash and application server developers who want to build Rich Internet Applications.
Use the following sources to help you understand and use the tools and technologies that Flash Remoting encompasses. • Flash MX 2004 Help is the comprehensive information source for all Flash MX 2004 features. To open Flash MX 2004 Help in your browser, either select Help > Using Flash, or click the Help button in any dialog box, or the question mark icon in inspectors, windows, and panels.
■ A new Connection class that helps you create and use Flash Remoting connections. Note: The Connection class supersedes the former NetConnection class. ■ ■ ■ A new PendingCall object returned on each call to a service method that is invoked using the Service object. The PendingCall object contains the responder property, which you use to specify the methods to handle the results of the service call.
Resource Description URL Developer resources www.macromedia.com/go/devnet All the resources that you need to stay on the cutting edge of Flash and application server development, including online discussion groups, Knowledge Base, technical papers, and more. Macromedia Alliance Connection with the growing network of solution providers, application developers, resellers, and hosting services creating solutions with Flash Remoting. www.macromedia.
CHAPTER 1 Getting Started Macromedia Flash Remoting for Flash MX 2004 ActionScript 2.0 is an application server gateway that provides a network communications channel between Flash applications and remote services. In this chapter, you learn the basics of Flash Remoting, including the Flash Remoting architecture and how to build a Hello World Flash Remoting application.
• Extensibility Flash Remoting is designed to integrate with established application design patterns and best practices to build well-designed Flash applications.
Once the application server or web service satisfies the service request, it returns the result to Flash Remoting, which in turn encapsulates the data in an ActionScript object, and returns it as an AMF message to the Flash application. In this example, the available seats are returned as a record set that lists the section, row, seat, and ticket price for each of the available seats.
For more information about using software design patterns with Flash Remoting, see Software Design Patterns for Flash Remoting on the Macromedia website at www.macromedia.com/ devnet/mx/flashremoting/articles/facades.html. Understanding the Flash Remoting service adapters Flash Remoting automatically maps incoming requests to the appropriate service adapters, each of which provide a direct connection to a specific application server technology.
Using Flash Remoting Like a web browser request for an HTML page, a Flash application that uses Flash Remoting connects to a remote service and makes a service function call. The service function call is a client-initiated event. The Flash application makes a request to the remote service; the service processes the request and returns the results. It is important to note that the Flash application does not wait for the result; it handles the result when the service function returns it.
Connecting to a service The fundamental step in using Flash Remoting in your Flash application is connecting to a remote service. In Flash Remoting for Flash MX 2004 ActionScript 2.0, you can connect to a remote service either by using the RemotingConnector component or by using the Flash Remoting ActionScript API to write code in the Actions panel.
Building the remote service Flash Remoting supports Java, ASP.NET, and ColdFusion-based remote services. For a simple Hello World application, the following table lists the application server code by platform and specifies where to save the file to make it available to Flash Remoting. Application server Application server code File location ColdFusion MX Save the ColdFusion page as helloWorld.cfm in a folder named remoteservices under your web root.
4. Highlight the text field and in the Property inspector, name the text field messageDisplay and select Dynamic Text in the menu. 5. Open the Actions panel and insert the following ActionScript code, replacing variables that appear in italics with the values that correspond to the server you are using. These values are provided following the code: import import import import import import import mx.remoting.Service; mx.services.Log; mx.rpc.RelayResponder; mx.rpc.FaultEvent; mx.rpc.ResultEvent; mx.
■ ■ The serviceName, which is the name of the remote service. To select the appropriate value for this example, see the table that follows this section. The two null values represent the connection and responder parameters, which are not used in this case. For information about these parameters, see the constructor for the Service class in Flash Remoting ActionScript Dictionary Help. The serviceFunctionName is the name of the service function that you call.
Migrating existing applications to Flash Remoting for Flash MX 2004 ActionScript 2.0 If you are a new Flash Remoting user who has not yet written any Flash Remoting applications, you can skip this section. If you have written Flash Remoting applications using ActionScript 1.0 and you want to migrate to Flash Remoting for Flash MX 2004 ActionScript 2.0, you have two choices regarding how to migrate your applications.
5. Adjust for and adhere to case sensitivity in ActionScript 2.0. ActionScript 2.0 is case sensitive. For example, myVar and myvar were treated as the same variable in ActionScript 1.0 but they are treated as two distinct variables in ActionScript 2.0: var myVar:Object = new Object(); var temp:Object = myvar; trace(temp); // will print undefined 6. Change *_result method names to *_Result. For example, you must change a method named getCategories_result() to getCategories_Result(). 7.
For more information on using Flash Remoting for Flash MX 2004 ActionScript 2.0 features, see Chapter 2, “Using Flash Remoting ActionScript,” on page 29 and Flash Remoting ActionScript Dictionary Help. For a simple example of a Flash Remoting application, see “Building a Hello World application with Flash Remoting” on page 18. For an example of how to use the RemotingConnector component in your application, see “Using the RemotingConnector in the CustomerInfoExampleCon application” on page 57.
3. In the ActionScript code in the Actions panel, change #include statements to import statements: // Old API #include "NetDebug.as" #include "NetServices.as" // New API import mx.remoting.*; import mx.rpc.*; These two import statements will import all of the Flash Remoting for Flash MX 2004 ActionScript 2.0 files. For information on importing specific Flash Remoting files, see “Importing Flash Remoting ActionScript classes” on page 35. 4.
The Service constructor both establishes the gateway URL and creates a reference to the remote service that is being accessed. The Service constructor passes the following parameters in this order: ■ The gatewayUrl, which in this case is "http://localhost:8100/flashservices/ gateway". ■ ■ ■ The Log, which is optional. For information about the Log, see the Log class in the Flash Remoting ActionScript Dictionary. The name of the service you are accessing, which is myServiceName in this case.
// maps result fields to the comboBox dataProvider; name is the label // field and categoryId is the data field. DataGlue.bindFormatStrings(combo, result.result, "#name#", "#categoryId#"); // dispatch a change event for the dataGrid to be updated. combo.dispatchEvent({type:"change", target:combo}); } function gotCatStatus(fault:FaultEvent) { trace(" Error : "+ fault.fault.
8. Set up DataGrid’s listener object to update the details TextArea: gridChange = new Object(); gridChange.change = function(evt) { // when the selectedIndex changes in DataGrid, a change event will be fired. // The details should be updated. details.text = evt.target.selectedItem.description; } grid.
CHAPTER 2 Using Flash Remoting ActionScript This chapter explains how to write ActionScript 2.0 code that uses Macromedia Flash Remoting for Flash MX 2004 to access application services. It explains how to configure connection information, call service functions, and handle the results that the service returns. After reading this chapter, you should be able to create a simple application that uses Flash Remoting to obtain data from an application server.
Note: Flash Remoting applications require that Macromedia Flash Player 6 (6.0.79.0), or later, is installed in the client browser. For information on how to detect the version of Flash Player that a user is using and how to respond accordingly, see Configuring publish settings for Flash Player detection in Using Flash Help.
5. Configure Flash Remoting (create a gateway and a reference to a remote service). 6. Call service functions and pass parameters. 7. Handle the results and error status information returned to Flash in result event-handler routines. The following ActionScript example connects to the petmarket.api.catalogservice service, creates the catalogService Service object, and calls two service functions, catalogService. getCategories() and catalogService.getProducts().
Although a more complex application might be structured differently, the preceding example shows the fundamental elements of a Flash Remoting application. Flash Remoting ActionScript classes The Flash Remoting ActionScript classes provide methods to configure Flash Remoting, to interact with the remote services, and to manipulate data on the client. The following table describes the Flash Remoting classes.
Class Purpose NetServices (Deprecated) Creates a gateway connection, sets a default gateway, and establishes a Connection object for the gateway. The gateway is established by the Flash Remoting software that resides on the application server. Use the NetServices.createGateWayConnection() method to create a gateway Connection object that connects your Flash application to a Flash Remoting gateway on the application server.
Properties and methods The following table shows the Flash Remoting related ActionScript classes and their properties and methods. Notice that the Connection class includes methods in two categories: creating and using connections and services, and debugging.
Purpose Class Managing record sets and data DataGlue RecordSet Properties Methods bindFormatFunction() bindFormatStrings() columnNames items length addItem() addItemAt() clear() contains() filter() getColumnNames() getEditingData() getItemAt() getItemID() getIterator() getLength() getLocalLength() getNumberAvailable() getRemoteLength() isEmpty() isFullyPopulated() isLocal() removeAll() removeItemAt() replaceItemAt() setDeliveryMode() setField() sort() sortItems() sortItemsBy() Importing Flash Remot
Import statement Purpose import mx.services.Log; Log object is optional parameter to Service constructor. You can use the Log class to create a customized logger for your Flash Remoting application. import mx.remoting.debug.NetDebug; Provides debugging methods for Flash Remoting applications. Remove it before publishing your application to a production server to prevent access to debugging information.
Establishing the Flash Remoting gateway connection The specific format of the URL that you use to specify the gateway depends on the application server to which you are connecting: • If you are connecting to a Java server or to Macromedia ColdFusion MX, use the following format: http://webServer[:port]/flashservices/gateway In this URL, flashservices is the name of the Java application context, and gateway is the servlet mapping.
You use the constructor for the Service class to create a new Service object.
Note: If you specify the Flash Remoting gateway in the web page, the ActionScript import mx. remoting.Service; directive must be on the Flash Timeline, not in a SWF file. When you specify the gateway connection in a Web page, you specify the gatewayUrl parameter as an empty string in the Service constructor that you create to access the service.
For example, to create a service object for the Macromedia Pet Market catalog web service, specify a line similar to the following: petMarketCatalogService = gatewayConnection.getService("petmarket.api. catalogservice”, this); Authenticating a user to the application server In some cases, your application server might require you to provide user authentication—a user name and password—before you can use a service.
Flash supplies the login credentials with each service request; therefore, your ActionScript should log the user out of the application server and reset the credentials when the user logs out of your Flash application. To log out the user and reset the credentials: 1. Call a logout service function on the server that logs out the user. For example, for ColdFusion, call a method that uses the cflogout tag. 2. Set the gateway connection credential information to empty strings.
In this example, the service function passes two parameters, a language specification (en_US), and a type of category ("Accessories"). Note: Parameters must be in the order required by the service function. import import import import import mx.remoting.Service; mx.remoting.PendingCall; mx.rpc.RelayResponder; mx.rpc.ResultEvent; mx.rpc.
Service type Function name ColdFusion pages (.cfm) ColdFusion page (without the cfm suffix) ColdFusion components (.cfc) Component method Note: Calling web services using Flash Remoting is supported only in Flash Remoting for ASP.Net and in the Flash Remoting support included with ColdFusion MX. Flash Remoting for Java and the Flash Remoting support in JRun do not support calling web services using Flash Remoting.
If you create a RelayResponder object at the time that you create a Service object, the result and fault handling methods must handle the result and fault outcomes for all functions that you call on that service. Flash Remoting returns a fault event instead of a result if either of the following conditions occur: • The Flash Remoting gateway encounters an error. • A service function encounters an error (throws an exception).
mx.remoting.debug.NetDebug.trace({level:"None", message:"There was a problem: " + fault.fault.faultstring }); } When you specify a RelayResponder object for a service, results for all service functions are relayed to the specified result and fault handling methods, which you must provide.
Handling the result object requires knowledge of the service function. The service function could return a simple string, as shown in the following HelloWorld_Result() method: function serviceFunctionName_Result(result:ResultEvent) { // display successful result messageDisplay.text = result.result; } The service function could also return a complex object such as a record set holding several records that were retrieved from a database.
Using the Flash Remoting ActionScript API in the CustomerInfoExampleAPI application The CustomerInfoExampleAPI application uses the ActionScript API to connect to the customerData remote service. This application illustrates the following features of Flash Remoting for Flash MX 2004 ActionScript 2.
The ActionScript code for this example imports the Service, Log, RelayResponder, FaultEvent, ResultEvent, PendingCall, and RecordSet classes for Flash Remoting. In addition, it imports the appropriate classes for the user interface components. The application creates the CustomerInfoForm class, which extends the Form class. The sections following the ActionScript code describe the functions in this class.
col = new DataGridColumn( "TotalSales" ); col.width = 80; col.textAlign = "right"; customers_grd.addColumn( col ); customers_grd.addEventListener( "change", onCustGrid_Change ); // setup remaining totalRec_txt.setStyle( "textAlign", "right" ); //set the textField to Left Align totalSales_label.
// handles the results from the request to getCustomers() method of the service function onCustomerData( re:ResultEvent ):Void { // update customer grid var rs:mx.remoting.RecordSet = mx.remoting.RecordSet( re.result ); rs.setDeliveryMode( "onDemand" ); totalRec_txt.text = String( rs.length ); customers_grd.dataProvider = rs; customers_grd.
Establishing the connection in the HTML file enables you to change it without needing to republish the application. After creating the custService Service object, CustomerInfoFormAPI() calls the custService. function to retrieve a record set of all categories, sets the alignment for the Total Sales label on the DataGrid component, and assigns a RelayResponder object to the responder property of the pc PendingCall object for the call to getCategories().
The onReveal() function calls the addEventListener() function to establish this function as the event handler for the customers_grd DataGrid component. onCustCat_Change() The onCustCat_Change() function is the event handler that is called when the selection in the Category ComboBox component changes. It calls the refreshCustomerData() function to retrieve the customers for the selected category.
CHAPTER 3 Using the RemotingConnector component (Flash Professional only) The RemotingConnector component, along with the WebServiceConnector component and the XMLConnector component, implements the Remote Procedure Call (RPC) Component API, which is a set of methods, properties, and events that define an easy way to send parameters to, and receive results from, an external data source.
Flash Remoting uses the schema of a RemotingConnector component to specify the characteristics of both the parameters that a remote service function requires and the results that it returns. You specify the schema values on the Schema tab of the Component inspector for the RemotingConnector component, as shown in the following example.
These parameters can take the following values: Parameter Type multipleSimultaneousAllowed Boolean Category Description General If it has the value true, this parameter allows the trigger() method to be invoked even if results have not yet been returned from a previous invocation. If it has the value false, the trigger() method does not invoke a method if a method call is already in progress. In this case, a status event occurs with code = "CallAlreadyInProgress".
Creating an instance of the RemotingConnector component You can create an instance of the RemotingConnector component in your Flash application by dragging it to the Stage, defining the schema, and binding the service parameters and the result to the UI component that uses them: To create an instance of the RemotingConnector component 1. In the Components panel, double-click the RemotingConnector component to place an instance on the stage.
The following section presents a sample application that uses the RemotingConnector component. Using the RemotingConnector in the CustomerInfoExampleCon application The CustomerInfoExampleCon application, which this section describes, illustrates the following Flash Remoting for Flash MX 2004 ActionScript 2.
The ActionScript code for this example imports the RemotingConnector class and the appropriate classes for the user interface components, and creates the CustomerInfoFormCon class, which extends the Form class. The sections following the ActionScript code describe the functions in this class. import import import import import import import import import import mx.data.components.RemotingConnector; mx.controls.DataGrid; mx.controls.gridclasses.DataGridColumn; mx.controls.ComboBox; mx.controls.TextArea; mx.
categoryData_con.trigger(); initialized = true; } } // updateDetails will update the details TextArea, textInput and the // Loader present on the screen changes will be updated when the selection // in DataGrid changes function updateDetails() { var curItem:Object = customers_grd.selectedItem; custInfo_txt.text = curItem.Details; totalSales_label.text = curItem.TotalSales; custLogo_ldr.contentPath = curItem.Logo; custLogo_ldr.load(); custLogo_ldr.
// handles the display of the fault information related to the category data // request to the user function onCategoryDataFault( status:Object ):Void { // notify the user of the problem if( status.code == "fault" ) { Alert.show( "Couldn't retrieve category data.", "Error", Alert.OK, this ); mx.remoting.debug.NetDebug.trace({level:"None", message:"There was a problem: " + status.data.
Finally, the onReveal() function calls the trigger() method for the categoryData_con RemotingConnector object to connect to the service, retrieve the Category data for the ComboBox component, and execute the data bindings to populate it. updateDetails() The updateDetails() function updates the text, the total sales, and the logo in the Customer Details section of the user interface. This function is called by the onCustGrid_Change() function.
Chapter 3: Using the RemotingConnector component (Flash Professional only)
CHAPTER 4 Using Flash Remoting Data in ActionScript This chapter explains how to handle data that your ActionScript sends to and receives from service functions. It discusses how Macromedia Flash Remoting for Flash MX 2004 ActionScript 2.0 converts data types, type-specific data handling issues, and how to use simple and complex data types. It also discusses using RecordSet objects and other object types in detail.
The following figure shows this data conversion: A two-step conversion process enables Flash Remoting to use a system-neutral, efficient representation for the data it transmits. This way, you can create a Flash application that can work with multiple application servers. Flash Remoting performs all data conversions automatically.
Converting from ActionScript to application server data types Flash Remoting automatically converts between ActionScript data and the data types specific to the application server programming environment. In strictly typed environments, such as Java and C#, the service function data types must correspond to (or be derived from) the listed data types.
Converted Visual Basic data type Converted Converted ColdFusion SOAP data type MX data type FlashGateway. IO.ASObject Complex type Struct Object of type FlashGateway. IO.ASObject For more information, see “Working with ActionScript typed objects” on page 71 flashgateway.io. FlashGateway. Object IO.ASObject consisting of ASObject name-value pairs passed as the only argument to a service function (Typically used to pass data to ColdFusion.) FlashGateway. IO.
The following is additional information on conversion from ActionScript data types to server data types: • Flash Remoting converts ActionScript Number data types to any valid Java or .NET numeric data type wherever possible. If the number cannot be converted to the appropriate data type for the service, if the number exceeds the valid range of an integer data type, for example, Flash Remoting throws an error on the server.
C# data type Visual Basic data type SOAP ColdFusion data type MX data type System.Collection System.Collection array s.ICollection s.ICollection object[] object[] System.Collection s.Hashtable System.Collection s.IDictionary System.Collection complex type s.Hashtable System.Collection s.IDictionary Sytem.Data. DataSet Sytem.Data. DataSet Converted ActionScript data type Array Collection Array Object[] array of primitive types Struct java.util.
The following is additional information on conversion from server data types to ActionScript data types: • If a string data type on the server represents a valid number in ActionScript, Flash can automatically cast it to a number if needed. • If you use the setType() method to assign an object type to a flashgateway.io.ASObject object on the server, and the type name matches the name of a registered class in ActionScript, Flash Remoting creates an instance of that type in ActionScript.
If a ColdFusion page or CFC returns a numeric value without specifically identifying the value as numeric, Flash Remoting treats the value as a string when passing it to the responder.
When you return an object from the server to Flash, Flash Remoting sends the contents of the object’s data properties to Flash as a Flash object. In Flash, you can access any of the object’s properties that are of types that can be converted to Flash data types. The following sections cover two special cases of objects: ActionScript typed objects and Java Serializable objects. Working with ActionScript typed objects If you use the Object.
The following example shows a Java class service function that creates a typed object and returns it to Flash: package mycompany.flash; import flashgateway.io.ASObject; public class MyFlashService { public MyFlashService() { } public ASObject getFlashObject() { ASObject aso = new ASObject("MyFlashObject"); aso.put("first", "apple"); aso.put("second", "banana"); return aso; } } Note that this example specifies the object type, MyFlashObject, in the constructor.
public String getText(){return this.text;} public void setText(String t){this.text = t;} public String getRecipient(){return this.recipient;} public void setRecipient(String r){this.recipient = r;} public Message getMessage() { return this; } } You can use the following ActionScript to set and get the result object’s properties. (For brevity, this example omits the code that configures the network connection and service object.) myBeanService.setText("Hello from Me."); myBeanService.
About record sets A record set is a two-dimensional data table. The rows of the table correspond to individual data records, such as the data for a particular product or employee. The columns of the table correspond to different fields of a record, such as an employee’s title or a product color. The following table shows a sample record set structure: lastName firstName emailAddress telExt Smith Dave dave.tomlin@macromedia.com 3456 Basham Meredith meredith.neville@macromedia.
RecordSet methods You can use the following methods to create and manage RecordSet objects. Method Description constructor for RecordSet Creates a new local RecordSet object. RecordSet.addEventListener() Registers a listener object with this RecordSet. When the RecordSet is modified in some way the listener can respond to these changes. The only event that the RecordSet emits is the modelChanged event. RecordSet.addItem() Inserts a record into the RecordSet object. RecordSet.
Method Description RecordSet.setDeliveryMode() Changes the delivery mode of a pageable record set from an application server. RecordSet.setField() Replaces one field of a record with a new value. RecordSet.sort() Sorts all the records using a comparison function that you specify as an argument to the method. RecordSet.sortItems() Sorts all the records using a user-specified comparison function RecordSet.
Getting information about a RecordSet object To get information about a RecordSet object, use the following methods: Method Description RecordSet.contains() Indicates whether the record set contains the specified record. RecordSet.getColumnNames() Returns an array of the names of the columns of a RecordSet object. RecordSet.getItemID() Returns the record ID used internally by Flash Remoting to identify the record. RecordSet.getIterator() Returns a new iterator for the record set.
Adding records to the RecordSet object To add items to a RecordSet object, use the addItem() or addItemAt() methods. The addItem() method adds a record at the end of the record set. The addItemAt() method inserts a record at the specific index location; the indexes of all the other records in the RecordSet object are automatically incremented by one.
To set up a notification event for an ActionScript object, use the RecordSet addEventListener() method and specify the object to notify when the RecordSet object changes. You can specify any object that receives change notifications in the addEventListener() method, as in the following example: myRecordSet.
Sorting record sets To sort the records of a RecordSet object, use the sortItems and sortItemBy() methods. The sortItemBy() method performs an ascending (the default) or descending sort on the records in the RecordSet object. The sortItems() method requires a comparison function as an argument, and uses that function to sort the records. The sortItemsBy() method is implemented natively in Flash Player 7.x and is substantially faster than the sortItems() method.
The following example filters a RecordSet object to produce a new RecordSet object with records that have contact fields that start with a specific letter: var mySelectionFunction = function(aRecord, letter) { return (aRecord.contact.charAt(0) == letter); } contact_grid.dataProvider = myRecordSet.filter(mySelectionFunction, theLetter); In this example: • The contact_grid variable represents a ListBox UI component.
Flash Remoting can deliver pageable record set data to your application in three modes, as described in the following table: Data delivery modes Description ondemand (default) When you access a particular record using the getItemAt() method, the RecordSet object requests the record from the server-side Flash Remoting RecordSet service. page When you use the getItemAt() method to access a record, the RecordSet object fetches data one or more pages at a time.
If the config_panel object specifies page mode, the setDeliveryMode() method tells Flash Remoting to set the page size to the number of rows in the contact_grid movie clip and to prefetch one additional page beyond the page with the requested data, if it is not in memory.
By default, each label value is a comma-delimited string that consists of the contents of one record’s fields; the data values are not set. However, you can use a RecordSet object directly in the dataProvider property to provide both the list and data values if the record set has two columns and the column names are label and data.
For example, the following formatting function takes a record that includes a parkname field. It converts the parkname text to all lowercase as the label, and uses the field’s length as the data. The bindFormatFunction() method calls the formatting function once for each record in the record set and uses the output of the function to populate a Flash UI component: function myFormatFunction ( record ) { // The label is the parkname record field, translated to lowercase var theLabel:String = record.parkname.
// Function that runs when the user clicks a "Test XML" button after // entering text in two text boxes. Handles a return message sent by // the server: function testDocument(){ // Create the XML document. var xmlDocument:XML = new XML(); var firstElement:XMLNode = xmlDocument.createElement("test"); firstElement.attributes.message = input1_txt.text; var secondElement:XMLNode = xmlDocument.createElement("insidetest"); secondElement.attributes.message = input2_txt.text; firstElement.
CHAPTER 5 The NetConnection Debugger This chapter describes how to use the NetConnection Debugger and the NetDebug and NetDebugConfig classes to debug your Flash Remoting application. It includes a brief description of the NetConnection Debugger interface and describes the types of events that the debugger can display. It also documents how you can use the NetDebug class to control the information displayed in the NetConnection Debugger, including displaying trace events.
To use the NetConnection Debugger with your Flash Remoting application 1. From the Window menu in Flash, select Other Panels > Common Libraries > Remoting. 2. From the Library panel, drag the RemotingDebugClasses library to the Stage. 3. Use the following import directive to import the NetDebug class at the beginning of the ActionScript code for your Flash application: import mx.remoting.debug.NetDebug; 4. Call the NetDebug.
If you experience connectivity problems with the NetConnection Debugger, try starting it outside the Flash authoring environment by following these steps: To start the NetConnection Debugger outside of the Flash authoring environment: 1. Locate the NetConnection Debugger SWF file. For Windows: C:\Program Files\Macromedia\Flash MX 2004\en\First Run\WindowSWF\ For Mac: HD:Applications:Macromedia Flash MX 2004:First Run:WindowSWF: 2.
The following table describes the information the NetConnection Debugger displays about specific event types. 90 Event type Information displayed by the debugger client Activity information sent from the client. The default value is true. For detailed information on client debug events, see “Client event messages” on page 92. You can selectively enable and disable the following subcategories of client events. trace Client Connection trace events.
Event type Information displayed by the debugger recordset Events associated with the partial delivery of pageable record set data from the server. These events occur only if the record set is pageable.The default value is true. coldfusion Information about Macromedia ColdFusion debug events. When enabled, any debug events enabled in ColdFusion are reported to the NetConnection Debugger.
Client event messages The following table describes the specific client events that the NetConnection Debugger reports, and the information it displays for each event: Event type Triggering event 92 Information fields Trace Trace The object passed to the NetDebug.trace() or Flash executed a NetDebug.trace() or Connection.trace() method. Typically a message. Connection.trace() method. Connect The Flash application requested a connection to the gateway.
Application server event messages The following table describes the specific app_server events that the NetConnection Debugger reports and the information it displays for each event: Event type Triggering event Information fields Error An unresolved error occurred Data Any object associated with the error event. Normally an Exception object. in the Flash Remoting gateway or adapter. These Message A message that describes the error. errors should not occur in normal processing.
ColdFusion event messages If you enable debugging output in ColdFusion, the NetConnection Debugger can report a subset of the debugging information that is normally displayed by the ColdFusion server.
Using the Netdebug.initialize() method The NetDebug.initialize() method initializes debug support for Flash Remoting. You must call this method prior to creating a connection or using any debugging operations, and typically before any ActionScript is executed in the SWF file. This method returns the Boolean value true if it initializes debug support successfully. Otherwise, it returns a value of false.
You can send a trace message that includes the connection ID by using the GatewayConnection object’s trace() method, as in the following example: gatewayConnection.trace("I just created myService2 over this connection."); Additionally, the getDebugId() method returns the ID set by the setDebugId() method, and the getDebugConfig() method returns the NetDebugConfig object for the specific connection.
CHAPTER 6 Using Flash Remoting with ColdFusion MX To use Macromedia Flash Remoting for Flash MX 2004 ActionScript 2.0 with Macromedia ColdFusion MX, you build ColdFusion pages or ColdFusion components (CFCs). In ColdFusion pages, you use the Flash variable scope to interact with Flash applications. ColdFusion components provide native support for Flash interactions.
For example, suppose you create a ColdFusion page named helloWorld.cfm in the directory helloExamples under your web root (web_root/helloExamples). You can then use the following ActionScript in your Flash application to call helloWorld.cfm: import mx.remoting.Service; import mx.remoting.PendingCall; import mx.rpc.RelayResponder; //… var CFMService:Service = new Service( "http://localhost/flashservices/gateway", null, "helloExamples", null, null); var pc:PendingCall = CFMService.helloWorld(); pc.
The Flash scope has several predefined variables that you can use to pass information, as described in the following table: Variable Description For more information Flash.Params Array containing the parameters passed from the Flash application to the ColdFusion page. If you do not pass any parameters, Flash.Params still exists, but it is empty. See “Using Flash.Params to access parameters in a ColdFusion page” on page 99. Flash.
In your ColdFusion page, you access the parameter using Flash.Params, as shown in the following example: SELECT ItemName, ItemDescription, ItemCost FROM tblItems WHERE ItemName='#Flash.Params[1]#' Because ColdFusion converts an ActionScript data type to the corresponding ColdFusion data type, you can perform CFML type-specific operations on the parameter.
The following table lists ActionScript collections and describes how to access them in ColdFusion pages: Collection ActionScript example Notes Strict array var myArray:Array = new Array(); myArray[0] = "zero"; myArray[1] = "one"; myService.myMethod(myArray); The Flash Remoting service converts the array parameters to a ColdFusion MX array. All CFML array operations work as expected.
You access x and y in your ColdFusion page using ColdFusion array and structure notation, as follows: arrayElement2=Flash.x[2]> structElement1=Flash.y.zero> structElement2=Flash.y.one> You can pass ActionScript objects to ColdFusion pages. The following ActionScript defines an object: var myObj:Object = new Object(); myObj.x = "one"; myService.
The directory name is the service address, and the helloWorld.cfm file is a method of the helloExamples directory of the Flash Remoting service. The following ActionScript example calls the helloWorld ColdFusion page: import import import import import mx.remoting.Service; mx.remoting.PendingCall; mx.rpc.RelayResponder; mx.rpc.FaultEvent; mx.rpc.
Depending on the SQL code of the query and the amount of data stored in the database, the query can return a single record, a few records, or a very large number of records. To pass the entire record set to the Flash application, you simply write the record set to the Flash.Result variable. In ActionScript, you access the record set columns to display the query. For example, you use the following ActionScript code to call a ColdFusion page named cfQuery.cfm that contains the previous query: myService.
When you assign a value to the Flash.Pagesize variable, you specify that if the record set has more than that number of records, the record set becomes pageable and returns the number of records specified in the Flash.Pagesize variable. For example: import mx.remoting.Service; import mx.remoting.PendingCall; //… var CFMService:Service = new Service( "http://localhost/flashservices/gateway", null, "helloExamples", null, null); var pc:PendingCall = CFMService.
Note: For ColdFusion component methods to communicate with Flash applications, you must set the cffunction tag’s access attribute to remote. You call these functions in ActionScript using the following syntax: CFCService.functA(); CFCService.functB(); Returning results to ActionScript In a ColdFusion component, you use the cfreturn tag to return a single variable to ActionScript.
The order in which you specify the cfargument tags in the function corresponds to the order in which the parameters are passed from ActionScript. For example, the following ActionScript call passes three parameters: CFCService.functA(a, b, c); The corresponding ColdFusion component defines three arguments, including the data type of the parameter:
The following example replicates the helloWorld() function that was previously implemented as a ColdFusion page. For more information, see “Using Flash Remoting with ColdFusion pages” on page 97. To create a ColdFusion component that interacts with a Flash application: 1. Create a ColdFusion component, and save it as flashComponent.cfc in the helloExamples directory. 2. Edit flashComponent.
You can also pass arrays, structures, and named objects using this syntax. The following ActionScript code defines an object: var params:Object = new Object(); params.first = "Hello"; params.second = true; service.
To create a ColdFusion component that describes itself to the Service Browser: 1. Edit the flashComponent.cfc file in the helloExamples directory by inserting the following code:
Using Flash Remoting with server-side ActionScript The ability to create server-side ActionScript provides a familiar way for Flash developers to access ColdFusion query and HTTP features without learning CFML. Identify the ActionScript files (with the .asr extension) that you want to call from the Flash application and place them on the server, anywhere under the web server’s root directory. To specify subdirectories of the web root or a virtual directory, use package dot notation.
"http://localhost/flashservices/gateway", null, "httpFuncs", null, null); // call service method - basicGet() var pc:PendingCall = myHttpService.basicGet("http://examples.macromedia.com/ flashservices/gateway"); // specify result and fault handler functions pc.responder = new RelayResponder(this, "basicGet_Result", "basicGet_Fault"); // display returned result function basicGet_Result(result:ResultEvent):Void { myDisplayScreen.text = result.result; } The CF.
Property Description Responseheader Response header. If there is one instance of a header key, you can access the value as a simple type. If there is more than one instance, values are put in an array in the responseHeader structure.
When using positional arguments, do not use curly braces. Using CF.query() The CF.query() function lets you perform queries against any ColdFusion data source. The CF.query() function maps closely to the cfquery CFML tag, although it currently supports a subset of the cfquery attributes. You use the CF.query() function to perform the following actions: • Identify the data source you want to query • Pass SQL statements to the data source • Pass other optional parameters to the database You can write the CF.
Calling web services from Flash Remoting Using Flash Remoting with ColdFusion, you can interact with web services directly from your Flash applications without having to build a ColdFusion page or component. You write the code to reference a web service in your Flash application and use ColdFusion only to perform the access. Web services are remote applications that expose their functions and associated parameters using the Web Services Description Language (WSDL).
To handle the results of the web service method, you create an event handler with the same name as the service functions with _Result or _Fault appended to the name. The result handler displays the results in the myGrid DataGrid component, as the following example shows: function getCategories_Result(result:ResultEvent):Void { // display successful result myGrid.dataProvider = result.result; } function getCategories_Fault(fault:FaultEvent):Void { message_txt.text = fault.fault.
> PAGE 118To simplify the debugging of your ColdFusion code, use the cftry and cfcatch tags in your ColdFusion page or component to catch errors and return helpful error messages about the errors to the Flash application. For example, the ColdFusion page causeError.cfm contains the following code: PAGE 119CHAPTER 7 Using Flash Remoting for Java This chapter describes how to use Macromedia Flash Remoting for Flash MX 2004 ActionScript 2.0 with services running in Java application servers. You can use Flash Remoting from ActionScript in a Flash application to call public methods on Java objects running in Java application servers.
About Flash Remoting for Java Flash Remoting exposes Java objects as services that are accessible from Flash applications as ActionScript functions that correspond to Java object methods. A Flash developer writes ActionScript that uses the ActionScript Service class to connect to a remote Java application server, get a reference to a service, and invoke the service’s functions.
You can use a value object to send a coarse-grained view of data to the server and get back fine-grained data. For example, you can call a single method on a value object that aggregates several method calls on an entity bean. The method result is returned to the Flash application as an ActionScript result object from which you can access data locally. This pattern can help to reduce network traffic and response time, and to reduce the load on EJBs.
The following table lists standard ways to add classes to the system classpath: Application server Classpath information Sun™ ONE Web Server In the Web Server Administration Server console, add classes to the Classpath field in the Configure JVM Attributes page of the Java panel. IBM® WebSphere® In the WebSphere Application Server Console, add classes to the Classpath field of the JVM Settings page for your server. In the server-cfg.
Invoking Java methods in ActionScript After you have created a reference to a Java class or JavaBean, you can use ActionScript functions to invoke that object’s public methods.
Looking at the JavaBean code The example Flash application invokes the setMessage(), getMessage(), testBoolean(), and testDate() methods of the following JavaBean: package com.samples; import java.util.Date; import java.io.Serializable; import org.w3c.dom.
Looking at the user interface for the JavaBean The following figure shows the user interface of the example Flash application with callouts that indicate the field types and variable names referenced in the ActionScript code. This Flash application invokes several ‘getter’ and ‘setter’ methods on a JavaBean in the remote server. The bean is statefil to this client, as indicated by the counter. This is designed to be identical to the useBean functionality of JSP.
invokeButton.addEventListener("click", runExample); // Set initial text for messageInput and dateInput text fields. messageInput.text = "[Enter a Message]"; dateInput.text = "" + flashDate; } // Invoke business methods when user clicks the runButton function runExample() { _parent.setMessage(); _parent.getMessage(); _parent.testBoolean(); _parent.testDate(); } // Business functions. function setMessage() { flashtestService.setMessage(messageInput.text).
// Handle results from server; display results in output fields. function setMessage_Result( re:ResultEvent ):Void { // shouldn't happen } function getMessage_Result( re:ResultEvent ):Void { messageOutput.text = re.result.toString(); } function setMessage_Fault( fe:FaultEvent ):Void { messageOutput.text = fe.fault.faultstring; } function getMessage_Fault( fe:FaultEvent ):Void { messageOutput.text = fe.fault.faultstring; } function testBoolean_Result(re:ResultEvent):Void { boolOutput.text = "result: " + re.
Calling Enterprise JavaBeans (EJBs) from Flash The following sections describe how to get a reference to an EJBHome object and call Enterprise JavaBeans (EJB) methods from ActionScript. Getting a reference to an EJBHome object in ActionScript Before calling the methods of an EJB from ActionScript, you must get a reference to an EJBHome object. To get a reference to an EJBHome object: 1. Import the mx.remoting.Service file: import mx.remoting.Service; 2.
mx.remoting.debug.NetDebug.initialize(); //… function runExample() { var SampleLoanHome:Service = new Service( "http://localhost:8300/flashservices/gateway", null, "SampleLoanEjbHome", null, null); var pc:PendingCall = SampleLoanHome.create(); pc.responder = new RelayResponder(this, "create_Result", "create_Fault"); } function create_Result( re:ResultEvent ) { flashStatelessEJB = re.result; calculate(); } function create_Fault( fe:FaultEvent ) { mx.remoting.debug.NetDebug.
Looking at the EJB code The example Flash application calculates loan payments by invoking the calculate() method on the following stateless session bean: package ejbeans; import java.rmi.*; import java.util.*; import javax.ejb.
Looking at the ActionScript code that calls the EJB The following code is the ActionScript of the example Flash application: // Import Flash Remoting files import mx.remoting.Service; import mx.remoting.debug.
Calling servlets and JSPs from Flash The following sections describe how to get a reference to a servlet or a JSP defined as a servlet in a web.xml file, and call the servlet or JSP. Note: Servlets are supported on Servlet 2.2- and Servlet 2.3-compliant application servers. JSPs are supported only on Servlet 2.3-compliant application servers.
Calling a servlet or JSP To call a servlet or a JSP defined as a servlet from ActionScript, use the servlet name specified in the web application’s web.xml deployment descriptor file as an ActionScript function name. For example, the servlet name is MyServlet in the following example: function go_Clicked() { var pc:mx.remoting.PendingCall = servletService.MyServlet(); pc.responder = new RelayResponder( this, "MyServlet_Result", "onCategoryFault" ); // etc. } The web.
} public String getServletInfo() { return "A test servlet."; } public ServletConfig getServletConfig() { return null; } public void destroy() { message = null; } } To handle the function results in ActionScript, you use a result handler function like this one: function MyServlet_Result (result:mx.rpc.ResultEvent):Void { ResultBox.text = result.result; } For more information, see “Handling function results in ActionScript” on page 137.
Getting a reference to an MBean in ActionScript Before calling the methods of an MBean from ActionScript, you must get a reference to an MBean. To get a reference to an MBean: 1. Import the Flash Remoting files: import mx.remoting.Service; 2. Connect to the Flash Remoting gateway and get a reference to the MBean object.
Getting a reference to a server-side ActionScript file Before calling the functions of a server-side ActionScript file (with the .asr extension), you must get a reference to the file. Place the server-side ActionScript file that you want to call in a web application. To get a reference to a server-side ActionScript file: 1. Import the Flash Remoting files: import mx.remoting.Service; 2.
For more information, see the next section. Handling function results in ActionScript In Java application servers, you handle function results in ActionScript the same way that you do for other platforms that Flash Remoting supports. You write an ActionScript result handler function and tell the RelayResponder object its name. For example, to pass the return value of the following ActionScript function to ActionScript: function calculate() { loanService.calculate( (number (principalInput.
The calculate() function returns the following LoanInfo bean: package samples; public class LoanInfo { private double principal; private int months; private float rate; private double monthlyPayment; public LoanInfo() { } public LoanInfo(double principal, int months, float rate, double monthlyPayment) { this.principal=principal; this.months=months; this.rate=rate; this.monthlyPayment=monthlyPayment; } public LoanInfo(double principal, int months, float rate, double monthlyPayment, String message) { this.
You can use the following ActionScript code to get the value of the LoanInfo bean’s MonthlyPayment property, or handle a fault condition: function calculateReturnComplex_Result (re:ResultEvent):Void { payOutput.text = re.result.monthlyPayment; } function calculateReturnComplex_Fault (fe:FaultEvent):Void { mx.remoting.debug.NetDebug.trace({level:"None", message:"There was a problem" + fe.fault.
The following example shows entries for the FlashRole role and corresponding EJB method permissions in an ejb-jar.
flashtestService.testDocument(xmlDocument); } Note: You can also create an XML document object in ActionScript by passing a string representation of the XML to the new XML(source) constructor. For more information, see the Flash documentation set. Returning an XML object from Java to Flash The JavaBean method discussed in the previous section returns an org.w3c.dom.Document object as follows: public Document testDocument(Document doc) { return doc; } Flash Remoting converts the returned org.w3c.doc.
Chapter 7: Using Flash Remoting for Java
CHAPTER 8 Using Flash Remoting for Microsoft .NET Macromedia Flash Remoting for Flash MX 2004 ActionScript 2.0 for Microsoft .NET is an ASP.NET web application that enables Flash applications to access and invoke ASP.NET pages, ADO.NET data, web services, and assemblies from ActionScript. This chapter contains the following sections: • • • • • • “Flash Remoting for Microsoft .NET” on page 143 “Calling ASP.NET pages from Flash” on page 147 “Using ADO.
Flash Remoting contains four service adapters for .NET technologies: • • • • ASP.NET adapter ADO.NET data-binding adapter Web services adapter Assembly (with the .dll extension) Flash Remoting for .NET requires the .NET Framework SDK to be installed. To check whether you have the .NET Framework installed, open the Windows Control Panel and double-click the Add/Remove Programs icon. In the Add/Remove Programs dialog box, look for Microsoft .NET Framework SDK.
The facade structural design pattern can be particularly useful with Flash Remoting by reducing the number of remote method calls required in a Flash application. You can use a service facade to provide a single point of contact to a set of ASPX pages or DLL methods. You can call methods on a DLL facade that is capable of calling various methods on several other DLLs, ASPX pages, or web services, depending on the user’s current context in the application.
As the figure shows, the local assembly cache in the myASPApp directory contains the Flash Remoting assembly, flashgateway.dll. Also, to connect a Flash application with a remote service, you must reference a physical resource in your application’s directory in the web root. Flash Remoting automatically installs a blank ASPX page named gateway.aspx, but you can use any ASPX file in the application directory. The web.config file contains the registration for the flashgateway.dll.
Your Flash Remoting-enabled ASP.NET application directory is now ready to use. Calling ASP.NET pages from Flash This section describes calling an ASPX page from Flash using Flash Remoting, working with the Flash Remoting custom server control in ASPX pages, using the Flash Remoting namespace in code-behind files, and so on.
function gotResourcesFault( fe:mx.rpc.FaultEvent ): Void { trace( "error occurred"+ fe.fault.faultstring ); } The gateway URL must reference an ASPX page inside the application directory. You should use the gateway URL only during development in the Flash authoring environment. When you deploy the Flash application, you should supply the gateway URL using a parameter in the HTML that embeds the SWF file in the web page.
Using the Flash Remoting custom server control in ASPX pages To access data passed from Flash applications or return results to Flash applications in ASPX pages, you use the Flash Remoting custom server control in your ASPX page. The Flash Remoting server control is provided by the flashgateway DLL, which is located in the local assembly cache (bin directory) of your application. You must first register this control, as you would any custom server control, in your ASPX page.
If more than one parameter is passed from Flash, you access the parameters in your .NET application in the same order that they were passed from the Flash application. For example, the following ActionScript function passes two parameters, assuming firstname and lastname are input text fields in a Flash application: ASPXservice.myASPPage(firstname.text, lastname.text); In an ASPX page, for example, you access the parameters using strict array syntax, as the following VB.
... } } The following VB.NET example performs the same operation: Namespace Samples.ado Public Class CustomerInfo Inherits System.Web.UI.Page Protected Flash As FlashGateway.Flash After you establish the Flash Remoting namespace, you can manipulate the server control properties in the Page_Load method definition, as the following VB example shows: Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load{ dim message as string message = "Hi " if Flash.Params.
To return a session variable, you use the Flash.Result property, as shown in the following example: <%@ Page language="c#" debug="true" %> <%@ Register TagPrefix="Macromedia" Namespace="FlashGateway" Assembly="flashgateway" %> <% Flash.Result = session.myPreference; %> In the code, the value of the myPreference variable is assigned to the Flash.Result property, which is returned to Flash.
Using ADO.NET objects with Flash Remoting Flash Remoting provides a service adapter for binding ADO.NET data tables and data views to the Flash Remoting custom server control. To bind data sets to the custom server control, you use the control’s DataSource property and DataBind method. In ActionScript, the results are exposed as a RecordSet object.
To display the data from the previous ASPX page, as CustomerCountries.aspx under the ADOExamples folder, in a DataGrid object called custCountry_grd, the ActionScript code would look like this: import import import import import mx.remoting.Service; mx.remoting.PendingCall; mx.rpc.RelayResponder; mx.rpc.FaultEvent; mx.rpc.ResultEvent; var custCountryASPX:Service = new Service( "http://localhost/flashremoting/ gateway.aspx", null, "flashremoting.samples.
Dim selectContactData As String 'insert Flash parameter into SQL statement selectContactData = "SELECT ContactName, City, Phone FROM Customers WHERE Country = \'" + selectedCountryName + "\'" End If 'create the data adapter object Dim countryAdapter As System.Data.OleDb.OleDbDataAdapter 'create a dataset object countryAdapter = New System.Data.OleDb.OleDbDataAdapter(selectAll, sqlConnection) 'fill the dataset with the query results countryAdapter.
import mx.rpc.RelayResponder; import mx.rpc.FaultEvent; import mx.remoting.PendingCall; // get a reference to the ASPX-based service var ASPXservice:Service = new Service("http://localhost/myASPApp/ default.aspx",null,"myASPApp",null,null); // call the ASPX page var pc:PendingCall = ASPXservice.myASPPage(); pc.responder = new RelayResponder(this, "myASPPage_Result", "myASPPage_Fault"); // handler for ASPX page results function myASPPage_Result(re:ResultEvent):Void { DataGlue.
Invoking web service methods using Flash Remoting Flash Remoting uses the .NET WSDL Tool to generate the necessary proxy classes automatically by specifying a valid URL to a WSDL file or to a URL that can generate a WSDL file, such as a .NET ASMX file. To invoke a local web service in an ASMX file from Flash, you enter the URL to the file appended with ?wsdl, as the following ActionScript example shows: var flashService:Service = new Service( "http://localhost/myASPApp/default.
null); var pc:PendingCall = flashService.getMessage(); pc.responder = new RelayResponder( this, "getMessage_Result", "getMessage_Fault" ); function getMessage_Result(var re:ResultEvent):Void { serviceMessage.text = re.result; } function getMessage_Fault(fe:FaultEvent):Void { serviceMessage.text = fe.fault.faultstring; } Invoking a remote web service from Flash Using Flash Remoting for .NET, you can invoke any remote .NET-compatible web service directly from your Flash application with no .
In the ActionScript code, you specify the serviceName argument with a URL that produces WSDL. The getTemp function maps to the web service method of the same name. Here, zip represents an input text field, and tempDisplay represents a dynamic text field. To see the web service proxy assembly (with the .dll extension) that Flash Remoting creates, look in your local assembly cache for a DLL with the same name as the web service. For the Temperature web service, look for a DLL named TemperatureService.dll.
"echoString_Fault"); function echoString_Result(re:ResultEvent):Void { stringDisplay.text = re.result; } function echoString_Fault(fe:FaultEvent):Void { stringDisplay.text = fe.fault.faultstring; } In the code, you use the fully qualified class name (FlashRemoting.EchoTests.EchoClass) in the serviceName argument. To call an assembly method, you use the class method name (echoString) as defined in the class file.
This code creates an instance of the ASObject object, named aso, and uses the ASType property to identify the object as Calculator. The Add method inserts key-value pairs into the object. Finally, aso is returned to Flash using the Flash.Result variable. Handling the ActionScript object in Flash The following ActionScript code handles the ActionScript object returned by the assembly: import import import import import mx.remoting.Service; mx.remoting.PendingCall; mx.rpc.RelayResponder; mx.rpc.
} function subtract():Number { return ( x - y ); } function add():Number { return( x + y ); } } Viewing Flash Remoting log entries Flash Remoting writes error messages to the flash.log file in the local assembly cache. You can change the log file settings in the Windows Registry. The Flash Remoting registry keys are located at HKEY_LOCAL_MACHINE\SOFTWARE\Macromedia\Flash Remoting\1\Registration.
APPENDIX A Using NetServices and Connection Classes This appendix explains how to use the NetServices object to create a gateway connection and return a Connection object. It also explains how to handle results and error information that are returned by a service.
You can also combine these techniques. If you do so, the gateway URL is determined as follows: 1. A URL specified in a createGatewayConnection() method takes precedence over any other URL. 2. A URL specified in the deployed web page takes precedence over a default gateway URL. 3. If you do not otherwise specify a gateway URL, Flash Remoting uses the gateway specified in a NetServices.setDefaultGatewayUrl() method.
Setting a default gateway URL provides you with the greatest flexibility in both development and deployment. It lets you provide a URL that works when you test your SWF file directly in the Flash development environment. Setting a gateway URL also lets you override the default value with a server-specific gateway that you specify in the web page when you deploy your SWF file.
The following example illustrates these steps: myService.logout(); gatewayConnection.setCredentials("", ""); The technique that you use to authenticate the user and to authorize access on the application server depends on the application server you are using. Creating the service object Before you access a service function, you must use the getService() method of the gateway connection object to create a service object in the Flash client. The gatewayConnection.
Handling results for a Connection object When you use the methods of the NetServices object to create a gateway connection and obtain a Connection object, you use the Connection.getService() method to access a service. When you access a service using the methods of the Connection object, you can either direct all results for a service to a single object or direct the results of a specific service call to a specific result handler. Note: Do not specify a responder object in the gatewayConnection.
// initialization code specifies gateway, creates connection, calls service if (inited == null) { inited = true; NetServices.setDefaultGatewayUrl("http://localhost:8300/flashservices/ gateway") var gatewayConnection:Connection = NetServices.createGatewayConnection(); // specify this object (this) as the responder object howdyService = gatewayConnection.getService("remoteservices", this); } // function specific result handlers function helloWorld_Result(result) { // display successful result messageDisplay.
// initialization code specifies gateway, creates connection, calls service if (inited == null) { inited = true; NetServices.setDefaultGatewayUrl("http://localhost:8300/flashservices/ gateway") var gatewayConnection:Connection = NetServices.createGatewayConnection(); // specify this object (this) as the responder object howdyService = gatewayConnection.getService("remoteservices"); } // function specific result handler objects function helloWorld_Result() { this.
The error object When Flash Remoting receives a status event, Flash passes an error object that contains information about the error to the status event handler. The error object has the following format: Key name Contents code Currently, always SERVER.PROCESSING. level Currently, always Error. description A string that describes the error. details A stack trace that indicates the processing state at the time of the exception. type The error class name.
Error-handling strategies Flash applications use error-handling code less often than server applications do, because Flash does not report errors to the user when the user is viewing SWF files. However, Flash Remoting does make error information available to the Flash SWF ActionScript, and your application can use this information. The error-handling hierarchy lets you handle errors with any degree of granularity.
this.onResult = function(result){ // display successful result resultDisplay.text = result; } this.onStatus = function(error){ // display successful result resultDisplay.text = error.description; } } // general responder object can be used for multiple service functions function general_Result() { this.onResult = function(result){ trace("result is: " + result); } this.onStatus = function(error){ trace("result is: " + error.
INDEX A Action Message Format See AMF ActionScript connecting to a service 18 data types, converting from application server 67 data types, converting to application server 65 debugging 94 function results, handling in 137 typed objects, using 71 XML object, sending to Java 140 ActionScript 2.
ASP.NET and helloWorld application 19 application 146 assemblies 159 pages 147 service name format 39 specifying functions 42 state management 151 ASPX page getting a reference to 147 using the Flash Remoting custom server control in 149 assemblies ASP.
using Flash Remoting MX with ColdFusion components 105 using Flash Remoting MX with ColdFusion pages 97 web services 115 ColdFusion pages ActionScript object access 101 arrays and 100 error handling 117 Flash Remoting MX and 97 Flash service name 97 pageable record sets 104 parameter passing 99 record sets, increments 104 record sets, returning 103 returning results from 102 security 116 service name format 39 specifying functions 43 structures and 100 ColdFusion security cflogin tag 116 example 116 roles 1
Error app_server event message 93 error app_server event type 90 error handling error object 170 example 168 Fault object 170 hierarchy 170 in ColdFusion 117 strategies 171 error object, handling 170 event types, debugger 89 events application server 93 client 92 ColdFusion 94 common debugger information 91 examples CustomerInfoExampleAPI 47 CustomerInfoExampleCon 57 helloWorld 31 helloWorld, steps to build 19 instructions 57 user interface 47, 57 F fault handling callback function 21 for helloWorld 21 Faul
flashvars attribute specifying gateway 38 flashvars parameter gateway connection 38 function results, handling in ActionScript 137 functions, specifying 42 G gateway specifying in a web page 38 specifying in createGatewayConnection NetServices object method 164 gateway connection establishing 37 using flashvars parameter 38 using the Service class 37 gateway URL determining 164 example 20 identifying specific format 37 getDebugConfig NetDebugConfig object method 96 H handling error hierarchy 170 error strat
M MBeans calling JMX from Flash 134 getting a reference to 135 invoking methods in ActionScript 135 Microsoft .NET about 143 Flash Remoting design patterns 144 Flash Remoting directory structure 145 migrating to ActionScript 2.
replaceItemAt method 78 See also record sets sorting 80 sortItemsBy method 80 using 73 using directly in components 83 values, returning 77 RecordSet class description 33 importing 36 reference ASPX page, getting 147 EJBHome, getting 128 MBean, getting 135 server-side ActionScript, getting 136 RelayResponder class description 33 importing 36 using 44 Remote DataGrid application migrating 24 remote functions specifying 42 remote service asynchronous communication 30 asynchronous nature 17 building for helllo
handling errors 43 handling results 43 passing parameters 41 result handling example 167 specifying 42 service name for helloWorld 21 Service object calling functions 41 creating 39 handling results 44 service request 17 session variables getting and setting with Flash Remoting MX 151 setCredentials function 116 setCredentials method 40 setDebugID NetConnection object method 95 setDefaultGatewayURL NetServices object method URL resolution 164 using 164 SOAP converting data to ActionScript 67 converting data