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#"
		flash.result = structNew();
		flash.result.status  = false;
		flash.result.result  = "Not authenticated";

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"

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

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)");
   case "0":
trace("E R R O R : " + result.result);

   case "1":
trace("R E M O T I N G : Flash remoting call returned a success
targetFunction = result.component + "_" + result.function + "_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";

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:


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

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"

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

Three more functions are required in RemotingSetup.as:


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]

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.

IoT & Smart Cities Stories
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...