Creating a Web Service Powered Flex Application in One Minute

This post belongs to the ‘How to Consume Web Services in Adobe Flex‘ series which provides tutorials and tips for Flex developers who want to access server-side data though Flex WebService. Read the introduction page here.

Your Key to the World of Web Services – Flex WebService

In old days, it sounded like very complex to call web services. SOAP, WSDL, Binding Style, Service, Port, Operation, Message, Type… just name a few of technical jargons here, you might feel lost already.

However, it’s actually very easy  to consume web services in Adobe Flex because it provides a built-in component – WebService. By using it, you can literally Create a Web Service Powered Flex Application in One Minute. Is that amazing?

Your First Flex WebService Application

What we want to build here is a very simple Flex application, which converts a temperature value from Fahrenheit to Celsius. Behind the scene, it calls an online web service provided by w3schools.com to do the conversion.

The final Flex application will look like this:

flextutorial-first-flex-webserivce-application-1

Once you type a Fahrenheit value (e.g. 100) into the input box and click Convert button, it will show the corresponding Celsius value.

flextutorial-first-flex-webserivce-application-2

Now, Let me show you how to build this Flex WebService application in 4 simple steps. You can literally finish it within one minute.

Step 1 – Create a New Project in Flex Builder

  1. Start your Flex Builder. On the top menu, click File -> New -> Flex Project
  2. Give a name to your project, e.g. FlexWebService.
  3. Keep the default value for the rest parts, click Finish button.

flextutorial-new-flex-webservice-project

Step 2 – Add Flex WebService Component

Flex provides a MXML tag <mx:WebService> to call web services, that is all you need right now. So just add the following lines to you main MXML file.

<mx:WebService id="myWebService"
    wsdl="http://www.w3schools.com/webservices/tempconvert.asmx?WSDL">
    <mx:operation name="FahrenheitToCelsius"
        result="resultHandler(event)"
        fault="faultHandler(event)">
    </mx:operation>
</mx:WebService>

What have we just done?

  • We create a <mx:WebService> with id myWebService.
  • We point <mx:WebService> to the URL (http://www.w3schools.com/webservices/tempconvert.asmx?WSDL) of a wsdl file created by our web service provider.
  • We specify the operation to use (FahrenheitToCelsius) and the functions to handle the result and fault event (resultHandler and faultHandler).

Step 3 – Add Flex WebService Event Handlers

Now, we add the following code to handle the Flex WebService result and fault event.

<mx:Script>
    <![CDATA[
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.controls.Alert;

	private function resultHandler(event:ResultEvent):void {
		cValue.text = event.result.toString();
	}

	private function faultHandler(event:FaultEvent):void {
		Alert.show(event.fault.message, "Error");
	}
    ]]>
</mx:Script>

The above code should be very simple to follow:

  • resultHandler function gets the web service’s return data from ResultEvent (event.result), converts it to a string, then bind it to a Flex Text component (cValue) for display.
  • faultHandler function gets the fault error message from FaultEvent (event.fault.message) and use Alert window to display it.

Step 4 – Add Flex UI Components to Display the Temperature Converter

In this last step, let’s create a simple UI:

<mx:Panel title="Fahrenheit to Celsis Converter"
    paddingTop="30" paddingRight="10"
    paddingBottom="30" paddingLeft="10">

    <mx:HBox>
	<mx:Label text="Fahrenheit Value: "/>
	<mx:TextInput id="fValue" />
	<mx:Button id="submit" label="Convert"
           click="myWebService.FahrenheitToCelsius.send(fValue.text)"/>
    </mx:HBox>

    <mx:HBox>
	<mx:Label text="Celsius Value: "/>
	<mx:Label id="cValue"/>
    </mx:HBox>

</mx:Panel>

Basically, we create a Panel which contains two HBox to get user input and display the result from the web service. The only thing special here is the Click Event of the Submit button.

<mx:Button id="submit" label="Convert"
    click="myWebService.FahrenheitToCelsius.send(fValue.text)"/>

Here we refer to our Flex WebService through its id myWebService, call its operation FahrenheitToCelsius, and pass a value coming from the TextInput control fValue.

Now let’s click Run button in your Flex builder and see what will happen… …

Congratulations! You Have Created a Web Service Powered Flex Application!

Recap what you have learned so far

  • You can consume web services in Flex simply through <mx:WebService>.
  • You can specify wsdl url, operation name, result event handler, fault event handler for <mx:WebService>.
  • You can trigger your WebService through an event (like button click event), call the send function of the operation, and pass parameters if needed.

Through the sample application we built today, I hope you will see how easy it is to consume web services in Flex.  You can download the complete source code here.

If you have any questions, please feel free to comment on this post or contact me directly .

For the next tutorial, we will talk about some details in Flex WebService and help you thoroughly understand it from A to Z.

About Bryan
Bryan Li has more than 10 years business consulting and project development experience with major corporate clients including Sony, Bank of Montreal, Bruce Power, etc. As a fan and advocate for RIA(Rich Internet Application) technologies, Bryan helps companies and developers learn, design, and build richer applications using Adobe Flex.

15 Comments on Creating a Web Service Powered Flex Application in One Minute

  1. young_flex // June 12, 2009 at 4:00 am //

    i m having problem when i create UI panel as a component. Error in my main xml inside actionscrip.

    Do you have any idea why?

    <![CDATA[
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.controls.Alert;

    private function resultHandler(event:ResultEvent):void
    {
    cValue.text = event.result.toString();
    }

    ————————————–

    the error at line ‘cValue.text = event.result.toString();’

  2. Hi young_flex! Thanks for your comment on FlexTutorial.org.

    Would you be able to provide me the error message for the further investigation?

  3. Hi there…
    I’ve used flex to consume an java axis web service before and it has worked very well, but recently I’ve been put on another project that consumes a jax-ws doc/literal service and I’m having a hell of a time getting flex to play nice with it.
    I was hoping, you would have some advice here. The problem( I think ) is that jax-ws autogenerates the schema and one of the nested element names is called “return” which I can’t change. Because of this I can’t use e4x dot notation to get to the return element because it sees it as a keyword in flexbuilder….Here is a sample of the xml that is returned to the flex client. The webservice itself is a tool to parse documents used internally at my org.

    1242
    Joe Bob
    5

    1243
    Jack Black
    6

    ….etc..
    What I want to do is put this into a datagrid, but I just can’t seem to get it to work.

    HERE IS THE CALL, this works:

    {FILE.text}

    HERE IS THE ReSPONSE…does not work. Note, I cannot do test.parseFile.lastResult.return because return is a keyword in flex and can’t use it….ugh…

    Anyway, I’m certainly not a flex expert, but any advice here would be greatly appreciated. I’ve tried a bunch of different ways to put the data into a datagrid and it just isn’t working. The only thing that seems to work si test.parseFile.lastResult.toXMLString()…but that doesn’t do me any good.

    Thanks again…
    Ron

  4. Hi Ron,

    It’s nice to see you on FlexTutorial.org!

    As your put, test.parseFile.lastResult.toXMLString() is working fine. You might get the result as String first, then replace the word “return” with some text you want. After this, you can cast the new String to the normal e4x format.

  5. Thanks a lot for the great tutorial!

  6. Thanks Vanessa for your comment! Hope to see you often on FlexTutorial.org.

  7. Excellent example on webservices

  8. kannansamynathan // August 19, 2009 at 9:16 am //

    Hi,

    I have created a webservice in C# ASP.Net,

    which will return a datatable.

    How can I show the datatable – return by the .net web service through flex datagrid.

    I used something like this,

    ——————

    public function mainMethod():void
    {
    var gateway:WebService = new WebService();
    gateway.wsdl = “../Service.asmx?wsdl”;
    gateway.loadWSDL();

    gateway.gettable.addEventListener(ResultEvent.RESULT,gettableHandler);

    gateway.gettable();
    }

    public function gettableHandler(e:ResultEvent):void
    {
    Alert.show(“hi”);
    var table:* = e.result.Tables.Table0.Rows;
    var AC_Temp:ArrayCollection=new ArrayCollection()
    var A_Revenues:Array=new Array()

    AC_Temp = table;
    A_Revenues=AC_Temp.toArray();
    DG1.dataProvider = A_Revenues;

    }
    ——————–

    But its not working – gettableHandler() not getting a call.

  9. kannansamynathan // August 19, 2009 at 9:16 am //

    Hi,

    I have created a webservice in C# ASP.Net,

    which will return a datatable.

    How can I show the datatable – return by the .net web service through flex datagrid.

    I used something like this,

    ——————

    public function mainMethod():void
    {
    var gateway:WebService = new WebService();
    gateway.wsdl = “../Service.asmx?wsdl”;
    gateway.loadWSDL();

    gateway.gettable.addEventListener(ResultEvent.RESULT,gettableHandler);

    gateway.gettable();
    }

    public function gettableHandler(e:ResultEvent):void
    {
    Alert.show(“hi”);
    var table:* = e.result.Tables.Table0.Rows;
    var AC_Temp:ArrayCollection=new ArrayCollection()
    var A_Revenues:Array=new Array()

    AC_Temp = table;
    A_Revenues=AC_Temp.toArray();
    DG1.dataProvider = A_Revenues;

    }
    ——————–

    But its not working – gettableHandler() not getting a call.

    Anyone kindly clarify my doubt as soon as possible.

  10. I’ve been able to do this in my Flex Builder, but when I export a release build and put it on my server everything works except after the Send nothing happens in the ResultHandler or FaultHandler – just nothing comes back from the Send.

    This all works in the Flex Builder when I click the Run or Debug, but once I create a release build it all works except the Send doesn’t trigger the Result or Fault routines.

    Ideas?

  11. kannansamynathan // August 19, 2009 at 10:11 pm //

    Hi darren,

    Also I’m facing the same problem, :(

  12. I think it’s a security issue. If the swf and soap are on different servers you need special permissions – if I figure it out I’ll post it here.

    It works in debug mode since the security is relaxed, but when you deploy it you need to set up the security (I think).

  13. Hi Bryan,

    Thanks for your excellent tutorial.I am eagerly waiting for your next series of this tutorial.

    Regards,
    Naveen.

  14. Well this script somehow didnt work for me. I mean I didnt get any error thats annoying. But it just would not return anything. Is it something related to crossdomain.xml?? I dnt knw, I am on it.

  15. I need brush java script file for adobe flex..,

1 Trackbacks & Pingbacks

  1. Daily Digest for March 8th at dandube.com

Leave a comment

Your email address will not be published.

*