September 5, 2006

Flash Remoting - Setting the alternate gateway URL through FlashVars

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 1:23 pm

When we are working with Flash Remoting we will need to set a URL for our Flash Movie to communicate through to the server. This URL is often specified as an absolute URL in the flash movie - eg, http://www.mysite.com/flashremoting/.

If we are to stage the site on a different domain and still want to access the Flash Remoting, we will need to set up a “crossdomain.xml” file that allows the staging domain to access the Flash Remoting Service - (See ‘Loading external data from Flash‘). This is achieved by creating a XML file named “crossdomain.xml” on the production domain and defining a set of properties specifying which other domains are allowed access its data (Remoting, XML etc).
This all works nicely when we are working with a contained Flash Movie, allowing us to maintain the state on a remote domain. What happens when we wish to access that state information on a different domain? When switching from Flash to another language (say PHP) you will lose your session information. When we are to “break” out from the Flash into an HTML process (- lets say a HTML checkout process) accessing the ‘State’ of the session will not be available as the cookie is set for the Remoting Domain, not the one serving our local HTML. (See ‘sharing a session across multiple domains‘).

If our staging server is a direct copy of the production server (or slightly modified) we would want to be able to specify a different Gateway URL for the flash player to load. Instead of authoring a different Flash Movie for each server (staging or production) we need to be able to change the absolute URL external. One of the ways we could do this is by parsing it in through the HTML.
FlashVars allow us to communicate between the HTML and the Flash Player. When we use the FlashVars parameter in the embed HTML code we can place variables on the root of the movie. This Adobe Flash TechNote article defines the basic use of the FlashVars capability.

We can specify a default Gateway URL to be the production server in our ActionScript like so:

NetServices.setDefaultGateway(”http://www.myproductionserver.com/flashservices/gateway”);

Using the Flash Vars we can overwrite the gateway URL through the HTML, allowing us to seperate out the Gateway URL for Flash Remoting into the HTML, so we can make a quick change without having to republish/export a new SWF file.

An example of an embed showing this in action is as below:

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
 codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/
 swflash.cab#version=6,0,0,0" WIDTH="550" HEIGHT="400"
 id="mymovie" ALIGN="">
 <PARAM NAME=movie VALUE="mymovie.swf">
 <PARAM NAME=FlashVars
  VALUE="gatewayURL=http://www.flash-remoting.com/flashservices/gateway">
 <PARAM NAME=quality VALUE=high>
 <PARAM NAME=bgcolor VALUE=#FFFFFF>
 <EMBED src="mymovie.swf" quality=high bgcolor=#FFFFFF  WIDTH="550"
  HEIGHT="400" NAME="Untitled-2" ALIGN=""
  TYPE="application/x-shockwave-flash"
  FlashVars="gatewayURL=http://www.flash-remoting.com/flashservices/gateway"
  PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
 </EMBED>
</OBJECT>

Thanks to O’Reilly Flash Remoting: The Definitive Guide

IMPORTANT NOTE: You then shouldn’t specify the URL when creating the gateway service, let it be handled by the NetServices which will have the FlashRemoting URL specified.

August 31, 2006

HTTPS Flash Remoting with IE 6 problems

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 3:52 pm

It looks like there are some problems using Flash Remoting with Internet Explorer 6 on PC. The problems looks like it is to do with caching, so we need to set some cache headers. An interesting article by Gary Matthew Rogers titled Flash Remoting: HTTPS & Internet Explorer can be viewed here.

The fix was to modify the HTTP header params to set Expiry, Pragma and Cache-control headers to ensure that content is not cached.

Flash: Invoking events based on changes using watch()…

You will find other articles relevant to this document in these sections:
Richard Lee @ 11:13 am

In Flash 6 a neat method called watch() was introduced for registering event handlers - to be invoked when a specific property changes. To explain the use of the watch() method lets consider a Flash based car game where you want to alert the player if they are speeding;

// Create a the car object
var myCar:Object = new Object();
 
// Add a property that tracks the cars speed
myCar.speed = 0;
 
// Write the callback function to be executed if the speed property changes
var checkSpeed:Function = function(prop, oldVal, newVal, speedLimit) {
// Check whether speed is above the limit
if (newVal > speedLimit) {
trace ("You are speeding.");
}
else {
trace ("You are not speeding.");
}
 
// Return the value of newVal.
return newVal;
}
// Use watch() to register the event handler, passing as parameters:
//   - the name of the property to watch: "speed"
//   - a reference to the callback function speedWatcher
//   - the speedLimit of 50 as the userData parameter
myCar.watch("speed", checkSpeed, 50);
 
// set the speed property to 44, then to 62
myCar.speed = 44; // output: You are not speeding
myCar.speed = 62; // output: You are speeding
 
// unwatch the object
myCar.unwatch("speed");
myObject.speed = 49; // there should be no output

(This example has been modified from the Actionscript Dictionary)

So essentially the watch() method calls the checkSpeed() function whenever the value of var speed changes, alerting the player if they are over the speed limit (var speedLimit). Easy no?.

Just remember the following in your callback function;

  • If you are merely monitoring the property, return the newVal parameter.
  • If you are modifying the value of the property, return your own value.
  • If you want to prevent changes to the property, return the oldVal parameter

August 30, 2006

Saving user info to the Flash Player to retrieve later

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 8:20 pm

A quick article on using the Flash Shared Object which allows you to ‘persist’ or save a variable that can be retrieved from the flash player when a visitor returns - view here.

In short, we use the shared object like this:

// Create the shared object
mySharedObject = SharedObject.getLocal("myUniqueObjectKey");
 
// Use the object to dynamicall set whichever variables and values we need
mySharedObject.myValueToRetrieveLater =  "Hello World!"; // how corny
 
// Save/Write the Shared Object data to the flash player
mySharedObject.flush();

We read in a value like below:

// Create the shared object again, it will automatically load any of the last flushed values
mySharedObject = SharedObject.getLocal("myUniqueObjectKey");
 
// Trace it to see if we have a value that we wanted to retrieve
trace(mySharedobject.myValueToRetrieveLater);

We could apply this in a lot of ways; one being a log in form, where you may want to remember the last logged in user for accessibility of your website visitor. Ensure that you don’t save the password too though!

July 26, 2006

Keep it real

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 8:39 pm

I am looking through bringing some enterprise development patterns/practices across to ActionScript and I found an interesting SWF:

http://svn.sourceforge.net/viewcvs.cgi/*checkout*/asunit/trunk/comm/marketing/trailer/fla/AsUnit-TechnicalMerit-Trailer.swf

July 10, 2006

Essential ActionScript 2.0 Book

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 10:37 am

I have started having a read through the book Essentail ActionScript 2.0 by Colin Moock (O’Rielly ISBN: 0-596-00652-7). To further my knowledge in ActionScript 2.0 for this latest project. Although I will not be contributing to the coding of the frontend development directly, it betters my understanding of how to prepare content to drive the frontend website. It also allows me to provide another programmers input to the development design.

In Essential ActionScript 2.0, bestselling author Colin Moock covers everything you’ll need to know about the new ActionScript language and its methodologies. Experienced Flash developers and programmers coming from other languages will enjoy the sheer depth of Moocks’s coverage. Novice programmers will appreciate the frequent, low-jargon explanations that are often glossed over by advanced programming books. Essential ActionScript 2.0 is the one book every ActionScript coder must own.

The book is an easy read and you quickly can get hold of ActionScript 2.0 syntax and programming style straight away. This is a great book for programmers wanting to crash course into ActionScript and apply their already developed theory.

Check out the book on the O’Reilly Network Safari Bookshelf

July 6, 2006

Loading external data from Flash

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 12:34 pm

As you may all know already, you will need to ensure that you have a crossdomain policy available on your domain to ensure that XML/external data can be read and loaded into your clients flash player.

Flash Player Security will not allow content to be read in from a different domain to where the current file is sitting on - and as you will most likely be aware, www.domain.com and domain.com are different, and not everyone uses the www. prefix.

If your flash application uses an absolute URL to load the content, say from reading an XML document or communicating with a data provider architecture (Flash Remoting, Web Services and the like) you will need to create a basic cross-domain.xml policy file that sits at the root of your domain (eg, www.domain.com/crossdomain.xml).

This is termed sandboxing and can be read on the Macromedia Developer Center: Security Changes in Macromedia Flash 7.

An example of a crossdomain.xml policy file from flash remoting random thoughts is as follows:

<br />
< ?xml version="1.0"?><br />
< !DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"><br />
<cross -domain-policy><br />
<allow -access-from domain="www.flash-remoting.com" /><br />
<allow -access-from domain="flash-remoting.com" /><br />
<allow -access-from domain="*.flash-remoting.com" /><br />
<allow -access-from domain="www.communitymx.com" /><br />
<allow -access-from domain="communitymx.com" /><br />
</cross><br />

Diagnosing if this is the issue

If you are trying to make a request (aka. such as reading in XML or communicating via Flash Remoting) to a remote domain (aka. lets say you are staging it on a test server connecting to a live server, like www.myserver.com looks at www.myclientshosting.com) the request will not leave flash and won’t receive a response from the target server. Most of the time a flash developer will see this as a continous load sequence that hangs during loading of the XML or Remoting request.

July 5, 2006

ActionScript compiling to SWF using ANT and as2ant

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 11:36 pm

I have been starting work on a project involving compiling multiple ActionScript classes. To help in the development process and shorten the time that the Flash Developers take to compile multiple classes into a single SWF movie I have researched into using ANT to compile the ActionScript classes. Using an Open Source Flash compiler (MTASC) and a As2ant (allowing us to create MTASC ant tasks) I have produced the following build.xml.

The build.xml expects that the project is setup with the folder:

  • build.xml
  • lib/as2ant.jar - required by ANT, available in the as2ant download package
  • src/**/*.as - All your class/classes (including subdirectories)

and creates the output to

  • build/*.swf

Have a look at the build.xml here.

You need to simply change you project name (for the output SWF) and the output settings, such as background colour, width/height params, main class and the like.
For any changes please email them to cameronmanderson@gmail.com.

July 4, 2006

Flash ActionScript strip slashes using Regular Expressions

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 2:23 pm

I am just having a bit of a play with some ActionScript 2 for an upcoming project. I have came across the necessity to strip slashes of a string that has been directly parsed from PHP. As it is a object containing many properties it may seem unfeasible to try and strip slashes for every property of the whole object. Instead I will look in flash on how to allow the Flash Developer to strip slashes when they wish to use the object property.

To do so we will want to have a look at Regular Expressions in Flash. Flash did not come packaged with any Regular Expression classes by default, so we will have a look at a using a popular package “RegExp.as” provided by Joey Lott at this URL: http://www.jurjans.lv/flash/RegExp.html. Once we have downloaded the package from their website, you can set it up in your flash file using a simple import.

Reading over the documentation to the behaviour of “addslashes” on PHP.net:

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote (), double quote (), backslash (\) and NUL (the NULL byte).

So our strip slashes will atleast need to ensure that the escaped characters do not contain escaping ‘\’ characters.

One basic way of doing this would be to create a Regular Expression that would match against those characters.

Regular Expression to match occurance of addslashes escaping

(\\([”‘\\])) - Starts with a slash followed by any of the escaped characters (NOTE: this contains single quote and double quote characters which need to be escaped)

The escaped value to use in our Flash Regular expression is “(\\\\([\”\’\\\\]))” (a mouth full of escaping due to the fact that we are matching escaped characters).

// FLASH ActionScript Strip Slashes Example
// Import our RegExp class
import RegExp;
 
// Some escaped text that has arived from PHP or a database
body = "\"foobar.html\" and then \\ \' this and that etc";
trace(stripslashes(body));
 
/**
* Strips slashes of a String
* @param str String Escaped String to strip slashes
* @return String with slashes removed
*/
function stripslashes(str:String):String {
    var stripSlashesRegExp = new RegExp("(\\\\([\"\'\\\\]))","gim");
    return str.replace(stripSlashesRegExp, "$2");
}

This will be much more powerful than a split(’\\’).join() style as that method will strip all backslashes in your document. You may want to consider using a wrapper class and create a Singleton design pattern to stop compiling the regular expression every time it is called. Maybe you could consider adding it as a prototype for the String Class also.

June 20, 2006

Flash Remoting with PHP

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 3:00 pm

After delving into a bit of research today into the advancements of the Adobe Flex framework I came across a way to perform Flash Remoting with PHP via an Open Source package called AMFPHP. Flash Remoting is a bridge between the Flash movie and your web application server. Typically this can be done with a REST-like remote procedure call where you invoke a method with parameters through $_GET/$_POST (maybe through a LoadVars call) and your response is XML.

Example: A way of making a HTTP-Request and returning a XML document into a typecasted ActionScript XML Element

// Create the Load Vars invocation class
myVars = new LoadVars();
myVars.action = "pingback"; // My RPC method
myVars.message = "hello world"; // My method parameters
 
// Create the XML response
myXML = new XML; // This is our target object, which the results from sendAndLoad are loaded into
myXML.onLoad = function(success) {
trace(this); // This is where we can process the required assets
}
 
// Invoke the command
myVars.sendAndLoad("PingBack.php", myXML, "POST");

Flash Remoting

Flash Remoting is apparently faster and more efficient to use than this method (or webservices), and will return native objects for you to work with.

On the Adobe site they mention under their Macromedia Flash Remoting MX product (which gets replaced with full functionality for PHP with AMFPHP):

Macromedia Flash Remoting MX provides the connection between Macromedia Flash and your web application server, making it fast and easy to create Rich Internet Applications. With its powerful yet simple programming model, you can easily integrate rich Macromedia Flash content with applications built using Macromedia ColdFusion MX, Microsoft .NET, Java, and SOAP-based web services.

A simple example may be creating a database query and relaying the result to Flash. With Flash Remoting you can simply perform your SQL statement and return a record set to Flash which can then be used in many different GUI components.

AMFPHP

AMFPHP is a framework that allows you to invoke Flash Remoting to PHP without requiring the Macromedia Flash Remoting product offered by Adobe. On their website they describe AMFPHP as:

AMFPHP is an open-source Flash Remoting gateway. It’s fast, reliable, 100% free and open-source. Flash Remoting is a technology built into the Flash player core that enables sending data between the server and the client seemlessly. If you’ve built XML-based RIAs you know how much of a pain it can be to serialize the data, debug, and integrate into your application.With Flash Remoting, you can call remote methods from the Flash client and the arguments will end up in the native remote language, and will come back to Flash correctly typed, so there’s no messing with serialization at all.

You will be able to see in their documentation how quickly you can get Flash Remoting up and working and they provide good resources to tutorials online for ways to interact with Flash Remoting.

AMFPHP automatically creates the ActionScript classes that you need to interact with your Services that you make. You can also test your Flash Remoting without even requiring Flash to be installed through a very handy Service Browser which comes packaged, and you can debug your connections through another NetConnection Debugger. After reading over this package and the documentation, and having my first play with the PingBack application, I think this is a very well made/simple framework to make life easier for PHP developers and further demonstrate the capabilities of PHP for Web Application Development.

« Previous PageNext Page »