Search Flex Components Free

Custom Search
Showing posts with label Flex with Web Services. Show all posts
Showing posts with label Flex with Web Services. Show all posts

January 1, 2008

Declaring an RPC component

You can declare RPC components in MXML or ActionScript to connect to RPC services. If you are not using Adobe Flex Data Services, you can use a WebService or HTTPService component to contact an RPC service directly.
NOTE

To use RemoteObject components, Flex Data Services or Macromedia ColdFusion MX 7.0.2 with the Remoting Update is required.
If you are using Flex Data Services, you have the option of connecting to RPC services directly or connecting to destinations defined in the services-config.xml file or a file that it includes by reference. A destination definition is a named service configuration that provides server-proxied access to an RPC service. A destination is the actual service or object that you want to call. A destination for a RemoteObject component is a Java object. A destination for an HTTPService component is a JSP page or another resource accessed over HTTP. A destination for a WebService component is a SOAP-compliant web service.
Destination definitions provide centralized administration of RPC services. They also enable you to use basic or custom authentication to secure access to destinations. You can choose from several different transport channels, including secure channels, for sending data to and from destinations. Additionally, you can use the server-side logging feature to log RPC service traffic.
Optionally, you can use an HTTPService component or a WebService component to connect to a default destination.
This section discusses the basics of declaring a service connection in MXML and configuring a destination. For information about calling a service in MXML and ActionScript, see Calling a service. For information about configuring destinations, see Configuring RPC Services.
Subtopics
Using a service without server-side configuration
Using an RPC component with a server-side destination

Calling a service

You can declare an RPC component and call the service in MXML or ActionScript. Regardless of the source of input data, calls to a service are asynchronous and require an ActionScript method, called an event listener, which is called after the RPC call is completed.
The two general categories of events are user events and system events. User events occur as a result of user interaction with the application; for example, when a user clicks a Button control a user event occurs. System events occur as a result of systematic code execution. For information about events, see Using Events.
Flex provides two ways to call a service: explicit parameter passing and parameter binding. You can use explicit parameter passing when you declare an RPC component in MXML or ActionScript. Parameter binding is only available when you declare an RPC component in MXML.
You can use an RPC component's requestTimeout property to define the number of seconds to allow a request to remain outstanding before timing it out. The requestTimeout property is available on RemoteObject, HTTPService, and WebService components.
Subtopics
Using explicit parameter passing
Using parameter binding

Handling service results

After an RPC component calls a service, the data that the service returns is placed in a lastResult object. By default, the resultFormat property value of HTTPService components and WebService component operations is object, and the data that is returned is represented as a simple tree of ActionScript objects. Flex interprets the XML data that a web service or HTTP service returns to appropriately represent base types, such as String, Number, Boolean, and Date. To work with strongly typed objects, you must populate those objects using the object tree that Flex creates.
WebService and HTTPService components both return anonymous Objects and Arrays that are complex types. If makeObjectsBindable is true, which it is by default, Objects are wrapped in mx.utils.ObjectProxy instances and Arrays are wrapped in mx.collections.ArrayCollection instances.
NOTE

Macromedia ColdFusion is case insensitive, so it internally uppercases all of its data. Keep this in mind when consuming a ColdFusion web service.
Subtopics
Handling results as XML with the e4x result format
Binding a service result to other objects
Handling result and fault events

Using a service with binding, validation, and event listeners

You can validate data before passing it to a service, and dispatch an event when the service returns a result or a fault. The following example shows an application that validates service request data and assigns an event listener to result and fault events.

This two-tier application does the following:

  1. Declares a web service.
  2. Binds user-interface data to a web service request.
  3. Validates a ZIP code.
  4. Binds data from a web service result to a user-interface control.
  5. Specifies result and fault event listeners for a WebService operation.

You can also create multitier applications that use an additional data-model layer between the user interface and the web service. For more information about data models and data binding, see Representing Data . For more information about data validation, see Validating Data .

<?xml version="1.0"?> <!-- fds\rpc\RPCBindValidateEvents.mxml. Compiles w destination error --> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="600" height="400"> <!-- WebService component handles web service requests and results. --> <mx:WebService id="WeatherService" destination="wsDest"> <mx:operation name="GetWeather" fault="showErrorDialog(event.fault.faultString)" result="log();"> <!-- The mx:request data model stores web service request data. --> <mx:request> <ZipCode>{myZipField.text}</ZipCode> </mx:request> </mx:operation> </mx:WebService> <!-- Validator validates ZIP code using the standard Zip Code validator. --> <mx:ZipCodeValidator source="{WeatherService.GetWeather.request}" property="ZipCode" trigger="{mybutton}" triggerEvent="click"/> <mx:VBox> <mx:TextInput id="myZipField" text="enter zip" width="80"/> <!-- Button triggers service request. --> <mx:Button id="mybutton" label="Get Weather" click="WeatherService.GetWeather.send();"/> <!-- TextArea control displays the results that the service returns. --> <mx:TextArea id="temp" text="The current temperature in {WeatherService.GetWeather.lastResult.CityShortName} is {WeatherService.GetWeather.lastResult.CurrentTemp}." height="30" width="200"/> </mx:VBox> <mx:Script> <![CDATA[ public function log():void { // function implementation } public function showErrorDialog(error:String):void { // function implementation } ]]> </mx:Script> </mx:Application>

Create a dynamic link

Create a dynamic link

The web service doesn't provide the full text of the posts, but you still want users to be able to read the posts if they're interested. While the web service doesn't provide the information, it does provide the URLs to individual posts. According to the API documentation for the getMostPopularPosts method (see Review the API documentation ), the information is contained in a field called postLink .

You decide to create a dynamic link that opens a browser and displays the full content of the post selected in the DataGrid control.

  1. In Source mode, enter the following click property in the <mx:LinkButton> tag (in bold): <mx:LinkButton x="30" y="250" label="Select an item and click here for full post" click="navigateToURL(new URLRequest(dgTopPosts.selectedItem.postLink));" />

    The value of the link field of the selected item in the DataGrid control, dgTopPosts.selectedItem.postLink , is specified in the argument to the navigateToURL() method, which is called when the user clicks the LinkButton control. The navigateToURL() method loads a document from the specified URL in a new browser window.

    NOTE

    The navigateToURL() method takes a URLRequest object as an argument, which in turn takes a URL string as an argument.

  2. Save the file, wait until Flex Builder finishes compiling the application, and click the Run button.

    A browser opens and runs the application. Click an item in the DataGrid control and then click the LinkButton control. A new browser window should open and display the blog page with the full post.

Populate the DataGrid component

You want to use the DataGrid control to display the data returned by the web service. Specifically, you want to display the titles of the most popular posts and the number of clicks each has received.

  1. In Source mode, enter the following dataProvider property in the <mx:DataGrid> tag (in bold): <mx:DataGrid x="30" y="75" id="dgTopPosts" width="400" dataProvider="{wsBlogAggr.getMostPopularPosts.lastResult}" >

    You want to display the results of the web service's getMostPopularPosts operation in the DataGrid control.

  2. In the first <mx:DataGridColumn> tag, enter the following headerText and dataField property values (in bold): <mx:DataGridColumn headerText=" Top Posts " dataField=" postTitle " />

    You want the first column in the DataGrid control to display the titles of the posts. You do this by identifying the field returned by the web service operation that contains the title data, and then entering the field name as the value of the dataField property. According to the API documentation for the getMostPopularPosts method, the field called postTitle contains the information you want.

  3. In the second <mx:DataGridColumn> tag, enter the following headerText , dataField , and width property values (in bold): <mx:DataGridColumn headerText=" Clicks " dataField=" clicks " width= " 75 " />

    You want the second column in the DataGrid control to display the number of clicks for each post during the last 30 days. According to the API documentation, the field that contains the data is called clicks .

  4. Delete the third <mx:DataGridColumn> tag.

    You don't need a third column.

    The <mx:DataGrid> tag should look as follows:

    <mx:DataGrid x="30" y="75" id="dgTopPosts" width="400" dataProvider="{wsBlogAggr.getMostPopularPosts.lastResult}"> <mx:columns> <mx:DataGridColumn headerText="Top Posts" dataField="postTitle"/> <mx:DataGridColumn headerText="Clicks" dataField="clicks" width="75"/> </mx:columns> </mx:DataGrid>
  5. Save the file, wait until Flex Builder finishes compiling the application, and then click the Run button in the toolbar to test the application. If you're using the plug-in configuration of Flex Builder, select Run > Run As > Flex Application.

    A browser opens and runs the application. You find a problem in the application's default state. The ComboBox reads Top 5 but the DataGrid does not display any information.

    The DataGrid should display the top five posts, but it doesn't because your application hasn't called the web service yet. The application only calls it when the ComboBox changes. Even if you click Top 5 in the ComboBox after the application starts, the call is still not made because the selected item hasn't changed.

    To fix the problem, you decide to also call the web service immediately after the application is created, as follows.

  6. In Source mode, enter the following creationComplete property (in bold) in the opening <mx:Application> tag: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="wsBlogAggr.getMostPopularPosts.send()" >

    The final application code should look like the following:

    <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="wsBlogAggr.getMostPopularPosts.send()"> <mx:WebService id="wsBlogAggr" wsdl="http://weblogs.macromedia.com/mxna/webservices/mxna2.cfc?wsdl" useProxy="false"> <mx:operation name="getMostPopularPosts"> <mx:request> <daysBack>30</daysBack> <limit>{cbxNumPosts.value}</limit> </mx:request> </mx:operation> </mx:WebService> <mx:Panel x="10" y="10" width="475" height="400" layout="absolute" title="Most Popular Posts"> <mx:ComboBox x="30" y="25" id="cbxNumPosts" change="wsBlogAggr.getMostPopularPosts.send()"> <mx:Object label="Top 5" data="5" /> <mx:Object label="Top 10" data="10" /> <mx:Object label="Top 15" data="15" /> </mx:ComboBox> <mx:DataGrid x="30" y="75" id="dgTopPosts" width="400" dataProvider="{wsBlogAggr.getMostPopularPosts.lastResult}"> <mx:columns> <mx:DataGridColumn headerText="Top Posts" dataField="postTitle"/> <mx:DataGridColumn headerText="Clicks" dataField="clicks" width="75"/> </mx:columns> </mx:DataGrid> <mx:LinkButton x="30" y="250" label="Select an item and click here for full post"/> </mx:Panel> </mx:Application>
  7. Save the file and run the application.

    Blog titles and click statistics should appear in the DataGrid control after the application starts, confirming that the application successfully retrieved data from the web service and populated the control.

Insert a WebService component


<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; font-weight:normal; color:#000000 ">
<tr>
<td>
<table width="100%" align="center" cellpadding="10" cellspacing="0" style="border-style:dashed;border-color:#666666;border-width:1px; background-color:#FEFFF2;padding:10px;font-family:Arial, Helvetica, sans-serif; font-size:12px; font-weight:normal; color:#009933 ">
<tr>
<td height="114"> <p> You use the Flex WebService component to access a SOAP-based web service and retrieve information about recent blog posts.</p>
<p>In Source mode, enter the following &lt;mx:WebService&gt; tag immediately after the opening &lt;mx:Application&gt; tag:&lt;mx:WebService id=&quot;wsBlogAggr&quot; <br>
wsdl=&quot;http://weblogs.macromedia.com/mxna/webservices/mxna2.cfc?wsdl&quot;<br>
useProxy=&quot;false&quot;&gt;<br>
&lt;/mx:WebService&gt;</p>
<p>The wsdl property specifies the location of the WSDL file for the web service. As of this writing, the location was still valid, but you should check to make sure it hasn't changed. You can find the latest WSDL file location on the developers page at www.adobe.com/go/mxna_developers, under Web Services.</p>
<p>NOTE<br>
<br>
If you want, you can also use the following alias in the component:

Flex and .NET web services part -2

Following my last piece on Flex and .NET web services I will show how to use datasets and Flex. Some folks have reported issues when working with datasets and Flex. Macromedia's" Mike Downey reports that Flash has no support for datasets but you must instead use object arrays.

In keeping with the previous article lets translate Mikes C# code into VB.NET

Imports System
Imports System.Web.Services


Public Class Employee
Public name As String
Public department As Integer
End Class


<WebServiceAttribute(Namespace:= "http://services.r.us/" , Description:= "Access the Employee database" )> _
Public Class Employees

<WebMethodAttribute(Description:= "Get a list of employees" )> _
Public Function getEmployees() As Employee()
Dim employees As Employee() = New Employee(1){}
employees(0) = New Employee()
employees(0).name = "Bob"
employees(0).department = 123
employees(1) = New Employee()
employees(1).name = "Mary"
employees(1).department = 456
Return employees
End Function
End Class

If we run this code we get

<? xml version="1.0" encoding="utf-8" ?> - < ArrayOfEmployee xmlns:xsd =" http://www.w3.org/2001/XMLSchema " xmlns:xsi =" http://www.w3.org/2001/XMLSchema-instance " xmlns = http://tempuri.org/Test/Service1 > - < Employee > < name > Bob </ name > < department > 123 </ department > </ Employee > - < Employee > < name > Mary </ name > < department > 456 </ department > </ Employee > </ ArrayOfEmployee >

Note that the serialized object array structure is a much simpler model than a serialized dataset (this means less issues with aggregating our SOAP packet). However note that they have been some reports of multi dimension arrays not serializing correctly , this could lead to data loss or corruption in your SOAP packets. Lets try our own example, here we will query the SQL Server pubs database and convert the dataset to an object array.

Public Class TitleInfo
Public strTitleName As String
End Class


<WebMethod()> _
Public Function GetTitleData() As TitleInfo()

Try
'create dataset
Dim dsTitleData As New DataSet

'create connection
Dim objCon As SqlConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'create data adapter
Dim cmdSQL As SqlDataAdapter = New SqlDataAdapter("select top 5 title from titles", objCon)
'fill dataset using data adapter
cmdSQL.Fill(dsTitleData, "titles")

'create object array, using row count as upper dim
Dim objTitles As TitleInfo() = New TitleInfo(dsTitleData.Tables(0).Rows.Count - 1) {}

'loop through dataset to add data to object array
Dim intRsCount As Int16
For intRsCount = 0 To dsTitleData.Tables(0).Rows.Count - 1
objTitles(intRsCount) = New TitleInfo
objTitles(intRsCount).strTitleName = dsTitleData.Tables(0).Rows(intRsCount)("title")
Next

'return object array
Return objTitles

Catch exp As Exception
Throw
End Try

End Function

This function does a simlar job to the code Mike showed, it connects to the database, obtains the data and creates the dataset. We then loop through the dataset to populate the object array and return the object array. I have not included any error checking (other than the Try-Catch) to keep the code simple, you would normally want to add error checking (for example our array depends on a row count to get its size). The resulting SOAP packet is as follows.

<? xml version="1.0" encoding="utf-8" ?> - < ArrayOfTitleInfo xmlns:xsd =" http://www.w3.org/2001/XMLSchema " xmlns:xsi =" http://www.w3.org/2001/XMLSchema-instance " xmlns = http://tempuri.org/Test/Service1 > - < TitleInfo > < strTitleName > But Is It User Friendly? </ strTitleName > </ TitleInfo > - < TitleInfo > < strTitleName > Computer Phobic AND Non-Phobic Individuals: Behavior Variations </ strTitleName > </ TitleInfo > - < TitleInfo > < strTitleName > Cooking with Computers: Surreptitious Balance Sheets </ strTitleName > </ TitleInfo > - < TitleInfo > < strTitleName > Emotional Security: A New Algorithm </ strTitleName > </ TitleInfo > - < TitleInfo > < strTitleName > Fifty Years in Buckingham Palace Kitchens </ strTitleName > </ TitleInfo > </ ArrayOfTitleInfo >

To get at this data in Flex we can now get at the data using a standard web service call

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=" http://www.macromedia.com/2003/mxml " width="600" height="450">
<mx:WebService id="TestApp" wsdl=" http://localhost/test/test.asmx?WSDL " showBusyCursor="true" fault="alert(event.fault.faultstring)">
<mx:operation name="GetTitleData">

</mx:operation>
</mx:WebService>
<mx:VBox>
<mx:Button click="TestApp.GetTitleData.send()"></mx:Button>
<mx:DataGrid dataProvider="{TestApp.GetTitleData.result}" widthFlex="1">
<mx:columns>
<mx:Array>
<mx:DataGridColumn columnName="strTitleName" headerText="Title Name"/>
</mx:Array>
</mx:columns>
</mx:DataGrid>
</mx:VBox>
</mx:Application>

Here we populate a datagrid from the strTitleName field in our object array when the button event fires. Nore that the datagrid provider points to our web service function (GetTitleData) and the columnname points to the strTitleName field (if you have more fields in your object array you could add more fields in your datagrid etc).

Flex, .NET and Flash Remoting








Code Example

Flex supports Flash Remoting as well as web services and the best bit is that calling out to .NET objects is a breeze. In order to use Flash Remoting to call out to .NET objects you will need Flash Remoting installed server side. This article shows how to use Macromedia's soloution but you could also use Flash ORB .


With Flash Remoting installed I will use the default folder that it sets up, setting up your own is easy though. So first things first we create our .NET assembly.


Imports FlashGateway.IO


Public Class RemotingTests


'returns what ever value is passed


Public Function EchoString( ByVal strValue As String )


Return strValue


End Function

End Class


This code echos back what ever value is passed. Note the inclusion of the Flashgateway.IO namespace, this is sourced from the flashgateway.dll assembly that you must referance. With this compiled copy the assembly into the bin folder of the default samples folder that the Flash remoting setup sets up. The next step is to add the Flash Remoting gateway to Flex. Open up your applications flex-config.xml file and add your gateway as follows.


<amf-gateway>http://localhost/flashremoting/gateway.aspx</amf-gateway>


This is the default Flash Remoting gateway that Flash Remoting sets up.


With this in place we can now write our Flex code.


<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx=" http://www.macromedia.com/2003/mxml" width="600" height="450">



<mx:Script>

var MyResult;

</mx:Script>



<mx:RemoteObject id="test" encoding="AMF" source="FlashRemotingCode.RemotingTests"

fault="alert(event.fault.faultstring, 'Error')" result="MyResult=event.result">

<mx:method name="EchoString"/>

</mx:RemoteObject>

<mx:Label text="{MyResult}">

</mx:Label>

<mx:Button click="test.EchoString('Flex and Flash Remoting rocks')">

</mx:Button>

</mx:Application>


Here I have created a simple Flex app that calls out to our .NET object via Flash Remoting passing a hard coded value. Note that the source attribute points to the .NET object fully referanced, that is any namespace names and then the class name (we will assume the default namespace for our .NET object is FlashRemotingCode).



Flex and .NET web services

Code Example

Seen a few requests for .NET web service and Flex examples, here is a quick example.

First create a web service function (my code is in VB.NET but you get the idea).

<WebMethod()> _
Public Function SayHello(ByVal strMessage As String) As String
Return "Hello " & strMessage
End Function

This amazingly complex bit of code echo's out it's arguement with the string "Hello" attached.

Now we will rig to Flex using the following code.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=" http://www.macromedia.com/2003/mxml " width="600" height="450">
<mx:WebService id="EchoStuff" wsdl=" http://localhost/EchoService/Echo.asmx?WSDL " showBusyCursor="true" fault="alert(event.fault.faultstring)">
<mx:operation name="SayHello">
<mx:request>
<strMessage>{name.text}</strMessage>
</mx:request>
</mx:operation>
</mx:WebService>
<mx:VBox>
<mx:TextInput id="name"></mx:TextInput>
<mx:Button click="EchoStuff.SayHello.send()"></mx:Button>
<mx:Label text="{EchoStuff.SayHello.result}"></mx:Label>
</mx:VBox>
</mx:Application>

Here we we will use a textbox (Flex calls them textinput) and on the button click event send it's contents to the web service. A label will then display the contents back. A few notes here.

Web services are called using the following.

<mx:WebService id="EchoStuff" wsdl=" http://localhost/EchoService/Echo.asmx?WSDL " showBusyCursor="true" fault="alert(event.fault.faultstring)">
<mx:operation name="SayHello">
<mx:request>
<strMessage>{name.text}</strMessage>
</mx:request>
</mx:operation>
</mx:WebService>

Note that the we specify the location to the WSDL for our webservice. We then map mx:operation to the method name of our web service. To send a request to the web service we use mx:request and within that the parameter name and what data we will send (in this case the textinput contents). To trigger the web service we use

EchoStuff.SayHello.send()">

which is tied to the button click event (it must have an event in order to trigger). The result can then be obtained using

EchoStuff.SayHello.result

Note that everything is case senstive so watch how you declare and make use of things within Flex. One of the interesting things I found was that if you get the case wrong when using mx:operation some odd things start happening. For example if you use.

<mx:operation name="Sayhello">

The web service method fires but the mx:request is not passed.

Develop Web services clients with Macromedia Flex

Flex the power of Web services by learning how to easily leverage them within a Rich Internet Application (RIA) using Macromedia Flex for a more complex, engaging, and interactive client-side experience. RIAs are an evolution of the traditional Web page based model for Web applications. A big part of the attraction in using Flex for RIA development is the speed and ease with which you can leverage Web services in your applications. The authors walk you through several examples and simplify how sometimes confusing WSDL constructs map to Flex declarations.

Introduction

Open standards are being embraced by enterprises as a means to drive down high integration and maintenance costs. The reality of today's heterogeneous software systems is that it is imperative to employ some strategy involving open standards, and Web services are quickly becoming an important piece to this puzzle. Up until now it has been quite tedious and cumbersome to build rich GUI clients to interact with these systems. Part of the problem is that Web Services Description Language (WSDL) tends to be the only description of the service endpoints, and it can sometimes be difficult to follow (even more so for the designers and user interface developers within the organization). Flex is a Rich Internet Application platform by Macromedia that bridges this distinct gap between user interface designers and the more traditional server-side developers. Traditional back-end programmers can leverage an extensive set of visually appealing controls, effects, layouts, and existing Flash components, together with their in-depth knowledge of the service endpoints, to put together an attractive client application. A designer can use these same facilities and leverage their creative skill set to build a comparable client, while shielded from complex service definitions. The end result, no matter what type of resources are available to your project at any given time, is the ability to easily create a highly interactive and engaging application that integrates your investment in Web services.




Understand WSDL

Flex uses existing WSDL definitions by referencing a URL where the document is located, in order to exchange messages between SOAP service endpoints (SOAP messaging in Flex is constrained to only use HTTP as the transport mechanism). The following elements are commonly found within a WSDL document:

Table 1. Common WSDL Elements

Element Description
types Defines data types that a Web service's messages can use.
message Defines the data that a Web services operation transfers.
portType Defines one or more operations that a Web service provides.
operation Defines a combination of input, output, and fault messages.
input Specifies a message that a client such as a Flex application sends to a Web service.
output Specifies a message that a Web service sends to a client such as a Flex application.
fault Specifies an error value returned as a result of a problem processing a message.
binding Specifies the protocol used to communicate with a Web service. Bindings exist for SOAP, HTTP GET, HTTP POST, and MIME. Flex supports the SOAP binding only.
service Defines a collection of ports. Each service maps to one portType and specifies different ways to access the operations in that portType.
port A Web services endpoint that specifies an association between a binding and a network address.

It helps to have a general idea of how these elements come together in a WSDL document to define various Web services and what they mean. Flex however tries to hide the complexity of the service definition from the developer, and for the most part it is sufficient to have a basic understanding of what functionality the service is to provide.

It is also important to point out that WSDL provides two very distinct styles of describing service operations: Remote Procedure Call (RPC) and document-oriented styles. A Flex call to a RPC service operation sends a SOAP message specifying the operation and wrapping its respective arguments. A Flex call to a document-oriented operation sends a SOAP message that encapsulates an XML document. Flex provides support for both, but the subtle differences between the two have implications as to the specific mark-up tags used. This paper walks you through various examples of these two styles in more detail in the examples below.




Use Web services in Flex

The basis for declaring a Web service within your Flex application is to use the <mx:WebService> MXML tag (XML tags prefixed by mx are part of the MXML namespace and are used to construct an MXML file). Typically you associate a wsdl attribute with this tag, and this points to the referencing WSDL URL. Flex provides a named service construct that moves some of this declaration to a specific block in the flex-config.xml document. The Flex documentation covers the use of named services in more detail. It also helps to use an id attribute with the Web Service in order to refer to it throughout the MXML application.


<mx:WebService id="serviceID" wsdl="http://somehost/someService/service.wsdl; <mx:operation name="someOP" result="someResultHandler()"fault= "someFaultHandler()"> <mx:request> <!-- parameters --> </mx:request> </mx:operation> </mx:WebService>

A corresponding ActionScript serviceID.send() call now invokes this Web services functionality. It is important to point out that when using the send() method with no parameters, all parameter binding should be defined within the actual Web services definition. In other words, parameter binding is implicitly associated using an XML data model within the <mx:request> tags.


<mx:WebService id="serviceID" wsdl="http://somehost/someService/service.wsdl; <mx:operation name="someOP" result="someResultHandler()"fault= "someFaultHandler()"> <mx:request> <param1>{input1.text}</param1> <param2>{input2.text}</param2> </mx:request> </mx:operation> </mx:WebService>

The other way of binding parameters to this service call is to explicitly pass them. A corresponding call that explicitly binds parameters looks like serviceID.send(input1.text, input2.text) , where it is no longer necessary to use the XML data model within the MXML declaration as previously described.

You have now seen the mechanism for invoking a Web service from a Flex application, but how do you process the results? Taking a closer look at the declaration above, you will notice a result and fault attribute on the <mx:operation> tag. These reference ActionScript methods to process the results and handle any faults your service call may have. The point to make here is that the invocation of your service as described above is an asynchronous call. This is an important difference to note since you are probably used to the case where a return from a method call implies that its work has finished completely. In your Flex application, statements that are defined after send() immediately executes without waiting for a return from the Web service. The application is able to process the results of the service call when the result handler (referenced in the operation attribute) is notified that the Web service has finished execution. In the case that there were some error, the associated fault handler is notified instead.

Hopefully you are getting a clearer picture of how integrating your Web services can be less tedious using the Flex environment. We now walk you through some examples describing the WSDL-specific MXML tags contained in the Web services declaration that we did not discuss in this section.




WSDL to Flex mapping by example

About the examples

The following examples cover different ways of defining SOAP-based Web services operations using WSDL, as well as how the WSDL definition maps to MXML's Web services constructs. We mentioned in the previous section that Web services can be declared in MXML using a parameter binding mechanism. This means that the parameters of the operation are included as part of the Web services declaration (within an XML data model) as follows:


<mx:WebService> <mx:operation> <mx:request> <!--parameters here--> </mx:request> </mx:operation> </mx:WebService>

The <mx:request> element inside the <mx:operation> element contains a mixture of XML and Flex Bindings necessary to construct the content of the message's SOAP Body.

The WSDL files used in the examples were automatically generated using IBM® WebSphere® Application Developer V5.1 Web Services Wizard (This Wizard and WebSphere Application Server WebService support are based on JSR 109). The Wizard generates the WSDL file, type mappings, serializers, and configuration entries required to host the Web Service in WebSphere Application Server V5.X (We used V5.1). Although there are multiple ways of declaring Web Services using WSDL, the following examples emphasize the set of WSDL definitions that are generated by this tool.

We begin by describing the mappings between the WSDL definition and the MXML Web services declaration that are common to any WSDL file. These include MXML elements and attributes which values are independent of the specific SOAP binding settings. Then, more complex mappings are explained, which depend on the operation style (Document or RPC), encoding mechanism used (literal or encoded), type (simple or complex) of parameter, and number of parameters.

Common mappings

The first step in declaring a Web service using MXML is to select the Web services WSDL definition. You can do this by setting the wsdl attribute of the <mx:WebService> element to the URL of the WSDL file (Newer versions of Flex allow you to lookup the WSDL URL by using the name of the service). Then you select the target service and port by setting the service and port attributes of the <mx:WebService> element. shows you where to find the values of these attributes in the WSDL definition.

mor info: http://www.ibm.com/developerworks/webservices/library/ws-macroflex/

Related Flex Tutorials