home > tutorials > flash




Returning the "Tip of the Day" Using Flash and Web Services

by Jen and Peter deHaan

For this example you are going to syndicate Ben Forta's CF Tips in Flash MX without writing any CFML. Data will be pulled from the web service, and displayed in a Flash movie.
Begin by creating a new file in Flash MX.
  1. Open a new Flash Remoting template by selecting File > New From Template... and then select Web from the Category list and Basic from the Category Items list. Before going any farther, open the Actions panel and scroll down through the generated ActionScript code. Change the connection settings for setDefaultGatewayUrl() to match your configuration. You will most likely change the port to 8500 if you are using the internal web server. Remove the port altogether if you are using IIS/Apache or have remapped the ColdFusion to respond to port 80.
  2. Set up the Stage by creating a new layer and selecting Insert > Layer, and rename it to Form. You need to create four dynamic text fields on this layer and two buttons which will be used to navigate to the next and previous days' tip. The finished project will look roughly like graphic below.


  3. Add a Dynamic, Single Line text field and give it an instance name of title_txt in the Property Inspector. It will hold the title and URL for the daily tips. Therefore, you need to select the Render text as HTML button in the Property Inspector (as seen in the following graphic) so you can display this as a link. You might want to format the field with a large, bold text size. This title seems to always return "Ben Forta's ColdFusion Tip-of-the-Day".


  4. Create another Dynamic text Single Line field and give the field an instance name of header_txt. It will be used to hold the name of the current tip. In the graphic below, you can see that some formatting has been added to this field by turning on italics and changing the text color. The font size is larger, as seen in the graphic at the end of this tutorial.
  5. The next dynamic text field will hold the date of the tip, and the product that the tip applies to (ColdFusion MX or Dreamweaver MX, and so on). Name this instance product_txt and set it at a smaller font size than the first two instances.
  6. Finally you need to create a large dynamic text field with the instance name body_txt that will contain the actual tip text. In the Property Inspector, set the Line type to Multiline so your text will wrap when necessary.
  7. Next you need to add two pre-made buttons to the Stage. As you probably know, Flash comes with a library of pre-made buttons, sounds, and actions. Select Window>Common Libraries>Buttons to access this Library.
  8. Double click on the folder icon to the left of Circle Buttons to open the folder. Drag an instance of the circle button - previous and circle button - next buttons onto the Stage. Then give them instance names of prev_btn and next_btn respectively. Refer to the first graphic above to see how the Stage is set up.
  9. Once you are satisfied with the layout of the Stage, select frame 1 of the Actions layer and type/paste the code below into the Actions panel:

    #include "NetServices.as"
    // uncomment this line when you want to use the NetConnect
    // debugger
    //#include "NetDebug.as"
    // --------------------------------------------
    // Handlers for user interaction events
    // --------------------------------------------
    prev_btn.onRelease = function() {
    global.Age++;
    refreshTip();
    };
    next_btn.onRelease = function() {
    _global.Age--;
    refreshTip();
    };
    // -------------------------------------------
    // Handlers for data coming in from server
    // -------------------------------------------
    /* this function is triggered after the Browse function is completed. It is responsible for displaying the information to the screen and enabling/disabling the previous/next buttons. */
    function Browse_Result(result) {
    var date_array = result.date.toString().split(" ");
    header_txt.text = result.header;
    product_txt.text = result.product+" "+result.product_version;
    product_txt.text +=
       " -- "+date_array[0]+" "+date_array[1]+" "+date_array[2]+
       " "+date_array[5];
    body_txt.text = result.body;
    title_txt.htmlText = "<a href='"+result.url+"'><u>"
       +result.title+"</u></a>";
    next_btn.enabled = (result.next == "true") ? true : false;
    prev_btn.enabled = (result.prev == "true") ? true : false;
    }
    // --------------------------------------------
    // Application initialization
    // --------------------------------------------
    if (inited == null) {
    inited = true;

    NetServices.setDefaultGatewayUrl(
       "http://localhost:8500/flashservices/gateway");
    gateway_conn = NetServices.createGatewayConnection();
    cfTips = gateway_conn.getService(
       "http://www.forta.com/cf/tips/syndicate.cfc?wsdl", this);
    global.Age = 0;
    refreshTip();
    }
    stop();
    /* this is the function that gets the tip for the current day and calls the "browse" function, which is responsible for displaying the content to the user. */
    function refreshTip() {
    cfTips.Browse({Age:_global.Age});
    }

  10. Let's go through each section of ActionScript and try and get a better understanding of what is happening. The first few lines of ActionScript are simply the #include statements you have seen in each of the previous examples.

    In the next section there are two functions handling what happens when a user clicks on the previous and next buttons.

    prev_btn.onRelease = function() {
    _global.Age++;
    refreshTip();
    };

    When a user clicks on the previous button, the value of the global variable Age is incremented. Then a function is called that will refresh the tip in the Flash movie. The Age of a tip is just a relative tip age displaying how many days old the tip is. So, if the tip has an Age of 0, then it is today's tip. If the Age is 7, then the tip is one week old.

    The code for the next button is similar except it decrements the global Age variable and calls a function to refresh the displayed tip. The next section of code handles data when it is received from the server.

    function Browse_Result(result) {
    var date_array = result.date.toString().split(" ");
    header_txt.text = result.header;
    product_txt.text = result.product+" "+result.product_version;
    product_txt.text += " -- "+date_array[0]+" "+
    date_array[1]+" "+date_array[2]+", "+date_array[5];
    body_txt.text = result.body;
    title_txt.htmlText = "<a href='"+result.url+"'><u>"
       +result.title+"</u></a>";
    next_btn.enabled =
    (result.next == "true") ? true : false;
    prev_btn.enabled = (result.prev == "true") ? true : false;
    }

    The first thing happening here is the Date object is turned into an Array object. This enables you to target specific tokens in the Date object. The result.date is returned from Flash Remoting, converted into a string, and then split into an array using a space as the delimiter. This is similar to using #ListToArray(result.date, " ")# in ColdFusion.

    Then the data returned to the function is taken and used to populate the text fields on the Stage. result.product (which is typically ColdFusion) is concatenated with result.product_version (which will be something like 5 or MX) and is displayed in the product_txt text field. The next line of code appends the date onto the product_txt text field using the date array created at the beginning of the function. The date is returned to Flash in the following format: Fri Oct 25 00:00:00 GMT-0400 2002. Remember that in ActionScript, arrays begin at index 0 and outputting date_array[0] will grab the first item from the array. This would be Fri in the above listing. The product_txt value will display text similar to ColdFusion MX -- Fri Oct 25, 2002.

    You have something different when you display the title_txt. Instead of setting the .text property, HTML formatting is enabled for the text field so Flash's limited HTML tag support can be used to create a hyperlink. (for more information on Flash HTML support, check out this URL: http://www.macromedia.com/support/flash/ts/documents/htmltext.htm

    If you are enabling the Render text as HTML button for a text field, then you have to have to set the .htmlText property instead of the .text property if you are using HTML tags.
    The final two lines of ActionScript are a little confusing at first glance. Buttons have a property called .enabled that is used to specify whether or not the button is active. If the property is set to false, then users will not be able to click on the button and the Click Handler or function for that button will not be executed. The result returned from the web service contains either a prev or next flag, which is responsible for telling the developer if there is a previous or next tip available or not.

    The value of prev and next will be returned to the Flash application as either true or false, which brings up an interesting problem. Flash interprets these values as strings instead of Booleans. To work around this, string comparison must be performed to check whether or not the value equals the string literal true. If so, the value is set to Boolean true, otherwise the value is set to Boolean false. Using this method, you can make sure ActionScript uses the values as a Boolean true or false instead of as a string. It is usually a better idea to return integers from ColdFusion instead of Boolean values when dealing with web services. Flash is able to correctly convert 0 and 1 to true and false, but it is unable to convert a string true to a Boolean.

    You also may not be familiar with the shortcut for evaluating if/else statements as seen in the following code:

    prev_btn.enabled = (result.prev == "true") ? true : false;

    First a string comparison is executed to see if result.prev equals the string true. If it does, then the Boolean true is returned and set to the rev_btn.enabled statement (the button is enabled). If the condition evaluates to false, then a Boolean false is returned and the button is disabled. The syntax for this shorthand conditional if statement is:

    (expression) ? true condition : false condition;

    and it is shorthand for the following:

    if (expression) {
    true condition;
    } else {
    false condition;
    }


    The rest of the ActionScript is fairly straightforward. You'll notice a couple differences from other examples you might read about Flash Remoting. The important is the call to:

    getService();
    cfTips = gateway_conn.getService(
    "http://www.forta.com/cf/tips/syndicate.cfc?wsdl", this);


    You can see here that instead of calling a CFC or CFM in relationship to the webroot, an absolute URL is being passed to the web service. Next, a default global variable for the Age of the tip is set up. You'll remember from the earlier explanation that the Age is a number relative to the current day, so you are setting the default tip to the current day's tip.

    Finally, the refreshTip() function is called to get the current tip from the remote web service.

    _global.Age = 0;
    refreshTip();


    The final piece of code to explain is the refreshTip() function. This is a very simple function, which is only used to call a Remote function in the web service and pass the Age of the tip that we want. Once Flash Remoting receives data from the server, the previously defined Browse_Result() function is triggered and handles displaying the new tip.

    function refreshTip() {
    cfTips.Browse({Age:_global.Age});
    }


    Another new thing not seen in the examples yet is how a variable is passed to the remote web service. Flash has a shortcut for creating objects, similar to how there is a shortcut for writing conditional if statements (as explained above). Instead of having to write:

    var params = new Object();
    params.age = _global.Age;
    cfTips.Browse(params);


    you are able to type {Age:_global.Age}. The curly brackets {} tell ActionScript that an Object is being created. The Age: tells ActionScript that Age is the Key, and _global.Age will be evaluated and passed to the remote function. If you needed to pass multiple parameters to a function using this method, you just separate each key/value with a comma, such as:

    myService.myFunction({ID:132,size:32,var3:'on sale'});

    There is also a shortcut for creating arrays in ActionScript. Instead of using curly brackets {}, like the example above you use square brackets [] and pass a comma separated list of values, as seen here:

    var pets_array = ['cat', 'dog', 'fish', 'badger'];
    which is shorthand for:
    var pets _array = new Array();
    pets _array[0] = 'cat';
    pets _array[1] = 'dog';
    pets _array[2] = 'fish';
    pets _array[3] = 'badger';


  11. The final step is to test the application. Test the movie by pressing Ctrl+Enter. Use the forward and backward navigation buttons to move through the tips. Refer to the picture below for the final result.


Download the source file here.

 
 
home | news | tutorials | reviews | resources | forum | about
 

search web search flash-mx.com


www.flashthefuture.com   www.flash-mx.com   swift dev   www.ejepo.com


©2003 ejepo.com | advertise | legal info | site design
 
Hosting provided by DataRide, Inc.