Thursday, October 23, 2008

Using Flex Webservice component in Flash CS4

One of the most common requests for the Flash team is to provide a Webservice component for Actionscript 3.0 like the one Flash has for Actionscript 2.0. Finally, Flash has provided the features in CS4 to allow users to use any Flex components that does not rely on Flex framework such as Flex WebService component and HTTPService.

In the below example am going to demonstrate how users can use Flex WebService in Flash to get countries names and populate them in a Flash DataGrid component.

1. File > New
2. Select "Flash File (Actionscript 3.0)".
3. Open the Component panel and drag a DataGrid component to the stage and call it "dg".
5. File > Publish settings and click on "Flash" tab.

6. Click on "Settings" button to launch "Advance Actionscript 3.0 Settings"

7. Click on the "library path" tab

8. Click on "Browse to SWC file" icon and get the "framwork.swc" and "rpc.swc" from the Flex SDK as follow :


You can download FlexSDK and select the above SWC's from the following location
"sdks/3.0.0/frameworks/libs/"

9. Open the action panel and import the following:
import mx.rpc.soap.*;
import mx.core.*;
import mx.rpc.events.*;
import fl.data.DataProvider;
10. The following 2 lines of code are required if you are using SDK 3.0.0 but not if you are using higher version of SDK

//The following 2 lines to register class for
//Interface"mx.interface::IResourceManager

var resourceManagerImpl:Object = ApplicationDomain.currentDomain.getDefinition("mx.resources::ResourceManagerImpl");
Singleton.registerClass("mx.resources::IResourceManager", Class(resourceManagerImpl));

11. Now copy the following and paste below the above 2 line of codes


var foo:WebService = new WebService();

foo.addEventListener("load", finishedLoading);

foo.loadWSDL("http://www.webservicex.net/country.asmx?WSDL");

var myOperation:Operation;

function finishedLoading(evt:LoadEvent):void
{
myOperation = Operation(foo.getOperation("GetCountries"));
myOperation.addEventListener("fault", wsdlFault);
myOperation.addEventListener("result", wsdlResult);
myOperation.send();
}


function wsdlFault(evt:FaultEvent):void
{
trace(evt.fault);
}

function wsdlResult(evt:ResultEvent):void
{
trace(evt.result);

var myResult:Object = evt.result;
var len:Number = myResult.length;
var xml:XML = XML(evt.result);
var dp:DataProvider = new DataProvider(xml);
dg.dataProvider = dp;

}

12. Test Movie and you should get a list of all the countries inside the datagrid :