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.

@ThingsExpo Stories
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
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...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...