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

ColdFusion: Article

Web Services in a Flash

Web Services in a Flash

Of course the latest buzzword in the world of Internet applications is Web services. So we're assuming that you already know what a Web service (WS) is and we're not going to worry about creating one. This article will focus on accessing a Web service using Flash Remoting, and displaying the information in a rich Flash UI.

We'll be looking into the emfusion.com Web service which supplies the latest news and information to many organizations. The emfusion engine gathers up-to-the-minute content and makes it accessible to developers and Web administrators through a WS. Although there are many methods available through the emfusion WS, we'll be focusing on two basic ones that allow us to access the necessary data for display in the Flash movie.

The emfusion WS we'll be accessing is a scaled-down version for developers to access and test with the application that will be discussed in this article. The Web Services Description Language (WSDL) file is located at www.emfusion.com/ws.cfc?wsdl. Feel free to access this file through the browser to see the basic structure of the file and the methods we'll be accessing. Let's get started!

Overview of the Application
This article assumes that you have the Flash Remoting components installed. If you don't, then you can download them for free from Macromedia's Web site: www.macromedia.com/software/flashremoting/ downloads/components. This will install the necessary documentation, ActionScript files, and even the NetConnection debugger, which can be useful for troubleshooting your Flash applications. We won't cover the NetConnection debugger but if you're interested in learning more about it, then feel free to check out my article, "Get Connected with Flash Debugging" in the October issue (CFDJ, Vol. 4, issue 10).

The Flash UI will be responsible for displaying data supplied from the WS. We're going to display a list of news categories and titles supplied by the WS. The initial Flash Remoting call will be made to the getCategories method. This will return a recordset of category IDs and category names, which will be used to dynamically display a list of PushButton components across the top of the Flash movie.

For the purpose of this article the news categories will be limited to U.S., Sports, and Religion. Depending on which category button is pressed, the corresponding category ID will be passed to the getNews method of the WS. The response will again be sent as a recordset and parsed inside of Flash. The news recordset will contain lots of data such as title, date, author, source, and URL fields. For our application we will be accessing only the title, date, and URL of each article. The values will be used to duplicate a movie clip for each record and then display it within the Flash ScrollPane component.

Now that we have a basic understanding of how the application will work, let's take a look at the communication process. Everything will start from the Flash movie where the user will interact and perform actions which, in turn, will make the necessary method calls to the WS. Figure 1 illustrates the communication process between Flash and the WS.

Before we actually dig into the code, let's take a quick look at the completed product to get a better idea of how it functions. If you have access to a Web browser check out the following URL: www.emfusion.com/cfdj/emfusion_ws.html. You will also be able to download all the source code from this page. When the URL is first accessed, the Flash movie makes two Remoting calls: one to the getCategories method and one to the getNews method of the WS. This is what initializes our application and sets it to its default state. We initially pass an ID of 1 to the getNews method and grab the U.S. news. This will happen each time the application is accessed or the browser is refreshed. Figure 2 is a screen shot of the finished application.

Digging into the Code
Due to space constraints we're not going to cover all of the Flash ActionScript code line by line. For more code detail feel free to download the source files at www.emfusion.com/cfdj/emfusion_ws.zip.

When the application is initialized the init code runs:

If(inited==null) {
inited = true;
NetServices.setDefaultGatewayURL
("http://www.emfusion.com/flashservices/gateway");
gw = NetServices.createGatewayConnection();
// create a reference to our Web Service cfc
newsService = gw.getService("ws", this);
// call the getCategories method of the WS
newsService.getCategories();
// grab the initial news headlines
newsService.getNews(1);
// more code down here
}

This happens only once per each instance of the application. If the browser is refreshed or the user leaves and comes back to the page, the init code will run again. This code segment handles establishing the connection with the Flash Gateway creating an object reference to the emfusion WS. This object reference is known as a service object and will then be used to make method calls to the WS.

The first parameter passed to this method is the name of the service, which is "ws". The second parameter of the getService method is the default responder. This is an object that will handle the response sent back from the WS. The value "this" used for the second parameter tells Flash Remoting that objects in _level0 or _root of the movie will handle responses sent from the WS.

In the code listing above, you can see that once a connection with the gateway is established, the getCategories and getNews methods of the WS are called. In Flash Remoting, each time a method of the WS is called, a default responder must exist to handle the response from the service. By default, Macromedia recommends using the format of methodName_Result. So the default responders for the getCategories and getNews methods would be getCategories_Result and getNews_Result respectively.

When the getCategories method is called, there are no parameters required by the Web service. So a basic call can be made to the method and then a list of category IDs and names will be sent to the caller, in our case Flash. The category information is passed to Flash as a RecordSet object. Therefore, we should be able to access the field names and values of each record using the Flash Remoting RecordSet methods. A truncated version of the getCategories responder is listed below:

function getCategories_Result(result) {
// get the number of categories
var len = result.getLength();
// initial x position where we'll place the first cat clip
var currx = 5;
// loop and place the clips next to each other
for(var i=0; i<len; i++) {
var cat_id = result.getItemAt(i).cat_id;
var cat_name = result.getItemAt(i).cat_name;
var clip_width = parseInt(cat_name.length) * 10;
var clip = "cat_" + cat_id;
// duplicate the master button to create the cat buttons
duplicateMovieClip("cat_btn", clip, i);
}
// more code down here
}

The RecordSet result is passed into the responder and the information is accessed and handled accordingly. We can access the number of records returned from the query and then duplicate the PushButton component as many times as necessary. The cat_id and cat_name fields are also accessed and used to populate the PushButtons. For demonstration purposes this query will return only three records, so we will have three buttons that display the values U.S., Sports, and Religion.

Immediately after the getCategories method is called, we make a call to getNews. Multiple requests/responses can happen at the same time, which makes Flash Remoting extremely powerful. By default, we pass a category ID of 1 as a parameter in the getNews method. This tells the WS to give us all news content that corresponds with U.S. news. A different responder exists to handle the news RecordSet object passed from the WS to Flash:

function getNews_Result(result) {
// more code up here
// get the number of news records
var len = result.getLength();
// loop through the news records and grab
// the title, link, and date of each article
for(var i=0; i<len; i++) {
var title = result.getItemAt(i).news_title;
var link = result.getItemAt(i).news_link;
// create a date object so we can access the necessary values
var news_date = new Date(result.getItemAt(i).publish_dt);
var display_date = news_date.getMonth() + 1 +"/"
+ news_date.getDate();
// call the method to duplicate the title clips and populate the data
setTitleText(title, link, display_date, i);
}
// refresh the scroll pane with the new contents
news_sp.refreshPane();
}

The news RecordSet contains certain fields such as title, link, and date. These fields are accessed from the RecordSet and then used to duplicate a movie clip for each record. The movie clips are then tiled vertically within the ScrollPane component. The actual duplication, text setting, and placement of clips is done within the setTitleText method which is called in each iteration of the RecordSet loop. Once the loop has completed, the refreshPane method of the ScrollPane is called to update the component.

Now we have an almost completely functioning application. The category buttons are displaying as well as the initial news titles. You can now click on a news title and you'll be directed to the corresponding article. The last thing that needs to be implemented is the user's interaction with the category buttons. By default, the first category button is disabled. We don't want the user to select the same category that he or she is already viewing. But if a user clicks another button, for example "Religion", then we should tell Flash to call the getNews method and send the corresponding cat_id to the WS.

Every PushButton component has a special Click Handler parameter that tells Flash what to do when the button is clicked. In our application we set the Click Handler during author time even though it can be specified at run time (via ActionScript code). Since we'll be using the same Click Handler for all category buttons, it makes sense to specify this within the authoring environment. The Click Handler we'll be accessing is called handleCategory. If you're viewing the emfusion_ws.fla Flash file you'll see a PushButton component sitting directly above the stage. The properties panel will allow a Click Handler to be specified for this component (see Figure 3).

The handleCategory code is:

function handleCategory(component) {
var start = component._name.indexOf("_");
var end = component._name.length;
var cat_id = component._name.substring(start+1, end);
// call the news service and pass it the selected category id
newsService.getNews(cat_id);
// more code down here
}

A nifty parameter that can be passed into the Click Handler method is a reference to the movie clip object that calls the method. This makes it simple to handle the actions of many buttons from a single method. We grab the cat_id from the button's name and then pass it to the getNews method. This allows us to grab the news for the selected category. Once again the getNews_Result responder will handle the news RecordSet and display the necessary news titles. That's it! You now have a fully functioning Flash UI that interfaces with the emfusion WS!

Conclusion
All in all, creating Flash applications that access Web services is very straightforward. Flash Remoting and the Flash components (PushButton, ScrollPane) have simplified a lot of the tasks mentioned in this article. To develop these components alone would take much longer than creating this entire application 10 times over! You're probably thinking that's an exaggeration, but I can't tell you how thorough the components are and how much time they saved me in the past.

We concentrated on two main methods of the emfusion WS in this article. Consider exploring more of the functionality built into the WS. For example, it might be a good idea to let the user pass a sort field to the WS and have the results sorted in alphabetical order or by date. You could even access the searchArticles method of the WS and let the user search for specific content, all from within the Flash UI. As you can see, there are vast amounts of possibilities and using Flash Remoting with Web services is a great way to access distributed data. Until next time, enjoy!

More Stories By Dennis Baldwin

Dennis Baldwin is a software developer for SensorLogic Inc, an M2M application service provider. He also runs and maintains an online community for Flash and ColdFusion developers at www.devmx.com.

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
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.
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
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 ...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
"Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, 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.
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
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...
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...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
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...
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 ...
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 ...