Flash programming

This article was originally published in VSJ, which is now part of Developer Fusion.
For .NET programmers the advent of Silverlight has been a talking point, even if you are not involved in an actual project using the technology. For many of us the possibility it offers of moving an application from the desktop to the web and perhaps even back again is interesting.

The biggest attraction is that, in theory, this is .NET technology and so you don’t need to learn anything. However, if you have been following any of the articles in VSJ on Silverlight then you will realise that this isn’t quite true and there are considerations and restrictions that make it more a “new” platform than you might initially believe. But any alternatives are so much more alien – a belief that might be stopping you looking outside of the box.

The obvious alternative to Silverlight is Flash, but if you have tried to “get into” Flash you have probably given up in a fog of new terminology and inappropriate marketing information. What is really amusing is to watch a .NET programmer try to find their way into Flash via any contact they might have with the web design department. Of course designers use Flash and have a “development” environment for it all set up and ready to go.

Only they don’t.

What they use is optimised to the production of animated graphics and multimedia extravaganzas. This is the better developed side of Flash – it is where it started – but it is not where you, as a developer, should start.

So here we take a look at the development environment that is Flash and see how it compares to Silverlight and .NET. You might be very surprised at how familiar it all feels once you approach it in the right way.

Screenshot
Creating a new project

Flash, Flex, ActionScript and AIR

First you need to know why Flash is so difficult for a developer to get into. Flash started life as a way of creating multimedia content, mainly animation, for web pages. As time went on it acquired a programming language – ActionScript – and an extensive framework – Flex. Although the name of the programming language makes it sound as if it was a niche language aimed at animation or special effects, ActionScript is a perfectly general-purpose language based on ECMAScript, aka JavaScript. In other words the chances are that you already know ActionScript.

Unfortunately if you try to use it via the standard Flash IDE – Adobe Flash CS4 – then you will have to look fairly hard even to find it. Adobe Flash CS4 is roughly the equivalent of Microsoft Blend, and you wouldn’t attempt to create a .NET project using Blend – well not anything even slightly complicated. CS4 does have buttons and other components, but the most prominent feature of the overall interface is an animation timeline and for most developers this just gets in the way. The correct place to start is to use FlexBuilder.

Flex is the ActionScript framework that provides all of the components and classes you need to build an application. FlexBuilder is an IDE that integrates ActionScript and Flex. To make things more complicated the latest version, 4 (currently in beta) has been renamed Flash Builder to rationalise the naming structure. In case you are wondering where “Flash” comes into it at all – this is the “player” that hosts the virtual machine (VM) that runs your application. This is the equivalent of the Silverlight add-on that runs .NET applications in a browser.

Finally there is AIR (Adobe Integrated Runtime) which can be used to run a Flash application on the desktop. You can think of AIR as being similar to the .NET runtime, but it came last in the development of things. Indeed you can see Flash as starting out by using the browser as a way to build animation and special effects and working its way to the desktop and a general purpose programming environment, whereas .NET started as a general purpose programming environment for the desktop and has worked its way to a browser add-in that can produce animation and special effects. This is the reason Flash is tough to get into for the developer and .NET hard to get into for the designer. There are some other issues however.

Perhaps the biggest hurdle for a .NET programmer in getting to grips with Flash is that FlashBuilder is designed as an Eclipse add-on. There is nothing wrong with Eclipse but it isn’t Visual Studio and it has its own sometimes strange ways of doing things. There is also the fact that it is sometimes idiosyncratic and often slow – a feature which causes it to appear even more idiosyncratic. However if you give it time you can grow to like Eclipse and it has the advantage that it has lots of add-ons for working with languages from Java, through JavaScript to PHP and more.

Despite the fact that Eclipse is free to download and oOpen source, FlashBuilder is a commercial product. You can however download it and use it for 30 days for free and this should give you plenty of time to find out if it is a suitable development environment. The examples in the rest of this article all use FlashBuilder 4 beta, but using the previous FlexBuilder 3 is very similar if not identical. You can either download the full standalone version or an Eclipse add-in. Clearly if you have Eclipse already installed then the add-in is a good choice but even in this case the standalone application has the advantage that it “just works” and can be removed in one easy step if you decide that you really don’t want to use it.

Screenshot
Select your project type

Hello Flash

As with all new languages and environments, the best way of getting started is to write the simplest possible program – hence “hello world”. If you download and install FlashBuilder 4 it starts off configured ready to create all types of Flash projects. The simplest option is to create a Flex project – which can contain multiple applications – but for the moment we will concentrate on just one. Create a new Flex Project called Hello World.

While you are creating your first project you should look at some of the alternative types on offer – you should be able to relate them to the sort of thing Visual Studio or any IDE creates. The New Project Wizard lets you target either the web, i.e. Flash Player, or the desktop, i.e. AIR. You might as well target the web in this first project and leave everything else at the default values.

When the new project Wizard has finished you can see the directory structure and the files it has created for you. The most important is the main.mxml file. As already mentioned MXML is the Flash equivalent of XAML. While MXML is often described as a markup language its better described as an object instantiation language – again just like XAML. The designer takes MXML and coverts it into ActionScript statements that create objects described by the MXML and sets their properties accordingly. The advantage of this approach is that the MXML code is shorter than the corresponding ActionScript and it can be generated by the designer.

To see this in action select the file main.mxml and select the Design tab. The designer is a full drag-and-drop editor and you can see a range of controls and other components listed in the Components window – bottom left. If you now drag-and-drop a button onto the design area you will be able to customise it by positioning it, resizing it and changing any of its properties in the Properties window – bottom right. If you have used any drag-and-drop designer then you will have no problems using this one.

If you switch back to the Source tab you should find that the following MXML has been generated:

<?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="1024" minHeight="768">
	<s:Button x="45" y="33"
		label="Button"/>
</s:Application>
There are two objects specified by the MXML – the Application and its single child object – a button. If you are familiar with HTML or any XML markup language then this should seem easy to follow. However it is worth being clear that the MXML is an object creation language and when it is compiled it is exactly equivalent to ActionScript creation and customisation of those objects. If you don’t want to use MXML you don’t have to and this is an exact parallel with XAML.

Our next task is to add some code. In most cases the code that you add is going to be in a separate ActionScript file but, you can add “inline code” or “code blocks” within the MXML. The designer will automatically generate a click handler for you. Simply right-click on the button and select Generate Click Handler. This modifies the MXML button tag to read:

<s:Button x="45" y="33"
	label="Button"
	click="button1_
	clickHandler(event)"/>
…which specifies a click handler in much the same way as in HTML or XAML. An inline code stub has also been added:
<fx:Script>
	<![CDATA[
		protected function
			button1_clickHandler(
			event:MouseEvent):void
		{
			// TODO Auto-generated method stub
		}
	]]>
</fx:Script>
Clearly inline code isn’t the way to build large applications but it is also supported in HTML and in XAML. To turn this into our Hello World program we can simply make use of the Alert object – which is similar to the Alert function in JavaScript:
<fx:Script>
	<![CDATA[
		import mx.controls.Alert;
		protected function
			button1_clickHandler(
			event:MouseEvent):void
		{
			Alert.show("Hello Flash World");
		}
	]]>
</fx:Script>
If you right-click and select Content Assist while typing you will be offered choices that you can select to complete the command – this is equivalent to Intellisense prompting. Using Content Assist to add code has the advantage that it automatically adds, or checks that you have, the necessary import statements to use the class that you have just referenced.

Now we can run the program and see how it works. Eclipse has a complicated or sophisticated (depending on your view point), system of debug/run profiles that, once you get the hang of using them can save a lot of time. In this case the easiest way to run the program is to simply Run or Debug Main from the Run menu or click on the “bug” icon in the toolbar. In a few moments a browser should open and display the button and if you click the usual message. If there are any errors they will be flagged in the Problems tab at the bottom of the screen and you can fix them and try again.

Notice that by selecting an AIR project type the example could be run as a desktop application. Currently there seems to be no facility for re-targeting an application from web to desktop but you can use the import application command to achieve the same result.

You can now explore the range of controls and other classes provided by the framework. You will discover that it has everything you would expect and there are really no big surprises if you have used the .NET framework or Java Swing or whatever. Using Flex from this point on is a matter of exploration and there is very little that is totally new.

Debugging

Another range of facilities that are worth investigating at this stage are the debugging options. You have all of the usual tools to hand. You can set breakpoints, single step, step over and out, and examine and change variables as you inspect the code. There are lots of other useful Eclipse modules installed by default and you can download and install others. In particular you can profile your application and there is a full source control and bug tracking system. All of this is icing on the cake but don’t expect them all to work in a way that is familiar – they take time to adapt to.

Screenshot
The designer

Code behind

Now we come to a controversial topic in the Flash/Flex world – code behind. It seems that scattering code in code blocks within an MXML file is the way that many Flash applications are written. It has to be admitted that it has a simplicity that is difficult to beat, but most programmers, especially .NET programmers, would find the mix of markup and code difficult to accept.

The solution is to use code behind, i.e. keep the code in one file and the markup in another. This can be done but there are no facilities in FlashBuilder to help you to do this. What is surprising is that nothing in this area has been improved in FlashBuilder 4 and the reasons why aren’t entirely obvious. For example, there is no way of automatically generating an event handler in a code behind file – you either have to use copy and paste from the MXML file or do the job by hand. It also doesn’t support features like partial classes that make mixing generated and customised code much easier. This isn’t difficult but it might well be a big enough disadvantage for a .NET programmer to decide that this isn’t a well developed system.

If you recall, MXML is essentially a way to instantiate objects and set their properties. As such you really don’t need it any more than you actually need HTML or XAML. The entire job can be done in an ActionScript file by creating the objects and setting properties. Before looking at this approach let’s first migrate the Hello World example to a code behind configuration.

First add a new ActionScript class to the project – leave it in the default package and name it MyApp.as. Enter the following code, some of which will have been generated and some can be generated if you use Content Assist to select completions:

package
{
	import flash.events.MouseEvent;
	import mx.controls.Alert;
	import spark.components.Application;
	public class MyApp extends Application
	{
		public function MyApp()
		{
			super();
		}
		public function button1_clickHandler(
			event:MouseEvent):void
		{
			Alert.show("Hello Flash World");
		}
	}
}
This essentially the same code we had earlier but now it is within a new class that inherits from the Application class complete with a suitable method to act as an event handler. Notice that at this stage the event handler isn’t connected to any objects events.

The next task is to modify the MXML file. This starts off in the usual way but now we need to link the MXML file to the ActionScript file we have just created. As it is in the same “default” package it is in the same namespace and so we can make the connection using xmlns:my=”*” which means include everything in the project directory. If you want to be selective about what is imported you need to store the class in a subdirectory and specify it in the xmlns attribute. The whole MXML file is:

<?xml version="1.0" encoding="utf-8"?>
<my:MyApp xmlns:my="*"
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="1024" minHeight="768">
<s:Button x="45" y="33" label="Button"
	click="button1_clickHandler(event)"/>
</my:MyApp>
Notice that now the application is actually an instance of MyApp which includes the event handler we want to use. This is the general principle of code behind – create new classes and instantiate them using MXML. If you run the project you should find that it produces the same result.

The event handler is associated with the button in exactly the same way that it was in the inline code example. Many programmers are of the opinion that this should be done in code. This too is easy and allows us to examine how to access more generally the objects that MXML creates. The basic idea is that the link is via the id you assign to the component and a public variable of the same name in the action script. So if we give the button in the MXML an id of MyButton:

<s:Button x="45" y="33" id="MyButton"
	label="Button" />
…we need to create a public variable of the same name:
public var MyButton:Button;
It also needs to be declared as “bindable” but for the moment let’s keep things simple. We can’t simply start using the object because we can’t be sure that the MXML has been processed and the objects created. The solution is to override the initialise method and explicitly call the base class initialise – which ensures that all objects defined in the MXML have been instantiated and their properties set to the appropriate values. Following this we can be sure that all the objects exist and continue to customise them in code. In this case we simply use the addEventListener method to add the click event handler:
override public function
	initialize():void
{
	super.initialize();
	MyButton.addEventListener(
		MouseEvent.CLICK,
		button1_clickHandler);
}
If you now run the program again the result should be the same.

Screenshot
A first program – working

Working in ActionScript

At this point you might think why bother with the MXML at all? The final example demonstrates that you can do the entire job in ActionScript if you want to:
override public function
	initialize():void
{
	super.initialize();
	MyButton=new Button;
	MyButton.addEventListener(
		MouseEvent.CLICK,
		button1_clickHandler);
	MyButton.label="Hello";
	addElement(MyButton);
}
In this case we create the button object, customise it and add it to the containers display list, all in the initialise function. We are still using an MXML file to create the application but we don’t even have to do this, however but removing it entirely would be some additional work and wouldn’t illustrate any new ideas.

It is worth looking at ActionScript a little more as it is more or less the only language that you can use to develop Flash/Flex/AIR applications. While being closely modelled on JavaScript it is optionally strongly typed. Of course the paradox here is the use of the words “optionally” and “strongly”. For example, this is legal ActionScript:

var i=32;
Alert.show(i);
…and so is this:
var i:Number;
i=32;
Alert.show(i.toString());
Notice that if you declare a variable to have a type then explicit type conversion doesn’t happen so you need the toString call in the Alert.show method. Also it is worth saying that “Number” is something of a generality as far as typing goes! It is also a reflection of the fact that ActionScript doesn’t have very many numeric types – and in particular it lacks a decimal type which makes financial calculations difficult.

If you don’t want to declare the type of every variable you don’t have to, and but this might create problems in using the strongly typed framework. On the other hand dynamic typing is popular at the moment and this might make an alternative untyped approach more attractive.

ActionScript is also fully object oriented. It has classes, methods, get and set properties and inheritance. You have already seen the syntax for defining a class and inheriting from another, for example:

public class MyApp extends Application
{
…and creating instances is just a matter of using “new”. However, ActionScript is still a dynamic interpreted language and this allows classes to have methods and properties added at run time – something that is only just becoming possible in .NET languages with the help of the dynamic language SDK. Finally it’s also worth mentioning that there is no credible threading support in ActionScript. It does support and treat asynchronous calls as the norm but you can’t do manual threading. How important this is depends on the complexity, interactivity and size of your project.

Many would consider ActionScript to be superior to JavaScript while retaining many of its key advantages – it is also very possibly the future of JavaScript as it evolves towards the same ECMA standard. The big disadvantage of the entire Flex framework is that it is a single language framework. If for any reason you don’t like ActionScript then unless you are prepared to create another language to run alongside ActionScript using the same VM there is nothing you can do about it. You can use JavaSscript with the help of an intermediate script library but this is little different from ActionScript and not really well supported.

Flash or Silverlight?

Perhaps the biggest problem with Flash is that it has developed from a designer-oriented special effects platform. It is very usable as a general development environment but it still lags behind .NET in its range of support. For example there are few (, compared to .NET), third party libraries for Flex. It also suffers from not really being understood by Adobe which still seems to think that FlashBuilder is targeted at the designer who has managed to learn to code. However, the one thing that Flash has in its favour, and it’s not a small consideration, is that it is found on most web browsers almost as standard and it is well accepted by end users. The same cannot be said for Silverlight which, even though it has been downloaded an impressive number of times, is still not commonplace. It is true that most uses of Flash are trivial animations or special effects but it all contributes to its acceptance.

Looking beyond the browser you also have to take into account that a Flex AIR application can work on Windows, Linux and Mac platforms without modification. A Silverlight application, on the other hand, has to be converted to a WPF application to run on the desktop as a true desktop application – even though most of the code would be the same.

As you can tell the decision isn’t an easy one but even if you are a .NET programmer the choice for Silverlight is by no means obvious. For small to medium projects with a lot of design, animation and multimedia then Flash has a lot to offer and it is not the strange and alien land you might have once thought it was.


David Conrad, who has a background in photography and design, has worked in the graphics industry for most of his programming career, using C++ and now .NET.

You might also like...

Comments

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.

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” - Donald Knuth