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.events.FaultEvent;
import mx.rpc.events.ResultEvent;
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("http://soapinterop.org/xsd","AuthenticationInfo");
var header1:SOAPHeader = new SOAPHeader(q1, {userName:FIELDS_USER, password:FIELDS_PWD});
_webServiceFields.addHeader(header1);
// add listeners
_webServiceFields.addEventListener(LoadEvent.LOAD, load_listener_fields);
_webServiceFields.addEventListener(ResultEvent.RESULT, result_listener_fields);
_webServiceFields.addEventListener(FaultEvent.FAULT, fault_listener);
// load wsdl
_webServiceFields.loadWSDL();
}


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 < event.target.OpGetList.lastResult.list.length)
{
fields.addItem(event.target.OpGetList.lastResult.list.source[i].chrChamp);
debug += "- " + event.target.OpGetList.lastResult.list.source[i].chrChamp + "\n";
i++;
}
debug +=fields.length + " fields found\n";
DataInit();
}

Finally, this function unleashes the power of your creation :
public function GetFields():void 
{
if (_webServiceFieldsLoaded)
{
// is wsdl is loaded
_webServiceFields.OpGetList(_source_Fieldstag);
}
else
{
FieldsInit();
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: