Using Adobe Flex in Visual Studio

One of the announcements from Adobe’s recent annual developer conference that should be of particular interest to .NET developers is the release of a free plug-in for Microsoft Visual Studio, which provides support for building rich Internet applications (RIAs) using Adobe's Flex framework. The release of the Ensemble Tofino plug-in will be important to the many enterprise development teams that have standardized on Visual Studio as their primary integrated development environment (IDE), but who want to take advantage of the ubiquitous Flash Player for deploying a RIA.

In this article we will look at what the Flex framework is and how to get started building an application in Visual Studio 2008.

Why use the Flex framework?

With increasing end-user expectations in relation to the quality, expressiveness and performance of web-based applications, developers need to focus more attention on the “richness” of the user experience. Whilst AJAX-style techniques can be used to enrich the user interface, plug-in based technologies such as Flash Player, and more recently, Silverlight, are extending the capabilities of the browser, to offer media playback, enhanced graphics and faster code-execution performance.

Traditionally, making use of the Flash Player meant using Adobe’s design tools, such as Flash Professional, to create interactive content. With the introduction of Flex, a free, open source framework for creating rich Internet applications, developers can now build and deploy web applications that leverage the existing installed base of Flash Player (installed on 98% of Internet-connected computers), and from the same codebase, deploy desktop applications using Adobe’s AIR runtime – both of which work consistently on Mac, Windows and Linux operating systems.

The Flex framework aims to make it easier and more productive for developers to build RIAs, providing two core languages - MXML, an XML mark-up language for declarative UI layout and ActionScript, a fully object oriented language, used for handling interactivity, events, data management and other client-side business logic.

Flex provides a comprehensive library of components and classes that can be used to accelerate RIA development – this includes visual controls, containers, navigators and charting components, as well as providing support for component skinning, internationalization, rich media streaming, data binding and interaction with RPC and messaging services. Check out the Flex Language Reference (http://livedocs.adobe.com/flex/3/langref/) to get a feel for what’s included in the Flex framework.

Most Flex developers today utilize the Eclipse-based Adobe Flex Builder tool, for developing, debugging and deploying rich Internet applications (RIAs). For developers committed to Visual Studio, Ensemble Tofino offers a .NET specific solution, making it possible to leverage the power of Flex within a .NET application environment.

What do I need to start working with Flex in Visual Studio 2008?

The only thing that you need to do to enable Flex development within your Visual Studio environment is to install the Ensemble Tofino plug-in, available free from http://www.ensemble.com/. At the time of writing, the plug-in is in an early stage of release, and currently includes the ability to create, compile and debug applications. Future releases of the plug-in will support intellisense and other code editing features typically found in the Visual Studio environment; over time it is likely that more of the features found in Flex Builder will be made available in the plug-in.

Note that you may be required to install a version of the Java Runtime Environment before the plug-in will install; the installer will provide a link to the required download if needed on your system.

You might also like to download and unzip the Flex Language Reference from http://www.adobe.com/support/documentation/en/flex/, which, when used in conjunction with the Visual Studio object browser, is a quick way of bringing yourself up to speed on the syntax and APIs for the core Flex framework classes.

With the plug-in installed and the documentation at your fingertips, you can start building your first Flex app: in this article we'll walk through the process of building a simple application that makes a call to a stock quoting web service and presents the results back to the user. You could of course build such a simple application with HTML/AJAX – to see the types of applications that Flex can be used for take a look at the Flex Showcase at http//www.flex.org/showcase/.

Getting started

The paradigm of working with Flex is similar to that of creating a .NET project, and for most experienced developers, the process should be intuitive.

The first thing, as with any development in Visual Studio, is to create a new project - in this case making use of a new template that has been provided via the Ensemble Tofino plug-in.

When you create a new project (File > New Project) you will see a new project type: Flex. This will show you the three installed templates: Actionscript Application, Flex Project and Flex Library Project. For this tutorial, we are going to create a Flex Project, which means a project that makes use of ActionScript, MXML and the core component library of the Flex framework. Name the project 'StockTool' - we will also use the same name for our compiled solution, but you could of course choose a different one.

Project Creation Options

Figure 1 - Project creation options

In the solution explorer, you will see that a number of folders have been created: these are the folders that a Flex Project uses to build and deploy the solution.

Flex development environment, including the Solution Explorer

Figure 2 - Flex development environment, including the Solution Explorer

The first – src – is where the code that you write will be placed, this includes all the MXML (.mxml) and ActionScript (.as) files. In Flex you create your custom components as classes and reference them just as you would in .NET. This directory can also include any external assets such as images/video and data files that you might want to include in your project.

The second folder – html template – contains the template for the html wrapper, which your application needs to display in the browser. When a Flex application is deployed onto the web, it is wrapped up inside an html page that takes care of detecting whether or not the user has the correct version of the Flash Player installed and, if required, can prompt the user to update their Flash Player. It is fully customisable, allowing developers to add in custom JavaScript functionality. When you compile your application this wrapper is added to the deployed files, with updated parameters relevant to your application.

The final folder is the bin folder, which is where your compiled application resources will end up - the contents of which would be deployed to your web server.

OK. Time to get our hands dirty...

Take a look at the default code that has been created for you. The MXML template contains a single tag:

<mx:Application>

This is the defining container for the whole application that you will build. MXML is an XML based language, and as such uses namespaces, the main one of which – mx – is bound via the xmlns URI in the application tag and refers to the Flex framework classes.

Beyond that, the only thing that is specified is that the layout is 'absolute'. There are three layout modes in the Flex framework: absolute (which means that we can position components by x and y coordinates), horizontal (everything flows down the page horizontally) and vertically (everything flows vertically). To make our lives simple for this application, we will change the layout mode to horizontal so that we let the framework do the heavy layout lifting.

The first item that we want to put on the page is a text input control that will let the user type in the company symbol that they are looking for (e.g. ADBE, MSFT). The Flex framework provides us with a common set of controls for use in Flex applications; these can be accessed by targeting the mx namespace and then simply typing the control name - just as in .NET.

So here we go – your first lines of MXML:

<?xml version="1.0" encoding="utf-8" ?> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal"> 
    <mx:TextInput id="stockName" /> 
</mx:Application>

Note that components in MXML need ids (as in .NET) so that they can be targeted programmatically in ActionScript.

To see what the application looks like you will need to build the solution using the usual VS build menu. You will see the output window confirms the build has been successful.

------ Build started: Project: StockTool, Configuration: Debug Any CPU ------ 

Loading configuration file C:\Program Files\Ensemble Systems\Tofino\flex_sdk_3\frameworks\flex-config.xml 
created: C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\StockTool\StockTool\bin\StockTool.swf (250917 bytes) 
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========

Looking inside the bin folder, you should see the output that has been compiled for you. Double click the html page to open the wrapper page containing the compiled SWF that is your application.

first Flex application running in browser

Figure 3 - Your first Flex application running in the browser

In order to explain what the text input box is for, we need to provide some sort of explanatory label for the user. Flex provides a label control which you can drop in just above the text input – remember Flex is handling the layout for us because we have set out layout property of the application to horizontal.

<mx:Label id=”stockLabel” text=”please enter your company symbol”/>

The Ensemble Tofino plug-in provides complete error feedback for the Flex framework – try missing a quote mark out for example and then building the solution to see an example.

Now we need to add a button for the user and then set about wiring it up to some sort of service to get the information that we want. A button is created in the same way as the other controls we have seen so far …

<mx:Button label=”click for quote” id=”stockBtn”/>

Getting the data

A Flex application is essentially data agnostic; you can use data from Web Services, XML, Java, PHP, .NET and a range of other technologies, and then render the results within data-aware display components. In the case of our application, we are going to use the webservicex price lookup Web Service. The WSDL can be viewed at http://www.webservicex.net/stockquote.asmx?WSDL

The Flex framework defines various data components to make working with data easy: Remote Object (for mapping to server side classes, including .NET classes), XML, HTTP Service, and, as we are going to use here, the WebService component.

Once again, defining it is a simple matter in MXML:

<mx:WebService id="stockWebService" wsdl="http://www.webservicex.net/stockquote.asmx?WSDL" />

The Ensemble Tofino plug-in provides information about the core Flex classes in the Visual Studio object browser, so if you wish to see the methods, properties and return types that a particular class uses, the they are fully exposed here. They are grouped according to the swc in which the classes are contained (similar to zip files which contain related collections of packages). So, we can find all the properties of the WebService class inside rpc.swc.

Object Browser showing WebService class

Figure 4 - Object Browser showing the WebService class

We can now return to the Button and invoke the operation of the service that we are interested in: GetQuote. This call requires one parameter: the recognised symbol of the company that we want to look up. We will retrieve this in our application from the text property of the stockName text input field.

All that remains is to attach the call to an event (in this case click on the button). Note that we are accessing the service call in the same way that we access properties and methods of components, so we get the text property of the stockName field by stockName.text and we access the GetQuote method of the web service by stockWebservice.GetQuote.() Parameters are passed inside trailing brackets.

<mx:Button label=”click for quote” 
id=”stockBtn”
click=”stockWebService.GetQuote(stockName.text)” />

Debugging

Before we add any display element to the application to view these results, we want to check that data is being returned correctly, which allows us to see the power of the Flex debugger. In order to view the results conveniently, we will specify a result handler and a fault handler for the web service. These are called automatically when the Web Service fires the event in question.

<mx:WebService id="stockWebService"  wsdl="http://www.webservicex.net/stockquote.asmx?WSDL" fault="handleFault(event)" result="handleResult(event)"/>

If you try to compile now you will get an error, as there are no matching methods on the application. As mentioned above, methods are added to the MXML in ActionScript – we can write ActionScript in the current document, but we need to tell the compiler that there is a block of script coming and mark it up as CDATA. After that, we can just go ahead and add our methods, property declarations and imports.

<mx:Script>
<![CDATA[
    	//import the classes that we will use 
    	import mx.rpc.events.FaultEvent;
    	import mx.rpc.events.ResultEvent;

    	//handler function for successful call to web service
    	private function handleResult(ev:ResultEvent):void {
    		//result code goes here
    	}

    	//handler function for failed call to web service
    	private function handleFault(ev:FaultEvent):void {
    		//fault code goes here
    	}

]]>
</mx:Script>

Its important to note that when these two functions are called they each receive a different type of event object, but we don't have to create those ourselves as its all built into the framework: they are dispatched with the data we need when the Web Service receives a result or throws a fault.

Debugging is simple, but first you need to make sure that you have the debug version of Flash Player installed - this can be downloaded from http://www.adobe.com/support/flashplayer/downloads.html.

You can debug your application by adding a breakpoint on the closing brace of both functions and clicking the debug icon. Type in your stock symbol name and press the button in the application; a call will be made to the Web Service and either a fault or a result will be returned (hopefully the latter). Visual Studio should then bring up the locals panel for you to see the object that has been returned.

The locals panel showing the fault event object

Figure 5 - The locals panel, showing the fault event object

The locals panel showing the result event object

Figure 6 - The locals panel, showing the result event object

There is a huge amount of information here and the exposing of all these objects makes debugging simpler and – therefore – application development quicker.

Now that we are satisfied that we are getting the required data we can display it using any of the data-aware controls available in the Flex framework, or indeed any custom controls we create.

Binding the result

Flex allows us to bind data from our data sources to a component. The framework handles all the necessary notifications and updates, all we need to do is define a control and bind the property that we actually want to display. Add a text control to the application, and set its text property to be bound to the lastResult property of the GetQuote service of our web service. We define data binding by wrapping the data property in braces ({}) as follows:

<mx:Text text=”{stockWebService.GetQuote.lastResult}” width=”200”/>

You should see the xml that is returned from the web service in response to your call invocation. This data could now be used to populate any of the Flex components or manipulated via ActionScript.

Controlling the visual look with CSS

Finally, we can add a style sheet to change the look of the application. The Flex framework supports a subset of CSS, allowing both class and selector level styles to be created. In order to create one, simply add a file to your project (File > Add file). You will see that there are a large number of file types available which all feed into the Flex application - select CSS and a create a file named styles.css. We'll create a simple rule that is applied to the Application class and all its children:

/* CSS file */ 
Application 
{ 
    background-color:Olive; 
    font-family: Arial; 
    color:White; 
    font-size:14; 
}

Now we just have to apply this style sheet to the application by using the tag inside the MXML page:

<mx:Style source="styles.css"/>

The application is now complete and can be rebuilt and tested.

Now that you’re setup to develop and build Flex applications using Visual Studio, I’d recommend that you head over to the Adobe Developer Connection website and follow the ‘Learn Flex in a Week’ video tutorials – these tutorials will provide you with everything you need to build more complex Flex applications.

If you have enjoyed this article and want to know more, look out for a follow up article on Developer Fusion. In addition, the links below form a valuable resource for anyone wishing to learn Flex.

Adobe Developer Centre - http://www.adobe.com/devnet/flex/ Learn Flex in a Week tutorials - http://www.adobe.com/devnet/flex/videotraining/ Learn Flex and .NET - http://www.adobe.com/devnet/flex/flex_net.html

You might also like...

Comments

About the author

Matt Wicks United Kingdom

Matt Wicks is a freelance developer, trainer and consultant. His clients have included BBC, The Guardian, The Ministry of Defence, The UK Fire Service, NICE, Adobe and hundreds of others. He has...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It works on my machine.” - Anonymous