MACROMEDIA Using Flash Remoting, FLASH REMOTING MX Use Manual

Using Flash Remoting for Flash MX 2004 ActionScript 2.0
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, MacRecorder Logo and Design, Macromedia, Macromedia Action!, Macromedia Breeze, Macromedia Flash, Macromedia M Logo and Design, Macromedia Spectra, Macromedia xRes Logo and Design, MacroModel, Made with Macromedia, Made with Macromedia Logo and Design, MAGIC Logo and Design, Mediamaker, Movie Critic, Open Sesame!, Roundtrip, Roundtrip HTML, Shockwave, Sitespring, SoundEdit, Titlemaker, UltraDev, Web Design 101, what the web can be, and Xtra are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally.
Third-Party Information
This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.
Apple Disclaimer
APPLE COMPUTER, INC. MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, REGARDING THE ENCLOSED COMPUTER SOFTWARE PACKAGE, ITS MERCHANTABILITY OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. THE EXCLUSION OF IMPLIED WARRANTIES IS NOT PERMITTED BY SOME STATES. THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. THIS WARRANTY PROVIDES YOU WITH SPECIFIC LEGAL RIGHTS. THERE MAY BE OTHER RIGHTS THAT YOU MAY HAVE WHICH VARY FROM STATE TO STATE.
Copyright © 2004 Macromedia, Inc. All rights reserved. This manual may not be copied, photocopied, reproduced, translated, or converted to any electronic or machine-readable form in whole or in part without prior written approval of Macromedia, Inc.
Acknowledgments
Project Management: Erick Vera
Writing: Robert Berry
Editing: Barbara Milligan, Antonio Padial, Lisa Stanziano
Production Management: Patrice O’Neill
Media Design and Production: Adam Barnett and John Francis
First Edition: June 2004
Macromedia, Inc. 600 Townsend St.
San Francisco, CA 94103
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. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Contacting Macromedia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
CHAPTER 1: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
About Flash Remoting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Flash Remoting data flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Understanding the Flash Remoting service adapters . . . . . . . . . . . . . . . . . . . . . 16
Building Flash applications with Flash Remoting . . . . . . . . . . . . . . . . . . . . . . . . . 16
Understanding the Flash Remoting development environment. . . . . . . . . . . . . 16
Using Flash Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Migrating existing applications to Flash Remoting for Flash MX 2004
ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Making the minimum changes to your application for ActionScript 2.0. . . . . . 22
Taking full advantage of Flash Remoting for Flash MX 2004 ActionScript 2.0. 23
Migrating the DataGrid application to Flash Remoting for Flash MX 2004
ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Example: migrating the DataGrid application . . . . . . . . . . . . . . . . . . . . . . . . . 24
CHAPTER 2: Using Flash Remoting ActionScript . . . . . . . . . . . . . . . . . . . . . . . . 29
Flash Remoting application structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Flash Remoting ActionScript classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Properties and methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Importing Flash Remoting ActionScript classes . . . . . . . . . . . . . . . . . . . . . . . . 35
Configuring Flash Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Establishing the Flash Remoting gateway connection . . . . . . . . . . . . . . . . . . . . 37
Specifying a service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Authenticating a user to the application server . . . . . . . . . . . . . . . . . . . . . . . . . 40
Calling service functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Specifying functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Calling functions using named arguments in ColdFusion. . . . . . . . . . . . . . . . . 43
3
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Using the Flash Remoting ActionScript API in the
CustomerInfoExampleAPI application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
onReveal() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
updateDetails(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
refreshCustomerData() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
onCustGrid_Change() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
onCustCat_Change() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
onCategoryData(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
onCustomerData() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
onCustomerFault(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
onCategoryFault() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
CHAPTER 3: Using the RemotingConnector component
(Flash Professional only). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
RemotingConnector parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Creating an instance of the RemotingConnector component . . . . . . . . . . . . . . 56
Using the RemotingConnector in the CustomerInfoExampleCon application. . . . 57
onReveal() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
updateDetails(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
onCustGrid_Change() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
onCustomerData() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
onCategoryData(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
onCustomerDataFault() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
onCategoryDataFault(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
CHAPTER 4: Using Flash Remoting Data in ActionScript . . . . . . . . . . . . . . . . . . 63
About Flash Remoting and data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Understanding Action Message Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Converting from ActionScript to application server data types . . . . . . . . . . . . . . . 65
Converting from application server data types to ActionScript . . . . . . . . . . . . . . . 67
ColdFusion to ActionScript data conversion issues . . . . . . . . . . . . . . . . . . . . . . . . 69
About working with objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Working with ActionScript typed objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Working withJava serializable objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
About working with RecordSet objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
About record sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
RecordSet methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Using RecordSet methods and properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Delivering RecordSet data to Flash applications in ColdFusion MX . . . . . . . . . 81
Using Flash UI components with RecordSet objects . . . . . . . . . . . . . . . . . . . . . 83
About working with XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4 Contents
CHAPTER 5: The NetConnection Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Using the NetConnection Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Enabling debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Disabling debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
NetConnection events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Specific event information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Common event information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Client event messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Application server event messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Flash Communication Server events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Using the NetConnection Debugger in ActionScript. . . . . . . . . . . . . . . . . . . . . . . 94
Using the Netdebug.initialize() method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Using the NetDebug.trace() method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Using connection-specific debugging methods . . . . . . . . . . . . . . . . . . . . . . . . . 95
Configuring debugger output in ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . 96
CHAPTER 6: Using Flash Remoting with ColdFusion MX . . . . . . . . . . . . . . . . . . 97
Using Flash Remoting with ColdFusion pages. . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Determining the Flash service name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Using the Flash scope to pass parameters to ColdFusion pages . . . . . . . . . . . . . 98
Accessing ActionScript objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Using Flash Remoting with ColdFusion components . . . . . . . . . . . . . . . . . . . . . 105
Determining the Flash service name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Returning results to ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Passing parameters to ColdFusion components. . . . . . . . . . . . . . . . . . . . . . . . 106
Accessing ActionScript objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Using component metadata with the Flash Remoting service . . . . . . . . . . . . . 109
Using Flash Remoting with server-side ActionScript . . . . . . . . . . . . . . . . . . . . . . 111
Using CF.http() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Using CF.query() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Calling web services from Flash Remoting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Invoking web service methods using Flash Remoting . . . . . . . . . . . . . . . . . . . 115
Securing access to ColdFusion from Flash Remoting. . . . . . . . . . . . . . . . . . . . . . 116
Assigning security roles to component functions. . . . . . . . . . . . . . . . . . . . . . . 117
Handling errors with ColdFusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
CHAPTER 7: Using Flash Remoting for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
About Flash Remoting for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
How Flash Remoting for Java works. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Where Flash Remoting fits into the Java application architecture . . . . . . . . . . 120
Calling Java classes or JavaBeans from ActionScript. . . . . . . . . . . . . . . . . . . . . . . 121
Making a Java class or JavaBean available to Flash Remoting . . . . . . . . . . . . . 121
Getting a reference to a Java class or JavaBean in ActionScript . . . . . . . . . . . . 122
Invoking Java methods in ActionScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Looking at a Flash application that calls a JavaBean . . . . . . . . . . . . . . . . . . . . 123
Contents 5
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Coding a servlet to use with Flash Remoting . . . . . . . . . . . . . . . . . . . . . . . . . 132
Getting a reference to a web application in ActionScript. . . . . . . . . . . . . . . . . 132
Calling a servlet or JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Calling JMX MBeans from Flash (JRun only) . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Getting a reference to an MBean in ActionScript . . . . . . . . . . . . . . . . . . . . . . 135
Invoking MBean methods in ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Calling server-side ActionScript from Flash (JRun only) . . . . . . . . . . . . . . . . . . . 135
Getting a reference to a server-side ActionScript file . . . . . . . . . . . . . . . . . . . . 136
Invoking server-side ActionScript functions . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Handling function results in ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Using Flash Remoting with JRun security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Looking at the ActionScript authentication code . . . . . . . . . . . . . . . . . . . . . . 139
Looking at the JRun security settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Passing XML objects between Flash and Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Sending an ActionScript XML object to Java . . . . . . . . . . . . . . . . . . . . . . . . . 140
Returning an XML object from Java to Flash . . . . . . . . . . . . . . . . . . . . . . . . . 141
Viewing Flash Remoting log entries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
CHAPTER 8: Using Flash Remoting for Microsoft .NET. . . . . . . . . . . . . . . . . . . 143
Flash Remoting for Microsoft .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Where Flash Remoting fits into the Microsoft .NET framework . . . . . . . . . . 144
Understanding the Flash Remoting for Microsoft .NET directory structure . . 145
Setting up a Flash Remoting ASP.NET application. . . . . . . . . . . . . . . . . . . . . 146
Calling ASP.NET pages from Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Making an ASP.NET page available to Flash Remoting . . . . . . . . . . . . . . . . . 147
Getting a reference to an ASPX-based service in ActionScript. . . . . . . . . . . . . 147
Invoking ASPX pages in ActionScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Using the Flash Remoting custom server control in ASPX pages. . . . . . . . . . . 149
Using the Flash Remoting namespace in code-behind files . . . . . . . . . . . . . . . 150
Using ASP.NET state management with Flash Remoting . . . . . . . . . . . . . . . . 151
Using ASP.NET exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Using ADO.NET objects with Flash Remoting. . . . . . . . . . . . . . . . . . . . . . . . . . 153
Displaying a RecordSet object in Flash with ActionScript . . . . . . . . . . . . . . . . . . 155
Calling web services from Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Invoking web service methods using Flash Remoting . . . . . . . . . . . . . . . . . . . 157
Invoking a remote web service from Flash. . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Calling ASP.NET assemblies from Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Calling assemblies from Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Returning an ActionScript object from an assembly . . . . . . . . . . . . . . . . . . . . 160
Viewing Flash Remoting log entries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
6 Contents
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 . . . . . . . . . . . . . . . . . . . . . . . . 165
Creating the service object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Handling results for a Connection object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Directing all results for a service to a single responder object . . . . . . . . . . . . . 167
Directing results for a service to specific responder objects . . . . . . . . . . . . . . . 168
Handling errors for a Connection object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
The error object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Error-handling hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Error-handling strategies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Contents 7
8 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 services. Using Flash Remoting is intended for Macromedia Flash and application server developers who want to build Rich Internet Applications.
This chapter contains the following sections:
“Who should read this book” on page 9
“About Flash Remoting documentation” on page 9
“What’s new in Flash Remoting for Flash MX 2004 ActionScript 2.0” on page 10
“Developer resources” on page 11
“Contacting Macromedia” on page 12
®
.NET, Java, and Simple Object Access Protocol (SOAP)-based web
Who should read this book
This book is intended for developers who have previous experience with Flash MX or Flash MX 2004 and an application server, including Macromedia ColdFusion MX, Java, or Microsoft .NET.
If you are not familiar with Macromedia Flash MX or Macromedia Flash MX 2004, read the documentation set. If you are not familiar with application server development, read the documentation included with your server.
About Flash Remoting documentation
The Macromedia Flash Remoting documentation is designed to provide support for the complete spectrum of participants. Organized to help you quickly locate the information that you need, the Flash Remoting documentation is provided in the Flash Help system. From the Help menu you can open the Help panel or press F1 as a shortcut to access Flash Help. Then select Using Flash Remoting or the Flash Remoting ActionScript Dictionary, depending on the information that you are seeking.
Flash Remoting documentation is available in Acrobat format (PDF) on the Flash Remoting product CD-ROM.
9
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.
The ActionScript Dictionary describes the syntax and use of ActionScript elements in
Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. To access the ActionScript Dictionary in Flash MX 2004, select Help > ActionScript Dictionary from the Help menu.
ColdFusion MX documentation is carefully crafted to assist you in every facet of ColdFusion
use. To access the ColdFusion MX documentation, activate the ColdFusion MX Administrator and click the Documentation link.
For information on other application servers, see the documentation for those products.
What’s new in Flash Remoting for Flash MX 2004 ActionScript 2.0
Flash Remoting for Flash MX 2004 ActionScript 2.0 consists of the following two principal features:
The Remoting Connector component
The RemotingConnector component is a new component that allows you to work directly with the new data binding features in Flash MX 2004 Professional. Simply drag the RemotingConnector onto the Stage and use the Component inspector to set up schema and bindings. In addition, the RemotingConnector component provides a simple API consistent with other connectors found in Flash MX 2004 Professional.
For more information on using the Remoting Connector, see Chapter 2, “Using Flash
Remoting ActionScript,” on page 29.
ActionScript 2.0 API
The Flash Remoting ActionScript API has been updated to comply with ActionScript 2.0. The ActionScript 2.0 version of the API consists of the following significant features:
Enforcement of strict data typing, which requires you to declare the data types of variables
and prohibits you from assigning different types of data to them.
Enforcement of case sensitivity, which means that myvar and myVar are two different
variables, though they were considered the same variable with different spellings in ActionScript 1.0.
A new Service class, which allows you to create a gateway connection and at the same time
obtain a reference to a service and its methods. It includes the returns the connection and also allows you to set credentials for authorization on the remote server.
connection property, which
Note: The NetServices class is still supported but has been deprecated in favor of the new Service and Connection classes
10 Introduction: About Flash Remoting
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 to specify the methods to handle the results of the service call
A new RelayResponder class, which specifies the methods to which the result and fault
responder property, which you use
.
outcomes of a service call are relayed.
A RecordSet object that contains new properties (columnNames, items, and length), new
methods (
getLocalLength(), getRemoteLength(), isEmpty(), and sortItems()), and the new modelChanged event.
clear(), contains(), editField(), getEditingData(), getIterator(),
For more information on the ActionScript 2.0 Flash Remoting API, see Flash Remoting ActionScript Dictionary Help.
If you are migrating existing applications to Flash Remoting for Flash MX 2004 ActionScript 2.0, see “Migrating existing applications to Flash Remoting for Flash MX 2004 ActionScript 2.0”
on page 22.
Developer resources
Macromedia is committed to setting the standard for customer support in developer education, documentation, technical support, and professional services. The Macromedia website is designed to give you quick access to the entire range of online resources. The following table shows the locations of these resources:
Resource Description URL
Macromedia website
Information on Flash Remoting
Macromedia Flash Remoting Support Center
Flash Remoting Online Forum
Installation support
General information about Macromedia products and services.
Detailed product information on Flash Remoting and related topics.
Professional support programs that Macromedia offers.
Access to experienced Flash and application server developers through participation in the Online Forums, where you can post messages and read replies on many subjects relating to Flash Remoting.
Support for installation-related issues for all Macromedia products.
www.macromedia.com
www.macromedia.com/go/flashremoting
www.macromedia.com/go/ flashremoting_support
www.macromedia.com/go/flash_forum
www.macromedia.com/support/email/ isupport
Training Information about classes, on-site
training, and online courses offered by Macromedia.
www.macromedia.com/go/flash_training
Developer resources 11
Resource Description URL
Developer resources
Macromedia Alliance
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.
Connection with the growing network of solution providers, application developers, resellers, and hosting services creating solutions with Flash Remoting.
www.macromedia.com/go/devnet
www.macromedia.com/go/partners
One of the best ways to solve particular programming problems is to tap into the vast expertise of the Flash and application server developer communities on the Macromedia Online Forums at
www.macromedia.com/go/flash_forum. Other developers on the forum can help you figure out
how to do just about anything with Flash Remoting. The search facility can also help you search messages from the previous 12 months, or beyond, allowing you to learn how others have solved a problem that you might be facing.
Contacting Macromedia
Corporate headquarters Macromedia, Inc.
600 Townsend Street
San Francisco, CA 94103
Tel: 415.252.2000
Fax: 415.626.0554 Website: www.macromedia.com
Technical support Macromedia offers a range of telephone and web-based support options.
Go to www.macromedia.com/go/flashremoting_support for a complete description of technical support services.
You can post comments to the Flash Remoting Support Forum (www.macromedia.com/go/flash_forum) at any time.
Sales Toll Free: 888.939.2545
Tel: 617.219.2100
Fax: 617.219.2101 E-mail: sales@macromedia.com
12 Introduction: About Flash Remoting
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. If you already use Flash Remoting, this chapter explains the requirements to migrate an existing application to Flash Remoting for Flash MX 2004 ActionScript 2.0.
This section contains the following sections:
“About Flash Remoting” on page 13
“Using Flash Remoting” on page 17
“Building Flash applications with Flash Remoting” on page 16
“Migrating existing applications to Flash Remoting for Flash MX 2004 ActionScript 2.0”
on page 22
About Flash Remoting
Macromedia Flash Remoting is an application server gateway that provides a network communications channel between Flash applications and remote services. Remote services consist of application server technologies, such as JavaBeans, a Macromedia ColdFusion component or page, an ASP.NET page, or a web service. Service functions represent a reference to a specific remote service from ActionScript in a Flash application.
When compared to other techniques for connecting Flash applications to external data providers, such as HTTP functions like Flash Remoting provides the following advantages:
getURL and loadVariables and XML functions like XMLSocket,
Ease of use Flash Remoting offers automatic data type conversion from native remote
service code, such as Java, CFML, and C#, to ActionScript and back again. Also, Flash Remoting automatically performs logging, debugging, and security integration.
Performance Flash Remoting serializes messages between Flash applications and remote
services using the Action Message Format (AMF is a binary format modeled on the Simple Object Access Protocol (SOAP) format). Using AMF, Flash Remoting encodes data types as they travel between the Flash application and the remote service over HTTP.
13
Extensibility Flash Remoting is designed to integrate with established application design
patterns and best practices to build well-designed Flash applications.
When compared to traditional HTML-based browser applications, Flash applications provide unique abilities to create dynamic and sophisticated user interactions, including the following:
Macromedia Flash Player runtime to execute code, transmit data, and invoke remote services
Separation of client-side presentation logic from the server-side application logic
Efficient use of bandwidth provided by the AMF protocol
Easy deployment on multiple platforms and devices
On the server side, Flash Remoting runs as a servlet in Java application servers, an assembly in .NET servers, and a native service in ColdFusion MX. Depending on the application server platform, Flash Remoting on the server contains a series of filters that perform logging, error handling, and security authentication, as well as automatically mapping the service function request to the appropriate server technology.
Using Flash Remoting, you can build sophisticated Flash applications, such as a message board, shopping cart, or product catalog. The following figure depicts a simplified representation of the Flash Remoting architecture:
Flash Remoting data flow
You typically initiate a service request by making a choice that requires Flash to request data from the server. For example, a sports fan might ask to see what seats are available in a particular section of an arena. The Flash Player uses the Action Message Format (AMF), to send the request over HTTP to Flash Remoting. Flash Remoting receives the service function request and dispatches it to the appropriate application server or web service call.
14 Chapter 1: Getting Started
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.
The Flash Remoting architecture facilitates the flow of messages between the client and server in a way that conforms to established design patterns and frameworks such as the model-view-controller (MVC) architecture. The following figure depicts the MVC architecture in the context of Flash Remoting:
In the MVC architecture, the model, view, and controller have the following roles:
Model The model represents the data of an application and the processing of that data and
other logic. In a web application, this typically consists of the application server program and the database.
View The view represents the user interface, which usually consists of user controls and
information display.
Controller The controller represents the logic that handles user input and changes the model
or view accordingly. Depending on your application design, the controller can be located on the client, the server, or a combination of both. To minimize the amount of network traffic and to take advantage of the Flash runtime, Flash Remoting implements the controller in Flash.
Flash Remoting MX enables the separation of the controller from the model by providing a communication channel between Flash applications and application servers or web services. By encapsulating the data in an ActionScript object, Flash Remoting reduces the number of service requests necessary to retrieve smaller pieces of data.
About Flash Remoting 15
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. When an HTTP request arrives at the server and contains AMF, Flash Remoting maps the request to the appropriate adapter by name. To avoid naming conflicts, you specify the directory structure, fully qualified class or package name, or Web Service Description Language (WSDL) URL of the web service in ActionScript.
Building Flash applications with Flash Remoting
Flash applications that use Flash Remoting resemble other client-server development platforms, including traditional HTML-based web applications. For example, Flash applications usually appear in the context of a browser window, much like HTML pages. In addition, Flash applications can contain controls for displaying text and graphics, gathering user input, and communicating with a remote server, much like HTML.
Understanding the Flash Remoting development environment
Because Flash Remoting connects two distinct and separate runtime environments, you build Flash Remoting applications in two programming languages: ActionScript and the programming language of your application server. Therefore, building Flash applications with Flash Remoting demands knowledge of at least two different development environments:
Flash To create Flash applications that use Flash Remoting, you use the Flash authoring
environment to design the user interface and write the client-side ActionScript.
An application server tool For ColdFusion, Java, or .NET development, you typically use a
text editor or an integrated development environment (IDE) that supports the associated programming languages and APIs. Macromedia Dreamweaver MX 2004 supports ColdFusion, J S P, a n d A S P. N E T d e v e l o p m e n t .
Note: For Java or .NET development, you need a Java or .NET compiler to create executable code.
Because of the separation between the client and server environments, you might develop Flash Remoting applications as a team project. In traditional HTML-based web applications, responsibilities usually fall into two general roles: designer and developer. The designer creates the HTML user interface and the developer creates the application server logic.
When developing Flash applications using Flash Remoting, you might find it useful to organize development roles as client-side designer, client-side developer, and server-side developer. Under this division of labor, the client-side designer creates the Flash user interface, including layout, animation, and effects. The client-side developer creates the ActionScript to connect to the remote service and handle the results. Finally, the server-side developer builds the business logic on the application server to serve as the remote service.
16 Chapter 1: Getting Started
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. The Flash application makes requests from ActionScript to the server and receives results asynchronously.
This means that the ActionScript code that immediately follows the service request executes before the result of the call is returned from the server. The following example illustrates this principle by invoking the
trace() function immediately after the service request and then again
when the result is returned by the server.
import mx.remoting.Service; // import Service class import mx.rpc.FaultEvent; // import FaultEvent class import mx.remoting.PendingCall // import PendingCall clsas import mx.rpc.ResultEvent // import ResultEvent class import mx.rpc.RelayResponder // import RelayResponder class
mx.remoting.debug.NetDebug.initialize(); var myService:Service = new Service("http://examples.macromedia.com/
flashservices/gateway",null,"petmarket.api.catalogservice", null, null); // connect to remote service
var pc:PendingCall = myService.getCatagories({locale:”en_US”}); // call
service method pc.responder = new RelayResponder(this, "getData_Result", "getData_Fault"); trace( "no response from server yet." );
function getData_Result( re:ResultEvent ):Void { // receive result trace( "got the response" ); } function getData_Fault( fe:FaultEvent ):Void { // receive fault trace( "got the response" ); }
The output from these calls to the trace() function would appear in the following order:
no response from server yet got the response
Notice that the first call to the trace() function executes before the result is returned from the service.
For more information on how to receive and process asynchronous messages from Flash Remoting, see “Handling service results and errors” on page 43.
Building Flash applications with Flash Remoting 17
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.
To connect to a service using the RemotingConnector component (Flash Professional):
If you use Flash Professional, you perform these basic steps to use the RemotingConnector to connect to a service.
1.
In the Components panel, select RemotingConnector from the Data Components section and
drag it onto the Stage.
2.
Set parameters in the Component inspector.
3.
Set bindings in the Component inspector.
4.
Write code in the Actions panel.
For more detailed information about connecting to a service by using the RemotingConnector component, see Chapter 3, “Using the RemotingConnector component (Flash Professional
only),” on page 53. You should read the following sections, however, even if you plan to use the
RemotingConnector to connect to your remote services.
To connect to a service by writing ActionScript code:
1.
From the Window menu in Flash, select Other Panels > Common Libraries > Remoting.
2.
From the Library panel, drag the RemotingClasses library onto the Stage.
3.
To use the NetDebug class and the NetConnection Debugger, you must also drag the
RemotingDebugClasses library to the Stage.
4.
Write your code in the Actions panel.
For more information on writing ActionScript code for Flash Remoting, see the following sections on building a Hello World application and Chapter 2, “Using Flash Remoting
ActionScript,” on page 29.
For more information on adding the RemotingDebugClasses library to your application, and on removing it, see “Using the NetConnection Debugger” on page 87.
Building a Hello World application with Flash Remoting
In this section, you build a simple Flash application that uses the Flash Remoting ActionScript API to connect to a remote service. You can choose among four different remote services, including a ColdFusion page, a JavaBean, an ASPX page, and a web service. Flash applications require minimal changes to call different remote services.
The following sections show you first how to build the remote service and then how to call the remote service from your Flash application using Flash Remoting ActionScript.
18 Chapter 1: Getting Started
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
ColdFusion MX
JRun 4
ASP.NET
Application server code File location
<cfset flash.result = "Hello from
ColdFusion MX!">
package com.remoteservices;
import java.io.Serializable;
public class FlashJavaBean
implements Serializable {
private String message;
public FlashJavaBean() {
message = "Hello from Java!"; } public String helloWorldJava() {
return message; }
}
<%@ Register TagPrefix="Macromedia"
Namespace="FlashGateway" Assembly="flashgateway" %>
<%@ Page language="c#" debug="true" %> <Macromedia:Flash ID="Flash"
runat="server">
Hello from .NET! </Macromedia:Flash>
Save the ColdFusion page as helloWorld.cfm in a folder named remoteservices under your web root.
Save the compiled JavaBean class file to classes/com/remoteservices folder under the SERVER-INF directory.
Save the ASPX page as helloWorldNET.aspx in the flashremoting directory under your web root.
For more information about application server-specific code, see the following chapters:
Chapter 6, “Using Flash Remoting with ColdFusion MX,” on page 97
Chapter 7, “Using Flash Remoting for Java,” on page 119
Chapter 8, “Using Flash Remoting for Microsoft .NET,” on page 143
Calling the remote service from Flash using Flash Remoting ActionScript
To build a Flash application that uses Flash Remoting, you write ActionScript in the Flash authoring environment to connect to the remote service and call a service function.
To build a Flash application that calls remote services using Flash Remoting:
1.
In the Flash authoring environment, create a new Flash file and save it as serviceTest.fla.
2.
Drag the RemotingClasses library onto the Stage as described in “Connecting to a service”
on page 18.
3.
In the Document window, insert a text field.
Building Flash applications with Flash Remoting 19
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 mx.remoting.Service; import mx.services.Log; import mx.rpc.RelayResponder; import mx.rpc.FaultEvent; import mx.rpc.ResultEvent; import mx.remoting.PendingCall; import mx.remoting.RecordSet;
// connect to service and create service object
var howdyService:Service = new Service(
"gatewayUrl", new Log(), "serviceName", null,
null ); // call the service helloWorld() method var pc:PendingCall = howdyService.serviceFunctionName();
// tell the service what methods handle result and fault conditions pc.responder = new RelayResponder( this, "serviceFunctionName_Result",
"serviceFunctionName_Fault" );
function serviceFunctionName_Result(result:ResultEvent) {
// display successful result messageDisplay.text = result.result;
}
function serviceFunctionName_Fault(fault:FaultEvent) {
//display fault returned from service messageDisplay.text = fault.fault.faultstring;
}
The ActionScript code creates a new Service object, howdyService, to create both the gateway connection and a reference to the remote service. You specify the following variables:
The gatewayUrl, which depends on the location of the application server running Flash
Remoting. For example, the following
http://localhost:8500/flashservices/gateway. Specify the appropriate gatewayUrl
gatewayUrl connects to a ColdFusion service:
value for your remote service.
The Log object, to which debugging messages are sent. For more information, see the Log
class in Flash Remoting ActionScript Dictionary Help.
20 Chapter 1: Getting Started
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. To select the
appropriate value for this example, see the table that follows this section.
The call to the PendingCall object, called
howdyService.serviceFunctionName() service function returns a
pc in this example. It contains a responder property which the
application sets with a RelayResponder object. The RelayResponder object specifies the object (first parameter) that contains the methods that handle the values returned by the service function. The second parameter in the RelayResponder constructor specifies the result handler method and the third parameter specifies the fault handler method.
This example handles the results returned by the service function using callback functions named the service function succeeds, the service function fails, the
serviceFunctionName_Result() or serviceFunctionName_Fault(). If the call to
_Result function is called and it processes the result. If the
_Fault function is called to handle the error.
The result, which is the value that you expect from the service function, is returned in a ResultEvent object. The fault, which the service returns for an error condition, is returned in a FaultEvent object.
For more information about connecting to remote services and handling results, see Chapter 2,
“Using Flash Remoting ActionScript,” on page 29.
6.
Save the file.
In the preceding ActionScript code, substitute the values from the following table for the
serviceName and serviceFunctionName variables, in accordance with the remote service that
you are using:
Remote service serviceName variable serviceFunctionName
variable
ColdFusion MX
JRun 4
ASP.NET
Web service
remoteservices helloWorld
com.remoteservices helloWorldJava
remoteservices helloWorldNET
http://services.xmethods.net/soap/
urn:xmethods-delayed-quotes.wsdl
getQuote
For more information about application server-specific service names and service function names, see the following chapters:
Chapter 6, “Using Flash Remoting with ColdFusion MX,” on page 97
Chapter 7, “Using Flash Remoting for Java,” on page 119
Chapter 8, “Using Flash Remoting for Microsoft .NET,” on page 143
Building Flash applications with Flash Remoting 21
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. First, you can make the minimum changes possible to allow your applications to run with ActionScript 2.0. Second, you can rewrite your application to take advantage of the improvements in ActionScript 2.0. The following sections describe the tasks that each choice entails.
Making the minimum changes to your application for ActionScript 2.0
This section describes the minimum changes that you must make to migrate an existing Flash Remoting application to Flash Remoting for Flash MX 2004 ActionScript 2.0.
To make the minimum changes to your application for ActionScript 2.0:
1.
Drag the RemotingClasses library to the Stage as described in the section “Connecting to a
service” on page 18. If you use the NetDebug class in your program, you must also drag the
RemotingDebugClasses library to the Stage. You can delete the icons from the Stage, if you want. They do not appear in the published application, however.
2.
Replace any Flash MX UI components with Flash MX 2004 UI components. Because ActionScript 2.0 is case sensitive, most of the components have been modified for case-sensitivity and logic issues.
3.
Change #include statements to the appropriate import statements. For example, if your application contains the following statements:
#include “NetServices.as” //… var con:Connection = NetServices.createGatewayConnection(…);
you must change them to the following:
import mx.remoting.NetServices; //… var con:Connection = NetServices.createGatewayConnection(…);
To de t e rmi n e wha t import statements you need, see “Importing Flash Remoting ActionScript
classes” on page 35.
4.
If you use the NetDebug class in your program, you must include the following statement in your application before connecting to a service:
mx.remoting.debug.NetDebug.initialize()
22 Chapter 1: Getting Started
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
7.
Adhere to the following ActionScript 2.0 restrictions:
Do not increment an undefined value. Whereas incrementing an undefined value in
getCategories_result() to getCategories_Result().
ActionScript 1.0 would set it to 1, doing so in ActionScript 2.0 will return "undefined".
In ActionScript 2.0, the expression Boolean("String") will return true and Boolean("")
will return
Boolean("1234") returned true.
The Object.constructor property must appear only on prototype objects.
8.
Change calls to the NetServices.setDefaultGatewayURL function to
NetServices.setDefaultGatewayUrl. Note the case difference between URL and Url.
false. In ActionScript 1.0, however, Boolean("String") returned false and
For an example of an Action 1.0 Flash Remoting example that has been converted with minimal changes to comply with ActionScript 2.0, see “Migrating the DataGrid application to Flash
Remoting for Flash MX 2004 ActionScript 2.0” on page 24.
Taking full advantage of Flash Remoting for Flash MX 2004 ActionScript 2.0
To take full advantage of Flash Remoting for Flash MX 2004 ActionScript 2.0, you should make the following changes to your existing applications in addition to making the changes noted in the previous section:
Use the new Flash Remoting API classes and methods:
Service class
PendingCall class
RelayResponder class
ResultEvent and FaultEvent classes
■ The new methods of the RecordSet class, including clear(), contains(), editField(),
getEditingData(), getIterator(), getLocalLength(), getRemoteLength(), isEmpty(), sortItems() and sortItemsBy() methods.
Consider using the RemotingConnector component.
Adhere to strict data typing.
Migrating existing applications to Flash Remoting for Flash MX 2004 ActionScript 2.0 23
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.
Migrating the DataGrid application to Flash Remoting for Flash MX 2004 ActionScript 2.0
This section presents two versions of the Remote DataGrid application to illustrate the minimum number of changes that you must make to an existing Flash Remoting application to run it under Flash Remoting for Flash MX 2004 ActionScript 2.0.
When migrating your existing Flash Remoting applications to the Flash Remoting for Flash MX 2004 ActionScript 2.0 API, follow these precautions:
Use the Flash MX 2004 UI Components with the new Remoting API. Do not use Flash MX
components.
Make sure your code is consistent in the use of uppercase and lowercase characters.
ActionScript 2.0 is case sensitive.
The DataGrid example uses Flash Remoting with a JavaBean. It simply populates a Flash DataGrid with dynamic data, listing customers who belong to a selected category.
You can find the Remote DataGrid application in the following folder:
/Program Files/Macromedia/Flash MX 2004/en/First Run/RemotingSamples
See the Readme.htm file in this folder for information on how to set up and use this sample application.
Example: migrating the DataGrid application
The following steps are the required steps to migrate the Remote DataGrid application from a previous release (shown as Old API code below) to Flash Remoting for Flash MX 2004 ActionScript 2.0 (shown as New API code below).
1.
Replace all existing Flash MX UI components with Flash MX 2004 UI components, such as DataGrid, ComboBox, TextInput, and TextArea. For information on Flash MX 2004 UI components, see Flash MX 2004 Help.
2.
From the Window menu, select Other Panels > Common Libraries > Remoting and click it. From the Library panel that opens, drag the RemotingClasses and the RemotingDebugClasses libraries to the Stage.
24 Chapter 1: Getting Started
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.
Initialize the NetDebugger (optional) and set up the DataGrid columns.
// New API
NetDebug.initialize();
// Old and New API
grid.columnNames = ["productId", "name", "categoryId", "price"];
5.
Create a gateway connection, establish a reference to a remote service, and set up a Responder object to call for result-handling and fault-handling.
The old version of the program calls three functions to accomplish these tasks:
NetServices.setDefaultGatewayUrl() to specify the gateway URL, NetServices.createGatewayConnection() to create the connection, and connection.getService() to create a reference, catalogService, to the remote service.
The Flash Remoting API accomplishes all three tasks by invoking the constructor for the Service object.
// Old API
NetServices.setDefaultGatewayUrl("http://localhost:8100/flashservices/
gateway"); connection = NetServices.createGatewayConnection(); //locate a remote service: the RemoteCatalog bean catalogService = connection.getService("samples.remoting.RemoteCatalog",
this);
// New API
var myService:Service = new Service("http://localhost:8100/flashservices/
gateway",
new Log(Log.DEBUG),
"samples.remoting.RemoteCatalog",
null,
null);
Migrating existing applications to Flash Remoting for Flash MX 2004 ActionScript 2.0 25
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.
The last two parameters, which have null values in this case, are a Connection object and a
Responder object. For more information on these parameters, see the Service class in the
Flash Remoting ActionScript Dictionary.
Note: The next step describes an alternate way to create a reference to a service in the new API.
6.
Invoke a service method and establish result and fault handler methods.
// Old API // invoke a service method
catalogService.getCategories();
function getCategories_Result(result) {
category_array = result;
for (i=0; i< category_array.length; i++)
{
category_cb.addItem( category_array[i].name,
category_array[i].categoryId); } category_cb.setSelectedIndex(0);
}
function getCategories_Status(fault) {
// do something here
}
// New API
// call getCategories service function and set the responder property of the // PendingCall object (implied here) that is returned by the service // function call. Sets the responder property with a RelayResponder object // that specifies the result handling method (“gotCatResults”) and fault // handling method (“gotCatStatus”) for the outcome returned by the service // function. myService.getCategories().responder = new RelayResponder(this,
"gotCatResults", "gotCatStatus");
function gotCatResults(result:ResultEvent) {
26 Chapter 1: Getting Started
// 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.faultstring);
}
You can set up the Responder object in one of the following two ways:
The Service constructor passes its name, in which cases it becomes the default handler for
the result and fault outcomes of any method called for the service.
The call to the service method specifies the Responder object that will handle the result or
fault only for that specific method invocation. The example uses this approach, using a RelayResponder object to specify the result handling and fault handling methods for the
getCategories() service function.
7.
Register a listener for the combo ComboBox and set up a responder object for the second service method call to the
getProductsByCategory() function, which will fetch the detail records
based on the items selected in the ComboBox. The parameter for the
getProductsByCategory() function is the selectedItem.data field.
myChangeObj = new Object(); myChangeObj.change = function(evt:Object) { // the textArea should be set to empty once new categories are being fetched, // so that it does not show any old data
details.text = ""; myService.getProductsByCategory(Number(evt.target.getValue())).responder
= new RelayResponder(_root, "catResult" , "catFault");
}
combo.addEventListener("change", myChangeObj); function catResult(result) {
// set up the grid.dataProvider based on the results from // getProductsByCategory()
grid.dataProvider = result.result;
}
function catFault(error) {
trace(" received fault ");
}
Migrating existing applications to Flash Remoting for Flash MX 2004 ActionScript 2.0 27
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.addEventListener("change", gridChange);
28 Chapter 1: Getting Started
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.
This chapter describes two ways to access a remote service. The first and easiest way is to use the RemotingConnector component. The second way is to use the methods of the Flash Remoting API. The chapter leaves the discussion of the RemotingConnector component to the end because whether you use it or the API, you need to understand the structure of a Flash Remoting application and how to handle the results that the service returns.
The chapter also contains two extended examples, CustomerInfoExampleAPI and CustomerInfoExampleCon, that are different versions of the same application. The CustomerInfoExampleAPI example uses the Flash Remoting API to connect to and access a service. The CustomerInfoExampleCon example uses the RemotingConnector component to connect to and access the same service. For descriptions of these examples, see “Using the Flash
Remoting ActionScript API in the CustomerInfoExampleAPI application” on page 47 and “Using the RemotingConnector in the CustomerInfoExampleCon application” on page 57.
This chapter contains the following sections:
“Flash Remoting application structure” on page 30
“Flash Remoting ActionScript classes” on page 32
“Configuring Flash Remoting” on page 36
“Calling service functions” on page 41
“Handling service results and errors” on page 43
“Using the Flash Remoting ActionScript API in the CustomerInfoExampleAPI application”
on page 47
Chapter 3, “Using the RemotingConnector component (Flash Professional only),” on page 53
“Using the RemotingConnector in the CustomerInfoExampleCon application” on page 57
29
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. For additional information on ensuring that the correct version of Flash Player is installed on the client’s computer, see the Flash Remoting Support Center on the Macromedia website at www.macromedia.com/support/flash/flashremoting.
For information on handling Flash Remoting data, and particularly record sets, using ActionScript, see Chapter 4, “Using Flash Remoting Data in ActionScript,” on page 63.
Flash Remoting application structure
Using Flash Remoting to call an application service is similar to calling a web service or making a remote procedure call (RPC). In each case, you make a call in your program to some remote service and you get a response from the service. As with web services and RPCs, data from the remote service is converted from the native data type of the remote service (such as a Java or C# data type) to a representation that is used to transfer the data over the network.
Unlike an RPC or web service request, a call made using Flash Remoting does not directly receive the results of the service. Instead, you write a result-handler callback routine to handle the returned data. Because the remote service call and the callback routine are separate, your service call and result handling are asynchronous. In other words, the service request is like a function call without a return, and the service result or response is like a Flash event, for which you write an event handler method. The following figure shows this relationship:
To interact with application servers using Macromedia Flash Remoting, do the following in your Flash application:
1.
From the Window menu in Flash, select Other Panels > Common Libraries > Remoting.
2.
From the Library panel, drag the RemotingClasses library onto the Stage.
3.
To use the NetDebug class and the NetConnection Debugger, you must also drag the RemotingDebugClasses library to the Stage.
4.
In the Actions panel, import the ActionScript Flash Remoting classes.
30 Chapter 2: Using Flash Remoting ActionScript
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 creates the
getCategories()
result-handler callback methods,
catalogService Service object, and calls two service functions, catalogService.
and catalogService.getProducts(). These functions have corresponding
gotCategories_Result() and gotProducts_Result() to
petmarket.api.catalogservice service,
show the results in the Flash application. They also has corresponding fault-handler callback methods,
gotCategories_Fault() and got_Categories_Result(), to handle any error
information if the service call fails.
Import Flash
Remoting ActionScript classes
Configure Flash
Remoting
Call the service
function(s)
import mx.remoting.Service; import mx.services.Log; import mx.rpc.RelayResponder; import mx.remoting.PendingCall; import mx.remoting.RecordSet; import mx.rpc.ResultEvent; import mx.rpc.FaultEvent; // Remove the slashes in the following two lines to use the
NetConnection Debugger // import mx.remoting.debug.NetDebug; // NetDebug.initialize();
function makePetMarketCalls(){
var catalogService:Service = new Service(
"http://examples.macromedia.com/flashservices/gateway", new Log(), "petmarket.api.catalogservice", null,null );
var cat_pc:PendingCall =
catalogService.getCategories({locale:"en_US"});
cat_pc.responder = new RelayResponder(this,"gotCategories_Result",
"gotCategories_Fault");
var prod_pc:PendingCall = catalogService.
getProducts({categoryoid:5});
prod_pc.responder = new RelayResponder(this,"gotProducts_Result",
"gotProducts_Fault"); }
callback functions
handle returned result and fault information
function gotCategories_Result(re:ResultEvent):Void{
} function gotCategories_Fault(fault:FaultEvent):Void{
} function gotProducts_Result(re:ResultEvent):Void{
} function gotProducts_Fault(fault:FaultEvent):Void{
} makePetMarketCalls();
trace("Got " + re.result.length + " Categor" + (re.result.
length>1?"ies":"y"));
trace("Categories Fault: " + fault.fault.description);
trace("Got " + re.result.length + " Product" + (re.result.
length>1?"s":""));
trace("Products Fault: " + fault.fault.description);
Flash Remoting application structure 31
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. For additional reference information on these classes, see Flash Remoting ActionScript Dictionary Help.
Class Purpose
Connection Helps you create and use connections to services.
The
Connection.setCredentials() method provides login information for the
gateway server. For more information on using this method, see
“Authenticating a user to the application server” on page 40.
The class includes four methods for debugging individual connections. For more information, see “Using connection-specific debugging methods”
on page 95.
The remaining methods in this class (
connect() and getService()) are lower-level utilities that are not needed in
most applications. For more information, see the Connection class in Flash Remoting ActionScript Dictionary Help.
addHeaders(), call(), close(),
DataGlue Binds RecordSet objects to Flash components, such as ListBox or
ComboBox, that have labels with associated data. The
bindFormatStrings()
RecordSet object to use to populate the UI component and tell Flash how to populate the component’s labels and data from the RecordSet object.
For more information on using DataGlue, see “Using DataGlue methods”
on page 84.
FaultEvent Returned as an argument to the fault handling method that you specify in the
responder object. It contains the fault information that is returned when a call to a service function results in a fault condition. For more information on using a FaultEvent object, see “Handling service results and errors” on page 43.
Log Provides a logger that you can specify as an optional parameter to the Service
constructor. It is the application author’s responsibility to customize this tool.
NetDebug Required by the NetConnection Debugger. Manages the local connection
between the Flash application that is being debugged and the NetConnection Debugger. Includes N the latter sends a trace event to the NetConnection Debugger with a specific ActionScript object.
The NetConnection Debugger reports information on Flash Remoting events. For Macromedia ColdFusion MX, these events also include server activity, such as SQL queries. For more information on using the NetConnection Debugger, see Chapter 5, “The NetConnection Debugger,” on page 87.
and DataGlue.bindFormatFunction() methods specify a
etDebug.initialize() and NetDebug.trace() methods;
DataGlue.
32 Chapter 2: Using Flash Remoting ActionScript
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. For more information on using NetServices methods, see “Using NetServices and Connection Classes”
on page 163.
PendingCall Generated on each call to a method of a Service object. Contains the
responder property, which gets or sets a Responder object for a PendingCall
object. For more information on obtaining the result of a call to a service, see
“Using PendingCall and RelayResponder objects for a specific service function” on page 45
.
RecordSet Accesses and manipulates RecordSet objects returned by a service. Also,
creates client-side record sets. RecordSet objects typically represent SQL query results and correspond to the ColdFusion Query objects and C# System.Data.DataTable objects. RecordSet methods include functions to create record sets and to add, delete, change, and get record set items. They also can get information about the record set, sort the record set, define an object to receive notifications when the record set changes, and set the way the record set is delivered from the server.
For more information on using the RecordSet class, see “About working with
RecordSet objects” on page 73.
RelayResponder A responder object that relays result and fault calls to corresponding functions
on the specified object. For more information, see “Using the
RelayResponder object for a service” on page 44.
RemotingConnector Provides an easy way for Flash Professional clients to call functions on
server-side objects that are deployed within ColdFusion, J2EE, or Microsoft’s .NET. For more information, see Chapter 3, “Using the RemotingConnector
component (Flash Professional only),” on page 53 and the
RemotingConnector class in the Flash Remoting ActionScript Dictionary.
ResultEvent Returned as an argument to the result handling method that you specify in the
responder object. It contains the result that is returned by a service function. For more information on using a ResultEvent object, see “Handling service
results and errors” on page 43.
Service Represents a reference to a specific remote service and the methods that the
service exposes. Remote services consist of application server modules that leverage technologies such as JavaBeans, Macromedia ColdFusion Components (CFCs), CFML pages, ASP.NET web services and pages. For more information, see “Calling service functions” on page 41.
Flash Remoting ActionScript classes 33
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 Properties Methods
Creating and using connections and services
Handling Results
Connection
Log
RemotingConnector
Service
NetServices (deprecated)
PendingCall
gatewayUrl serviceName methodName multipleSimultaneousAllowe d suppressInvalidCalls shareConnections userId password
connection name
responder
addHeader() call() clone() close() getService() setCredentials() trace()
onlog()
trigger()
new Service(…)
createGatewayConnection() getConnection() getHostUrl() getHttpUrl() setDefaultGatewayUrl() setGatewayUrl()
RelayResponder
Debugging Connection
NetDebug
34 Chapter 2: Using Flash Remoting ActionScript
new RelayResponder(…)
getDebugConfig() getDebugId() setDebugId()
initialize() trace()
Purpose Class Properties Methods
Managing record sets and data
DataGlue
RecordSet
columnNames items length
bindFormatFunction() bindFormatStrings()
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 Remoting ActionScript classes
Before you can import Flash Remoting classes in your application, you must first place the required Flash Remoting libraries on the Stage. For more information, see “Connecting to a
service” on page 18.
Use the
import directives from the following table at the top of your ActionScript code to
eliminate the need for using the fully qualified class name each time you need to refer to the class. This is typically done in the first frame of the Flash application or at the top of any class files as required:
Import statement Purpose
import mx.remoting.Connection
import mx.remoting.DataGlue;
import mx.rpc.FaultEvent;
Replaces NetConnection class. Macromedia recommends that you use the Service class to connect to remote services and use the methods of the Connection class to perform connection-related tasks such as authenticating users.
Use DataGlue methods to simplify providing record set data to Flash UI components.
Fault handling object that is returned to fault handling method when an error occurs on a call to a remote service function.
Flash Remoting ActionScript classes 35
Import statement Purpose
import mx.services.Log;
import mx.remoting.debug.NetDebug;
import mx.remoting.NetServices;
(Deprecated)
import mx.remoting.PendingCall;
import mx.remoting.RecordSet;
import mx.rpc.RelayResponder;
Log object is optional parameter to Service constructor. You can use the Log class to create a customized logger for your Flash Remoting application.
Provides debugging methods for Flash Remoting applications. Remove it before publishing your application to a production server to prevent access to debugging information.
To initialize debugging support in a single statement without first importing the class, you can add the following statement to your code before creating a connection:.
mx.remoting.debug.NetDebug.initialize();
Methods in this class allow you to create and manage gateway connections.
Facilitates asynchronous interaction between the client application and a service function. Use if you use the Service class to reference remote service functions.
Use this statement if you create client-side record sets or need to access or manipulate record sets that are returned as the result of a call to a remote service.
Enables the Responder object that relays result and fault calls from a service to a corresponding function on the specified object.
import mx.data.components.
RemotingConnector;
import mx.rpc.ResultEvent;
import mx.remoting.Service;
Implements a component that provides an easy way for Flash Professional clients to call functions on server-side objects.
Result handling object that contains the result returned by a remote service function.
Use this statement to establish a gateway connection and reference a specific remote service and the methods that it exposes.
Configuring Flash Remoting
Before you can call a remote service, you must configure Flash Remoting, which consists of completing the following tasks.
Note: The client does not access the remote server when you configure Flash Remoting. The client first communicates with the remote server when it makes the first service function call.
Establishing a Flash Remoting gateway connection.
Getting a Flash Remoting service object.
Authenticating the user, if your application server or service requires user authentication.
The following sections describe these Flash Remoting configuration tasks.
36 Chapter 2: Using Flash Remoting ActionScript
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. If you do not use the default Flash Remoting deployment configuration, replace
flashservices with the application context, and replace gateway with the servlet
mapping.
If you are connecting to a .NET server, use the following format:
http://webServer[:port]/flashremoting/gateway.aspx
In this URL, flashremoting is the logical directory used for Flash Remoting, and gateway.
is an intentionally blank file installed with Flash Remoting; the aspx suffix identifies this
aspx
as a .NET request. If you do not use the standard installation configuration for Flash Remoting, you might need to change these values to reflect your configuration.
You can establish a gateway connection in Flash Remoting in one of the following ways:
If you use Flash Professional, create an instance of a RemotingConnector component. For
more information, see “Flash Remoting ActionScript classes” on page 32.
Create a Service object, creating a gateway at the same time that you create a reference to a
remote service and its methods. Macromedia recommends this technique.
Identify a remote gateway and create a Connection object that enables Flash Remoting to
connect to it. For information on this technique, see <<<xref Connection class>>> and
Appendix A, “Using NetServices and Connection Classes,” on page 163.
Note: This technique has been deprecated in Macromedia Flash Remoting for Flash MX 2004 ActionScript 2.0.
Specify the gateway in a web page.
Note: Although using NetServices to establish a connection object is still supported, Macromedia no longer recommends it. Macromedia instead recommends that you establish a gateway connection using the Service object. For information on using NetServices to establish a gateway connection, see Appendix A, “Using NetServices and Connection Classes,” on page 163.
The remainder of this section describes how to establish a gateway connection using a Service object or a web page.
Creating a gateway connection using the Service class
To create a gateway connection in ActionScript, Macromedia recommends that you create a Service object, creating the gateway connection at the same time that you create a reference to a remote service and its methods.
Configuring Flash Remoting 37
You use the constructor for the Service class to create a new Service object. The following example shows how to create a Service object ( connection (" (
custService) to a remote service ("CustomerInfo"):
custService = new Service("http://localhost:8300/flashservices/gateway”,
http://localhost:8300/flashservices/gateway") and a reference
new Log(), "CustomerInfo", null, null);
new Service()) while simultaneously creating a gateway
When you create a gateway connection in this manner, you can access the Connection object through the
connection property of the Service object. For more information, see the Service
class in Flash Remoting ActionScript Dictionary Help.
Specifying the gateway connection in a web page
You specify the gateway in the web page that loads your SWF file by adding entries in the
OBJECT
tag that calls the SWF file. You must use different techniques for Microsoft Internet Explorer and Netscape Navigator browsers:
To specify the gateway for Internet Explorer, specify the gateway URL as a flashvars
parameter in an HTML
PARAM tag inside the OBJECT tag body.
To specify the gateway for Netscape, specify the gateway URL as a flashvars attribute to the
HTML
The following HTML example runs the myMovie.swf Flash application and specifies http://apps. myCompany.com/flashservices/gateway as the URL for the Flash Remoting services gateway. The first highlighted line contains the code for Internet Explorer. The second highlighted line contains the code for Netscape.
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash. cab#version=6,0,0,0" WIDTH="100%" HEIGHT="100%" id="MyMovie"> <PARAM NAME="flashvars" VALUE="gatewayUrl=http://apps.myCompany.com/
<PARAM NAME=movie VALUE="MyMovie.swf"> <PARAM NAME=quality VALUE="high"> <PARAM NAME=bgcolor VALUE="#000099">
<EMBED src="MyMovie.swf"
</EMBED>
</OBJECT>
EMBED tag that specifies the Flash application.
flashservices/gateway">
FLASHVARS="gatewayUrl=http://apps.mycompany.com/flashservices/gateway" quality=high bgcolor="#000099" WIDTH="100%" HEIGHT="100%" NAME="movieName" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
38 Chapter 2: Using Flash Remoting ActionScript
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, the following HTML Service parameter, which accesses the
gatewayUrl parameter.
<param name="flashvars" value="gatewayUrl=http://localhost:8300/flashservices/
gateway/"/>
// Service constructor custService = new Service(
"", // set using flashvars to http://localhost:8300/flashservices/ null, "customerData", null, null);
flashvars parameter creates the gateway connection and the subsequent
customerData service, submits an empty string for the
Specifying a service
The service name format depends on the type of service you are using. The following table lists the ways that you can specify service names for the supported service types:
Service type Service name Example
Web services (accessed through ColdFusion or .NET servers)
ASP.NET pages (.aspx) Logical directory path from the web
DLL files (.dll) Fully qualified class name. Flashgateway.Samples.
EJBs JNDI name of the EJBHome
Java classes, including JavaBeans
Java servlets Web application context root. WeatherService
JMX (JRun 4 only) MBean object name. DefaultDomain:service=
ColdFusion pages (.cfm) Path from the web root to the page’s
URL of the WSDL file for the service.
root. Replace all slash or backslash characters in the path with periods.
binding.
Fully qualified Java class name. com.mycompany.samples.
directory. Replace all forward slash or backward slash characters in the path with periods.
http://www.xmethods.net/sd/ 2001/BabelFishService.wsdl
FlashGateway.Samples. WeatherService
WeatherService
com.mycompany.samples. WeatherService
WeatherService
DeployerService
Flashgateway.samples. WeatherService
ColdFusion components (.cfc) Qualified ColdFusion component
name starting from the web root.
Flashgateway.samples. WeatherService
Configuring Flash Remoting 39
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 Remoting provides the
setCredentials() method of the Connection object to allow you
to specify authentication credentials to send to the application server. Flash Remoting sends the credentials in the header of every service function call. This method is currently supported on the following servers:
ColdFusion MX
JRun 4
To use the connection and before you call a service function. For a Flash application that is run by a single user during a session, you can call the gateway connection object. If you created the gateway object using the Service object, you can access the connection object through the provide authentication, as shown in the following example:
import mx.remoting.Service; import mx.remoting.PendingCall; import mx.rpc.RelayResponder; import mx.rpc.ResultEvent; import mx.rpc.FaultEvent
function getCategories_Result (re:ResultEvent):Void {
trace("Got Categories - " + re.result.length + " Record" + (re.result.
length>1?"s":"")); } function getCategories_Fault (fault:FaultEvent):Void {
trace("CategoriesCallFailed-" + fault.fault.description); } var myResponder:RelayResponder = new
RelayResponder(this,"getCategories_Result","getCategories_Fault"); var petMarketService:Service = new Service(//establish connection
"http://examples.macromedia.com/flashservices/gateway",
null,
"petmarket.api.catalogservice",
null,
myResponder ); // set user credentials petMarketService.connection.setCredentials("myUserName","myPassword"); // call service function var temp_pc:PendingCall = petMarketService.getCategories("en_US");
setCredentials() method, call the method after you have created the gateway
setCredentials() method any time after creating the
connection property and call setCredentials() to
Note: To ensure security, never include specific user names or passwords in ActionScript.
40 Chapter 2: Using Flash Remoting ActionScript
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
2.
Set the gateway connection credential information to empty strings.
cflogout tag.
The following example shows 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’re using.
Using authentication in ColdFusion MX
If you use ColdFusion, the
setCredentials() method causes Flash Remoting to put the login
ID and password in the ColdFusion page’s CFLogin scope whenever you request a service. The Application.cfm page for the ColdFusion page or ColdFusion component should process this information as necessary in a
cflogin tag. For more information on implementing security in
ColdFusion, see “Securing access to ColdFusion from Flash Remoting” on page 116.
Using authentication in JRun 4
Authentication in JRun 4 is only meaningful for EJBs, where you can use the
setCredentials()
method to enable access to secured EJB methods. You must configure your application server for single sign-on. The Flash gateway provides the security credentials to the login module. For more information on authentication in JRun 4, see “Using Flash Remoting with JRun security”
on page 139.
Calling service functions
To call the functions exposed by a Service object, you use the object name followed by the service function name. In the following example,
getCategories() is the name of the function that is called:
var temp_pc:PendingCall = petMarketService.getCategories("en_US");
The getCategories() function exists in the application server as a public method or application page. The function also passes a string parameter, function should return the categories. To pass multiple parameters to service functions, you include a comma-separated list of values in the service function call. If the function also allowed you to specify a type of category, for example, the parameters would look like this:
petMarketService.getCategories("en_US", "Accessories");
petMarketService is the Service object name and
"en_US", to specify the language in which the
getCategories()
Calling service functions 41
In this example, the service function passes two parameters, a language specification (en_US), and a type of category (
Note: Parameters must be in the order required by the service function.
import mx.remoting.Service; import mx.remoting.PendingCall; import mx.rpc.RelayResponder; import mx.rpc.ResultEvent; import mx.rpc.FaultEvent
// create RelayResponder to specify result handling methods var myResponder:RelayResponder = new
RelayResponder(this,"getCategories_Result","getCategories_Fault");
// establish gateway and create a Service object to refer to the service var petMarketService:Service = new Service(
"http://examples.macromedia.com/flashservices/gateway",
null,
"petmarket.api.catalogservice",
null,
myResponder );
// set user credentials petMarketService.connection.setCredentials("myUserName","myPassword");
"Accessories").
// call service function var temp_pc:PendingCall = petMarketService.getCategories("en_US"); // getCatergories_Result and getCategories_Fault are result/fault handlers function getCategories_Result (re:ResultEvent):Void {
trace("Got Categories - " + re.result.length + " Record" + (re.result.
length>1?"s":"")); } function getCategories_Fault (fe:FaultEvent):Void {
trace("CategoriesCallFailed-" + fe.fault.description); }
Specifying functions
The way you specify the service function name depends on the type of service you are using. The following table lists the ways that you specify the function names for the supported service types:
Service type Function name
Web services (SOAP-based) Web service function exposed through WSDL
ASP.NET pages (.aspx) ASP.NET page (without a suffix)
DLL files (.dll) Public method
EJBs EJBHome and EJBObject methods
Java classes, including Java Beans Public method
Java servlets Servlet-name registered in the web.xml file
JMX (JRun 4 only) MBean method
42 Chapter 2: Using Flash Remoting ActionScript
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.
Calling functions using named arguments in ColdFusion
If you are calling a ColdFusion page or ColdFusion component that can take named arguments, you can also call a service function and pass it a single ActionScript object that contains name-value pairs for the arguments, as shown in the following example:
myService.myFunction({dept: "Sales", name: "BobZ"});
The ColdFusion page or component uses the object elements, dept and name, as named arguments. For more information, see “Passing parameters to ColdFusion components”
on page 106.
Handling service results and errors
When you call a service function, there are two possible outcomes: the result that you expect or a fault (error). These outcomes are relayed to a result handler method and an error handler method, respectively, which you specify. For example, a result handler could display the results in the Flash application, while an error handler might call trace functions to report the error descriptions. You can specify the result and fault handling methods either for all results and faults that occur for the service or for specific server function calls.
In both cases, you specify a responder object. The responder object can be any ActionScript object that implments the mx.rpc.Responder interface. The Responder interface exposes two methods (
onResult() and onFault()) that respond to the results and faults for the current
pending call. For convenience Flash Remoting API provides an implementation of the mx.rpc. Responder interface that you can use: mx.rpc.RelayResponder.
The RelayResponder relays any result and fault responses to any object and any method of that object. To specify the methods that handle the result and the fault conditions, the constructor for the RelayResponder object has, as its second and third parameters, the names of the methods that handle the ResultEvent and FaultEvent objects that the service method returns. The first parameter specifies the name of the object that contains these methods. For example, the RelayResponder in the HelloWorld example specifies that the result handling method is
helloWorld_Result(), the fault handling method is helloWorld_Fault(), and the class that
contains them is this class (this).
pc.responder = new RelayResponder( this, "helloWorld_Result",
"helloWorld_Fault" );
Note: Do not specify result handler and fault handler methods when you create the service object and when you call a service function. Specifying methods in both places can cause errors in your application that might be difficult to diagnose.
Handling service results and errors 43
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).
You write fault handlers to respond to the errors, typically by displaying an error message or logging the error information. In some cases, you might be able to include recovery code, such as code to retry a call to a busy server, in the error handler.
For information on handling result and fault outcomes when you have connected to a service using the deprecated NetServices class, see Appendix A, “Using NetServices and Connection
Classes,” on page 163.
Using the RelayResponder object for a service
To direct all results for a service to a single object, specify a RelayResponder object for the
responder parameter when you create the Service object. For example, the responder
parameter, which is the last parameter, of the following Service constructor specifies that the
onCustData() method is the result handler and the onCustFault() method is the fault handler
method. It also specifies with the first parameter that this object (
this) contains both methods.
// Service constructor creates RelayResponder custService = new Service(
"http://localhost:8300/flashservices/gateway",
null,
"CustomerInfo",
null,
new RelayResponder(this, "onCustData", "onCustFault")); // … // Result handling method specified in RelayResponder for custService function onCustData( re:ResultEvent ):Void {
// update customer grid
var rs:RecordSet = RecordSet( re.result );
rs.setDeliveryMode( "onDemand" );
// create columns
if( customers_grd.columnCount == 0 ) {
var col:DataGridColumn = new DataGridColumn( "ID" ); customers_grd.addColumn( col ); col = new DataGridColumn( "Active" ); col.width = 80; customers_grd.addColumn( col ); col = new DataGridColumn( "Name" ); col.width = 100; customers_grd.addColumn( col );
customers_grd.addEventListener( "change", onCustGrid_Change ); } // Fault handling method specified in RelayResponder function onCustFault( fault:FaultEvent ):Void {
// notify the user of the problem //…
44 Chapter 2: Using Flash Remoting ActionScript
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.
Using PendingCall and RelayResponder objects for a specific service function
After the Flash client application calls a service function, it does not stop executing to wait for the return value; it continues to execute and specify which methods will handle the result or the fault condition that the service function returns.
A call to a service method immediately returns a PendingCall object, which has a
responder
property. You can handle the result and fault outcomes for each service method by creating an mx. rpc.RelayResponder object, or any ActionScript object that implements the mx.rpc.Responder interface, and assign it to the
For example, in the following code, the method of the petMarketService object. The return value is a PendingCall object, code assigns a RelayResponder object to the the RelayResponder object specifies that handle a result outcome and
responder property of the PendingCall object.
petMarketConn() function calls the getCategories()
temp_pc. The
responder property of temp_pc. The constructor for
getCategories_Result() function is the function to
getCategories_Fault() function is the function to handle a fault
outcome.
function petMarketConn() {
petMarketService = new Service( "http://examples.macromedia.com/flashservices/gateway", new Log(), "petmarket.api.catalogservice", null,
null); var temp_pc:PendingCall = petMarketService.getCategories("en_US"); temp_pc:responder = new
RelayResponder(this,"getCategories_Result","getCategories_Fault"); } function getCategories_Result(result:ResultEvent){
// display successful result
myGrid.dataProvider = result.result; } function getCategories_Fault(var fault:FaultEvent):Void {
message_txt.text = fault.fault.description; }
For more information on the PendingCall and RelayResponder objects, see the PendingCall class and the RelayResponder class in Flash Remoting ActionScript Dictionary Help.
Using the ResultEvent class
A successful call to a service function returns a ResultEvent object as an argument to the result handling method. The ResultEvent object contains a object that the service function returned.
result property, which stores the result
Handling service results and errors 45
Handling the result object requires knowledge of the service function. The service function could return a simple string, as shown in the following
function serviceFunctionName_Result(result:ResultEvent) {
// display successful result
messageDisplay.text = result.result; }
HelloWorld_Result() method:
The service function could also return a complex object such as a record set holding several records that were retrieved from a database. The handling method for the call to the
custService.getCategories() method, receives a record
set and binds the Name and ID fields of the records in the record set to the ComboBox. In this case, the the
DataGlue.bindFormatStrings() function.
function onCategoryData( re:ResultEvent ):Void {
mx.remoting.debug.NetDebug.trace({level:"Debug",
message:"onCategoryData" }); // use data glue to remap the fields so that label = name field and // data = id field
DataGlue.bindFormatStrings( custCat_cmbo, re.result, "#Name#", "#ID#" ); custCat_cmbo.addEventListener( "change", onCustCat_Change ); refreshCustomerData();
}
result property (re.result) holds the record set that is passed to
onCategoryData() method, which is the result
custCat_cmbo
For more information about the ResultEvent class, see the ResultEvent class in Flash Remoting ActionScript Dictionary Help.
Using the FaultEvent class
If a call to a service function results in an error, Flash Remoting returns a FaultEvent object as an argument to the fault handling method that you specified in the RelayResponder object. The FaultEvent object contains a
faultstring, description, detail, and type properties. These properties contain information
fault object (mx.rpc.Fault), which has faultcode,
about the error that occurred including a code, descriptions, a stack trace, and the error class name. You can display this information to the application user in order to document the error. In the following example, the object and calls the
fault.faultstring
function onCategoryFault( fault:FaultEvent ):Void {
// notify the user of the problem mx.remoting.debug.NetDebug.trace({level:"None",
message:"There was a problem: " + fault.fault.faultstring }); }
NetDebug.trace() method to display a description of the error (fault.
onCategoryFault() fault handling function receives a FaultEvent
).
For more information about the FaultEvent object, see the FaultEvent class in Flash Remoting ActionScript Dictionary Help.
46 Chapter 2: Using Flash Remoting ActionScript
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.0:
Using the Service object to create a gateway connection and a reference to a remote service
Using the PendingCall and RelayResponder objects to specify result-handling and
fault-handling methods
Formatting and paging of a record set result
Assigning a record set to a DataGrid user interface component
Using event listeners to trigger refreshing of the data
You can find the CustomerInfoExampleAPI application in the following folders:
/Program Files/Macromedia/Flash MX 2004/en/First Run/RemotingSamples/Client
/Program Files/Macromedia/Flash MX 2004/en/First Run/RemotingSamples/Server
See the Readme.htm and RemotingCustomerExamplesWalkthrough.htm files in the RemotingSamples folder for information on how to set up and use this sample application. You can access the Flash and ActionScript files for this example in the Client subfolder.
The following figure depicts the user interface. Based on the category that a user selects in the Category list, the application returns a paged record set containing the qualifying customers from the customers database and displays it in a DataGrid in the Customers section. The Customer Detail section of the user interface displays a logo and descriptive text about the customer that is currently selected in the DataGrid.
Data is the result of remoting service call to CFC that returns a paged record set.
Total number of customers for the current category.
Category list filters data in grid. List is populated by remoting service call to CFC.
Loader displays images referenced by URL in Access database.
Customer detail information is populated from currently selected item in data grid.
Using the Flash Remoting ActionScript API in the CustomerInfoExampleAPI application 47
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.
import mx.remoting.Service; import mx.rpc.RelayResponder; import mx.rpc.FaultEvent; import mx.rpc.ResultEvent; import mx.remoting.PendingCall; import mx.remoting.RecordSet; import mx.controls.DataGrid; import mx.controls.gridclasses.DataGridColumn; import mx.controls.ComboBox; import mx.controls.TextArea; import mx.remoting.DataGlue; import mx.screens.Form; import mx.controls.TextInput; import mx.controls.Label; import mx.controls.Loader; import mx.controls.Alert;
class CustomerInfoFormAPI extends Form {
function CustomerInfoFormAPI() {
super();
mx.remoting.debug.NetDebug.initialize(); // initialize the NCD
initialized = false;
custService = new Service(
"", // set using flashvars to http://localhost:8300/flashservices/ null, "customerData", null,
null); // load category combo var pc:PendingCall = custService.getCategories(); // get all categories totalSales_label.setStyle( "textAlign", "right" ); pc.responder = new RelayResponder( this, "onCategoryData",
"onCategoryDataFault" );
addEventListener( "reveal", onReveal );
}
// initializes the display function onReveal():Void {
if( !initialized ) {
var col:DataGridColumn = new DataGridColumn( "ID" ); customers_grd.addColumn( col ); col = new DataGridColumn( "Active" ); col.width = 80; customers_grd.addColumn( col ); col = new DataGridColumn( "Name" ); col.width = 250; customers_grd.addColumn( col );
48 Chapter 2: Using Flash Remoting ActionScript
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.setStyle( "textAlign", "right" ); 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():Void {
var curItem:Object = customers_grd.selectedItem; custInfo_txt.text = curItem.Details; totalSales_label.text = curItem.TotalSales; custLogo_ldr.load( curItem.Logo );
}
// gets the customer data for the current category selected function refreshCustomerData():Void {
var pc:PendingCall = custService.getCustomers( custCat_cmbo.selectedItem.
data );
pc.responder = new RelayResponder( this, "onCustomerData",
"onCustomerDataFault" ); }
// updates the detail section when a new item is selected in the grid function onCustGrid_Change( eventObj: Object ):Void {
mx.remoting.debug.NetDebug.trace({ level:"Debug",
message:"onCustGrid_Change" });
eventObj.target._parent.updateDetails();
}
// updates the grid with the new customers based on the category selected function onCustCat_Change( eventObj: Object ):Void {
eventObj.target._parent.refreshCustomerData();
}
// handles the results from the getCategories() call function onCategoryData( re:ResultEvent ):Void {
mx.remoting.debug.NetDebug.trace({level:"Debug", message:"onCategoryData"
});
// use data glue to remap the fields so that label = name field and data =
id field
DataGlue.bindFormatStrings( custCat_cmbo, re.result, "#Name#", "#ID#" ); custCat_cmbo.addEventListener( "change", onCustCat_Change ); refreshCustomerData();
}
Using the Flash Remoting ActionScript API in the CustomerInfoExampleAPI application 49
// 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.selectedIndex = 0; updateDetails();
}
// handles the display of the fault information related to the customer data request // to the user function onCustomerDataFault( fault:FaultEvent ):Void {
// notify the user of the problem Alert.show( "Couldn't retrieve customer data.", "Error", Alert.OK, this ); mx.remoting.debug.NetDebug.trace({level:"None", message:"There was a
problem: " + fault.fault.faultstring }); }
// handles the display of the fault information related to the category data // request to the user
function onCategoryDataFault( fault:FaultEvent ):Void {
// notify the user of the problem Alert.show( "Couldn't retrieve category data.", "Error", Alert.OK, this ); mx.remoting.debug.NetDebug.trace({level:"None", message:"There was a
problem: " + fault.fault.faultstring }); }
private var custService:Service; private var customers_grd:DataGrid; private var custCat_cmbo:ComboBox; private var custInfo_txt:TextArea; private var totalRec_txt:TextInput; private var totalSales_label:Label; private var custLogo_ldr:Loader; private var initialized:Boolean;
}
CustomerInfoFormAPI()
The
CustomerInfoFormAPI() function is the constructor for the class. It calls the super()
method to initialize the Form super class. It also calls the initialize Flash Remoting debug support and sets the
NetDebug.initialize() method to
initialized variable to false to indicate
to later code that initialization has not been completed. Then it calls the constructor for the Service object to create a reference ( submits an empty string for the established by the following
flashvars parameter in the CustomerInfoExampleAPI.html file,
custService), to the customerData service. The constructor
gatewayUrl parameter because the gateway connection is
which you open to run the application:
<param name="flashvars" value="gatewayUrl=http://localhost:8300/flashservices/
gateway/"/>
50 Chapter 2: Using Flash Remoting ActionScript
Establishing the connection in the HTML file enables you to change it without needing to republish the application.
After creating the
getCatergories()
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
RelayResponder specifies the object ( and the fault handling method (“ condition returned by the
addEventListener() to register the onReveal() method, the method to call when a reveal
getCategories() function. RelayResponder calls
this), the result handling method (“onCategoryData”),
onCategoryFault”) that will handle the result or fault
event occurs.
onReveal()
The
onReveal() function performs initialization tasks for the CustomerInfoFormAPI class if the initialization variable is not equal to true. These tasks include defining the columns ("ID", "Active", "Name", and "TotalSales") for the DataGrid component that displays the customer
information returned from the customer’s database. The next line, shown here, registers the
onCustGrid_Change() function as the event handler to be called if a change occurs in the customers_grd DataGrid component.
customers_grd.addEventListener( "change", onCustGrid_Change );
Next, the onReveal() function aligns text for the Total and the Total Sales labels and sets the
initialized variable to true.
updateDetails()
The
updateDetails() function updates the data displayed in the Customer Details section
when the customer selected in the DataGrid component changes. This information includes the customer description, the Total Sales amount, and the logo. This function is called by the
onCustGrid_Change() function.
refreshCustomerData()
The
refreshCustomerData() function calls the getCustomers() function of the customerData
service (referenced as
custService) to retrieve the customers for the selected item in the
Category ComboBox component.
This function calls the RelayResponder constructor to establish the as the function to receive the results of this call, and the
onCategoryFault() function as the
onCategoryData() function
function to receive an error or fault condition.
onCustGrid_Change()
The
onCustGrid_Change() function is the event handler that is called when the selection in the
DataGrid component changes. This function calls the documents the call to this function. Then it calls the
NetDebug.trace() function to
updateDetails() function to update the
Customer Details section.
Using the Flash Remoting ActionScript API in the CustomerInfoExampleAPI application 51
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.
The
onCategoryData() function calls the addEventListener() function to register this
function as the event handler for the
cust_Cat_cmbo ComboBox component.
onCategoryData()
The
onCategoryData() function handles the result of a call to the custService. getCategories()
result handler for the
function. The CustomerInfoFormAPI() function named this function as the
getCategories() function.
This function first calls the Then it calls the
DataGlue.bindFormatStrings() function to make the Name field the label that
NetDebug.trace() function to document the call to this function.
appears in the ComboBox component and make the ID field the data field for the record. The call to change occurs to the selection in the the
addEventListener() makes the onCustCat_Change() function the event handler when a
custCat_cmbo ComboBox component. This function calls
refreshCustomerData() function to display the customers in the current category.
onCustomerData()
The
onCustomerData() function handles the results of the call to the custService. getCustomers()
of the call to the
onDemand, which means that the server will deliver records for this record set in groups of up to
25 records for each call to the the returned record set into interface. Then it sets for the grid. Finally, it calls the
function in the refreshCustomer() function. This function assigns the result
getCustomers() function to the rs record set. It sets the delivery mode to
getCustomers() function. Next, this function loads the length of
totalRec_txt.text variable for display in the Total field of the user
customers_grd.dataProvider to rs to specify that rs provides the data
updateDetails() function to update the Customer Details
section for the selected customer.
onCustomerFault()
The
onCustomerDataFault() function handles the fault outcome of a request for customer data.
It calls to display a message and report the status as specified by the
Alert() to notify the user of the problem and then calls the NetDebug.trace() function
faultstring property of the Fault
object that is passed to the function in a FaultEvent object.
onCategoryFault()
The
onCategoryDataFault() function handles the fault outcome of a request for Category data.
It calls
Alert() to notify the user of the problem and then calls the NetDebug.trace() function
to display a message and report the status as specified by the object that is passed to the function in a FaultEvent object.
52 Chapter 2: Using Flash Remoting ActionScript
faultstring property of the Fault
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.
The RemotingConnector component enables you to access any remote service and function exposed by Flash Remoting and to interactively create data bindings that update component properties in your application. The most common applications of data binding are to gather input parameters from various UI components to send to a service function and to display the results of a service function call.
You can find the RemotingConnector component under the Data Components section of the Components panel, as shown in the following example:
Typically, a remote service function accepts parameters and returns a result. Using Flash MX Professional 2004 and the RemotingConnector component, you can both connect to a remote service and bind the result of a remote service function to the properties of a UI component.
Note: A single instance of the RemotingConnector component allows you to make multiple calls to a single remote method. To call a different remote method, you must create a different instance of the RemotingConnector component.
53
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.
You can set the following schema properties in the Schema tab:
Property Name Description
params A property that holds the parameters that are sent to the specified method.
You create schema fields under this property and bind them to properties to set parameter values.
results A property that holds the results returned by the service function.
Once you have defined the schema, you can bind the items to a variety of UI controls to provide values for the parameters or to display the results of the web service. For more information, see “Working with schemas in the Schema tab (Flash Professional only)” in Using Flash Help.
RemotingConnector parameters
For each RemotingConnector component instance, you set parameters in the Parameters tab of the Component inspector, as shown in the following example.
54 Chapter 3: Using the RemotingConnector component (Flash Professional only)
These parameters can take the following values:
Parameter Type Category Description
multipleSimultaneousAllowed
shareConnections
suppressInvalidCalls
Boolean 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".
Flash Player might place limits, which vary by version and platform, on the number of simultaneous network operations.
Boolean Advanced If it has the value true, this parameter allows
multiple instances of this component to share a single connection as long as they all use a common gatewayUrl.
Boolean Advanced If this parameter has the value true, the
trigger() function does not perform a call if
the databound parameters fail the validation. A Status event occurs with code =
"InvalidParams". If it has the value false,
the call takes place, using the invalid data as required.
password
userId
gatewayUrl
methodName
serviceName
String Other (Optional) The password required for
connecting to the service.
String Other (Optional) The user ID required for
connecting to the service.
String General The parameter that specifies the URL of the
gateway to which the connection will be established.
String General The parameter that specifies the name of
the method to call in the remote service.
String General The parameter that specifies the fully
qualified name of the service.
55
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.
Note: The RemotingConnector component appears on the stage during application development but is not visible when you execute the application.
2.
Enter the instance name of the component in the Property inspector.
3.
Modify the schema for the component on the Schema tab of the Component inspector.
You can edit this schema as needed to change the data type of the result, to add a complex, structured result, or to provide additional formatting or validation settings. For example, you would perform the following steps to call a service that takes two parameters (state and zip) and returns a paged RecordSet object.
Note: Use the Add Field button to make all modifications to the schema for the RemotingConnector component. There is no need to use the Add Property button.
a
Select the Params : Object item in the Schema tab.
b
Select the Add Field button and set the field name property to state. There is no need to change String as the default data type.
c
Select the Params : Object item again.
d
Select the Add Field button, and set the field name property to zip.
e
Next to the data type entry, click the Value field to activate the pop-up menu, and select Number from the list for the data type.
f
Select the Results : Object item in the schema list, and choose RecordSet from the drop-down menu for the data type.
g
Click the Value field next to validation options, and click the magnifying glass icon, which appears, to bring up a dialog box for RecordSet options. Select the paging option.
4.
Using the Binding tab in the Component inspector, bind the service parameters and results that you have defined in your schema to the UI components that will send the parameters and display the results in your application.
5.
Use one of the following techniques to add a trigger to initiate the binding operation.
Attach the Trigger Data Source behavior to a button.
In the Actions panel, add a call on the RemotingConnector component to the ActionScript
trigger() function.
Create a binding between a parameter and a UI control, and set the Kind property to
AutoTrigger. This causes a call to the location during a data binding operation. For more information, see “Schema kinds (Flash Professional only)” in Using Flash Help.
56 Chapter 3: Using the RemotingConnector component (Flash Professional only)
trigger() function when a value is copied to this
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.0 features:
Querying of a database (Microsoft Access) using ColdFusion Component (CFC)
Formatting and paging of a RecordSet result
Data binding using the RemotingConnector component
Specifying of the gateway URL using HTML
You can find the CustomerInfoExampleCon application in the following folders:
/Program Files/Macromedia/Flash MX 2004/en/First Run/RemotingSamples/Server
/Program Files/Macromedia/Flash MX 2004/en/First Run/RemotingSamples/Server
See the Readme.htm and RemotingCustomerExamplesWalkthrough.htm files in the RemotingSamples folder for information on how to set up and use this sample application. You can access the Flash and ActionScript files for this example in the Client subfolder, if you want to make changes to it.
The following figure illustrates the user interface for the application. Based on the category that a user selects in the Category list, the application returns a paged RecordSet object containing the qualifying customers from the database. The application uses the RemotingConnector to bind the data in the RecordSet object (ID, Active, Name, and Total Sales) to the corresponding columns in the data grid. The Customer Detail section of the user interface displays a logo and descriptive text about the customer that is currently selected in the DataGrid component.
Data is the result of remoting service call to CFC that returns a paged record set.
Total number of customers for the current category.
Category list filters data in grid. List is populated by remoting service call to CFC.
Loader displays images referenced by URL in Access database.
Customer detail information is populated from currently selected item in data grid.
Using the RemotingConnector in the CustomerInfoExampleCon application 57
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 mx.data.components.RemotingConnector; import mx.controls.DataGrid; import mx.controls.gridclasses.DataGridColumn; import mx.controls.ComboBox; import mx.controls.TextArea; import mx.screens.Form; import mx.controls.TextInput; import mx.controls.Label; import mx.controls.Loader; import mx.controls.Alert;
class CustomerInfoFormCon extends Form {
function CustomerInfoFormCon() {
super(); initialized = false; addEventListener( "reveal", onReveal );
}
// initializes the display
function onReveal():Void { // initialize stuff
if( !initialized ) {
var col:DataGridColumn = new DataGridColumn( "ID" ); customers_grd.addColumn( col ); col = new DataGridColumn( "Active" ); col.width = 80; customers_grd.addColumn( col ); col = new DataGridColumn( "Name" ); col.width = 250; customers_grd.addColumn( col ); col = new DataGridColumn( "TotalSales" ); col.width = 80; col.textAlign = "right"; customers_grd.addColumn( col );
// register a listener for change in selection in DataGrid
customers_grd.addEventListener( "change", onCustGrid_Change );
// setup remaining
mx.remoting.debug.NetDebug.initialize(); // initialize the NCD totalRec_txt.setStyle( "textAlign", "right" );
totalSales_label.setStyle( "textAlign", "right" ); // Now we are ready to trigger categoryData_con to fetch all the // categories in ComboBox - invoking trigger()
categoryData_con.addEventListener( "status", onCategoryDataFault );
categoryData_con.addEventListener( "result", onCategoryData );
customerData_con.addEventListener( "result", onCustomerData );
customerData_con.addEventListener( "status", onCustomerDataFault );
58 Chapter 3: Using the RemotingConnector component (Flash Professional only)
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._visible = true;
}
// updates the detail section when a new item is selected in the grid function onCustGrid_Change( eventObj: Object ):Void {
mx.remoting.debug.NetDebug.trace({ level:"Debug",
message:"onCustGrid_Change" });
eventObj.target._parent.updateDetails();
}
// handles the result of the call to the getCustomers() service function
function onCustomerData( re:Object ):Void {
_parent.customers_grd.selectedIndex = 0; _parent.updateDetails();
}
// handles the results from the getCategories() call. It executes the
// binding which will force the customer data connector to fire and get the // appropriate customers for the currently selected category.
function onCategoryData( re:Object ):Void {
_parent.customerData_con.refreshFromSources();
}
// handles the display of the fault information related to the customer data // request to the user
function onCustomerDataFault( status:Object ):Void {
// notify the user of the problem
if( status.code == "fault" ) {
Alert.show( "Couldn't retrieve customer data.", "Error",
Alert.OK, this );
mx.remoting.debug.NetDebug.trace({level:"None",
message:"There was a problem: " + status.data.faultstring });
}
}
Using the RemotingConnector in the CustomerInfoExampleCon application 59
// 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.faultstring });
}
}
private var customerData_con:RemotingConnector; private var categoryData_con:RemotingConnector; private var customers_grd:DataGrid; private var custCat_cmbo:ComboBox; private var custInfo_txt:TextArea; private var totalRec_txt:TextInput; private var totalSales_label:Label; private var custLogo_ldr:Loader; private var initialized:Boolean;
}
CustomerInfoFormCon()
The
CustomerInfoFormCon() function is the constructor for the class. It calls the super()
method to initialize the Form super class. It also sets the variable for the initial call to the The
addEventListener() function registers the onReveal() method as the event handler for a
reveal event.
onReveal() method, which performs initialization tasks for this class.
initialized to the value false
onReveal()
The
onReveal() function performs initialization tasks for the CustomerInfoFormCon class.
These tasks include defining the columns (
"ID", "Active", "Name", and "TotalSales") for the
DataGrid component that displays the customer information returned from the database. The next line, shown here, registers the called if a change occurs in the
customers_grd.addEventListener( "change", onCustGrid_Change );
onCustGrid_Change() function as the event handler to be
customers_grd DataGrid component.
Next, the onReveal() function calls the NetDebug.initialize() method to initialize Flash Remoting debug support. Then it aligns text for the Total and the Total Sales labels and registers the following functions as event handlers:
onCategoryDataFault() to handle a status outcome for an access on Category data
onCategoryData() to handle the result of an access on Category data
onCustomerData() to handle the result of an access on Customer data
onCustomerDataFault() to handle a status outcome for an access on Customer data.
60 Chapter 3: Using the RemotingConnector component (Flash Professional only)
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.
onCustGrid_Change()
As noted earlier, the selection in the DataGrid changes. This function calls the a debug message that documents the call to this function. Then it calls the
onCustGrid_Change() function is the event handler that is called when the
NetDebug.trace() function to display
updateDetails()
function to update the Customer Details section.
onCustomerData()
The
onCustomerData() function handles the results of a request to retrieve Customer data and
populate the DataGrid component. It sets the selection index to 0 to make the first customer in the list the current selection. Then it calls the
updateDetails() function to update the
Customer Details section for the selected customer.
onCategoryData()
The
onCategoryData() function handles the result of a request to access Category data. This
function forces the RemotingConnector for Customer data (
customerData_con) to get the
appropriate customers for the currently selected category.
onCustomerDataFault()
The
onCustomerDataFault() function handles the fault outcome of a request for Customer
data. It calls the
NetDebug.trace() function to display a message and report the status.
onCategoryDataFault()
The
onCategoryDataFault() function handles the fault outcome of a request for Category data.
It calls the
NetDebug.trace() function to display a message and report the status.
Using the RemotingConnector in the CustomerInfoExampleCon application 61
62 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.
This chapter contains the following sections:
“About Flash Remoting and data types” on page 63
“Understanding Action Message Format” on page 64
“Converting from ActionScript to application server data types” on page 65
“Converting from application server data types to ActionScript” on page 67
“ColdFusion to ActionScript data conversion issues” on page 69
“About working with objects” on page 70
“About working with RecordSet objects” on page 73
“About working with XML” on page 85
About Flash Remoting and data types
When Flash Remoting sends data from a Flash application to an application server, and when a server returns data to a Flash application, the data is converted twice:
In the Flash client, between ActionScript data types and Action Message Format (AMF)
At the server gateway, between Action Message Format and the native language of the
application (Java, C#, Visual Basic, or CFML)
63
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. In most cases, the conversion is straightforward; you simply pass the ActionScript data as arguments to a remote service, and process or display the returned data in your callback functions. In a few cases, you must understand data type conversion considerations to ensure correct application behavior. This chapter includes information about these considerations.
Understanding Action Message Format
To send and receive messages from remote services, Flash Remoting uses Action Message Format (AMF), a binary message format designed for the ActionScript object model. Using AMF, Flash Remoting encodes data types back and forth between the Flash application and the remote service over HTTP. Modeled on the Simple Object Access Protocol (SOAP), AMF uses a packet format to relay information. An AMF packet consists of the following parts:
Packet header that contains AMF version information
Context header count
Array of context headers that contain information describing the context in which individual
AMF messages should be processed
Message count
Array of messages
Server function requests are automatically serialized into AMF format. On the server, Flash Remoting deserializes the incoming AMF messages. When the server-side processing finishes, the results are serialized to AMF and sent back to the Flash application. The format of the server-generated AMF message is identical to the client-generated packet. The body of the individual AMF message contains the error or response object, which is expressed as an ActionScript object. For more information about error and response objects, see Chapter 2,
“Using Flash Remoting ActionScript,” on page 29.
64 Chapter 4: Using Flash Remoting Data in ActionScript
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. In loosely typed programming environments, such as ColdFusion or Visual Basic, the environment must be able to use the listed data type for the service function variable.
The following table lists the server data types into which the Flash gateway converts ActionScript data types:
ActionScript Data Type
null null null Nothing null null (not
undefined null null Nothing null null (not
Boolean Boolean System.Boolean Boolean boolean Boolean
Number Number Any numeric type,
String String System.String String string String
Date Date System.DateTime Date dateTime Date
Converted Java data type
Converted C# data type
as appropriate
Converted Visual Basic data type
Any numeric type, as appropriate
Converted SOAP data type
decimal, float, double, integer, int
Converted ColdFusion MX data type
defined) ColdFusion
uses a null value internally, but reports an undefined variable
defined)
Number
Array
(contiguous numeric indexes)
Associative
Array
(named indexes)
RecordSet Cannot be sent
ArrayList System.Collections
java.util.Map
(case-insensitive implementation)
to Server
System.Collecti
.ArrayList
System.Collections .Hashtable
Cannot be sent to Server
Converting from ActionScript to application server data types 65
ons.ArrayList
System.Collecti ons.Hashtable
Cannot be sent to Server
array Array
Complex type
Cannot be sent to Server
Struct
Cannot be sent to Server
ActionScript Data Type
Converted Java data type
Converted C# data type
Converted Visual Basic data type
Converted SOAP data type
Converted ColdFusion MX data type
Object flashgateway.io.
ASObject (which implements java.util.Map)
Object consisting of
flashgateway.io.
ASObject name-value pairs passed as the only argument to a service function
(Typically used to pass data to ColdFusion.)
FlashGateway.
IO.ASObject (which implements the ICollection interface)
FlashGateway.
IO.ASObject
FlashGateway.
IO.ASObject
FlashGateway.
IO.ASObject
Complex type
Complex type
Struct Object of type
FlashGateway.
IO.ASObject For more
information, see “Working
with ActionScript typed objects” on page 71
For a CFML page, the Flash scope with the object key names being the scope variables. For more information, see “Using the
Flash scope to pass parameters to ColdFusion pages” on page 98.
For a ColdFusion component (CFC), each name-value pair is a named argument to the function
For more information, see
“Accessing ActionScript objects” on page 101.
XML org.w3c.dom.
Document
66 Chapter 4: Using Flash Remoting Data in ActionScript
System.Xml.Xml
Document
System.Xml.Xml
Document
Cannot be converted
XML
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.
Flash Remoting can convert ActionScript data to Java Boolean and numeric primitive types
that correspond to the listed class types.
Flash Remoting treats all ActionScript arrays with non-contiguous indexes (for example, arrays
with indexes of example, arrays with indexes of cases, it converts the numeric indexes to keys with numbers as the strings (for example, " "
1", "2").
0, 2, and 3 but not 1) or those with both numeric and text indexes (for
0, 1, 2, "data1", and "data2") as associative arrays. In these
Converting from application server data types to ActionScript
Flash Remoting automatically converts between the data types specific to the application server programming environment and ActionScript.
The following table shows how Flash Remoting converts data returned from the application server to ActionScript data types:
0",
C# data type Visual Basic
data type
null Nothing null N/A null null
bool System.Boolean
any number type any number type decimal,
System.Char System.String
Boolean boolean Boolean, 0, or 1
Char String
SOAP data type
float, double
string String String
ColdFusion MX data type
For details, see
“ColdFusion to ActionScript data conversion issues” on page 69
Val(Number) For details, see
“ColdFusion to ActionScript data conversion issues” on page 69
Java data type
Boolean Boolean
Number Number
Character
Converted ActionScript data type
String See notes
following this table.
System.DateTime Date dateTime Date Date Date
Converting from application server data types to ActionScript 67
C# data type Visual Basic
data type
SOAP data type
ColdFusion MX data type
Java data type
Converted ActionScript data type
System.Collection s.ICollection
object[]
System.Collection s.Hashtable
System.Collection s.IDictionary
Sytem.Data.
DataSet
System.Collection s.ICollection
object[]
System.Collection s.Hashtable
System.Collection s.IDictionary
Sytem.Data.
DataSet
array Array Collection
complex
Struct java.util.Map Associative
type
Complex
——Associative type (DataSet)
System.Data.Data
Table
System.Data.Data
Table
Query object java.sql.Result
Query object
(Flash.pagesize
variable set)
FlashGateway.IO.
ASObject System.Exception
FlashGateway.IO.
ASObject System.Exception
Complex type
A Java object as
listed in the next
column
Object[] array of
primitive types
Set
flashgateway. sql.Pageable
ResultSet
flashgateway.i
o.
ASObject Serializable Dictionary Throwable
Array
array
array of RecordSet objects
RecordSet
Paged RecordSet
Object
FlashGateway.IO.
ASObject with Type property set
System.Xml.
XmlDocument
FlashGateway.IO.
ASObject with Type property set
System.Xml.
XmlDocument
Complex type
Java Object of
class
flashgateway.io.
ASObject with
Type property
flashgateway.i
o.
ASObject with Type property set
set
(Set the type
using a Java
expression once
you create the
object using
CFML.)
XML org.w3c.dom.
Document
flashgateway.i o.ASXMLStri ng
Typed Object.
See notes following this table
XML
68 Chapter 4: Using Flash Remoting Data in ActionScript
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. For more information see “Working
with ActionScript typed objects” on page 71.
To return multiple, independent, values to your Flash application, place them in a complex
server variable that can hold all the required data, such as a variable that converts to a Flash Object, Array, or Associative Array data type. Return the single variable and use its elements in the Flash application.
ColdFusion to ActionScript data conversion issues
ColdFusion is a loosely typed (untyped) language, where the data type of a variable can be ambiguous. As a result, Flash Remoting cannot always determine how to convert between ColdFusion data and ActionScript data. Boolean data in ColdFusion
If a ColdFusion page or CFC returns Boolean values, it represents these values as strings. Flash does not have rules for converting strings to Boolean values. Instead, it converts the string to a number, and then converts the number to a Boolean value. This operation converts all representations of Boolean values except 1, which equates to the Boolean value of Therefore Flash converts ColdFusion Boolean values of
"Yes", "True", and true to false.
true, to false.
To return a Boolean value correctly from ColdFusion to ActionScript, do either of the following:
Return a 1 (true) or 0 (false) numeric or string value. For example, the following function
converts any ColdFusion Boolean value to a value that ActionScript can use correctly. (For simplicity, this example omits error-handling code.) Your ColdFusion page can call this function before returning a Boolean value to Flash Remoting:
<cffunction name="convertBool">
<cfif Arguments[1] >
<cfreturn "1">
<cfelse>
<cfreturn "0">
</cfif>
</cffunction>
Specify the returnType="boolean" attribute in the cffunction tag, as in the following
example. When a Flash application calls this ColdFusion function as a service, the function returns a valid Boolean value of
<cffunction name="getBool" access="remote" returntype="boolean">
<cfset foo = True>
<cfreturn foo>
</cffunction>
true to Flash.
ColdFusion to ActionScript data conversion issues 69
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. For example, if you have the following user-defined function and ActionScript code, Flash displays 22, not 4, in the trace message:
ColdFusion
<cffunction name="getNumber"access="remote">
<cfreturn 2>
</cffunction>
ActionScript
function getNumber_Result (result) {
myVar = (result + 2); trace (myVar);
}
To prevent such problems, do either of the following:
Specify the returnType="numeric" attribute in the cffunction tag, as in the following
example:
<cffunction name="getNumber" access="remote" returnType="numeric">
<cfset foo = 2>
<cfreturn foo>
</cffunction>
Use the Val function to explicitly convert the value to a number before you return it, as in the
following example:
<cffunction name="getNumber" access="remote">
<cfset foo = Val(2)>
<cfreturn foo>
</cffunction>
If you call either of these getNumber() functions from Flash, the ActionScript
getNumber_Result() function in the previous example displays the value 4.
About working with objects
When you pass a Flash object in a service function call, the object’s properties are sent to the gateway. In Java environments, an instance of the implements java.util.Map) represents a Flash object. In .NET environments, an instance of the
FlashGateway.IO.ASObject class (which implements the ICollection interface) represents a
Flash object. Therefore, you can pass Flash objects to any service function that accepts a Map or ICollection argument.
Because Flash Remoting transmits data only, the object methods are not available on the server. Similarly, the object properties must be data types that Flash Remoting can handle. For example, you cannot include a Flash RecordSet object in an object that you pass to a service function, because Flash Remoting cannot convert the RecordSet object to a data type on the server.
flashgateway.io.ASObject class (which
70 Chapter 4: Using Flash Remoting Data in ActionScript
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.RegisterClass method to register an object in ActionScript, you create a
typed object. Typed objects are useful in Flash applications for creating subclasses of Flash objects. You can use typed objects in calls to Flash Remoting service functions.
If you use an instance of the object type in a service function call, the
Flashgateway.IO.ASObject object represents the argument on the server that includes the
object type name.
For example, the following ActionScript creates a typed object and uses it in a service function:
// Make a class (Class constructor) class myClass extends Object {
myClass() { super(); value1 = "Test1"; // Register the class definition Object.registerClass("testClass", myClass); }
public var value1:String; }
// Send instance of registered class to a Flash Remoting gateway service myService.myFunction(new myClass());
When the service function on the application server receives this request, the argument is an object of type
FlashGateway.IO.ASObject in .NET environments. The service function can access the class
type name, testClass, using the object’s
flashgateway.io.ASObject in Java and ColdFusion, or
getType() method in Java or ColdFusion or the ASType
property in .NET.
When a service function must create a new typed object to return to Flash Remoting, it creates an object of type
FlashGateway.IO.ASObject in .NET environments. The service function uses the object’s
constructor or
flashgateway.io.ASObject in Java or ColdFusion, or of type
setType() method in Java, setType() method in ColdFusion, or the ASType
property in .NET to set the class type name to the type specified in the ActionScript
Object.registerClass() method.
When the Flash client receives the typed object from the service function, Flash runs the constructor for the type and attaches all the object’s prototype functions.
About working with objects 71
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.
To create a Flash typed object in ColdFusion, use the function, specifying the type as object’s
setType() method to set the Flash object type name. The following CFML code is the
Java and class as flashgateway.io.ASObject. Then use the
cfobject tag or the CreateObject
equivalent to the Java code:
<cffunction access="remote" name="getFlashObject">
<cfobject type="JAVA" class="flashgateway.io.ASObject" name="myOb
" action="CREATE" >
<cfset myobj.setType("MyFlashObject")> <cfset myobj.put("first", "apple")> <cfset myobj.put("second", "banana")> <cfreturn myobj>
</cffunction>
Working withJava serializable objects
If a service function returns an object that implements the Java Serializable interface, its public and private properties are available as ActionScript properties. For example, a Java service method might return the following JavaBean as the result of a Flash Remoting method invocation. In this case, all three private properties, text, recipient, and server, are available to Flash.
public class Message implements java.io.Serializable {
private String text; private String recipient; private String server;
public Message() {
this.text = "Default message";
this.recipient = "user@macromedia.com";
this.server = "smtp.macromedia.com";
}
72 Chapter 4: Using Flash Remoting Data in ActionScript
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.setRecipient("me@macromedia.com"); myBeanService.getMessage();
function getMessage_Result(msgEvent:mx.rpc.ResultEvent) {
myMessageText.text = msgEvent.result.text; myServerInfo.text = msgEvent.result.server
}
In this case, ActionScript does not get the value of the Message.text property by explicitly calling the
getMessage() method, but directly from the properties returned from the Flash
gateway on the server.
About working with RecordSet objects
Using Flash Remoting, you can return RecordSet objects from application servers, manipulate the records in the RecordSet object, and display information from the records in a Flash application. Typically, application servers create record sets from the results of a database query. Some uses for RecordSet objects in ActionScript include the following:
Providing product catalog, employee directory, or other information from an application server
database query, and browsing the results in a Flash application
Downloading a set of product options from the application server, and then using the data to
build an online catalog in a Flash application
Retrieving personal data, such as buddy lists or e-mail messages, that are stored in a database,
and displaying the lists or e-mail messages in a Flash application
About working with RecordSet objects 73
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.com 7890
Card Sean sean.carr@macromedia.com 1234
Randolph Themis themis.cripps@macromedia.com 5678
Sykes Andrew andrew.gruber@macromedia.com 9012
A RecordSet object represents a record set in Flash and contains the following elements:
An array of records
The names of the columns
A reference to the application server, if the record set is pageable
Note: For information on pageable record sets, see “Delivering RecordSet data to Flash applications
in ColdFusion MX” on page 81.
Typically, service functions return RecordSet objects to your Flash application. However, you can also use ActionScript RecordSet methods to create and manage record sets directly in ActionScript. The ability to create a RecordSet object enables you to create custom client-side data structures for use in Flash UI Components. For more information on using
RecordSet
methods, see “RecordSet methods” on page 75.
You access record set rows using the row index, much like in an array. Record indexes are relative. The first record is at index 0, the second record is at index 1, and so on. If you insert a record into a record set, all the indexes of all records in the RecordSet object starting with the index at which you insert the new record get incremented by one.
RecordSet object records also have unique IDs that are never changed. If you insert a record in a RecordSet object, it gets a new unique ID and all other record IDs are unchanged. If you delete a record, its ID is deleted and is not reused. Flash Remoting uses this ID internally, and you cannot use it to access a record, but you can use the
RecordSet.getItemID() method to determine the
ID for any record.
Note: You cannot send RecordSet objects to the application server.
74 Chapter 4: Using Flash Remoting Data in ActionScript
RecordSet methods
You can use the following methods to create and manage RecordSet objects.
Method Description
constructor for RecordSet
RecordSet.addEventListener()
RecordSet.addItem()
RecordSet.addItemAt()
RecordSet.clear()
RecordSet.contains()
RecordSet.editField()
RecordSet.filter()
RecordSet.getColumnNames()
RecordSet.getIemAt()
RecordSet.getItemID()
RecordSet.getIterator()
Creates a new local RecordSet object.
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.
Inserts a record into the RecordSet object.
Inserts a record into the RecordSet object at the specified index.
Removes all items from the record set.
Returns true if the record set contains the record or false if it does not.
Replaces the value in one field of a record.
Creates a new RecordSet object that contains selected records from the original RecordSet object.
Returns the names of all the columns of a RecordSet object.
Returns a record if the index is valid and the record is available.
Returns the record ID of a record.
Returns a new iterator for this RecordSet that iterates each item (record) in the data set.
RecordSet.getLength()
RecordSet.getLocalLength()
RecordSet.getNumberAvailable()
RecordSet.getRemoteLength()
RecordSet.isEmpty()
RecordSet.isFullyPopulated() RecordSet.isLocal()
RecordSet.removeAll()
RecordSet.removeItemAt()
RecordSet.removeEventListener()
RecordSet.replaceItemAt()
Returns the number of records in a RecordSet object.
Returns the number of records currently available (or downloaded locally).
Returns the number of records that have been downloaded from the server.
Returns the number of records in the RecordSet object on the server side.
Determines whether the RecordSet object is empty.
Determine whether a RecordSet object is fully available on the client system. (Both methods are equivalent.)
Same as RecordSet.clear(). Removes all records from the RecordSet object.
Removes the specified record from the RecordSet object.
Removes the specified event listener.
Replaces a record at the specified index.
About working with RecordSet objects 75
Method Description
RecordSet.setDeliveryMode()
RecordSet.setField()
RecordSet.sort()
RecordSet.sortItems()
RecordSet.sortItemsBy()
Changes the delivery mode of a pageable record set from an application server.
Replaces one field of a record with a new value.
Sorts all the records using a comparison function that you specify as an argument to the method.
Sorts all the records using a user-specified comparison function
Sorts all records in the RecordSet object in ascending or descending order, according to the current locale’s sorting order.
For more information about each of these methods, see Flash Remoting ActionScript Dictionary Help. The following sections describe how you can use these methods to create and manage RecordSet objects in ActionScript code.
Using RecordSet methods and properties
The following sections describe how to use
RecordSet methods to manage RecordSet objects.
Creating RecordSet objects
Most RecordSet objects are returned by service functions, so you do not typically have to create them. However, you can use the RecordSet object constructor to create a record set directly in ActionScript. For example, the following line creates a new RecordSet object with two columns: DepartmentID and DepartmentName. This RecordSet object does not contain any data:
myRecordSet = new RecordSet(["DepartmentID", "DepartmentName"]);
Getting values and information from RecordSet objects
The following sections describe how to get record set values and information.
Getting record set data values
To get a specific record in the RecordSet object, specify the record’s 0-based index in the
getItemAt() method. For example, the following line gets the third record in a record set:
myRecord = myRecordSet.getItemAt(2);
To get the value of a specific field in a record, use the column name as a property of the record. For example, use the following line to get the value of the DepartmentName field of the fourth record in the RecordSet object named myRecordSet:
myDept = myRecordSet.getItemAt(3).DepartmentName;
Note: Because the RecordSet object implements all of the ActionScript DataProvider methods, you can also use RecordSet objects directly with any object that takes a DataProvider, such as the Flash UI ComboBox Component. For more information on using RecordSet objects with Flash UI components, see “Using Flash UI components with RecordSet objects” on page 83.
76 Chapter 4: Using Flash Remoting Data in ActionScript
Getting information about a RecordSet object
To get information about a RecordSet object, use the following methods:
Method Description
RecordSet.contains()
RecordSet.getColumnNames()
RecordSet.getItemID()
RecordSet.getIterator()
RecordSet.getLength()
RecordSet.getLocalLength()
RecordSet.getNumberAvailable()
RecordSet.getRemoteLength()
RecordSet.isEmpty()
RecordSet.isFullyPopulated() RecordSet.isLocal()
Indicates whether the record set contains the specified record.
Returns an array of the names of the columns of a RecordSet object.
Returns the record ID used internally by Flash Remoting to identify the record.
Returns a new iterator for the record set. For more information see Collections in Flash.
Deprecated. Returns the number of records in a RecordSet object.
Returns the number of records downloaded, or currently available locally. In length of the remote record set.
Returns the number of records that have been downloaded from the server.
Returns the number of records in the RecordSet on the server.
Determines whether a RecordSet object is empty.
Returns true if the RecordSet object was created locally using the New operator or if the record set was returned by a Flash Remoting service function and all the data in the record set has been returned from the server.
A RecordSet object must be fully populated before you can change its contents or use the
These two methods are currently equivalent.
fetchAll mode this value is equal to the
RecordSet.filter() method.
In the following example,
// Get an array of the column names and convert it to a comma delimited list columns = theRecordSet.columnNames.join(); // The total number of records in the RecordSet recordcount = theRecordSet.length; // The number of records that are currently available to the Flash client recordsavail = theRecordSet.getNumberAvailable(); // Have all the records been returned? (Only true if recordcount == // recordsavail) allthere = theRecordSet.isFullyPopulated();
theRecordSet represents a RecordSet object:
Changing record set data
After you download all records into the RecordSet object or create a new ActionScript, you can use the
RecordSet ActionScript class data-editing methods to insert,
RecordSet object in
update, and remove records. Changes to the RecordSet object in the Flash application are not propagated back to the application server. To insert, update, or remove records in a database, you must call application server methods or pages using service functions.
About working with RecordSet objects 77
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. For example, the following adds a single record at the beginning of the myRecordSet object:
var newRecord = {DepartmentID: "BA1EA7FF0-7D79-32D3-A9280050042189548",
DepartmentName: "Technical Publications"}; myRecordSet.addItemAt(0, newRecord);
Removing records from the RecordSet object
To remove records from a RecordSet object, use the removeItemAt(), removeAll(), and
clear() methods. The removeItemAt() method removes a record at a specific index location,
and the
removeAll() and clear() methods remove all records from the RecordSet object. For
example, the following line removes the record at the first index location (0). The indexes of all the other records in the RecordSet object are automatically decremented by one:
theRecordSet.removeItemAt(0);
Replacing and renaming records in the RecordSet object
To replace a record in a RecordSet object, you use the replaceItemAt() method. To replace a specific field in a record in a RecordSet object, use the following code replaces the contents of the third record in the contents of the
newRecord variable. It then replaces the contents of the third record’s
editField() method. For example, the
theRecordSet RecordSet object with
DepartmentName field:
var newRecord = {DepartmentID: "BA1EA720-7D79-11D3-A9280050042189548",
DepartmentName: "Complaints"}; theRecordSet.replaceItemAt(2, newRecord); theRecordSet.editField(2,"DepartmentName","Compliments");
Using notifications with RecordSet objects
You can notify any ActionScript object of changes in a RecordSet object’s internal state. For example, if you associate a RecordSet object with a ListBox component, and the record set gets sorted into a different order, Flash can notify the ListBox component that the record order changed, so the ListBox component can redraw itself according to the new order.
Similarly, a RecordSet object can notify its associated ListBox component when all records arrive from the server. Then, if required, the ListBox can redraw itself to update its display.
Note: Flash UI components such as ListBox incorporate notifications as a standard part of their use of the RecordSet ActionScript class. The to receive notifications in your own ActionScript code, for example, if you create your own UI component.
addEventListener() method is only necessary if you need
78 Chapter 4: Using Flash Remoting Data in ActionScript
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.addEventListener("modelChanged", contact_grid);
In this example, the myRecordSet object represents a record set returned from Flash Remoting, and the
addEventListener() method tells Flash Remoting to notify the contact_grid object
whenever the theRecordSet object changes.
The object that receives the notification must include a handle the notification. Whenever the RecordSet object changes, the
modelChanged callback function to
modelChanged function
gets called with a message object that consists of one or more entries, as follows:
The first entry, eventName, identifies the type of event or change that was made to the record.
For some types of events, the message object also includes entries identifying the first and last
record in the record set that were affected by the event.
The types of events that can occur and be specified in the
allRows, fetchRows, sort, removeItem, removeItems, and updateItems. Depending on the
value of
lastItem, removedIDs, and removedItems. For descriptions of RecordSet events and properties,
eventName, the following properties might provide additional information: firstItem,
see the RecordSet class in Flash Remoting ActionScript Dictionary Help.
The following example creates a
modelChanged function that displays a trace message with the
event type and sets it up as the callback handler for changes to the myRecordSet object:
var myObj = new Object(); myObj.modelchanged = function(info) {
trace("Caught modelChanged event: " + info.eventName); }
myRecordSet = new RecordSet(["DepartmentID", "DepartmentName"]); myRecordSet.addEventListener("modelChanged", myObj);
eventName property are addItems,
The following example of activity on the myRecordSet RecordSet causes the modelChanged function to display
var newDept = {DepartmentID: "6504", DepartmentName: "Customer Relations"}; myRecordSet.addItemAt(15, newDept);
addItems as the event name:
For more information on the RecordSet.addEventListener() and
RecordSet.removeEventListener() methods, see the RecordSet.addEventListener() and the
RecordSetRemoveEventListener in Flash Remoting ActionScript Dictionary Help.
Sorting and filtering record sets
The
RecordSet class has methods for sorting an existing RecordSet object or creating a new
RecordSet object from an existing one by applying a selection (filter) function.
About working with RecordSet objects 79
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 and uses that function to sort the records. The in Flash Player 7.x and is substantially faster than the
sortItems() method requires a comparison function as an argument,
sortItemsBy() method is implemented natively
sortItems() method.
Sorting a RecordSet object changes the order of the records in the object, but does not otherwise change the object. Subsequent calls to the
getItemAt() method return records according to the
new order. After you sort a RecordSet object that was returned from an application, the object no longer reflects the order of the records on the server-side record set.
The following one-line example sorts the myRecordSet object according to the value of the DepartmentName field in descending order:
myRecordSet.SortItemsBy("DepartmentName", null, Array.DESCENDING);
The following example sorts a record set prior to displaying it in a ListBox UI component:
function onCustData( re:ResultEvent ):Void {
var rs:RecordSet = RecordSet( re.result );
rs.sortItemsBy(["TotalSales","Name"], null, Array.DESCENDING |
Array.NUMERIC);
DataGlue.bindFormatFunction( cust_ListBox, rs, formatSales); }
In this example, cust_ListBox represents a ListBox UI component in the Flash application. In the
rs.sortItemsBy() method, it sorts the records according to the contents of the TotalSales
column in descending order.
For an example of using the
sortItems() method, see the RecordSet.sortIems() method in Flash
Remoting ActionScript Dictionary Help.
Note: For RecordSet objects containing 2,000 or fewer records, the sortItems() method generally takes less than one second to finish on a Pentium 3 computer. The length of time to sort RecordSet objects increases rapidly as the number of records grows.
Filtering an existing RecordSet object to create a new RecordSet object
The filter() method creates a filtered view of a RecordSet object that contains only records that conform to a set of rules specified by a selection (filter) function that you define. Unlike the
sortItems() method, the filter() method creates a new RecordSet object. The original
RecordSet object and its records remain unchanged.
The selection function that you define takes a record as the first argument, and can take an optional second argument to determine how to select the records. The function must return a Boolean which the selection function returns
true or false value. Flash Remoting includes in the filtered RecordSet those records for
true. When you call the filter() method, you pass it your
selection function and, optionally, the value to use as the selection function’s second argument. The
RecordSet.filter() method calls the selection function once for each record in the record
set.
80 Chapter 4: Using Flash Remoting Data in ActionScript
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.
The myRecordSet variable represents a record set that has been retrieved by calling a service
function.
The theLetter variable represents user input in the Flash application (a single letter).
The mySelectionFunction() function takes a record and a letter and returns the value true
if the first letter of the record matches the specified letter.
The myRecordSet.filter() method filters the myRecordSet object using the
mySelectionFunction() function to create a new RecordSet object. Only those records for
which the
object.
mySelectionFunction() function returns true are included in the new RecordSet
The Contact_grid component’s dataProvider property receives a filtered copy of
myRecordSet object, generated by the
contact_grid ListBox.
Note: For RecordSet objects that have 2,000 or fewer records, the filter() method generally takes less than one second to finish. The length of time to filter RecordSet objects increases rapidly as the number of records grows.
Delivering RecordSet data to Flash applications in ColdFusion MX
By default, Flash Remoting returns a RecordSet object to the Flash client in a single response when the application server finishes retrieving the data.
In ColdFusion MX, if you expect to return a large record set and the available data transmission speeds are slow, such as when using dial-up modem, you can choose to return a record set from the application server in increments. Incremental record sets are also known as pageable record sets.
When you use pageable record sets, the following events occur:
myRecordset.filter() method, as the data for the
On the server, the record set is held in session data, and server-side Flash Remoting RecordSet
service provides access to the records.
On the client, the RecordSet object can download records when needed by the Flash
application.
About working with RecordSet objects 81
Flash Remoting can deliver pageable record set data to your application in three modes, as described in the following table:
Data delivery modes
ondemand (default)
page When you use the
fetchall As a background activity, the RecordSet object fetches the entire contents of the
Description
When you access a particular record using the RecordSet object requests the record from the server-side Flash Remoting RecordSet service.
getItemAt() method to access a record, the RecordSet object
fetches data one or more pages at a time. You specify the number of records per page when you set the delivery mode. The
default page size is 25 records. You can also tell Flash Remoting to get, or prefetch, a number of pages of data
that follow the page that contains the requested data. Flash Remoting stores these additional pages in the client if it has not already fetched them in a previous request. The default prefetch value is 0 (only get the page with the requested data).
For example, if you specify a page size of 15 records and a number of pages to prefetch of 3, Flash Remoting automatically fetches 45 records when you make your first request for a record in the data set. If you then request a record on the second page that was returned, Flash Remoting prefetches an additional 15 records.
record set from the server, starting when the service function that retrieves the record set on the application server returns.
You can specify a page size when you set the delivery mode to Remoting continues requesting one page at a time from the server until all pages have been returned. The default page size is 25 records.
getItemAt() method, the
fetchall. Flash
You change a RecordSet object’s delivery mode by calling the
setDeliveryMode() method, as in
the following example:
function getCustomerData_Result( dataEvent:mx.rpc.ResultEvent ):Void {
if (config_panel.deliveryMode.getData() == "page")
{
theRecordSet.setDeliveryMode("page", contact_grid.getRowCount(), 1); } else if (config_panel.deliveryMode.getData() == "fetchAll") {
theRecordSet.setDeliveryMode("fetchAll", 10); } else {
theRecordSet.setDeliveryMode("onDemand"); }
}
In this example, theRecordSet object represents the record set returned from Flash Remoting, and the
config_panel object represents a Flash movie clip. Using the deliveryMode.getData()
method, the code evaluates the delivery mode specified by
setDeliveryMode() method to set the mode of delivery for the RecordSet object.
config_panel, and uses the
82 Chapter 4: Using Flash Remoting Data in ActionScript
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.
If the
config_panel object specifies fetchall mode, the setDeliveryMode() method tells Flash
Remoting to set the page size to 10 records and start getting the records, one page at a time (if they are not already on the client), until the entire record set has been fetched.
For all delivery modes, after a record is received from the application server, it is held inside the RecordSet object. Any subsequent
getItemAt calls for records that the client has not yet received fetch the requested record as soon
as possible and return a
fetch pending message.
getItemAt calls immediately return the record. Any
Using Flash UI components with RecordSet objects
Many Flash UI components can use RecordSet objects to provide both label and data information. These components use Flash DataProvider objects to supply the following information:
Label values that appear to the user
Corresponding data values that are available by using the component’s getValue() method
after the user selects a label
Objects that can use DataProvider objects are often referred to as data consumers. Flash components that can be data consumers currently include the following:
ComboBox
DataGrid
ListBox
Additional UI objects might be available at the Macromedia Flash Exchange at http://
dynamic.macromedia.com/go/fl_exchange.
The following sections describe how to use the RecordSet objects with these components.
Using RecordSet objects directly
You can use RecordSet objects directly in the component to specify that the RecordSet object provides the component’s values.
The following example is a result handler for a single-column record set that contains product names. It populates a ListBox component with the returned RecordSet object’s records:
function getProductList_Result (resultEvent:mx.rpc.ResultEvent):Void { catalogListBox.dataProvider = resultEvent.result); } catalogService.getProductList();
dataProvider property of a data consumer
getProductList() service function that gets a
About working with RecordSet objects 83
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 SQL code produces a record set that, when passed to the preceding
getProductList_Result() function, populates the
catalogListBox object with both label and data values:
SELECT COST_CENTER AS DATA, DESCRIPTION AS LABEL FROM EMPDB_DEPARTMENT WHERE STATUS='Active'
Using DataGlue methods
The DataGlue class methods,
bindFormatStrings and bindFormatFunction, let you specify
how a RecordSet object supplies the contents of both the data and value fields of a data consumer. The DataGlue class methods provide substantial flexibility in formatting the contents of the labels and data, as follows:
The bindFormatStrings() method lets you independently specify strings that contain any
number of record set fields and other data as the sources of the label and data contents.
The bindFormatFunction() method lets you specify any function to provide the data to the
data consumer. The function must take a record as an argument and returns an object that consists of two entries: a label field and a data field. The function has full flexibility in using the record contents to generate and format the label and data values.
The DataGlue class methods do not make a copy of the DataProvider object. However, the data is fetched from the data provider as needed by the component.
Using the bindFormatStrings method
The bindFormatStrings() method lets you freely format record fields and string data. For example, the following method uses values from two fields to generate the labels and from three fields to generate the data values:
DataGlue.bindFormatStrings (myComboBox, myRecordSet, "#parkname#
(#parktype#)", "#city#, #state# #zipcode#");
In this example, myComboBox represents a ComboBox component in the Flash application, and myRecordSet represents the RecordSet object. The parkname, parktype, city, state, and zip code variables represent record field names. The Flash application displays the parkname and parktype variables in the ComboBox. The city, state, and zipcode variables are returned when the user selects the record and ActionScript code uses a
Using the bindFormatFunction() method
The bindFormatFunction() method lets you call a function to format the data for your data consumer. Your function must take a record as its argument and return an object with the following format:
{label: labelValue, data: dataValue};
84 Chapter 4: Using Flash Remoting Data in ActionScript
getValue, getSelectedItem, or similar, method.
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.toLowerCase();
// The data is the length of the parkname record field var theData:Number = record.parkname.length;
// Return the label and value to the caller return {label: theLabel, data: theData};
} // Call the bindFormatFunction() method DataGlue.bindFormatFunction(dataView2, result, myFormatFunction);
About working with XML
When you use Flash Remoting you can use either of the following patterns for handling XML data:
You do not use XML in Flash. The Flash application sends information to the server using
simpler data types, including objects if needed. The service functions can generate and manipulate XML data as necessary. They convert any XML to simpler data types to return to your Flash application.
You use XML directly in Flash. The service functions get XML from, and return XML to, the
Flash application. Your Flash application uses ActionScript XML objects and methods to generate and manipulate XML as needed.
Your decision as to which method to use should depend on whether it is preferable in your environment to do more processing in the server or in the client Flash application. For example, many application servers, such as ColdFusion, provide tools that are specifically optimized for XML manipulation. Therefore, although Flash includes support for XML objects and provides methods for manipulating them, you might find it more efficient to process complex XML on your server and send the processed data to Flash in custom objects, rather than having your service functions return XML to Flash. However, if you are using Flash Remoting to call a service that returns XML, you can use the Flash XML methods to access the XML directly.
If you do use XML objects in your Flash application, Flash Remoting converts between the Flash XML objects used on the client and the standard XML document object type for the application server: System.Xml.XmlDocument in .NET environments, org.w3c.dom.Document in Java, and XML document objects in ColdFusion.
The following example sends the contents of two input boxes in an XML object. The first XML element has the contents of the first text input; this element has a single child that has the contents of the second text box. The server echoes the XML back to the Flash application, and the testDocument_Result result handler concatenates the contents of the two nodes to create a single string for the output box.
About working with XML 85
// 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.appendChild(secondElement); xmlDocument.appendChild(firstElement); // Call the service function and pass it the XML document trace(xmlDocument);
} // Result Handler to handle the results returned by the Remoting call function testDocument_Result(result){
// Result is an XML object // For this example, get an attribute from the first node output_txt.text = result.firstchild.attributes["message"] + result.firstchild.firstchild.attributes["message"];
}
Note: Because the Flash XML object is a standard Flash object and not part of Flash Remoting, this document does not cover the details of using XML objects in Flash. For more information on using the Flash XML objects, see Flash Help.
86 Chapter 4: Using Flash Remoting Data in ActionScript
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.
This chapter contains the following sections:
“Using the NetConnection Debugger” on page 87
“NetConnection events” on page 89
“Using the NetConnection Debugger in ActionScript” on page 94
Using the NetConnection Debugger
To debug Flash Remoting applications, you use the NetConnection Debugger in the Flash authoring environment. The NetConnection Debugger shows calls and responses from the following software components:
Flash Player
Flash Remoting
Flash Communication Server
Application server
Note: This document does not cover using the NetConnection Debugger with Macromedia Flash Communication Server applications. For more information about Flash Communication Server applications, see Managing Flash Communication Server.
Enabling debugging
Flash Remoting for Flash MX 2004 ActionScript 2.0 separates the debugging library from the RemotingClasses library so that you can add debugging capabilities to your application when you need them and remove them to reduce the size of your application when you publish it.
The debugging library is the RemotingDebugClasses library. The following sections tell you how to add it to and remove it from your application.
87
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.initialize() method at the beginning of your code, prior to establishing a connection or using any debugging operations, to initialize debugging.
5.
Open the NetConnection Debugger by selecting Window > Other Panels > NetConnection Debugger in the Flash authoring environment.
The NetConnection Debugger window appears:
This document does not describe the NetConnection Debugger interface in detail.
88 Chapter 5: The NetConnection Debugger
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.
Select the NetConnection Debugger SWF file and open the context menu with a right-mouse click on Windows or a Ctl-Click on Mac. Select the Open With menu item and then the stand-alone player (Macromedia Flash Player 7.0 on Windows or SAFlashPlayer Mac).
Disabling debugging
When you no longer need Flash Remoting debugging capabilities, you can remove the RemotingDebugClasses library from your application to reduce its size by approximately 6K.
To remove the RemotingDebugClasses library and disable debugging in your Flash Remoting application:
1.
Press Control+L to open the Library panel.
2.
Select the RemotingDebugClasses library and delete it.
3.
Remove debugging statements from your code in the Actions panel, if you like. This step is optional.
NetConnection events
The NetConnection Debugger can display information about a variety of events, and you can select which event types to display. The following sections describe the event types and the information provided in their messages.
Specific event information
The NetConnection Debugger displays information about events belonging to three event categories: client (client), server (app_server), and Flash Communication Server (flashcomm_server). Each category has one or more specific event types. You can enable or disable all events in a category, or specific event types.
Note: The Network Connection Debugger Filters panel provides the best method for selecting which events to display. However, you can use ActionScript to enable or disable the display of specific event types for individual Connection objects. For more information on using ActionScript to enable or disable event information, see “Configuring debugger output in ActionScript” on page 96.
NetConnection events 89
The following table describes the information the NetConnection Debugger displays about specific event types.
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. If client trace reporting is enabled, the
NetConnection Debugger displays the output of
NetDebug.trace() methods. The default value is true.
http Client Connection events that communicate with the remote source using
HTTP. These events include connecting to the server, and Flash Remoting service calls and the returned results. The default value is
recordset Events associated with the delivery of pageable record set data to the
client. These events occur only if the record set is pageable.The default value is
true.
rtmp Client Connection events that communicate with the remote server using
Real-Time Messaging Protocol (RTMP). Communication with the Flash Communication Server uses RTMP. Flash Remoting does not use RTMP. The default value is
true.
Connection.trace() and
true.
app_server Information about events on the application server. This category
includes activities reported by the server itself and Flash Remoting gateway activities.
For detailed information on server debug events, see “Application server
event messages” on page 93.
You can selectively enable and disable the following subcategories of app_server events. The default value is
trace Server trace events. The default value is
true.
true.
(This event type is not used currently.)
error Server error events. These include any errors generated during the
execution of the Flash Remoting gateway or adapters. The default value is
true.
httpheaders Server HTTP header events. When enabled, the NetConnection
Debugger reports a server HTTP header event for each HTTP request. The default value is
false.
amfheaders Action Message Format (AMF) header events. When enabled, the
NetConnection Debugger reports a server AMF request header event and a server AMF response header event for each AMF request and response. A single AMF request can include multiple service function calls. The default value is
false.
amf Server AMF events. When enabled, the NetConnection Debugger
reports a server AMF method call event and a server AMF method response event for each service function call and response. The default value is
false.
90 Chapter 5: The NetConnection Debugger
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. If ColdFusion debugging information is not enabled in ColdFusion, a single debug error event that notifies the developer that ColdFusion debugging information has not been enabled on the server is returned per transaction. For more information on configuring debugging information in ColdFusion, see the ColdFusion documentation. The default value is
true.
flashcomm_server/ realtime_server
Information about Macromedia Flash Communication Server events. This option is not used for debugging Flash Remoting applications. The default value is
true.
Note: The user interface uses the term flashcomm_server. In ActionScript, you must use realtime_server.
You can selectively enable and disable the following subcategory of events.
trace Flash Communication Server trace events. The default value is
Common event information
The following table describes the information that the NetConnection Debugger displays for all events. Two fields, DebugID and Protocol, are not used for trace events initiated by the
Netdebug.trace() method.
Field Information displayed by the debugger
DebugID The DebugID specified in a
connection being used. If you do not use the Remoting sets this ID to a numeric value.
Not displayed for
NetDebug.trace() events.
EventType A string identifying the type of event being reported.
Connection.setDebugId() method for the
setDebugId() method, Flash
true.
MovieUrl The URL of the Flash application associated with the event.
Protocol The protocol used for communication with the server. The value is
Source The source of the event; always Client.
Time A numeric millisecond timestamp that indicates when the event occurred.
Date The date and time when the event occurred, including information about
http
for all Flash Remoting applications. Not displayed for
NetDebug.trace() events.
the time value’s offset from Universal Time (also known as GMT or UTC).
NetConnection events 91
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 Information fields
Trace Flash executed a
NetDebug.trace() or Connection.trace() method.
Connect The Flash application
requested a connection to the gateway.
AddHeader The Flash Remoting client
added an additional header that is sent with each message to the gateway. This event occurs when you use the
Connection.
setCredentials()
method.
Result Flash Remoting received a
result message from the gateway.
Status Flash Remoting received an
error message from the gateway.
Call Flash Remoting sent a
service function call to the gateway.
Trace The object passed to the
Connection.trace() method. Typically a message.
NetDebug.trace() or
ConnectString The connection string sent to the gateway. The gateway URL.
HeaderName The type of header being sent, such as Credentials.
MustUnderstand A Boolean value that specifies whether the server must understand and process this header before the server can handle any further headers or messages.
HeaderObject The object that will be sent in the added header. For example, the password and user ID.
Result The object sent by the gateway in response to the request.
Status An error object that describes the error. For more information about the error object, see “The error
object” on page 170.
MethodName The service function being called. Parameters The arguments of the service function
call.
Close Flash Remoting closed the
connection to the gateway. Initiated by a
Connection.close() method.
92 Chapter 5: The NetConnection Debugger
None.
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
in the Flash Remoting gateway or adapter. These errors should not occur in normal processing.
HttpRequest
Header
AmfRequest
Header
AmfResponse Header
AmfMethod
Call
The gateway received an HTTP request.
The gateway received an AMF request message. Each HTTP request received by the gateway includes an AMF request.
The gateway returned a response to the Flash Remoting client. This event occurs for each HTTP request.
The gateway received a service function call. A single AMF request can contain multiple AMF method calls.
Data Any object associated with the error event. Normally an Exception object.
Message A message that describes the error.
HTTPHeaders The contents of the HTTP request headers.
AmfHeaders The contents of the AMF headers. The headers include the Credentials header, if the Flash Application uses the method, and the amf_server_debug header, which contains the NetConnection Debugger app_server debugging settings.
AmfHeaders The contents of the AMF headers sent in the response, if any. The gateway returns a header if the client does not support cookies and URL rewriting is being used for session management.
MethodName The service function being called. Response URI The client-side identifier for the
responder. This value is internally generated by Flash Remoting.
Parameters The arguments passed to the service function.
setCredentials()
AmfResponse Call
AmfStatusCall The Flash gateway or
Information Server or AMF status
The Flash gateway sent result data to the client.
application server threw an exception.
information.
MethodName The Response URI identified by the AmfMethodCall message, followed by
Response URI Normally “(undefined)”. Parameters The data returned by the service
function.
MethodName The Response URI identified by the AmfMethodCall message, followed by
Response URI Normally “(undefined)”. Parameters An error object that describes the
error. For more information about the error object, see “The error object” on page 170.
Message A message that provides information about the status.
NetConnection events 93
/onResult.
/onStatus.
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. The NetConnection Debugger can report the following ColdFusion debugging information:
Template type (for CFM pages only, not CFCs)
Execution time
SQL query
cftrace tag output
Exceptions (for exceptions caught in ColdFusion only)
HTTP (for cfhttp tag)
Note: If debugging is enabled but no debugging information is available, the NetConnection Debugger displays an information event that reports that ColdFusion debugging is not enabled on the server. For example, if an error occurs when running a CFML service function, the NetConnection Debugger displays this information event.
For more information on ColdFusion debugging information, see Developing ColdFusion MX Applications with CFML.
Flash Communication Server events
If you enable Flash Communication Server (flashcom_server) debugging events, the NetConnection Debugger displays an event message when the Flash Communication Server application calls a Communication Server logging API Info object for the event.
trace function. The message includes the trace call parameter and the Flash
Using the NetConnection Debugger in ActionScript
Flash Remoting provides several objects and methods that let you control the information that appears in the NetConnection Debugger. These tools include the following:
The NetDebug.initialize() method, to initialize debug support for Flash Remoting.
The NetDebug.trace() method, to display trace messages in the debugger
Connection object methods, to provide debugging information for specific connections
The NetDebugConfig object, to select the information that the debugger displays
94 Chapter 5: The NetConnection Debugger
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 if it initializes debug support successfully. Otherwise, it returns a value of
false. The following
statements, for example, initialize debug support for Flash Remoting before creating a connection to a remote service. The example connects to the CustomerData service used by the CustomerInfoExampleAPI sample application:
import mx.remoting.Service; import mx.services.Log; import mx.remoting.debug.NetDebug; function CustomerDisplayForm() {
NetDebug.initialize(); super(); var custService:Service = new Service(
"http://examples.macromedia.com/flashservices/gateway/",
new Log(Log.DEBUG,"CustomerDisplayApp"),
"petmarket.api.catalogservice",
null,
null);
} CustomerDisplayForm();
true
For more information on the NetDebug.initialize() method, see the NetDebug class in the Flash Remoting ActionScript Dictionary in Help. For information about the CustomerInfoExampleAPI sample application, see “Using the Flash Remoting ActionScript API
in the CustomerInfoExampleAPI application” on page 47.
Using the NetDebug.trace() method
The
NetDebug.trace() method displays a trace message in the NetConnection Debugger. For
example, the following
NetDebug.trace() method displays a trace message with the text “I just
created myService.” in the NetConnection Debugger:
NetDebug.trace("I just created myService.");
The argument to the NetDebug.trace() method is not limited to a string. It can be a Flash object. For example, you can use the
NetDebug.trace() method to report the values of multiple
variables, as in the following code:
NetDebug.trace({arg1value:arg1, arg2value:arg2});
Using connection-specific debugging methods
If your application uses multiple connections, you can use the debugging-related methods of each Connection object to debug the individual connections.
The
setDebugId() method creates an ID that is displayed in the NetConnection Debugger
output for events associated with the specific Connection object; for example:
gatewayConnection.setDebugId("Gateway Connection");
Using the NetConnection Debugger in ActionScript 95
You can send a trace message that includes the connection ID by using the GatewayConnection object’s
gatewayConnection.trace("I just created myService2 over this connection.");
trace() method, as in the following example:
Additionally, the getDebugId() method returns the ID set by the setDebugId() method, and the
getDebugConfig() method returns the NetDebugConfig object for the specific connection.
For more information on using the
getDebugConfig() method, see, “Configuring debugger
output in ActionScript” on page 96.
Configuring debugger output in ActionScript
You can specify the information that the NetConnection Debugger displays by selecting options on the debugger Filters panel, or you can do it programmatically in ActionScript. This section describes how to use ActionScript to display debugger output. For information on using the Filters panel, see Flash Help.
In ActionScript, you configure NetConnection Debugger output for each connection individually. As a result, if your Flash Remoting application has multiple connections, you can configure different levels of debugging detail for each connection.
To configure debugging output:
1.
Use the Connection getDebugConfig() method to get the connection’s NetDebugConfig object.
2.
Set the required property of the NetDebugConfig object. The table in “Specific event
information” on page 89 specifies the properties you can set.
You can combine both steps in a single line, as in the following example, which turns off application server AMF debugging messages:
gatewayConnection.getDebugConfig().app_server.amf = false;
Note: You can only use this technique to select or disable individual event types. You cannot use a single call to select or disable all debugging information for the client, application server, or Flash Communication Server.
96 Chapter 5: The NetConnection Debugger
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. In addition, you can use ColdFusion’s server-side ActionScript functionality, which lets you query databases and perform HTTP operations in ActionScript files on the server.
This chapter has the following sections:
“Using Flash Remoting with ColdFusion pages” on page 97
“Using Flash Remoting with ColdFusion components” on page 105
“Using Flash Remoting with server-side ActionScript” on page 111
“Calling web services from Flash Remoting” on page 115
“Securing access to ColdFusion from Flash Remoting” on page 116
“Handling errors with ColdFusion” on page 117
Using Flash Remoting with ColdFusion pages
When developing ColdFusion pages for use with Flash Remoting, you need to know how to do the following:
Determine the Flash service name for the ColdFusion page
Pass parameters back and forth between the Flash application and the ColdFusion page
Return information to a Flash application from a ColdFusion page
The following sections describe how to perform these actions.
Determining the Flash service name
When you build a ColdFusion page called from Flash applications, the directory name on the server containing the ColdFusion page translates to the service name called in ActionScript from Flash. The ColdFusion page names contained in that directory translate to service functions in ActionScript.
97
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.responder = new RelayRsponder(this, "helloWorld_Result",
"helloWorld_Fault");
//…
To specify subdirectories of the web root directory or a virtual directory, use package dot notation. If helloWorld.cfm is in the directory web_root/helloExamples/ColdFusion, you can use the following ActionScript to create the service:
import mx.remoting.Service; // var CFMService:Service = new Service(
"http://localhost/flashservices/gateway", null, "helloExamples.ColdFusion", null, null);
Remember to use periods to delimit directory names for the new Service() constructor.
Using the Flash scope to pass parameters to ColdFusion pages
ColdFusion MX defines an application scope called Flash that you use to access parameters passed from Flash applications and return values to Flash applications. The application scope associates variables with one, named application on a server.
98 Chapter 6: Using Flash Remoting with ColdFusion MX
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
Flash.Result
Flash.Pagesize
Array containing the parameters passed from the Flash application to the ColdFusion page. If you do not pass any parameters, but it is empty.
Result returned to the Flash application from the ColdFusion page.
Note: Because ActionScript performs automatic type conversion, do not return a Boolean literal to Flash from ColdFusion. Return and return
Number of records in each increment of a record set returned to Flash from a ColdFusion page.
0 to indicate false.
Flash.Params still exists,
1 to indicate true,
See “Using Flash.Params to
access parameters in a ColdFusion page” on page 99.
See “Returning results to
ActionScript” on page 102.
See “Returning record sets to
Flash” on page 103.
When you call a ColdFusion page from a Flash application, the Flash Remoting gateway converts ActionScript data types to ColdFusion data types. The data type of any results returned from ColdFusion to the Flash application are converted to ActionScript data types. For more information on this conversion, see Chapter 4, “Using Flash Remoting Data in ActionScript,” on
page 63.
Using Flash.Params to access parameters in a ColdFusion page
The
Flash.Params array contains one element for each parameter passed from ActionScript, in
the order that the parameters were passed to the ColdFusion page. You use standard ColdFusion array syntax to reference the parameters.
For example, the following ActionScript call passes three parameters:
myService.myMethod(param1, param2, param3);
In your ColdFusion page, you access these parameters using Flash.Params, as follows:
<cfset p1=Flash.Params[1]> <cfset p2=Flash.Params[2]> <cfset p3=Flash.Params[3]>
The following ActionScript code calls a ColdFusion page to execute a query. The ActionScript passes a single parameter to the ColdFusion page:
myService = new Service(
"http://localhost/flashservices/gateway", null, "doc_code", null, null);
var pc:PendingCall = myService.query1param("RipperStik");
Using Flash Remoting with ColdFusion pages 99
In your ColdFusion page, you access the parameter using Flash.Params, as shown in the following example:
<cfquery name="flashQuery" datasource="exampleapps" > SELECT ItemName, ItemDescription, ItemCost FROM tblItems
WHERE ItemName='#Flash.Params[1]#'
</cfquery>
<cfset Flash.Result=flashQuery>
Because ColdFusion converts an ActionScript data type to the corresponding ColdFusion data type, you can perform CFML type-specific operations on the parameter. Therefore, if a parameter passed from a Flash application is an ordered array, you can perform all CFML array operations on the parameter.
For example, suppose you pass an array using the following ActionScript:
var array1 = new Array(); array1[0] = "zero"; array1[1] = "one"; myService.myMethod(array1);
You access the elements in the array in your ColdFusion page using ColdFusion array notation, as follows:
<cfset arrayElement1=Flash.Params[1][1]> <cfset arrayElement2=Flash.Params[1][2]>
Note: Although ActionScript indexes start at 0, ColdFusion array indexes start at 1.
ActionScript also supports named (associative), arrays. These arrays have the following form:
var struct1 = new Array(); struct1["zero"] = "banana"; struct1["one"] = "orange"; myService.myMethod(struct1);
ColdFusion converts associative arrays into ColdFusion structures. To access the associative array elements from
<cfset structElement1=Flash.Params[1].zero> <cfset structElement2=Flash.Params[1].one>
Note: You can use most of the CFML array and structure functions with ActionScript collections. However, one CFML function,
Flash.Params, you use structure notation, as follows:
StructCopy(), does not work with ActionScript collections.
100 Chapter 6: Using Flash Remoting with ColdFusion MX
Loading...