May 19, 2010

How to consume AR System web services with Flex

Note : This post was copied from BMCDN

I can't just give the source because it won't make much sense (that's to not tell it's a horrible mess ...), but here are a few copy/paste that could help :

First, you will need to import these :
import mx.rpc.soap.SOAPHeader;
import mx.rpc.soap.LoadEvent;
import mx.rpc.soap.WebService;

I declared these variables :

public var _webServiceFields:WebService; // web service
public var _webServiceFieldsLoaded:Boolean = false; // flag noting when wsdl has been loaded

Then, you initialize your webservices and declare the events and their handlers (if you already know Flex, it's likely to be familiar to you ). FIELD_WS holds the complete URL for the WSDL file. You have to add the header for authentication.

public function FieldsInit():void 
_webServiceFields = new WebService();
_webServiceFields.wsdl = FIELDS_WS;
var q1:QName=new QName("","AuthenticationInfo");
var header1:SOAPHeader = new SOAPHeader(q1, {userName:FIELDS_USER, password:FIELDS_PWD});
// add listeners
_webServiceFields.addEventListener(LoadEvent.LOAD, load_listener_fields);
_webServiceFields.addEventListener(ResultEvent.RESULT, result_listener_fields);
_webServiceFields.addEventListener(FaultEvent.FAULT, fault_listener);
// load wsdl

The fault listener is pretty generic :
public function fault_listener(event:FaultEvent):void 
debug += event.fault.faultCode + "\n"+ event.fault.faultString + "\n"+ event.fault.faultDetail;texteditor.text = debug;

The load listener starts once loadWSDL() is done, and calls the GetField function below.
public function load_listener_fields(event:LoadEvent):void 
debug +="WS Loaded ... Retrieving fields\n";
_webServiceFieldsLoaded = true;GetFields();

The result listener fires when the result has been received.
public function result_listener_fields(event:ResultEvent):void 
var i:int = 0;
while (i <
debug += "- " +[i].chrChamp + "\n";
debug +=fields.length + " fields found\n";

Finally, this function unleashes the power of your creation :
public function GetFields():void 
if (_webServiceFieldsLoaded)
// is wsdl is loaded
callLater(GetFields); // wait a frame and try again

NB : Since then I have used Flex + WS in a production environment, and it's pretty reliable. But as an afterthought, I would have rather made it a datavisualization plugin.

No comments: