Dennis Baldwin

Subscribe to Dennis Baldwin: eMailAlertsEmail Alerts
Get Dennis Baldwin: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


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.