Andrei Kuzmenkov

May 3, 2010

Flex AdvancedDataGrid: Hierarchical View on Plain Data

Filed under: ActionScript,Flex,RIA — kouzmenkov @ 12:19 am
Tags:

Ever had to squeeze more info into a narrow grid of data? This is an example of adding one more dimension to otherwise plain data. Additional info about an object can be shown on the second (third, etc.) hierarchy level in ADG, but the original objects don’t need to be modified to support Hierarchical View. No need to have “children” field, the original objects remain plain.

Pictures first. A simple example with a data grid showing a list of ski resorts:

Collapsed list

And now click the node expand icon to see the list of tracks (random number) the resort has:Expanded list

The second level item renderer spans over all columns thus giving completely different layout to child data. The renderer consists of DataGrid and a Button, wrapped into a VBox. Resizing the first level columns resizes columns in all first-level rows. Resizing datagrids in second level doesn’t affect others unless the same renderer instance is being reused, which may happen with large lists. A possible workaround for that is to make renderers listen to column resizing events and update accordingly when the data grid gets resized.

Here is the working sample: http://orlamo.com/flex/plainhd2/PlainHD2.html

And the source code is here http://orlamo.com/flex/plainhd2/PlainHD2.zip

If there is interest I’ll write about implementation details later.

April 29, 2010

Flex: world of 32-bit integers

Filed under: .net,ActionScript,Flex,RIA,Silverlight — kouzmenkov @ 1:27 am
Tags:

Decision makers, be aware! One day your database may no more cooperate with Flex UI, because 64-bit (long) ID can’t be precisely presented in UI.

Also if the UI has to deal with money and even worth do calculations, take extra precaution! Flex has no embedded Decimal type. You may need to look for third-party implementations.
Or consider Silverlight, which has all embedded: 64-bit long and 128-bit 28-29 digits decimal.

Flex/ActionScript has 2 basic numeric formats: 32-bit int/uint and 64-bit Number.
Most likely for dealing with IDs UI developers choose Number. There is a chance they pick String, which costs more in space, conversion expenses and potential type safety issues.

Now to details and Math.

32-bit positive int has maximum value of 2147483647, uint 4294967295 (9-10 digits precision)
DB2 identifier uses 18-19 digits wide Long, so int isn’t good for IDs.

64-bit Number is based on IEEE-754-1985 standard, which reserves 52+1 bit for fraction (mantissa) presentation.
http://en.wikipedia.org/wiki/IEEE_754-1985
For whole numbers this means the practical limit of continuous presentation for whole numbers is 2^53=9007199254740992
This is 15-16 digits. Compare:
Max exact double:                9,007,199,254,740,992
Max +long:                   9,223,372,036,854,775,807

15 integer digits should be more than enough for hundreds years, but it may depend on business.
At the same time if by a chance a larger ID appears in the system, client will be broken.
If possible the database should have constraints on allowed ID values.
Otherwise IDs should be treated as String by Flex, which can bring performance and more importantly code reliability issues.

Try yourself in Flex:
var d:Number = 9007199254740992;
d += 1; // What is the result? 9007199254740993? No!! It’s still 9007199254740992!!!

Double can’t exactly represent 9007199254740993, as the number requires 54 bits for mantissa, while 53 is available only.
But it can do 9007199254740994, as it has trailing 0 bit in binary form.
So after 9007199254740992 there will be gaps in whole numbers.
That is a problem for any language/environment using IEEE-754 doubles.

Though strictly speaking not quite correct (due to differences in decimal and binary arithmetic, see below), Double type precision imposes following approximate limitations on money numbers in Flex (the number only as an example):
Max exact 2-digits precise money:           90,071,992,547,409.92
Max exact 4-digits precise money:              900,719,925,474.0992
Max exact 5-digits precise money:               90,071,992,547.40992

90 trillions is a large number, but still it may be too small for many countries in the world.

In general double numbers shouldn’t be used for storing exact numbers, like money.
See float and double in http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html

For example, is 0.1 + 0.2 equal to 0.3? (0.1 + 0.2 == 0.3)?
NO! In Flex 0.2 + 0.1 = 0.30000000000000004
0.1 can’t be represented exactly as a double, as in binary form it’s the endless 0.000110011(0011) fraction.
Mathematically speaking 0.9999(9) is equal to 1.0
Somehow toString() method is capable to recognize that and produce nice “0.1” string for 0.1 number.
But with arithmetic operations errors accumulate into imprecise results.

Strictly speaking floating numbers shouldn’t be compared exactly (==), not without rounding.

Will Flex/ActionScript ever be extended breaking from its JavaScript roots?

April 27, 2010

Fast, Faster, Fastest… Search Benchmarks for Flex Collections

Filed under: ActionScript,Flex,RIA — kouzmenkov @ 3:37 am
Tags:

One day I decided to write some code for searching a string value in a short array (less than 20) of objects. While I was going to do that with a primitive for each a colleague of mine already did that utlizing the weapon of homo sapiens: IViewCursor. We argued a little bit about if the small potential gain in search performance worth waisting memory for extra objects.

That led me to creating a set of small benchmark tests. Origionally I was generating Array, ArrayCollection of SomeObject having fields key and name equal to their indexes from 0 to N. The lists have been searched with for, for each and IViewCursor. Still I could not resist spending more time extending these “benchmarks” with Dictionary, and XML. I’ve also added uploading of input sample words to eliminate potential benefits the Dictionary could have from ordered lists of numbers.

AIR and Web benchmarks harnesses have been created. As single-threaded environments both Flex and AIR are weak running long computations. When working with long lists and XML the computer may spend dozens seconds, which causes Flash player to break after 15 seconds. In Silverlight calculations could be easily run in a separate thread, benefiting from multiple cores of modern CPUs and not freazing the UI. In Flex we have to jump over hoop to split long processes into chunks, which I didn’t want to do in these tests.

To get the full picture I was also considering time spent to generate these collections. To be complete memory must be measured, but somewhere a stop sign must appear.

Before jumping to the actual code and results here are some conclusions. The absolute performance winner is Dictionary. Timer’s precision isn’t enough to get the exact numbers. Standard for, for each are also not bad, though the end result greatly depends on where the target is (on average n/2 cycles). IViewCursor is very fast indeed, but it takes significant milliseconds preparing it. XML is extremely slow preparing, giving a clear explanation why all-XML approach don’t buy anymore.

So for the purpose of the original task the spent efforts were a waste. For searching in list of 20 items the actual approach doesn’t matter. It’s even difficult to measure the delay. Probably plain for, for each are better as they don’t need extra long-living objects.

To run benchmarks go to: http://orlamo.com/flex/benchmarks/web/benchmarksweb.html

Or download the source and binary files to run them on your computer: http://orlamo.com/flex/benchmarks/kolinIT.benchmarks.zip

Here are some results.
count=5, length=1000, target=999
Source=Array, Method=for each, Create=3ms, Run=1ms, Found=999-999
Source=Dictionary, Method=direct, Create=3ms, Run=0ms, Found=999-999
Source=ArrayCollection, Method=cursor, Create=9ms, Run=1ms, Found=999-999
Source=ArrayCollection, Method=for, Create=0ms, Run=25ms, Found=999-999
Source=ArrayCollection, Method=for each, Create=1ms, Run=27ms, Found=999-999
Source=XML, Method=direct, Create=380ms, Run=10ms, Found=999-999
Source=XML, Method=for, Create=0ms, Run=10ms, Found=999-999
Source=XML, Method=for each, Create=0ms, Run=10ms, Found=999-999

Note how how large is the time for creating XML (E4X). I’ve turned off XML for large collections to ensure scripts run within 15 seconds:
count=5, length=10000, target=9999
Source=Array, Method=for each, Create=14ms, Run=6ms, Found=9999-9999
Source=Dictionary, Method=direct, Create=20ms, Run=0ms, Found=9999-9999
Source=ArrayCollection, Method=cursor, Create=150ms, Run=1ms, Found=9999-9999
Source=ArrayCollection, Method=for, Create=4ms, Run=262ms, Found=9999-9999
Source=ArrayCollection, Method=for each, Create=7ms, Run=247ms, Found=9999-9999

Note how large is the create time for the Cursor=150ms. The search should be used at least 10 times to offset ease of Array creation. At the same time looping through ArrayCollection is very slow and Cursor may greatly help here.

That’s enough for now. Later I may add more details on the code itself, which might of interest for someone.:
The test is isolated in a shared library. Web and AIR use the same Runner component, adding environment-specific file handling. The list of words was taken from spellchecker dictionaries http://wordlist.sourceforge.net
Source data generators get injected into Benchmark runner, depending on if it’s the external sample file or Mock number generator. Tests are preconfigured in dictionary trees, taking user’s input on what sources should be generated. Functional pointers are being used. The list of possible sources is computed with reflection from class static constants.

/Thanks.

January 27, 2010

Flex 3.4: Complex properties and DataGrid

Filed under: ActionScript,Flex,RIA — kouzmenkov @ 1:09 am
Tags:

In Flex SDK 3.4 (didn’t check 3.3, definitely not in 3.2) DataGrid component supports complex properties in dataField. Previously dataField was treated as a solid name of a property in row’s data item. Now if the name contains dot(s) “.” it is considered a complex property, and the value gets extracted from the object chain. This eliminates need for labelFunction. In rare cases that may eventually break existing functionality if your fields ever used dots in names, which is only possible with dynamic objects.

Unfortunately Adobe’s developers were in rush implementing this very useful feature and didn’t give it a full testing. Trying to sort columns showing complex properties throws exception, as sorting doesn’t support dot-parsing. So it is still better to survive to the old technique of labelFunction and sortCompareFunction.

That has been fixed in SDK 3.5.

January 17, 2010

Flex vs. Silverlight

Filed under: .net,ActionScript,Flex,RIA,Silverlight — kouzmenkov @ 11:25 pm
Tags:

Being a multi-years .NET and over a year a Flex developer I was tempted for long time to compare the major player on RIA plug-in market Flex/Flash with its younger competitor Silverlight from developer’s or if you like coder’s point of view. Both platforms are very similar in target audience, features and eventually both will become equally wide spread.

I’ve highlighted just differences as knowing them can save efforts understanding both environments and make an educated choice if there is one. For somebody who spent years using different tools doing something it gradually becomes irrelevant which tools to use as long as they let the job get done.

I attempted not to include features which are equal. Still it didn’t work all the time. I don’t follow any particular order. The order may emerge after gathering more facts. The list may change over time due to adding and corrections. Info about Flex is based on multiple sources and my own experience working on a multimillion project as a GUI developer, notes about Silverlight were taken while reading “Pro Silverlight 3 in C#” and some experimenting. Differences in implementations of most features often can be pros for some and cons for others no judgment was made, unless the winner is absolute.

Current players are Flex 3 and Silverlight 3. Flex 4 and Silverlight 4 are both in beta state and seems not to introduce any dramatic changes.

Paragraphs about Flex are black, Silverlight – dark blue.

Grid

Flex uses container approach for organizing elements in rows and columns. Rows are defined by GridRow element, which can have several GridChild container, which in their turn hold other elements as children.

In Silverlight Grid is a Layout, not a container. Rows and Columns are defined explicitly by providing RowDefintion and ColumnDefinition elements. Positioning of each cell component is specified byGrid.Row and Grid.Column property of any element, placed in the Grid. Interestingly enough none of UI elements define such properties. These are “Attached” properties, which are kept in a loose collection inside dependent UI components. Parent is using them as required, so any property can be added. That’s very flexible, but requires from the developer to be very careful about positioning. This approach is also less visual. Developers have to put some efforts to keep all organized.

Binding

In Flex binding is easily to define in MXML by using curly braces in element ids:

< .. text=”{someUIElement.value}” ../>

In Silverlight more efforts are required, but some extra perks like double-binding are possible at the spot:<.. text=”{Binding ElementName=SomeUIElement, Path=Value, Mode=TwoWay}” ../>It’s possible to handle binding exceptions when value in one of pair member becomes invalid (build-in validator):

<TextBox Margin=”5″ Grid.Row=”2″ Grid.Column=”1″ x:Name=”txtUnitCost”

Text=”{Binding UnitCost, Mode=TwoWay, ValidatesOnExceptions=True}”></TextBox>

From may CLR collections only one supports adding/removing items: ObservableCollection, which implements INotifyCollectionChange, which can be used for custom collections if required. But in Flex there is just one rich collection class: ArrayCollection.

Layouts

In Flex there are following predefined layouts: Canvas, Grid, VBox, HBox, Panel

In Silverlight layouts are: Canvas=Flex.Canvas, Grid=Flex.Grid, StackPanel=Flex.VBox/HBox, DockPanel, WrapPanel. Developer can create custom layout containers, like round layout.

Canvas Clipping

In Flex clipping of the contents happens automatically (??)

In Silverlight programmer has to describe clipping manually in <Canvas.Clip> element. At the same time the shape may have any form, e.g. Ellipse or an arbitrary Path.

Border

In Flex like in HTML almost any element can have Border defined via properties like borderStyle, borderColor, borderThickness

In Silverlight there is a special element for Border, called Border. But only few UI elements have border-related properties. TO VERIFY if Style can do that. That means more coding is required, but more flexibility is possible, like rounded corners.

Scrolling

In Flex almost any container provides scrolling.

In Silverlight ScrollViewer must be used as wrapper to provide scrolling.

Scaling

In Flex almost any component has ScaleX, ScaleY property to change scaling of the contents.

In Silverlight scaling is defined via RenderTransform and ScaleTransform elements and ScaleX/ScaleY properties.

Full Screen

For security reasons in Full Screen support for some functionality (like keyboard) is limited. To get there in in Flex use:

Application.application.stage.displayState = StageDisplayState.FULL_SCREEN;
Similar in Silverlight. It’s possible with some security limitations, like limited keyboard support.

Event handling

In Flex event may have up to 3 phases: capturing, targeting and bubbling. Anything can dispatch any kind of events, which is often used to build very loosely-coupled systems.

In Silverlight event lifecycle is limited to just bubbling, which in its turn is limited to just few user activity events like keyboard or mouse.

Cursor

In Flex custom cursor ?

In Silverlight custom cursors are not supported, but standard are.

Core fonts

Flex guaranteed supports fonts: ??

Silverlight supports core fonts: Arial, Arial Black, Comic Sans MS, Courier New, Georgia, Lucida Grande/Lucida Sans Unicode, Times New Roman, Trebuchet MS, Verdana

Basic types

Flex/ActionScript supports following basic types: int, uint, Number, String, Date, Time(?), Object, Hashtable, Array, ArrayCollection

Silverlight supports all basic .NET types (value only): byte, short, (u)int, (u)long, float, double, decimal, String, DateTime, array [], enums, not counting multiple Lists, Collections, Dictionaries.

Advanced programming language features

Flex’s ActionScript was born from dynamic JavaScript and as such bares both features of dynamic and strongly typed languages. It has keyword dynamic to allow a class to acquire new properties of any type.

Silverlight isn’t monopolized by a single language and therefore a favorite language can be used. Or even mix of languages. C# as the language of choice is an A-class high-level language, comparable with Java in features and having a number of other features, accelerating development or allowing building safer programs. It’s easy to forget something, so just in no specific order what C# can and ActionScript can’t: generics, shorter property definitions (implicit get/set functions, or even automatically generated property holders if required), …

Image formats

Flex supports: GIF, PNG, JPEG

Silverlight supports: JPEG, PNG (excluding 64-bit and grayscale).

Out of Browser

Flex offers AIR as a way to run Flex code on desktop. Some relatively minor code adaptation are required. Set of available features gets extended by Drag and Drop, File System access, etc.

Silverlight has similar feature, but it purposely limited. The XAP file can be installed on desktop, but as a matter of fact behind the scene specially decorated version of browser (IE?) is being used to run the XAP. The only difference is that the program gets 25MB of storage by default, instead of 1MB. Microsoft encourages using WPF and full-scale .NET Framework for building desktop applications.

Multithreading

Flex is single-threaded.

Silverlight is multi-threaded.

States (View States)

Flex has controls for supporting states.

Silverlight has a set of classes starting with VisualState: VisualStateManager, VisualStateGroup, VisualState which should be implementing similar functionality. These states may apply to templates only?

Visibility

In Flex UI components two properties support visibility: visible and includeInLayout.

In Silverlight there is a single property is called Visibility, taking enum values of Visible and Collapsed. There is no way to hide a component, but keep its place. That works in WPF, but considered useless in Web apps.

Browser Integration, Navigation and Deep Linking

Some search engines like Google are able to parse Flex contents. What else?

Silverlight has Frame objects, which can navigate to a different XAML page from the same application, which works in a browser history friendly manner. Page name gets added like a local mark like MainPage.html#/PageName.xamlStill that works for a single Frame per App.That is also called “Deep Linking”

URI Mapping

In Flex?

Silverlight has UriMapper and other components in System.Windows.Navigation namespace to support URI mapping, which can help masking physical URI and files.

Static Effects

In Flex:

Blur, Resize, TBD

In Silverlight:Effects:Pixel Shaders: BlurEffect, DropShadowEffect, ShaderEffect (DirectX HLSL language),

Dynamic Effects (Animation)

In Flex: TBD

Silverlight prefers property-based animation. Time interpolation (linear and a number of non-linear interpolations), key frame interpolation and discrete frame are 3 supported types of timeline support. Different timeline type animations can be mixed.

Styles (CSS)

Flex supports most features of CSS and CSS stylesheets.

Silverlight doesn’t support styles but not like CSS. Style definitions can’t be shared between elements of different types (unless inherited), can’t be applied automatically. On the other side styles change properties and allow complex objects to be applied.

Behaviors, Actions, Triggers

In Flex??

Silverlight proposes behavior actions initiated by triggers, in order to allow building libraries of “styled” actions, similar to styles.

Templates

Flex has no such thing

Silverlight implements another extension to “behavior styles” called Templates, which are detailed definitions of visual elements. Templates get applied in a similar way as styles.

Queries

Flex has no support.

Silverlight supports LINQ.

Embedded XML support

Flex is strong at supporting XML, provides embedded XML type, which implements X3? Specs. It’s easy to create hardcoded XML in ActionScript.

Silverlight has some support for embedded XML at least in VB.NET, in other languages it may be limited due to syntaxis limitations.

Modularization/Libraries

Flex supports libraries (*.swc), modules (*.swf), subapplications (*.swf). Libraries can be embedded into code, or loaded on demand. Flex Builder can extract only required (referenced) classes from libraries and embed them into final code. Flex Builder can reference other libraries. Some efforts (ant or maven scripts) are required to support multi-project workspaces.

Visual Studio provides native support for modularization. Most often that’s the first step that developers do. Still usage of build scripts (nant, msbuild, etc.) is possible. Compiled code can be zipped together into *.xap files or kept separate from the main application or application loader to be loaded/unloaded on demand.

Performance of code execution

Both systems represent code in intermediary format, compiled by JIT compiler on client.

Flex interprets some of code (e.g. in constructors according to Farata Systems), which is much slower. Handling of dynamic types (*, dynamic properties) requires usage of reflection and is slower by an order.Silverlight compiles all code.

Timelines

Flex is Frame-based, meaning that execution of functions, events happens when new animation frame need to be drawn. Flex draws 30 frames per second if possible. Graphical functions have priority and get called immediately. Asynchronous service calls get postponed by Flex till exiting the current function till next Frame if not later. Keep this in mind.

Silverlight can tagged up to 60 frames per second, but the actual rate depends on hardware performance. Silverlight calculates itself how many frames are required to execute an action.

Advanced Data Grids (non-3rd party)

Pro version of Flex Builder is supplied with AdvancedDataGrid control, which enables building complex data grids, including hierarchical structures, grouping, sorting, rearranging columns, etc. Problem is the control has a number of issues, but eventually it may improve over time.

Silverlight has DataGrid control, which is similar in functions and is also supporting grouping and other advanced features, but also adds support for paging via PagedCollectionView.

Client Data Storage

In Flex it’s called CacheObject

In Silverlight the same feature is called Isolated Storage.

XML Namespaces, property references

….

Complex Properties

….

Error Handling

TBD

IDEs

For Flex: Flex Builder standalone or plugin for Eclipse/RAD/IntelliJ/etc. Conditional breakpoints are promised in FlexBuilder 4. Still Eclipse and alike have many nice features. Debugging Flex application is amazingly fast, even when browser is IE.

In Silverlight:  Visual Studio 2008, 2010.  Many may disagree (in particular these who never used it) but Visual Studio is the best development environment overall.  Conditional breakpoints have always been there.

Create a free website or blog at WordPress.com.