Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion, Adobe Flex

ColdFusion: Article

Flash Remoting: An Alternative Approach

Bucking the conventional wisdom with CFM files

Although an "undeniably excellent" product, Flash Remoting presents a few problems. This article offers solutions in the areas of authentication and error-handling.

Most people who have experienced Flash Remoting seem to be impressed with it. I, for one, couldn't help but be impressed by the demonstration Macromedia gave at one of their seminars. (See reservations.broadmoor.com for an excellent example.)

Building on the component structure provided by ColdFusion MX, Flash Remoting promises the world: a platform-independent rich client that interacts seamlessly with the server. Using Flash Remoting developers can produce dynamic clients that encompass more functionality per page than was previously possible. Since the Flash client remains loaded on the client's machine, and all that is sent back and forth is the data, less bandwidth is required, and the load on the servers is lessened.

Sounds perfect! But every silver lining has its associated cloud, and the same is true of Flash Remoting. Whereas it is undeniably excellent, Flash Remoting does present its own problems. The thing is, can we get around these problems in a way that makes Flash Remoting still worth using?

How do we use this wonderful product? Well, conventional wisdom says that we use components (CFCs) on the server to collect together related functions, and call those functions directly from the Flash client. What's wrong with that? you ask. Well, there are two main reasons why I did not take this approach.

  1. I wanted a central authentication system that just worked without my having to add code to every function to call the authenticator.
  2. I wanted to handle errors such as message timeout, authentication errors, wrong parameters, or just about anything else in a sensible manner so that I could pass back useful error results to the client.
So why couldn't I achieve these results with CFCs? Originally I thought I could, and maybe sometime in the future (when suitable modifications have been made to ColdFusion) I will be able to, but right now I can't.

If I use an Application.cfm file, then I should be able to add my authentication there and halt the call to the CFC function if it is not authenticated. Macromedia provides a really useful function, getHTTPRequestData(), which should show the contents of the message sent to the server from the client. The problem is, it doesn't work. It supplies some information. However, some of the data that I need to access (which function was called, what parameter values were provided) is simply not available.

Without knowing which function was called, I cannot decide whether or not authentication is required. (I did not require it for every function, as some parts of the site are accessible without logging in.) Even if I did authenticate for every function, I cannot access the parameter values, so I can't access the username/password. It's possible that I could obtain the values that I need by directly accessing structures within the Java factory, but I am reluctant to use such undocumented features on critical projects, as they may not be there in future versions.

Therefore, I'm stuck with putting the authentication inside each and every CFC <function> tag. The thing I really hate about this is that if another developer comes along in the future and adds a function but forgets to add the authentication code, then we have a security problem. To my mind, this is simply unacceptable.

The other thing I wanted was to be able to trap errors and return sensible error messages to the client. <cferror> in Application.cfm would seem to do the trick; but, alas, no. When calling a CFC function, a <cferror> is ignored.

What about <cftry>/<cfcatch>? The problem is that we can only put these inside the <cffunction> tags, which means they won't trap errors such as missing or mistyped parameters. Also, as with putting the authentication inside each function, we have the problem that if a future developer forgets to add this code, then we lose our error trapping.

The Silver Lining
Okay, enough of the cloud! Where's that silver lining I mentioned earlier? Well, it comes in the form of CFM files. If you delve into the ColdFusion documentation you will find that not only can you call functions within CFCs via Flash Remoting, but you can also call code in a CFM file as if it were a function.

But who would want to put each of their functions into separate CFM files? Not me, for a start! When I said that the answer "comes in the form of CFM files" I actually meant "file," not "files." What I did was to create a "gateway" CFM file that accepts calls from Flash. This CFM file contains all the functionality needed to decide whether or not to authenticate, call the authenticator if required, invoke the required function (in a separate CFC file), and trap any errors by wrapping the whole thing in a <cftry> tag.

The main part of the server gateway code (see Listing 1) looks like this (the code for this article can be downloaded from www.sys-con.com/coldfusion/sourcec.cfm):


<cfif authenticated>
	<cfinvoke component="#flash.params[1].module#"
	method="#flash.params[1].method#"
		returnvariable="flash.result"
		argumentcollection="#flash.params[1].params#"/>
<cfelse>
	<cfscript>
		flash.result = structNew();
		flash.result.status  = false;
		flash.result.result  = "Not authenticated";
	</cfscript>
</cfif>

This is wrapped in a <cftry> tag to catch any errors, such as an invalid module or method name, or missing required parameters.

We also pass back the module and method name so that our Flash client knows which message is being replied to.

<cfset flash.result.component = flash.params[1].component>
<cfset flash.result.function = flash.params[1].function>

First we call our authenticate function to do the usual username/password check and return a true/false value.

If we pass the authentication test, then we try to invoke the function in the component requested by the Flash client. If that function does not exist, or we pass it the wrong parameters, or if something goes wrong that is not trapped within that function, then the error is caught here courtesy of our <cftry>/<cfcatch> tags. If we did not trap it, then a <function>_Status message containing information about the exception will be returned to the Flash client. By trapping the error, we can instead send more relevant information back to the client.

There are many more things we can do in our CFM file to make our lives easier, and I'll cover some of them later, but first let's consider the Flash client.

The Flash Client
In order to communicate with the server from Flash, we need to define a connection to the gateway. For this example, my serverRequest.cfm is located in a directory called "client" within the Web root directory, and I'm using the Web server provided with ColdFusion. I'm sure you've all seen code like this:

#include "NetServices.as"

NetServices.setDefaultGatewayUrl("http://localhost:8500/flashservices/gateway")
gatewayConnection = NetServices.createGatewayConnection()
remotingService = gatewayConnnection.getService("client", this)

We need a function to prepare our remoting call. This will add the username and password to the parameters prepared for the function call.

function serverRequest(params)
{
    params.username = _global.username
    params.password = _global.password
    remotingService.serverRequest(params)
}

We need to be able to handle the results, which will be returned to our Flash function, serverRequest_Result(). This function will check the status of the result, calling a specific handler function if the call is successful, and producing some tracing if it is not.

function serverRequest_Result(result)

{
   switch (result.status)
   {
    case -1:
trace("E R R O R : Authentication error - need to login (again)");
   break;
   case "0":
trace("E R R O R : " + result.result);
   break;

   case "1":
trace("R E M O T I N G : Flash remoting call returned a success
message");
targetFunction = result.component + "_" + result.function + "_Result";
this[targetFunction](result.result);
}
}

The following code shows a typical invocation. We are calling a function, "getPageTemplate", from a component called "coursePlayer". We are passing two parameters to this function. Note: Because we are using argumentcollection="#flash.params[1].params#" in serverRequest.cfm, we must pass the params parameter, even if it's an empty structure.

flash = new Array();
flash.component = "coursePlayer";
flash.function = "getPageTemplate";

flash.params = new Array();
flash.params.param1 = "Hello";
flash.params.param2 = "World";
serverRequest(flash);

The following code shows our function, which is called if we have a successful reply.

function coursePlayer_getPageTemplate_Result(result)
{
   trace("coursePlayer_getPageTemplate_Result called")
}

We now have a ColdFusion CFM file that acts as a gateway to our main functions (located in various CFC files) and that centrally controls whether or not authentication is required, and if so, handles that authentication. The CFM file also manages error trapping and returns useful errors to our Flash client.

The Ramifications of #include "NetServices.as"
Now let's think a little more about our Flash client. We've all used this line of code (see Listing 2):

#include "NetServices.as"

But how many of us have stopped to think about what it does - besides the obvious of handling the remoting communication? Since the remoting is pretty much taken care of, perhaps the most important thing for us to consider is that it adds 4.5KB to our SWF file.

Who cares, you ask? Well, if you create your Flash client as a single huge movie clip, then not you. On the other hand, if, like me, you prefer to split your client into smaller parts, then read on.

Hey, 4.5KB is not that much....Well, let's put in some code to add some authentication to the message. This brings the communication code up to 6.5KB.

So what's the problem? Well, if you just add "#include NetServices.as" to each of those movie clips, then you add 6.5KB to each one. If your client consists of 50 movie clips, then you've added over 300KB. This is rather a lot, so what can we do about it?

The obvious thing is to add this code only to our root movie, using calls like:

_root.remotingService.myFunction()

That'll do it. Problem solved. End of article. Bye, see you next time. Hang on, maybe there's more than meets the eye here? Rather than doing that sort of call, I created a function in my root movie to handle it for me.

function serverRequest(params)
{
   params.username = _global.username
   params.password = _global.password
   remotingService.serverRequest(params)
}

Now I don't need to worry about adding the authentication information to my functions; it's done for me. So if we go this route, won't all the remoting call results be sent back to the root movie? Yep. So how does the root movie get the results back to the movie that originally made the call? We use:

Flash.path = targetPath(this)

This function returns a string that represents the calling movie clip's position in the hierarchy. Say we have a movie called "outer.swf". Into this we load a movie clip called "middle.swf", and into that we load "inner.swf". Inner.swf wants to make a remoting call, so it makes a call to targetPath(this), and gets back "middle.inner". The movie clip that wants to send the remoting call calls this first, and passes the result as a parameter (path), which gets sent on to ColdFusion, which passes it back in the return message. When the remoting result is received in the root Flash movie, it invokes a function:

function serverRequest_Result(result)

Using this path parameter, the result function can route the results back to the movie clip that made the call.

targetMovieClip = this
targetPath = result.path.split(".")

// Loop through our list of movie clips, building targetMovieClip up into a
reference to the target move clip

for (i=0;i<targetPath.length;i++)
   targetMovieClip = targetMovieClip[targetPath[i]]

targetFunction = result.component + "_" + result.function + "_Result"
targetMovieClip[targetFunction](result)

This calls a function <component>_<function>_Result in the target movie clip. Component and Function are also returned from ColdFusion to enable this routing. We simply add the following line of code to serverRequest.cfm:

<cfset flash.result.path = flash.params[1].path>

What other useful features can we add to our remoting interface? A fairly common problem is clients losing connection to the server. Either the server fails, or more often, the client loses the Internet connection. We could let each part of our client deal with it, or better still, we can add a central timeout handler.

What we need to do is make note of the function calls that are sent to the server and check them off as they are responded to. If we don't get a response, then we can deal with it. In this example, we are going to pop up an information panel to tell the user that the server is not responding and ask if he or she wishes to retry or not. If the user chooses to retry, then all the messages that were not responded to will be re-sent. After we have done this, if we do eventually receive a response from the server to the original messages, we'll just discard them. Of course you can adapt and change this handling. Maybe you'd prefer to accept the original response and trash the response to the duplicate message.

First we need to make a copy of the message that we are sending. To do this, I've added the following function to RemotingSetup.as:

function RemotingMessage(params,messageID,secure)
{
    this.component = params.component
    this.function = params.function
    this.path = params.path
    this.params = params.params
    this.timerID = setInterval(messageTimeout,timeoutPeriod,messageID)
    }

and the following declarations:

// Used to record messages sent to the server
var messageID = 1
var sentMessages = new Array()

// Used to hold messages that have failed authentication, or have timedout,
// and are awaiting resubmission.

var queuedMessages = new Array()

We now have a counter to provide a unique ID for each message, an array to hold a list of messages that we have sent, and a second structure to hold a list of messages waiting to be re-sent. I need to add two lines of code to the serverRequest function in order to pass the message ID through to the CF server, and to save this message in the sent messages array:

params.messageID = thisMessageID

_root["sentMessages.message_" + thisMessageID] = new
RemotingMessage(params,thisMessageID,secure)

Three more functions are required in RemotingSetup.as:

messageTimeout(messageID)
clearMessageQueue()
resendQueuedMessages()

The messageTimeout() function is invoked when the setInterval timer expires. It removes the message from the sentMessages array and adds it to the queuedMessages array. Then it opens a pop-up requester to alert the user. If the user elects to retry, then resendQueuedMessages() re-sends all the messages in the queue, and clearMessageQueue() is used to abort, resulting in failure messages being returned to the originator of each of the messages in the queue. That way no function is ever left hanging, waiting for a response.

The last thing we need to do is add a few lines of code to the serverRequest_Result function:

messageData = _root["sentMessages.message_" + result.messageID]
delete _root["sentMessages.message_" + messageID]
clearInterval(messageData.timerID)

This clears the timer and removes the message from the sentMessages array. If the message has already timed out, then messageData will be undefined and we just discard the message. If it is not, then we deal with the message as normal.

As we are now keeping a copy of the message in the Flash client, there is no need to pass information such as the path to the CF server since we can retrieve it from our new data stored in the sentMessages array.

We now have a central handler for Flash Remoting messages that will gracefully handle a loss of communication to the server, giving the user the option of resending any messages for which a response was not received. When responses are received, they are routed to whichever part of the Flash client initiated the communication.

What the Client Doesn't Know...
Before we finish, let's put our new message queue to one more use. As I mentioned earlier, some functions in my project require the user to be logged in, others do not. Obviously, the server knows which are which, so why worry about programming your client to know? Why not just let the client request a restricted function without having already forced the user to log in?

If the client requests a restricted function, the function call will fail, and the client will receive an authentication failure response. Rather than pass this failure back to the calling function, we can simply pop up a login box for the user, and ask him or her to log in. We can then automatically resend our failed request, but this time, with a (hopefully) valid username/password. We should then receive a successful response, which we can pass back to the calling function. It receives the information it requires without having been aware of the authentication failure or the re-sent message. See Listings 3 and 4 for the full code.

More Stories By Ian Bale

Ian Bale is co-director of Celtic Internet ltd. (www.celticinternet.com), a UK-based software engineering and consultancy company. Ian has worked as a consultant since 1989 in both the telecom and Internet industries.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...