Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET

Connecting Flex 4 with WCF Services

4.43/5 (4 votes)
7 Apr 2011CC (ASA 3U)4 min read 19.5K  
WCF and Flex provide numerous benefits for developing server-side functionality in .NET and implementing rich client applications with Flex/ActionScript. The question of integration between these two technologies comes up quite frequently as developers and business want to leverage the best the fram

Solution

There are at least two approaches for solving the problem. One is to use HTTP/SOAP binding in WCF to expose WCF services as Web Services. Flex client can connect to WCF using the WebService API. Another approach is to use AMF/Remoting on the Flex side and leverage the power of a remoting gateway on the server to communicate with WCF. The recipe review the latter approach using WebORB for .NET as the remoting gateway. WebORB is available as a free product in the form of Community Edition or commercially as Enterprise Edition. All the features described in the recipe are available at no cost in the Community Edition of the product.

Detailed Explanation

Integration Options - Web Services, AMF, etc.

Flex and .NET integration includes several options including web services, HTTP services and AMF Remoting. Each option has its own pros and cons. Specifically with WCF, the framework on the .NET side includes support for exposing WCF services as SOAP/REST web services. Since Flex has built-in support for SOAP web services, it is possible to integrate the client and the server environments using that approach. It is important to understand though that the integration through web services may have negative impact on application's performance as well as the development timeline (time to market). The impact is caused primarily due to the involved complexity and additional hand-coding the web services approaches may require. As for the performance impact, see the AMF/Remoting vs. Web Services comparison benchmark article. Based on our experience, the approach which provides the best application's performance and speeds up the development is the one based on AMF Remoting between a Flex client and the WCF services. An example of such integration is an architecture which includes an AMF remoting gateway between a Flex client and the .NET backend. A Flex client uses the RemoteObject API to communicate with the remoting gateway, which brokers requests to the backend WCF services. WebORB for .NET is an example of an AMF remoting gateway with solid, industry-proven track record.

Developing a WCF Service

In this article, you will develop a WCF service hosted in IIS. The service will be exposed as a remoting service which can be consumed by a Flex client using WebORB for .NET. WebORB will handle invocations of the WCF service and delivery of the invocation results back to Flex. A future article will review a similar integration where a WCF service is not hosted in IIS but is running standalone in the WCF's service host. To get started, follow the example reviewed on the following page to develop a sample WCF service: http://msdn.microsoft.com/en-us/library/ms733766.aspx. The service you developed should have the following source code:

C#
                using System;
using System.ServiceModel;
 
namespace Microsoft.ServiceModel.Samples
{
  [ServiceContract]
  public interface ICalculator
  {
    [OperationContract]
    double Add( double n1, double n2 );
    [OperationContract]
    double Subtract( double n1, double n2 );
    [OperationContract]
    double Multiply( double n1, double n2 );
    [OperationContract]
    double Divide( double n1, double n2 );
  }
 
  public class CalculatorService : ICalculator
  {
    public double Add( double n1, double n2 )
    {
      return n1 + n2;
    }
    public double Subtract( double n1, double n2 )
    {
      return n1 - n2;
    }
    public double Multiply( double n1, double n2 )
    {
      return n1 * n2;
    }
    public double Divide( double n1, double n2 )
    {
      return n1 / n2;
    }
  }
}

You can also download a Visual Studio project with the source code listed above.

The configuration file (web.config) for your service and web application should contain the following elements:

XML
                <?xml version="1.0" encoding="utf-8"
?>
<configuration>
  <system.serviceModel>
    <services>
      <service
name="Microsoft.ServiceModel.Samples.CalculatorService">
        <endpoint address=""
                  binding="wsHttpBinding"
                 
contract="Microsoft.ServiceModel.Samples.ICalculator" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

To complete the deploying of the server-side of the application, deploy WebORB into the created ASP.NET application where your WCF service is running. Make sure to include the WebORB management console into the deployment so you can verify the presence of your WCF service. To do that, navigate to "weborb.aspx" in your application, the console should open up. If you use WebORB version 3, select Management and locate an assembly with your WCF code in the services tab. If you use WebORB version 4, you should find your WCF service under the "WCF Services" node in the "Services" section.

Alternatively, you can create a class library with the source code shown above and deploy it into the default WebORB application created by the installer. Make sure to modify web.config with the configuration shown above.

Developing Flex Client

Create a Flex Project using Flash Builder as described in the Introduction to Flex with .NET integration article. Replace the contents of the default MXML application with the source code shown below. Also can download and use the full source code listing for the example.

XML
                                <?xml version="1.0"
encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/halo"
               creationComplete="init()">
  <fx:Script>
    <![CDATA[
      import mx.controls.Alert;
      import mx.rpc.events.FaultEvent;
      import mx.rpc.events.ResultEvent;
      import mx.rpc.remoting.RemoteObject;
      
      [Bindable]
      private var ops:Array = ["+", "-", "*", "/" ];
      private var wcfProxy:RemoteObject;
      
      private function init():void
      {
        wcfProxy = new RemoteObject( "GenericDestination" );
        wcfProxy.source =
"Microsoft.ServiceModel.Samples.CalculatorService";
        wcfProxy.addEventListener( ResultEvent.RESULT, gotResult );
        wcfProxy.addEventListener( FaultEvent.FAULT, gotError );
      }
      
      private function calculate():void
      {
        if( opList.selectedLabel == "+" ) 
          wcfProxy.Add( arg1.text as Number, arg2.text as Number );
        else if( opList.selectedLabel == "-" ) 
          wcfProxy.Subtract( arg1.text as Number, arg2.text as
Number );
        else if( opList.selectedLabel == "*" ) 
          wcfProxy.Multiply( arg1.text as Number, arg2.text as
Number );
        else
          wcfProxy.Divide( arg1.text as Number, arg2.text as Number
);
      }
      
      private function gotResult( event:ResultEvent ):void
      {
        result.text = event.result.toString();
      }
      
      private function gotError( event:FaultEvent ):void
      {
        Alert.show( "Server reported an error - " +
event.fault.faultDetail );
      }
    ]]>
  </fx:Script>
  <s:Panel y="10" height="258" width="405" x="10" title="WCF
Calculator">
    <mx:Form left="20" right="20" top="20">
      <mx:FormItem label="Argument 1">
        <s:TextInput id="arg1" width="100%"/>
      </mx:FormItem>
      <mx:FormItem label="Operator">
        <mx:ComboBox id="opList" editable="false" width="100%"
dataProvider="{ops}" />
      </mx:FormItem>
      <mx:FormItem label="Argument 2">
        <s:TextInput id="arg2" width="100%"/>
      </mx:FormItem>
    </mx:Form>
    <s:Button x="20" y="149" label="Calculate"
click="calculate()"/>
    <s:Label x="21" y="183" text="Result:"/>
    <s:Label x="69" y="178" id="result" />
  </s:Panel>
 
</s:Application>

The Flex client uses the AMF Remoting (RemoteObject) API to invoke the WCF service operations. This is not different than invoking regular .NET methods from Flex. On the server-side, when an invocation of a WCF operation takes place, the handling will vary depending on the version of WebORB installed:

With the version 3 of WebORB, the call processing will be the same as for a regular .NET assembly/class. However, the version 4 of the product automatically detects that the target service is a WCF service and includes special handling logic to accomodate WCF invocation handling pipeline. In that case, most of the WCF operation/class annotations will be included in the processing.

Serialization of invocation result values is handled the same way as with the non-WCF classes. WebORB serializes return values into AMF and delivers response back to Flex.

A copy of this article is also available on the Midnight Coders website.

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License