How-To Develop Adobe Flex Web Services with Actionscript

This tutorial will walk you through setting up a Web Service Consumer in ActionScript (Adobe Flex or Flash). Microsoft C#  will be used to serve the data. The returned data will be in XML and will be loaded into an ArrayCollection.

The web service, to be coded in Flex, will be written in ActionScript. To make this tutorial a little exciting, the data for the tutorial will be stored in a SQL database and will be accesses through LINQ. The LINQ query will then convert the result set to XML using XELement and returned to Flex.

First the ActionScript Web Service in Flex

To create a web service in ActionScript in Flex or Flash, you start out by declaring a Web Service variable and importing the proper library:

import mx.collections.ArrayCollection;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.soap.WebService;


public var aWS:WebService = new WebService();
To initialize the web service, I declare a function which will be called from the CreationComplete property in the Application element in the mxml file. The function initializes the wsdl address and sets up the different event listeners. Finally the loadWSDL method is called to load the web service which will call the onWSDLoad method. The resultWebService and faultWebService will be used to handle the result and/or fault events for the incoming data coming from the web service provider.

private function initApp():void
{
	aWS.wsdl='http://somedomain.com/endpoint?WSDL';
	aWS.addEventListener(LoadEvent.LOAD, onWSDLoad);
	aWS.GetCountryData.addEventListener(ResultEvent.RESULT, resultWebService);
	aWS.GetCountryData.addEventListener(FaultEvent.FAULT,faultWebService);
	aWS.loadWSDL();
}

Function to retrieve data from web service provider

private function onWSDLoad():void
{
	aWS.GetCountryData();

}

Function to Build ArrayCollections


To build the Adobe Flex ArrayCollection in ActionScript, we need data. This will be provided  by the web service provider. The incoming data will be received by the result method, resultWebService. This method will declare an XML variable which will contain the raw xml. Next an XMLDcoument variable will be used to handle the root element. This root element will be used to determine which xml result set will be incoming and direct the flash runtime player accordingly. In our example, we will show you the countries xml that will be sent by the provider.

When this data is received, it will be directed to the ‘countries’ case. In this branching, the countryArr ArrayCollection will be initialized. An empty row will be added to display an empty row in the combobox that will eventually use the countryArr as a dataProvider. After that, its simply a question of looping through the xml and assigning data to the region and country objects in the countryArr and regionArr Adobe Flash ArrayCollection. Finally the data providers for the cbCountry and cbRegion will be set.

I also declare a filter function to remove the duplicates from the regionArr Flex ArrayCollection since there will be many duplicate region values for each country but we only need one of each. To see the filter function code check out my article that discusses this in detail: “ActionScript - How to Find an Item in ArrayCollection using getItemIndex()”.

private function resultWebService(e:ResultEvent):void
{
	var xml:XML = new XML(e.result);
	var xmldoc:XMLDocument = new XMLDocument(xml);

	
	switch(xmldoc.firstChild.localName)
	{
		case 'countries':
		
			countryArr = new ArrayCollection();
			countryArr.addItem({country:''});
			
			for each(var x:XML in xml.value)
			{
				
				countryArr.addItem({region:x.region, countrycode:x.countrycode, countryname:x.countryname});
				var regionStr:String = x.region.toString();
				regionArr.addItem({region:regionStr});
			}
			this.cbCountry.dataProvider = countryArr;
			this.cbCountry.labelField = "country";
			
			this.cbRegion.dataProvider = regionArr;
			this.cbRegion.labelField = "region";
			
			regionArr.filterFunction = removedDuplicates;
			regionArr.refresh();
			regionArr.addItem({region:''});
			cbRegion.selectedIndex = 0;
		break;
		case 'products':
			â¦..		
		
		break;
		
	
	
	}

Create a Web Service project in Visual Studio 2008.

Now for the Web Service Solution provider in C#.

From Visual Studio 2008 Professional, Express or Ultimate, create a new C# Web Service project. Call CountryDataServices. Check to create new folder for the solution and click ok.

Delete the Service1.asmx file that is created by default and then right-click on the solution folder in the Solution Explorer and select new item and then browse to the C# Web Service item. Give a name like countryService.

Next we will create a Linq to SQL item (you will need access to a SQL Server (Express or Full version). You will also need to create a database or use an existing one. Afterwards, you need to create a table to store the data
  • Setup SQL elements (db, table, add data)
  • Create a database (if needed)
  • Create Table to store data.


Here is the table definition:

Create table RegionAndCountry
(
	countryCode char(3) primary not null,
	countryName varchar(100),
	regionName varchar(100)
)

Create a Linq to SQL item



Right- click on the Solution in Solution Explorer in Visual Studio 2008 or 2010 and browse to the C# data node and select Linq for SQL. Call it CountryData. This will create a dbml file and will open a Visual Designer and you can use to drag and drop the “RegionAndCountry” table.

Once the dbml file and Designer are open, switch to the Server Explorer in Visual Studio 2008 or 2010 and create db connection to you database. Once this is done, expand the db connection node and browse to the table “RegionAndCountry”. Select the table in the Server Explorer and drag over onto the CountryData.dbml Designer in Visual Studio 2008 or 2010. This will create a (ORM) class to match the table.

Create a WebMethod


[WebMethod]
public string GetCountryData()
{
     xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
 xe = new XElement("countries",
                        (from rc in dbTest.RegionAndCountries 
                         select new XElement("value",
                                     new XElement("countrycode", rc.countryCode ),
                                     new XElement("countryname", rc.countryName ),
			 new XElement("region", rc.regionName  )

                                     )
                        )

                );

            xml += xe;
return xml;   
}
This web method will build our xml structure using LINQ For SQL and XML (XELement). This xml will be return to our Adobe Flex application as string. It will be re converted to xml with the
var xml:XML = new XML(e.result); in our ActionScript method.

That is pretty much it. If you have any questions, comments, or suggestions, post them in the comments section.

More by this Author


Comments 2 comments

keirnanholland 3 years ago

I think what would really help your tutorials is a UML diagram beforehand so we can see how things are connecting.. Those who like combining technologies together also like shooting themselves in the foot when one or more technologies fail in the integration, it's due to the reliance on technology layering (also know as "job insurance") that I think these overly complex job postings come from. If employers were smarter about their technology they would select only a handful of open source technologies and fire people less. But they probably fire people when the complex layering of technologies doesn't get them the solution quickly. It's better to have a correct solution than a cumbersome correct solution. When someone shows me a microsoft technology for instance, I put up my index-fingers in a cross.. Thanks but no thanks, commercial software never plateaus because its business model is to always change regardless of whether it needs to change or not, that means solutions always break. Open source not being driven by money changes only when it absolutely needs to, Probably good for the developers, to keep them in jobs, but bad for the software which may lead to the company losing money because it fails to service customers. Now if you are designing this system for a subsidiary of the KOCH brothers assets, by all means throw as many technologies at this as possible, we need to sabotage that machine.


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

keirnanholland ,

Thanks for your suggestions. I appreciate them.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working