Click here to Skip to main content
Click here to Skip to main content

Introduction to Flex 4 and .NET Integration

, 7 Apr 2011
Rate this:
Please Sign up or sign in to vote.
The recipe provides clear step-by-step instructions for configuring a Flash Builder project to work with .NET backend. It reviews a basing .NET (C#) service and demonstrates how ActionScript code can be integrate with it using Flex Remoting API (RemoteObject).

Solution

The proposed solution uses Flash Builder version 4, RemoteObject API and WebORB to provide integration between Flex and .NET.

Detailed Explanation

This article describes the process of building a very basic .NET application and integrating it with a Flex client. The purpose of the article is to review the configuration steps required to create a client/server development environment when working with Flex and .NET. You will need the following software:

  • Adobe Flash Builder 4
  • Microsoft Visual Studio
  • WebORB for .NET v. 3.6.0.3 or higher

This article consists of the following sections:

  • Flex and .NET Integration Options
  • Project Description
  • .NET Service
  • Deploying .NET Code as Class Library
  • Deploying .NET Code as Web Site Project
  • Setting Up Flash Builder Project
  • Developing ActionScript Code
  • Final Steps

To get started install WebORB for .NET and verify the installation by opening WebORB Management Console. The console is available at the following URLs:

If there is a problem with installation or configuration, the console will display an error message.

Flex and .NET Integration Options

One of the first questions you might asking at this point is what is WebORB and why you need it to integrate Flex and .NET. Indeed, Flex supports several options for connecting the client-side with the server application. These options include XML/SOAP web services, integration through basic HTTP GET/POST requests and AMF Remoting. While each of these alternatives have its own pros and cons, the AMF Remoting provides the best performance as well as simplicity and speed of development. The performance factor is significant as Rich Internet Applications created with Flex require fast response times to avoid scenarios when users have to wait for a screen to update or a business transaction to be completed. (There is a live benchmark comparing performance of AMF/Remoting and Web Services) The speed of development is equally important as businesses strive to complete projects on time and beat the time to market.

Project Description

Since the article focuses on the subject of client-server integration between Flex and .NET, the application will be as simple as possible. The server side will contain a .NET class exposed as a remoting service through WebORB. The Flex side will use the RemoteObject API to invoke methods on the .NET service. To keep things simple, the service has one method - receiving and returning a string value.

NET Service

In this section you will learn about ways to expose a .NET class as a Flex remoting service. Consider the code below:

using System;
 
namespace WeatherServiceNamespace
{
    public class WeatherService
    {
        public Weather GetWeather(String zipCode)
        {
            Random randomValue = new Random();
 
            Weather weather = new Weather();
            weather.temperature = randomValue.Next( 100 );
            weather.humidity = randomValue.Next(100);
            weather.condition = WeatherCondition.SUNNY;
            return weather;
        }
    }
 
    public class Weather
    {
        public double temperature;
        public float humidity;
        public WeatherCondition condition;
    }
 
    public enum WeatherCondition
    {
        SUNNY, CLOUDY, RAIN, FOG
    }
}

The code shows 2 classes (WeatherService, Weather) and an enumeration (WeatherCondition). The WeatherService class will be exposed as a remoting service. Notice the class does not use any special interfaces or annotations. As long as it is deployed in WebORB, it will automatically become a remoting service. Once it is deployed, the public method in the class (GetWeather) can be accessed by Flex clients.

Deploying .NET Code as Class Library

There are two ways for deploying your .NET code. The easiest approach is to create a Class Library project in Visual Studio so the code is compiled as a .NET assembly. When you installed WebORB, the installer created a fully functional .NET application which you can use to deploy your code. The compiled assembly should be copied into the /bin folder of the WebORB application. If you use WebORB version 3, the bin folder is located at /inetpub/wwwroot/weborb30/bin. In case of WebORB version 4, the bin folder is at /Program Files/WebORB4/bin. Once the assembly is copied, you can verify it in the WebORB Management Console available at:

WebORB version 3: http://localhost/weborb30/weborb.aspx
Select 'Management', locate your assembly in the Services tab.

WebORB version 4: http://localhost/weborb4/weborb.aspx
Select 'Services', expand the '.NET Assemblies' node and locate your assembly.

If you decide to proceed with the Class Library approach, you can download a complete Visual Studio project for the WeatherService class.

Deploying .NET Code as Web Site Project

Another option for deployment is to create an ASP.NET Web Application project in Visual Studio. In that case all the code would be contained with the project and you would need to deploy WebORB into the project as well. Follow the instructions below to deploy WebORB into your Visual Studio Project:

Open Web.config in your project and add the following HTTP handler configuration to the <system.web><httpHandlers> element:

 <add verb="*" path="weborb.aspx" type="Weborb.ORBHttpHandler" />
 <add verb="*" path="codegen.aspx" type="Weborb.Management.CodeGen.CodegeneratorHttpHandler" />
 <add verb="*" path="dcd.aspx" type="Weborb.RDS.Handler.FrontEndHttpHandler"/>

For IIS7 deployments, also add the following configuration to <system.webServer><handlers>:

 <add name="weborb.aspx_*" verb="*" path="weborb.aspx" type="Weborb.ORBHttpHandler" />
 <add name="codegen.aspx_*" verb="*" path="codegen.aspx" 
    type="Weborb.Management.CodeGen.CodegeneratorHttpHandler" />
 <add name="dcd.aspx_*" verb="*" path="dcd.aspx" type="Weborb.RDS.Handler.FrontEndHttpHandler"/>

For detailed instructions on http handler registration see the following page: http://msdn.microsoft.com/en-us/library/46c5ddfy.aspx

Add the following files and folders from the WebORB installation to your project:
/weborb.config
/WEB-INF folder

to deploy WebORB console into your application (optional, but will be very helpful):
/console folder
/weborbconsole.html
/weborbassets folder

Add weborb.dll as a reference into your project

Compile and run your Web Application project. When the browser opens with your default page, navigate to the "/weborb.aspx?diag" page. If WebORB is deployed correctly to your site, you should see the WebORB diagnostics information. If you deployed the WebORB console, you can open weborb.aspx or weborbconsole.html.

Setting Up Flash Builder Project

This article assumes you are using Flash Builder to develop Flex applications. However, if you are using Flex Builder, you can read about setting up Flex Builder to work with .NET.

From Flash Builder main menu select New > Flex Project. In the "New Flex Project" dialog enter project name and select ASP.NET for the Application Server Type.

Click "Next >". The next step sets up the web server paths. This is an important step since Flash Builder will be using the path to deploy, run and debug compiled Flex application (for running and debugging, application will be loaded from the web server via http:// url).

Select "Use Internet Information Services (IIS)" in the Server section. If you installed WebORB for .NET version 3 enter paths in the Server location section as shown below:

Web application root: /inetpub/wwwroot/weborb30

Web application URL: http://localhost/weborb30

If you use version 4 of WebORB for .NET, the paths should be:

Web application root: /Program Files/WebORB for .NET/[VERSION OF WEBORB]
Web application URL: http://localhost/weborb4

The "VERSION OF WEBORB" is the name of the directory corresponding to the version of WebORB installed. For example, the web application root for version 4.1.0.1 will be : c:/Program Files/WebORB for .NET/4.1.0.1

The "Output folder" path is adjusted automatically.

Click the "Validate Configuration" button. Flash Builder should display a confirmation message at the top of the window as shown in the image above.

Click "Next >" and then "Finish" to finalize creation of the project. Flash Builder sets up a project and opens application's main MXML file. From the main menu open Project and select Properties. Click 'Flex Compiler' in the Properties window. Enter the following text in the "Additional compiler options":

If you use WebORB version 3:
-services c:/inetpub/wwwroot/weborb30/WEB-INF/flex/services-config.xml

If you use WebORB version 4:
-services c:/

/Program Files/WebORB for .NET/[VERSION OF WEBORB]/WEB-INF/flex/services-config.xml

Click OK to finalize project setup.

Developing ActionScript Code

Enter the following code in the application's main file. You can download complete MXML code listing and copy and paste from there:

<?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" 
  minWidth="400" minHeight="200"
 
  creationComplete="init()">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<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 temperature:Number = 0;
[Bindable]
private var humidity:Number = 0;
[Bindable]
private var condition:String;
 
private var remoteObject:RemoteObject;
 
private function init():void
{
remoteObject = new RemoteObject( "GenericDestination" );
remoteObject.source = "WeatherServiceNamespace.WeatherService";
remoteObject.GetWeather.addEventListener( ResultEvent.RESULT,
gotWeather );
remoteObject.GetWeather.addEventListener( FaultEvent.FAULT,
gotError );
}
 
private function getWeatherInZipCode():void
{
var zipCode:String = zipCodeField.text;
remoteObject.GetWeather( zipCode );
}
 
private function gotWeather( resultEvent:ResultEvent ):void
{
temperature = resultEvent.result.temperature;
humidity = resultEvent.result.humidity;
condition = resultEvent.result.condition;
}
 
private function gotError( fault:FaultEvent ):void
{
Alert.show( "Server reported an error - " + fault.fault.faultString
);
}
]]>
</fx:Script>
<fx:Declarations>
 
</fx:Declarations>
<s:HGroup width="100%">
<s:Label text="Enter ZIP code:"  paddingTop="5"/>
<s:TextInput id="zipCodeField" width="100" />
<s:Button label="Get Weather" click="getWeatherInZipCode()"
/>
</s:HGroup>
<s:HGroup width="100%">
<mx:Form width="100%">
<mx:FormHeading label="Weather From Server:"/>
<mx:FormItem label="Temperature:">
<s:TextInput editable="false" width="100" text="{temperature}"
/>
</mx:FormItem>
<mx:FormItem label="Humidity:">
<s:TextInput editable="false" width="100" text="{humidity}"
/>
</mx:FormItem>
<mx:FormItem label="Condition:">
<s:TextInput editable="false" width="100" text="{condition}"
/>
</mx:FormItem>
</mx:Form>
</s:HGroup>
</s:Application>

User enters a zip code in the Flex client application and clicks the "Get Weather" button. The button click results in a remote method invocation of the .NET service. The service returns a Weather object with information about the weather. The Flex client retrieves the data from the received object and updates the user interface through data binding.

The code uses the RemoteObject API to communicate with the .NET backend. The API provides Flex/.NET integration using the AMF protocol. Application declares remoteObject variable which will be used a proxy for the remote service. The initialization code in the init() function configures the remote object with a destination name, full name of the server-side class and callback events for the GetWeather method. The init() function is invoked through the creationComplete event.

It is important to understand the significance of the destination name used by the remote object. The "GenericDestination" used in the constructor of the RemoteObject provides a way to invoke server-side classes exposed by WebORB. The destination became "known" to the Flex application as a result of the configuration step made earlier when you referenced services-config.xml in the additional compiler arguments.

Final Steps

At this point your Flex application is ready to run. Click Run from the main menu in Flash Builder and select "Run WeatherApp". Additionally, you should try setting a few breakpoints in the code and run the application in the debugger. If you are new to remoting, stepping line-by-line through the code is a great learning exercise.

A copy of this recipe with some additional information including screenshots and code listings is available on the Midnight Coders side at:

http://www.themidnightcoders.com/products/weborb-for-net/developer-den/technical-articles/introduction-to-flex-and-net-integration.html

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

mapableuser

United States United States
No Biography provided

Comments and Discussions

 
QuestionIs it Possible to Bind .Net Web Service Results to flex xmllist? Pinmemberjeanlustria18-Jan-12 4:18 
QuestionWeborb PinmemberMahbeer27-Dec-11 2:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 7 Apr 2011
Article Copyright 2011 by mapableuser
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid