setting the context traditional programming techniques • oop (c++/c#/java)

80

Upload: api-10856936

Post on 12-Nov-2014

86 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)
Page 2: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

Setting the ContextSetting the Context

Page 3: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Traditional Programming Techniques• OOP (C++/C#/Java)

• Old-School Declarative (SQL + HTML)

• Scripting (Perl, JavaScript, etc.)

• Other Traditional Programming Techniques

Page 4: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Mixed-Language Programming Techniques• Active Server Pages (HTML + VB or JScript)

• Java Server Pages (HTML + Java)

• DHTML/Ajax (HTML + JavaScript + XML)

Page 5: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Client-Side/Desktop Applications• Compiled to the OS

• Usually full access to local disk

• Sometimes connect to external network

• Sometimes connect to databases

• Sometimes use other web services

Page 6: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Traditional Browser-Based Applications• Coded to work across multiple browser versions

• Usually static UI or some simple movement

• Usually screen refresh with each data post/update

• Problem: different browsers = different JS

• Problem: different same browser on different OS = different/missing behavior

• More complex GUIs = spaghetti code (DHTML/Ajax)

• Client is “stateless” (data comes and leaves with the UI)

Page 7: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

RIAs: A New Type of Application• Web based

• Client is “stateful” (Data is independent from the UI)

• Runs within a mini-OS running within a browser

• Since the OS is always the same, it doesn’t matter what browser you’re in.

• Code once, run anywhere

• Animation, fluid-transitions very easy

• No screen refreshes required for data posts/updates

• Feels like a traditional “desktop” application

• Still limited to “sandbox” provided by browser (ie, not much local access of devices, disk, etc.)

Page 8: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

RIAs: New Programming Languages• DHTML/Ajax (but get spaghetti code)

• Flash with HTML & JavaScript

• Flex

• SVG + JavaScript (clunky, no good players)

• Microsoft’s WPF/E

• XUL, XForms, XBL, etc.

• Laszlo Systems

• XML, Web Services, REST, etc.

Page 9: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

RIAs: New Techniques• Much more emphasis on “user experience” and visuals

earlier in the development cycle (because much of the work is in the realm of the desktop part of the app)

• Multi-Language development on the client (declarative + procedural)

• Design and development of “choreography”/”transitions” between UI states.

• Integration of artwork into UI choreography

Page 10: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

RIAs: More New Techniques• Offload much of the UI-centered processing from a web

server back onto the client.

• Plan for requirement of both a “backend” piece and a “client” piece – nor more “thick” client applications with no “back ends”.

• Customers can have updated versions of software delivered to their browser by simply clicking on the URL for your app. (Like automatic upgrades of your app)

• Consider leveraging the “cookie cache” for some offline storage

Page 11: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

Flash Programming ModelFlash Programming Model

Page 12: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Programming with a timeline

Page 13: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Layers within the timeline

Page 14: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Timelines within timelines (Movies within Movies)

Page 15: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Applications live on a single frame

Page 16: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Main Actors in a Flash application

• Graphics

• Movie Clips

• Buttons

• Code (ActionScript)

Page 17: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Main Actors • Graphics

• These are jpg’s, gif’s, png’s, and vector images

• Don’t respond to events.

• Don’t contain Code

• Think of these like you would background images in a web page

Page 18: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Main Actors • Movie Clips

• Have frames (as in frames of a movie)

• Can respond to events and user gestures

• Can contain Graphics, Buttons, Code, and other Movie Clips

• Are the “base class” of all interactive elements within Flash applications.

• Can contain Code

Page 19: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Main Actors • Buttons

• Are a specialization of Movie Clips

• Have only 4 frames: up, over, down, hit

• Can contain Graphics and Movie Clips

• Can NOT contain Code

Page 20: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Main Actors • Code

• ActionScript is based on ECMAScript standard (v4)

• ActionScript 2.0 and 3.0 are strongly typed. ActionScript 1.0 is not.

• Code housed within a FLA file (not an external file) can behave like ActionScript 1.0 – weak typed.

• ActionScript supports OOP notions such as:

ClassesInterfacesInheritancePropertiesPolymorphism

Page 21: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Where Action Script Can “Live”• In a “Behavior”

1. Select an object on stage2. Go to Behaviors panel3. Enter parameters

• Into an object’s own ActionScript area1. Select an object on stage2. Go to the Actions window3. Enter event handlers using ActionScript syntax

• In a “keyframe” of a MovieClip (like a module/file in C)

• In an external “.as” file as code #imported into the FLA

• In an external “.as” file containing the definition of an ActionScript class. (Use “new” operator to instantiate.)

Page 22: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Available ActionScript Classes

• Flash has a built-in library of ActionScript classes

• Some are same as in JavaScript, such as: String, Array, and Number

• Some are APIs you use to communiate with the Flash Player, such as: Stage, System, and MovieClip

• Many for Drawing: BitmapData, GlowFilter, Matrix

• Networking APIs: LoadVars, FileReference, WebService

• Application Widgets: Button, ComboBox, Accordion

Page 23: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Creating Your Own AS Classes

• Use ActionScript like you would any other OO language, such as C#, Java, or C++.

• Create Singletons, Events, UI “Controllers”, Business Logic, Data Models, and Data Access

• Organize your classes into packages for cleaner code

• If you want to create your own custom components (like built in ones such as TextField, ComboBox, etc.), you need to use ActionScript

Page 24: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Custom Components

• Can be used to build applications just as the built-in classes are

• Are ActionScript classes that implement a specific interface

• Use Graphics and/or Code and/or other Components as their “skins”

• Are NOT! Instantiated with the “new” operator. Instead: this.attachMovie(“CircleComponent", "circle1_mc", this.getNextHighestDepth());

• Must be explicit coded to support event listeners

Page 25: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Stacking / Z-Order

Page 26: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Stacking / Z-Order

• By default, layers you create define Z-Order

• Within each layer, there is Z-Order based on when object was dragged onto the stage

• Components created within the IDE have a lower Z-order than those you create dynamically using ActionScript

• You can swap depths, make a component the top, etc.

• Functions:• getNextHighestDepth()• getDepth()• swapDepths ()• attachMovie ()• createEmptyMovieClip ()• etc.

Page 27: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Built-In Application Support

• Form, Screen, Slide

• Flash IDE will allow you to switch into “Application” or “Slide Show” development mode

• I never figured out how to use these!

• I basically do this:• The main timeline has a single frame where the app sits for its entire run• There are many layers containing widgets, code, etc.• There are many component/library Movie Clips that do the work• There are AS classes to encapsulate the code

Page 28: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Other Built-In Application Support

• Events

• Simple Drag & Drop Support

• Classes & Instances of those Classes

• Components

• Library of Classes used by the application

• DOM API for XML Data

• Built-In Widget Components

• Network Access Components

Page 29: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Built-In Widget Components

• TextField, TextFormat, TextInput, TextArea,

• ComboBox, CheckBox, RadioButton, List, DataGrid

• Alert, Window

• Accordion, ProgressBar, ScrollPane, Menu, MenuBar

Page 30: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Network Access Components

• XML, XMLSocket

• WebService, WebServiceConnector, SOAPCall

• LoadVars

• NetConnection, NetStream

• Sound, Video

• Etc.

Page 31: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Oh Yea…

• There are drawing tools too!

Page 32: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

Flex Programming ModelFlex Programming Model

Page 33: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Just One Layer & One Frame

• No concept of a layer

• No concept of a timeline

• Is, however, the concept of time:

Which is used to animate things around the screenAnd is used for “Timer” objects that periodically “ping” callbacksSo there are Flex objects that use the timeline, but you just never are aware

of it.

Page 34: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Flex Programming Model

• Flex is a layer on top of Flash. (You can always use the stuff you learn from Flash)

• ActionScript classes in Flex are a superset of Flash classes

• With Flex, you can express all, part, or none of your code in MXML.

• You can also express all/part/none in ActionScript

• Mixed-code programming style – like Active Server Pages (ASP) and Java Server Pages (JSP)

• MXML allows you to include script blocks within the XML or script can live in external files

Page 35: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

XML, ActionScript, CSS: Oh My!

• Use MXML to define the “structure” of the UI

• Use ActionScript to express any actions, procedural logic, conditional logic, etc.

• Use CSS to “parameterize” the MXML UI, specifying:Background colors and graphicsFont typefaces, font sizes, text colorAnimation effectsMargins, borders, etc.References to customized “skins” that are coded or assets from a SWF

Page 36: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Example Charting Application

Page 37: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Source Code<mx:Application xmlns:mx=http://www.adobe.com/2006/mxml fillAlphas=“[1,1]” backgroundGradientColors=“[0x707f7e,0x707f7e]”>

<mx:Script><![CDATA[

import mx.collections.ArrayCollection;

[Bindable]private var expensesAC:ArrayCollection = new ArrayCollection( [

{ Month: "Jan", Profit: 2000, Expenses: 1500, Amount: 450 },{ Month: "Feb", Profit: 1000, Expenses: 200, Amount: 600 },{ Month: "Mar", Profit: 1500, Expenses: 500, Amount: 300 },{ Month: "Apr", Profit: 1800, Expenses: 1200, Amount: 900 },{ Month: "May", Profit: 2400, Expenses: 575, Amount: 500 } ]);

]]></mx:Script>

<mx:Panel title="LineChart and AreaChart Controls Example" height="100%" width="100%" layout="horizontal">

<mx:LineChart id="linechart" height="100%" width="45%"paddingLeft="5" paddingRight="5" showDataTips="true" dataProvider="{expensesAC}">

<mx:horizontalAxis><mx:CategoryAxis categoryField="Month"/>

</mx:horizontalAxis>

<mx:series><mx:LineSeries yField="Profit" form="curve" displayName="Profit"/><mx:LineSeries yField="Expenses" form="curve" displayName="Expenses"/><mx:LineSeries yField="Amount" form="curve" displayName="Amount"/>

</mx:series></mx:LineChart>

<mx:Legend dataProvider="{linechart}"/>

<mx:AreaChart id="Areachart" height="100%" width="45%"paddingLeft="5" paddingRight="5" showDataTips="true" dataProvider="{expensesAC}">

<mx:horizontalAxis><mx:CategoryAxis categoryField="Month"/>

</mx:horizontalAxis>

<mx:series><mx:AreaSeries yField="Profit" form="curve" displayName="Profit"/><mx:AreaSeries yField="Expenses" form="curve" displayName="Expenses"/><mx:AreaSeries yField="Amount" form="curve" displayName="Amount"/>

</mx:series></mx:AreaChart>

<mx:Legend dataProvider="{Areachart}"/>

</mx:Panel></mx:Application>

Page 38: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Main Actors in a Flex application• Sprite and UIComponent

• Container classes (VBox, HBox, Canvas, ViewStack, etc.)

• Collections (Array, ArrayCollection, XMLListCollection)

• “Widget” Components & “Network/Data” Components

• Data Models (ActionScript & XML)

• View States

• CSS

• Skins

Page 39: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Custom Components• Can be written in ActionScript or in MXML

• Components you write in MXML are derived from other MXML components – either ones you have written or built-in Flex ones

• Components you write in ActionScript are derived from other ActionScript components you’ve written or from Flex ones

• Within ActionScript code you can use the “new” operator to instantiate new components. You can use this to instantiate components you’ve written in ActionScript as well as ones written in MXML

• Likewise, you can use your AS components within MXML by using an XML tag with the same name as the AS class.

Page 40: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

When to use MXML and when to use AS• Most of the visual Components I create are MXML components that derive from VBox or HBox.

• Sometimes create MXML components derived from other bulit-in MXML components besides VBox or HBox

• I use ActionScript to create Singletons, “Skins” (for drawing the backgrounds of components), Business Logic, Data/Network access logic, custom Events, etc.

Page 41: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

The Relationship Between MXML & AS• MXML components are written in XML. Flex compiles them into AS classes.

• When you have a <mx:Script> section within an MXML component, all that code gets included into all of the code for the AS class generated for that MXML component.

• Think of MXML as a peer with AS in the sense that they are two different languages you can use to specify what becomes compiled AS classes.

• MXML is more terse, but doesn’t have constructs for procedural logic, conditional logic, etc.

• AS is procedural. But if you created an entire Flex application in only AS, the code would be really long and complex.

Page 42: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Stacking / Z-Order

• No layers, no “depth” attribute

• Much simpler than Flash. Children are added to containers.

• Functions:• container.addChild (child), container.addChildAt(child,idx)• idx = container.getChildIndex(child)• container.getChildAt(idx)• container.setChildIndex(child, new index)• etc.

• Higher index == higher Z-order

Page 43: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

“Container” Components• HBox, VBox, VDividedBox, HDividedBox, Canvas, etc.

• Control the layout and positioning and sizing of children

• Containers can contain other containers

• “relative” and “absolute” layout.

• “relative” is like HTML flow layout. Uses % width/heights, literal width/heights, container layout logic

• “absolute” allows you to position/layout yourself. Can specify “x”, “y”, literal width, height, etc.

• “absolute” also allows for constraint-based layout (like, “position my left edge 10 pixels from the left of the screen”)

Page 44: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

When to use the Canvas (and “absolute”)

• The Canvas is the one container that contains no “relative” layout logic

• Use it when you want to create a component that has widgets on top of other widgets. (You can’t do this with VBox, HBox, etc.)

• Use it when you want to create a smooth scrolling “viewport” view on a larger page/screen.

Page 45: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Skins

• These are classes (and sometimes drawn grapical assets) that are used to create the visual representations of widgets and containers

• Some of the Flex-provided ones (used by flex components):• ButtonSkin• BusyCursor• HaloBorder• HaloFocusRect• ProgressBarSkin• ScrollThumbSkin• etc.

• “backgroundColor”, “backgroundAlpha”, “borderStyle”, etc. all are CSS values read and used by Skins during drawing.

• Skins are the “manifestation” of Flex components.

Page 46: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

CSS (“parameterization”)

• MXML is used to specify the structure of UI elements.

• CSS is used to specify the “personality” of the UI

• CSS is how you pass parameters to the Skins

• These parameters include information regarding: colors, borders, animation effects, etc.

Page 47: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

More about CSS

• CSS can exist “inline” within MXML XML declarations.

• CSS can live in an <mx:Style> tag within your MXML file

• CSS can live in an external *.css file that is imported into your application with an <mx:Style> tag.

• As you develop your application, the CSS moves from inline, to within the file in an <mx:Style> tag, to an external file.

• You are not limited to the out-of-the-box style names (such as “backgroundColor” and “borderStyle”). Can create custom styles that you use within your custom-coded Skins or even within other parts of your application.

Page 48: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

CSS Example<mx:Style>

Application {fillAlphas: 1,1;backgroundGradientColors: #707f7e, #707f7e;fontFamily:"Lucida Sans";fontSize:10;

}

.darkButtonStyle {fillColors:#000000,#000000;fillAlphas:1,1;themeColor:#707f7e;highlightAlphas:.7,.1;color:#FFFFFF;fontSize:20;textRollOverColor:#F0E249;

}

</mx:Style>

<mx:VBox width=“100%” height=“100%”><mx:Button label=“PressMe” styleName=“darkButtonStyle” />

</mx:VBox>

Page 49: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Yet more about CSS

• At runtime, you can change the style used by a component by changing the value of the “styleName” property.

• Can change/override individual CSS style parameters using the “setStyle” method:

myButton.setStyle ( “color”, 0xFF0000 );

• Can obtain the value of any parameter within any style by using the “StyleManager” class:

var myfontSize:Number =

StyleManager.getStyleDeclaration(‘darkButtonStyle').getStyle(‘fontSize')

Page 50: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Bindings

• They automatically set up an “observer” of a property. When the property changes, the observer receives an event and re-obtains the value of the property.

<mx:Script><![CDATA[

[Bindable]private var m_listData:ArrayCollection = null;

private function fillMyList () {m_listData = … fill with data.

}

]]></mx:Script>

…<mx:VBox width=“100%” height=“100%”>

<mx:List width=“100%” height=“100%” styleName=“myListStyle”dataProvider=“{m_listData}”

</mx:VBox>

Page 51: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Data “Model” Objects

• Client-side ActionScript classes

• FDS client-side ActionScript “proxy” classes

• XMLNode (DOM-style API)

• XML (E4X style API – is like DOM with XPath built-in)

• Arrays, ArrayCollection, XMLListCollection, etc.

Page 52: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Animation/Effects

• Can use MXML to do “declarative” animations

• Can use ActionScript classes to create and invoke the animations procedurally.

• Can invoke “declarative” MXML animations from within ActionScript.

• Can use XML to specify when declarative MXML animations should be invoked.

• Everywhere you can use a “declarative” MXML animation, you can also use one you created in ActionScript code.

Page 53: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Examples of “declarative” Effects

<mx:Fade id=“myFade” target=“{somewidget}” alphaFrom=“0” alphaTo=“1” duration=“1000” />

1) Single animation

<mx:Parallel id=“myParallel” target=“{somewidget}” duration=“500” ><mx:Fade alphaFrom=“0” alphaTo=“1” /><mx:Move xTo=“500” />

</mx:Parallel>

2) Concurrent/parallel animations

<mx:Sequence id=“mySequence” target=“{somewidget}” ><mx:Fade alphaFrom=“0” alphaTo=“1” duration=“1000” /><mx:Move xTo=“500” duration=“250” />

</mx:Sequence>

3) Sequential animations

Page 54: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

When Animation Effects are Called

• hide/show of a component

• hide/show a page in a ViewStack

• Tons of other places you can “declare” for an animation to run.

• Hand-coded calls to either declarative (MXML) or procedural (ActionScript) effects:

// Fade it in. myFade.play ();

Page 55: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Network Data Access Components

• FileReference, FileReferenceList

• NetConnection, NetStream, Socket, URLStream, XMLSocket

• WebService, SOAPHeader, Operation

• RemoteObject (FDS)

• HTTPService, AsyncToken

Page 56: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Everything is Asynchronous!!!

• Can’t code like you did with JDBC or ODBC or other synchronous data access APIs.

• Must build your entire application to deal with data asynchronously.

• A common design pattern has these parts:

• Model: (sometimes global) data that supports “binding” to it• UI: List, Grid, or other component that is “bound” to data• Data Access: Data provider (one of many network/data access components)• Code that “pokes” the Data Access component to get data:

accessToMyRemoteFile.send();

• Callback handlers to be invoked when/if errors occur and when data arrives. • Callback updates application Model.• Sometime later, the UI is populated with the data!

Page 57: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

One way to use the AsyncToken...<mx:HTTPService id="MyService" destination="httpDest" result="resultHandler(event)"/>...<mx:Script>

<![CDATA[...public function storeCall():void {

// Create a variable called call to store the instance// of the service call that is returned. var call:Object = MyService.send();

// Add a variable to the call object that is returned.// You can name this variable whatever you want.call.marker = "option1";...

}

// In a result event listener, execute conditional// logic based on the value of call.marker.private function resultHandler(event:ResultEvent):void {

var call:object = event.tokenif (call.marker == "option1") {//do option 1}else ...

}]]>

</mx:Script>...

Page 58: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

HTTP POST/GET Parameter Passing<!-- HTTP service call with an object as a send() method parameter that provides query parameters. --><mx:Button click="MyService.send({param1: 'val1'});"/>

<!-- HTTP service call with a send() method that takes a variable as its parameter. The value of the variable is an Object. -->

<mx:Script><![CDATA[

public function myFunction():void {// Cancel all previous pending calls.MyService.cancel();

var params = new Object();params.param1 = 'val1';

MyService.send(params);

}]]>

</mx:Script><mx:Button click="myFunction();"/>...

Page 59: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

A Web Service Call<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.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() {

// function implementation}

public function showErrorDialog(error:String) {// function implementation

}]]>

</mx:Script></mx:Application>

Page 60: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Flex Data Services• Not the same thing as Flex or Flex Builder

• Is an extra product you would use instead of a 3rd party back end such as standards-based web services, JSPs, ASPs, etc.

• Provides for an EJB-style coding style where the client code uses OOP code to access the back-end through client-side “proxy” objects with same “shape” as back-end objects.

• Data transfer is in a binary format (AMF) over HTTP or HTTPS

• You don’t need FDS if you use XML as your “model” data. I don’t use them currently.

• If you want strongly-typed business objects as your “Model” and your back-end is in Java, then FDS is for you!

Page 61: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

CairngormCairngorm

Page 62: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

What is Cairngorm?

• MVC framework for Flash and Flex RIAs

• A collection of design patterns that make sense for RIAs

• Both patterns and base classes that implement/enforce them.

• They call it a “microarchitecture” (smaller than a framework and larger than a single pattern)

• A starting point for your technical architecture that solves the problems as they have been solved successfully before

Page 63: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Addresses These Key Areas

• Handling user gestures on the client

• Encapsulating business logic and server interactions

• Managing state on the client and representing this state to the user interface

Page 64: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Core Principles

• Client is stateful. Your model should be a “real” model.

• Model should be in ActionScript objects with meaning, strong typing, etc.

• Don’t use opaque types like XML for your model.

Page 65: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Some Key Concepts

• Value Objects. (eg, Book, Author, ListOfAuthors vs. DataSet, ResultSet, XMLNode)

• They are strongly typed• They have “meaning• They abstract away the notion of what technology was used in the data tier

• Flex Data Services is optional

• If using FDS, can automatically generate AS Value objects from Java using XDoclet2

• Always use Bindings to connect model to UI

•“Model Locator” Pattern – an alternative to passing references to data into MXML components. Is the “model” that all of your UI “binds” to. Is a singleton.

Page 66: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

“Model Locator” Pattern• Is a pattern for storing/manipulating/using the “Model” of your application.

• The UI “Binds” to this model

• Is an alternative to passing references to data into MXML components.

• Is a singleton.

• Since it is global, can be found and written to from anywhere within the “hierarchy” of your Flex application.

Page 67: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

“Front Controller” Pattern• User gestures (mouse down, drag-drop, etc.) and system- generated events are all translated into Cairngorm events.

• Any time any gesture or event wants to execute business logic, the application fires the appropriate event.

• “Command” classes execute the logic.

• Extending the functionality of the application is as easy as rewiring the relationships between event types and the Commands that service those events.

• “Front Controller” ties events together with their handlers.

• Singleton “Event Broadcaster” is like an application-wide event bus. Connects UI to Front Controller (s).

Page 68: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

“Service Locator” Pattern• Is a singleton.

• A single place where all of your network/data access points reside (HTTPService, WebService, RemoteObject, etc.)

• Serves up “model” objects to the rest of the application.

• Abstracts away from the application whether the back-end was XML, HTTP, Java/AMF/FDS, etc.

• When data is retrieved by a call to a Service Locator method, the “Model” is updated, and all bound UI elements updated from the data.

Page 69: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Where to get it

• Version 2.1 for Flex 2: http://download.macromedia.com/pub/labs/cairngorm/cairngorm2_1.zip

• Version 2.0 for Flex 2: http://download.macromedia.com/pub/labs/cairngorm/cairngorm2.zip

• Version .99 for Flex 1.5: http://download.macromedia.com/pub/labs/cairngorm/cairngorm.99.zip

Page 70: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

FlexUnitFlexUnit

Page 71: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Tester Application<?xml version="1.0" encoding="utf-8"?><mx:Application xmlns:mx="http://www.macromedia.com/2005/mxml" xmlns="*"

xmlns:flexunit="flexunit.flexui.*"creationComplete="onCreationComplete()">

<mx:Script><![CDATA[

import flexunit.framework.TestSuite;

// After everything is built, configure the test// runner to use the appropriate test suite and// kick off the unit testsprivate function onCreationComplete(){

testRunner.test = createSuite();testRunner.startTest();

}

// Creates the test suite to runprivate function createSuite():TestSuite {

var ts:TestSuite = new TestSuite();

// TODO: Add more tests here to test more classes// by calling addTest as often as necessaryts.addTest( TemperatureConverterTest.suite() );

return ts;}

]]></mx:Script>

<!-- flexunit provides a very handy default test runner GUI --><flexunit:TestRunnerBase id="testRunner" width="100%" height="100%" />

</mx:Application>

Page 72: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

package {

import flexunit.framework.TestCase;import flexunit.framework.TestSuite;

public class TemperatureConverterTest extends TestCase {

public function TemperatureConverterTest( methodName:String ) { super( methodName ); }

public static function suite():TestSuite {var ts:TestSuite = new TestSuite();

ts.addTest( new TemperatureConverterTest( "testToFahrenheit" ) );ts.addTest( new TemperatureConverterTest( "testToCelsius" ) );return ts;

}

/*** Ensures the celsius to fahrenheit conversion works as expected.*/public function testToFahrenheit():void {

// Test boiling pointvar celsius:Number = 100;var fahrenheit:Number = TemperatureConverter.toFahrenheit( celsius );assertTrue( "Expecting 212 fahrenheit", fahrenheit == 212 );

// Test freezing pointvar celsius:Number = 0;var fahrenheit:Number = TemperatureConverter.toFahrenheit( celsius );assertTrue( "Expecting 32 fahrenheit", fahrenheit == 32 );

}

/*** Ensures the fahrenheit to celsius conversion works as expected.*/public function testToCelsius():void {

// Test boiling pointvar fahrenheit:Number = 212;var celsius:Number = TemperatureConverter.toCelsius( fahrenheit );assertTrue( "Expecting 100 celsius", celsius == 100 );

// Test freezing pointfahrenheit = 32;celsius = TemperatureConverter.toCelsius( fahrenheit );assertTrue( "Expecting 0 celsius", celsius == 0 );

}

}}

A Test Suite

Page 73: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Class Being Tested

package {

public class TemperatureConverter {

public static function toFahrenheit( celsius:Number ):Number {return 0;

}

public static function toCelsius( fahrenheit:Number ):Number {return 0;

}}

}

Page 74: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

So Will FlexUnit Allow You To Test?• You can test individual classes with well understood states

• But a GUI?

• How would you use FlexUnit to test these?:Animation effectsCorrect display of icons, visuals, video, etc.Correct behaviour of UI elements (comboBoxes, lists, drag-and-

drop,etc.)

• You might want a combination of FlexUnit + other more sophisticated GUI-oriented testing tools

Page 75: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

Flex Lessons LearnedFlex Lessons Learned

Page 76: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Coding Workflow

1. Start with more/better articulated definition of the eventual UI look and feel. This must include “choreography” info.

2. Start with 1 big file, embedded CSS and ActionScript

3. Start to build AS classes you need

4. Start to move CSS into a <mx:Style> section

5. Start to break up big obj into components. This requires events sinks/sources.

This often leads to custom Event classes.It also leads to custom “Skin” classesUse local data in local *.xml files to begin with. Use this as an easy way to refine

the data model.Once the data model in the XML makes sense, can start to implement the back-

end RDBMS and other data stores

Page 77: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Other things

• Embrace use of CSS early, it makes your entire app more amenable to changes through time.

• Don’t forget how to code! The Flex examples are NOT good models for building “real/deep” applications.

• This is OOP. Use all the OOP techniques you already know.

• Remember that the desktop is NOT!!! your OS. Instead your app runs within a “virtual” OS.

• This OS is “sandbox” that includes both the Flash miniOS in the browser and the server-side code that the client uses.

Page 78: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

A

Other things

• Wait as long as possible to partition your app into tiny, individual MXML files.

• If you need to radically reorder the UI, it is much tougher to redo the many MXML files than work in a single file or a few large files.

• Wait as long as possible to “lock down” the data model. This allows you to be more flexible thru time. Gives more time to evolve/mature/improve the app in an iterative way.

• Learn to use XML APIs. XML is pervasive across modern technologies. The APIs are very easy to use.

• Use the XML as the application’s in-memory data “Model”

Page 79: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

Bring on the Demos!Bring on the Demos!

Page 80: Setting the Context Traditional Programming Techniques • OOP (C++/C#/Java)

Transitioning to The WorldTransitioning to The World of Flash/Flex Software Developmentof Flash/Flex Software Development

scott lane williamsUser Experience/XD Team

[email protected]