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;
gw = NetServices.createGatewayConnection();
// create a reference to our Web Service cfc
newsService = gw.getService("ws", this);
// call the getCategories method of the WS
// grab the initial news headlines
// 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

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
// 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!

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
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.
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.
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...
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...
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...
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.
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...
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 IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
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...
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...