Flash & Flex Developer Magazine — Flash CS 4 New Features (1/2009)

Page 1



Editor’s Note Dear FFD Readers,

I

am really happy to begin the 2009 New Year with you - with the new challenges, new projects, new expectations and new features in Flash and Flex. As we start a brand new year here at FFD Magazine, we have been really lucky to have the chance to give you a bundle of very useful and interesting articles covering many important points in the Flash and Flex Developer’s Community. The first question I asked the FFD Beta testers was about the main theme that we should highlight on the cover and this gave me the feeling of great joy and confidence that this issue will be a great success. The vast majority of them expressed interest in the new features in Flash CS4, but none of the ideas will be ignored. That means that we hit the nail on the head. In the last issues, we have presented a hand-picked collection of greatly selected articles and tutorials. Now it is time for a fresh portion of healthy Flash and Flex learning material. Take a look at the main article in this issue about Flash CS4 New Features. Once you hear about all of the new features included, I don’t think there will be a doubt in your mind about the value of the upgrade. Before you are ready to start Flex-ing take a look into what Adobe Flex is. It is one of the leading technologies for RIA’s and how you can make simple applications with and without the Flex Builder – page 18. Are you a fan of Nintendo Wii? Flash games? Take a gander at page 64, and you will find a tutorial on how to develop Flash Games for the Nintendo Wii. I hope you find the articles in this issue worth while and engaging. As the new FFD magazine’s Editor-in-Chief, I am proud to have been a part of an incredibly successful publication and the community we can create together. This position has always been educational, though challenging, exciting, yet equally as demanding as it is rewarding. Ultimately, the stellar final product, and the supportive feedback we receive from you, the reader, provide the greatest rewards for me and the other members of our Editorial Board. I hope the magazine continues to evolve and reach your community. If you have ideas about topics you would like to see us cover in 2009, or if you have opinions about anything we are doing, please let us know. You can always write to us at editors@ffdmag.com. In the end, we want to continue working to make FFD Magazine more relevant to you—but we can only do this if you tell us what it is that you want to see. Your opinions are what we will use to help us determine what topics to focus on in the coming year. Special Thanks to the Beta testers and Proofreaders who helped us with this special issue, without whom there would not be FFD magazine.

Ewa Samulska ewa.samulska@ffdmag.com

Printed in Poland by: PlusMedia

Editor in Chief: Ewa Dudzic ewa.dudzic@ffdmag.com Executive Editor: Ewa Samulska ewa.samulska@ffdmag.com DTP Team: Ireneusz Pogroszewski ireneusz.pogroszewski@software.com.pl Przemysław Banasiewicz przemyslaw.banasiewicz@software.com.pl Art Director: Agnieszka Marchocka agnieszka.marchocka@software.com.pl CD: Rafał Kwaśny rafal.kwasny@gmail.com Senior Consultant/Publisher: Paweł Marciniak pawel@software.com.pl Production Director: Marta Kurpiewska marta.kurpiewska@software.com.pl Marketing Director: Ewa Dudzic ewa.dudzic@software.com.pl Subscription: customer_service@software.com.pl Publisher: Software Wydawnictwo Sp.z.o.o 02-682 Warszawa, ul. Bokserska 1 Poland Worldwide Publishing

Business addres: Software Media LLC 1521 Concord Pike, Suite 301 Brandywine Executive Center Wilmington, DE 19803 USA Tel: 1 917 338 3631 Tel: 1 866 225 5956 www.ffdmag.com

Software Media LLC is looking for partners from all over the World. If you are interested in cooperating with us, please contact us by e-mail: cooperation@software.com.pl

01/2009 (3)

Distributed in the USA by: Source Interlink Fulfillment Division, 27500 Riverview Centre Boulevard, Suite 400, Bonita Springs, FL 34134 Phone: 239-949-4450. Whilst every effort has been made to ensure the high quality of the magazine, the editors make no warranty, express or implied, concerning the results of content usage. All trade marks presented in the magazine were used only for informative purposes. All rights to trade marks presented in the magazine are reserved by the companies which own them.

To create graphs and diagrams we used company.

program by

CD included to the magazine were tested with AntiVirenKit by G DATA Software Sp. z o.o The editors use automatic DTP system Mathematical formulas created by Design Science MathType™

ATTENTION!

Selling current or past issues of this magazine for prices that are different than printed on the cover is – without permission of the publisher – harmful activity and will result in judicial liability.

DISCLAIMER!

The techniques described in our articles may only be used in private, local networks. The editors hold no responsibility for misuse of the presented techniques or consequent data loss.

3


Contents SPECIAL REPORT 06 Flash CS4 New Features

LEE BRIMELOW The article touches upon the new features of CS4.

08 CD Contents

48 Flex Application Accessing Microsoft Analysis Services to Retrive OLAP Cube Data ERIC KO In this article Eric shows you how to connect Flex to an OLAP cube.

54 Contextual Awareness- Parsing the Stack Trace

TOOLS

CHRISTOPHER W.ALLENPOOLE You will learn from this article how to parse the stack trace from an error message and how to create contextual awareness in a program.

12 What to expect with Flash 10’s “Astro”

SERVER-SIDE INTERACTION

KEVIN MARTIN

14 SpicyNodes – New Technology for Better Navigation in the Information Sea

58 Weather Flash Plus

PAUL GRITSAY

CLIFFORD ECLIPSE WILSON This tutorial will walk you through programming Weather Flash Plus in ActionScript 3.0.

FOR BEGINNERS

SOUND AND ANIMATION

16 Introducing the XMLLoader

60 XML- based Photo Gallery & Slideshow

CLEMENTE GOMEZ Clemente Gomez gives the short class on using XMLLoader Class.

CHETANKUMAR AKARTE In this article Chetankumar Akarte will teach you how to create an XML-based photo gallery and slideshow.

ACTIONSCRIPT DEVELOPMENT 18 Will you Flex? BERNARD PINEDA Bernard defines the most important new Adobe Flex’s features.

22 Getting Started with Google Maps in Flash JASSA AMIRLANG In this article Jassa Amir Lang will teach you basic steps needed to get started with GoogleMaps in the Flash IDE..

28 Visualizing GeoSpatial Data using Vector Maps JEANMARC WIELAND AND SANDRA ENGENE With this tutorial you will explore new methods for creating maps and visualizing the world.

32 Socialbloom. A look at Flex Data Driven Application

64 How to Develop Flash Games for the Nintendo Wii BILL VOLPE With this article you will get the excellent opportunity to develop your own Flash games for the Nintendo Wii.

COLUMN 70 Adobe Genesis: AIR Refreshes The Desktop CHRIS CHARLTON

CASE STUDY 72 Lex Framework Takes e-publishing to the Next Level 74 KING BEE Animation

WALT SCHLENDER In this tutorial you will learn data driven applications and some of the cool Flex visual effects.

76 OMNIS DATA

40 In bed with Flash and HTML: Embedding Flash content with SWFObject 2

78 Interview with Justin Everett- Church

ARAN RHEE In this article Aran Rhee will teach you how to embed Adobe Flash content using SWFObject 2.

44 Increasing Flash and Flex Search Engine Optimization

INTERVIEWS FFD TEAM

BOOKS REVIEW 80 Reviews of two amazing books

R.JAN MACDONALD AND JASON MCCOSKERY From this article you will learn to working solution for Flash SEO using SWFAddress and PHP.

4

01/2009 (3)



Product Review

Flash CS4 New Features by Lee Brimelow Sometimes when new versions of software get released there is a debate about whether or not they are worth the price to upgrade. Once you hear about all of the new features included in Flash CS4, I don’t think there will be a doubt in your mind about the value of the upgrade.

O

nce you have read the article, be sure to watch the accompanying video tutorial that is included on the CD in which I use some of the new Flash CS4 features in a real-world example. In the past, releases of the Flash authoring tool have been cyclical with regard to the audiences they target. Flash MX 2004 was aimed clearly at developers with its focus on integrating ActionScript 2.0 into the environment. Flash 8 saw many designer improvements including the addition of bitmap filters and video alpha channels. Keeping up the cycle, developers were the primary focus of Flash CS3 with the integration of the new ActionScript 3.0 language. Now Flash CS4 is upon us with a plethora of new features aimed squarely at the designer crowd. Ok enough chitchat; let’s get right to the new features. The user interface has been significantly revamped in Flash CS4. Many of the changes reflect things that are consistent across all the products in the suite. This includes things like the panel layouts and the new custom window chrome. Upon first opening the tool, the first thing you will notice is that nothing is where it usually is. The timeline is located across the bottom of the screen and the properties panel is now positioned to the right of the stage in a new vertical layout. Like previous versions of Flash, the user interface is full customizable and allows you to save your favorite layouts as workspaces. Like all CS4 products, the workspaces can be accessed by a new menu located on the top right of the application. Flash CS4 also comes with a range of workspaces right out of the box for people who want to focus on things like development, design, and animation.

New Timeline and Animation Model This is definitely the biggest new feature and is the one you will notice right off the bat. 6

For years Flash users have been asking for an object-based, auto-keyframing animation system similar to the one found in tools like After Effects. Well I’m happy to report that Adobe has finally listened. Gone are the days of having to add and remove keyframes manually on the timeline. In the new model you simply create a motion tween on a MovieClip and then keyframes will automatically be created for any property that you modify. Another huge benefit of the new system is that each property of your MovieClip is animated independently of each other allowing you to create some very complex animations very easily. In earlier versions of Flash it was extremely difficult to speed up or slow down a timeline animation that had a considerable amount of keyframes in it. In Flash CS4 it is as simple as grabbing the end of the motion tween in the timeline and adjusting it accordingly. All of the keyframes will automatically be adjusted for you. This is an amazing timesaver! Speaking of things that were typically hard to do in Flash, one would have to be moving or resizing an entire animation on the timeline. It required selecting multiple frames and took the steadiness of a surgeon’s hand in order to accomplish what you wanted. In Flash CS4 you can simply get the free transform tool and then move or scale the entire animation itself without affecting the size of the actual MovieClip the animation is targeting.

Motion Editor With the release of Flash 8, we had a primitive easing curve editor that we could use to adjust the timing of our animations. This was a very basic tool and it didn’t allow you to save the resulting easing curves when you were done. The new motion editor in Flash CS4 represents a huge step forward, bringing Flash on par with more professional animation tools like After Effects. You can adjust the easing

curves for every property independently of one another allowing you to easily create complex animations. Included with the editor are a host of popular easing types like bouncing and springing. You can also create your own easing curves very easily for those who want a more custom animation effect. What makes things even more exciting is that each animation property can have its own unique easing type. So you can apply a bounce to the X property and a spring to the Y property.

Motion Presets Let’s say you spend hours fiddling with the Motion Editor to achieve a stunning animation effect. It sure would be nice if you could save all of that work in case you wanted the same type of effect later on. This is where the Motion Presets panel comes in. This new panel allows you to save your own custom animation presets and also comes stocked with some common animation effects right out of the box. The included presets range from being cheesy to somewhat useful. The real power of the presets panel is in creating your own and building a library of your most-used effects. These can also be easily shared with the community if you are feeling generous. Thanks to the new native 3D support in Flash Player 10, there are now tools for manipulating MovieClips in 3D space directly inside of Flash. It’s important to note that this is not meant to be a replacement for the popular community-based 3D projects like Papervision3D, Away3D, and Sandy. These new 3D features are for doing simple “postcards in space” animations similar to what is possible in After Effects. If you are looking for the ability to apply shaders and lights or to import 3D models, you will still want to look to one of the aforementioned community projects. 01/2009 (3)


Flash CS4

There are two new tools available in Flash CS4 for working in 3D. The 3D rotation tool allows you to rotate MovieClips on the X, Y, and Z axis. Any rotations you do can be fully animated on the timeline just like any other properties. The 3D translation tool allows you to move a MovieClip along the X, Y, or Z axis. All of the 3D properties can also be adjust using sliders in the Properties panel if you’d prefer. Another cool thing is that MovieClips that are positioned in 3D space are automatically anti-aliased for you so that they look just as good in 3D as they do in 2D. The MovieClips also remain fully interactive so that you can still respond to mouse events even when the clips are set in 3D space.

Inverse Kinematics (IK) This exciting new feature is aimed clearly at those doing character animation in Flash. Inverse kinematics refers to the ability to build a skeleton structure on a character or object, which enables you to easily create joint-based animations. There are two new tools in Flash CS4 which make doing IK

animation a snap. The bones tool allows you to actually draw the bones that make up a full skeleton or armature. When you start creating bones, Flash will turn the current layer into an armature layer, which is a new layer type in Flash CS4. This layer type has some special properties dealing specifically with inverse kinematics. Here you can choose whether or not you want to animate the IK structure at authortime or runtime. If you choose runtime, Flash will automatically write the ActionScript code needed to make the object fully interactive at runtime. There is a new ActionScript 3.0 package that allows advanced developers to manipulate armatures at runtime. The bind tool is slightly more advanced and allows you to assign a particular bone to manipulate a specific vertex of the object. If you have experience with 3D animation tools like Maya or 3D Studio Max then these things will be very familiar to you. The new IK features are not just limited to MovieClips. You can actual draw a bones structure through a raw graphic shape allowing you to do some crazy shape tweening.

It’s going to be very interesting what the Flash community does with this feature.

New Project Panel One of the things that I honestly have never used in the Flash authoring tool is the project panel. This panel has always lacked the advanced features needed by developers to effectively manage their projects. Due to this lack of features, community member Grant Skinner created a more advanced panel called gProject that aimed to fill the gap left by the native project panel. Instead of spending precious development time building a new panel from scratch, Adobe instead decided to buy gProject and use it as the basis of the new panel. The new panel was actually built using Flex and takes advantage of the Flash JSAPI. Features include the ability to generate class files directly from the panel as well as setting up custom file paths for source folders and the Flex SDK.

Better Integration with Flex This is one area that the community has been very vocal about. Flash and Flex have never really worked smoothly together. One problem dealt with the fact that the SWC formats supported by each tool were not compatible with each other. This has been fixed in Flash CS4 so you can now include an ActionScriptonly SWC file created in Flex Builder into your FLA-based projects. Another feature of Flash CS4 that aids the integration with Flex is the ability to include metadata.

Native AIR Integration For a while now, Flash developers have been able to leverage their skills to build desktop applications using Adobe AIR. There was a free extension for Flash CS3 made available on the Adobe Labs site that allowed developers to take full advantage of the authoring environment to build applications. In Flash CS4 no such extension is needed as the AIR support is built natively into the tool. The AIR settings window can now be launched right from the properties panel once your publish settings have been changed to target AIR rather than the standard Flash Player. Believe it or not, the features I have talked about in this article are only some of the new things included in this release. I can’t recall there ever being a more feature-packed version of Flash. This may definitely lead to some sleepless nights for you so make sure you get plenty of rest now in preparation.

Figure 1. New Features

01/2009 (3)

LEE BRIMELOW 7


CD Content

CD Contents Y

ou will find lots of useful and interesting software and articles on the accompanying Flash & Flex CD. These were carefully chosen with the help of our Betatesters. So what can you expect to find in this new edition? Well for starters there are 2 fantastic new video tutorials to learn from. There are several new programs to try out and keep, provided by highly respected Flash and Flex industry experts. But that's not all put the CD into your drive and Enjoy!

Applications You will find the following programs in Apps directory on the FFD CD. Most of them are full versions, without any limitations, negotiated with the vendors especially for you. 3D chart (v. 1.7) system ADVANCE-MEDIA is glad to be able to present to you one of the most comprehensive 3D chart system around. 3D charting is the enticing way to visualize and to present data. Why choose 3D? Because we humans got two eyes made for three dimensional sight. We are used to gather a lot of information with our three dimensional perception at a glimpse, 3D will ease the flow of information. This chart application offers a traditional 2D view option as well to satisfy all and lets the user toggle between the 3D and 2D view with a simple click of a button while runtime. Of course any surface charting is native to 3D! • Here you will learn how to integrate the 3D chart to your homepage into html or nested inside another Flash movie and even in a powerpointTM slide presentation while maintaining full interactivity. • All data is retrieved via a simple editable XML file. This XML file can be generated by any middleware language such as ASP.NET, ASP, Cold Fusion, JSP, PHP or Pearl etc. to hook-up to any database for advanced dynamic real time charting. Yet this XML file can be created with any text editor, no database is needed, and it does support UTF-8 multilingual fonts.

• Animated and interactive charts, no boring static image picture file. Highly customizable via its XML data structure. Simply set xml attributes to suit a wide range of various homepage designs. Page integration is made very easy. Customizable externally loaded hover sound effects (.mp3) will further help to catch the user's attention. • No extra server sided component is needed, flash chats will not put strain on your server. In case this is not done already, just configure your sever to put out flash's .swf format (mime-type). • The very small file size will boot quickly. The chart movie will be cached by the browser, a second chart movie displaying completely different data will not load the entire movie all over again resulting in a swift experience. • Multi and single series are supported. Combine Column floatingColumn Cylinder floatingCylinder Line Area (Wall) and Surface charts colored by series or regions (height) plus combine the innovative Candlestick 3D chart type for advanced stock charting. A second movie will display your Pie or Doughnut charts with slicing option. All charts feature drill down links and much more. Have fun charting! www.advance-media.com Clear Data Builder 3.0 Beta Clear Data Builder Plugin for Eclipse automates Flex-Java development with LCDS, BlazeDS or OpenAMF: whether you are a Java Pro or have never coded in Java before, Clear Data Builder will let you create a complete Flex-Java-Database apps in minutes. Here is how it works: you provide method declarations annotated with SQL statements, and leave the rest to Clear Data Builder. No need to write and debug Java code, no need to create O/R mappings. Clear Data Builder creates all Java code, then compiles, builds and hot deploys Java JARs. It also creates all required Flex code. Next thing you see, your CRUD application running in your Web browser. For legacy Java applications Clear Data Builder generates wrapper classes plus ActionScript Transfer Objects matching their Java peers. Note, that now you can control complex database transactions including SQL updates to multiple tables and stored procedures calls entirely from ActionScript! www.faratasystems.com

Figure 1. Advanced media

8

Flash Player XP Flash Player XP is a stand-alone player that provides many expanded functions to Web Designers and Flash users the opportunities to play and enjoy Flash movies from the web as well as from other medias without the help of a browser. Macromedia

01/2009 (3)


CD Content

Windows and .NET. ActiveSWF generates Flash content dynamically and can be easily programmed to build Flash movies from XML. Being compatible with most of Windows oriented technologies including COM and .NET ActiveSWF SDK opens the world of Flash for millions of VisualBasic, C# and Visual C++ developers. Features: ActiveSWF supports all basic Flash graphical primitives, animations and scripting. Audio and image compression methods allow to significantly reduce movie size with minimum quality loss. www.activeswf.com

Figure 2. Flash Player XP

Flash is the world's most pervasive software platform, reaching 98% of Internet-enabled desktops worldwide, as well as many popular devices. With the integrated technology of Adobe Flash Player 9, Flash Player XP can display flash movies such as web application front-ends, e-greetings, high-impact website user interfaces, interactive online advertising, flash games, short-form to long-form animation and more. Flash Player XP offers a variety of playback capabilities including full-screen mode. The program can itself associate with Flash files. So you can open any flash file with Flash Player XP by just double-clicking it.

Swift 3D Swift 3D is a standalone application enabling designers to quickly and easily create high-quality 3D animations and scenes for use in Adobe Flash, Papervision3D, video, and other rich media design projects. Swift 3D v5 is a powerful, easy-to-use 3D solution that delivers high-quality results and a broad spectrum of output options for an unbeatable price.

www.mskprathap.com ActiveSWF ActiveSWF is innovative rich media platform specially designed for web developers and Flash professionals building applications for

Figure 4. Swift3d

Electric Rain’s intuitive and easy-to-use Swift 3D has become the de-facto application for designers exporting vector and rasterbased 3D animations to Adobe Flash, as well as to video and common vector-based formats, such as Adobe Illustrator® and EPS. Recent updates are making it even easier for designers of all levels to introduce 3D to their projects. Swift 3D 5.0 further extends its leadership role in creating 3D for the Web and the desktop with the ability to export 3D scenes and animations to XAML (Extensible Application Markup Language), providing simulated 3D support for the Microsoft® Silverlight™ online media platform, as well as the WPF desktop platform. For more information on Swift 3D 5.0 please visit: http:// www.erain.com/products/swift3d/ Flex SDK An official Adobe product, with released versions found at http: //www.adobe.com/go/flex3_sdk. The Adobe Flex SDK contains everything you will need to build and deploy Flex RIAs. It is licensed under the Adobe Flex SDK license because it contains a Figure 3. Active swf

01/2009 (3)

9


CD Content

Figure 5. Flexsdk

mixture of open and closed source components (see license info above). The Flex framework source code included in this package is called out explicitly as licensed under the MPL. However, if you want just the open source stuff, you should look at the Open Source Flex SD The Flex SDK provides a highly productive, open source framework for building and maintaining expressive web applications that deploy consistently on all major browsers, desktops and operating systems. It provides a modern, standardsbased language and programming model that supports common design patterns suitable for developers from many backgrounds. Flex applications run in the ubiquitous Adobe Flash Player and Adobe AIR. You can use the Flex SDK to create a wide range of highly interactive, expressive applications. For example, a data visualization application built in Flex can pull data from multiple back-end sources and display it visually. Business users can drill down into the data for deeper insight and even change the data and have it automatically updated on the back end. A product configuration application can help customers navigate the process of selecting or customizing products online. And a self-service application can guide customers through an address change or help employees complete an otherwise complicated multi-step benefits enrollment. In addition to the Open Source Flex SDK, Adobe produces the Free Adobe Flex SDK which contains everything in the Open Source Flex SDK plus useful tools for enhancing the application development experience such as the debugger Adobe Flash Player runtime and Adobe AIR. Adobe also provides a professional IDE, Adobe Flex Builder, for building Flex applications using either the Adobe Flex SDK or the Open Source Flex SDK. http://opensource.adobe.com/wiki/display/flexsdk/About SiteGrinder from MediaLab It’s not easy to actually build a beautiful website that matches a design created in an application like Photoshop. Photoshop gives an artist total design freedom, but that’s not the case with Web code. The Web uses many confusing technologies, none of which place emphasis on design integrity. As a result, those who are good at Photoshop struggle with creating webpages, and they don’t want to spend months or years learning confusing programming code like XHTML, CSS, Javascript, and more, just to create a halfway decent looking website.

10

SiteGrinder 2 turns Adobe Photoshop into an easy-to-use and powerful website design and production tool. It’s true! In fact, a SiteGrinder 2-equipped designer with no HTML expertise needs only their Photoshop skills to go from design concept to full deployment of a professional, standards-compliant website in just minutes with no programming whatsoever … and they do it all from within Photoshop. SiteGrinder 2 takes care of everything, even ensuring cross-platform browser compatibility. Best of all, pages created with SiteGrinder 2 retain the exact look and layout of the parent Photoshop file from which they were created. You know Photoshop. SiteGrinder 2 knows CSS, HTML, Web image formats, and much more. All you have to do is tell SiteGrinder 2 about special layers, like buttons, by adding “Hints” to your layer names. To the right you see the words “button”, “rollover”, and “popup” in the layer names.

Figure 6. Site grinder

Those are Hints, and they’re the only things required to create a website that’s as gorgeous as your design. Once you’ve added a few Hints to your layer names, just launch the SiteGrinder 2 plug-in and it’ll build your page in minutes with just a click of the mouse. There’s nothing complicated about it. Just create your web design in Photoshop, add Hints to your layer names, and before you know it, you have a fully functional, CSS-rich, standards compliant webpage. SiteGrinder 2 does all the complicated stuff for you with just a mouse click. You can even add Flash animations, slideshows, and much more to your webpages. Doing so is a breeze. And the best part is that your gorgeous designs remain looking just as you created them … gorgeous. SiteGrinder has a series of training videos, extensive online documentation, a host of sample files, very responsive technical support, forums and free weekly training classes. You are not alone when using SiteGrinder. If you have questions, we have answers. www.medialab.com

PROJECT FILES FFD CD includes also the supplements for some of the articles. You'll find there the materials which were prepared by the authors. It can help you train the techniques presented by the authors in the articles.

01/2009 (3)


If the CD contents can't be accessed and the disc isn't physically damaged, try to run it in at least two CD drives. If you have experienced any problems with this CD, e-mail cd@ffdmag.com

11 01/2009 (3)

02/2008 (2)

11


Tools

What to expect with Flash 10's "Astro" Adobe has been working on a new version of Flash and extending ActionScript. With the new version of Flash, version 10, we can expect many features that we have been waiting for, such as 3D space and a better drawing API. In this tutorial, I will show you how to utilize some of the new features in Flash 10, code named "Astro."

Y

ou can go to the Adobe Labs site to download Flash 10 with proper instructions on how to install it. Once you have it set up, you can test your installation using the demo section located on the site. Currently there is no GUI for creating Flash 10 content, though you can use the new version of the MXMLC compiler tool for the command line that comes with the Flex SDK. Many people have a small misconception that Astro is based on a new version of ActionScript (version 4), but, in reality, it just extends the current ActionScript 3 API. ActionScript 4, as some of us know, will be based on ECMAScript 4, which is still being planned out and developed. In the new 3-dimensional space model used in Astro, we can stop using graphical frameworks such as Papervision and Away3D to create a pseudo-3D space. The developers at Adobe added two new attributes to Spritebased classes (any class that extends Sprite): z and rotationZ. With 'z' we can change how far an object is. The rotationZ allows us to rotate along the z-axis. There is a nice application under the links section where you can test the rotationZ attribute, along side with the rotationX and rotationY attributes, created by Mike Chambers. Adobe has also improved the performance in Flash by sending some of the

processes to the video card which decreases the pressure on the CPU so that it can run faster. This is especially useful for heavy content, such as video and games. Even with other new features such as the unexpected Pixel Benders and other visual effects, Astro is prone to bloating as easily as before. As said above, Pixel Benders are new in Flash, yet they are not a new concept either. The technology has been used for Adobe AfterEffects and can be created using a simple language using Adobe Pixel Bender. The toolkit itself allows you to preview the filter as you make it without sending it to flash to view. The final file size for an average filter is usually about 1KB. Another great improvement for Astro is the new Text Layout. It now has better international support for languages that read right to left, and vice-versa. It even allows you to have text to overflow to another textfield automatically.

Above that, it has also recieved a performance boost, according to Adobe, for which they have identified a bottleneck and fixed. Overall, Flash 10 is a much needed improvement for us to further develop. The great thing is that it does not provide us with a new version of ActionScript – it just extends version 3 and obviously, provides excellent performance improvements.

On the Net • • •

Figure 2. 2008 09 16 1511

http://labs.adobe.com/technologies/ flashplayer10/ http://labs.adobe.com/technologies/ flashplayer10/demos/ http://www.mikechambers.com/blog/ 2008/08/25/flash-player-10-rotation-xyzproperties-example/ h t t p : / / w w w . y o u t u b e . c o m/ watch?v=ympeCv8lLmw

KEVIN MARTIN

Figure 1. 2008 09 16 1509

12

Figure 3. 2008 09 16 1524

Kevin Martin is an innovative developer who has worked with many web languages, such as PHP, HTML, CSS, and Javascript. He began using Flash before Adobe owned Macromedia, when Flash 5 was the current stable release. Currently, he is freelance developer and owns several domains including his portfolio located at http:// synarchydesign.com/

01/2009 (3)



Tools

SpicyNodes – New Technology for Better Navigation in the Information Sea by Paul Gritsay I’m glad to introduce a new technology to you. Please welcome, SpicyNodes comes on stage. This is a new and intuitive way to browse the information on your website through by means of radial tree.

W

hat is new and what is interesting in SpicyNodes? First of all, this technology offers a new way to browse different linked and hierarchically structured data. You need to try it yourself to understand how information navigation might be that intuitive and inviting in terms of nodes. Radial layout is the main feature of SpicyNodes, however it’s accompanied with a set of useful tools and functionalities, which assist you during the browsing and definitely improve the overall impression. They are: • Breadcrumbs, showing your current position relating to the home node

• Search bar, which perform the search of needed terms and allows to jump straight to the results found • Previous, Home and Next buttons, allowing you read the information in order • Sound-FX effects allowing SpicyNodes to sound, but that’s more for using SN in entertainment industry • Full screen toggle button, if a nodemap is big enough you may turn on a full screen mode, to see more nodes and to navigate more comfortably

supported. Users are offered a wizard-like online application, where they can create and customize their own information structures, which then will be turned into the nodemaps. The steps are simple. 1. Create new nodemap. 2. Define its structure and data. 3. Choose a style.

Nodemap creation All nodemaps created are located in the gallery, so you may simply find them later to

SpicyNodes is a Flash-based technology, what guarantees a correct functionality in any browser and any operation system, where flash player is Figure 2. Defining a nodemap’s structure

Figure 3. Selecting a node skin

Figure 1. Creating new nodemap

14

Figure 4. Selecting the colors

01/2009 (3)


SpicyNodes

edit or to use. (Figure 1) shows the interface of this step.

Constructing the nodemap At (Figure 2) you can see the way a nodemap is defined. User may create the structure

according to his needs, which then can be used in his special project, web site or application. Each node can contain simple text information or HTML format data. Nodes may be associated with URLs to navigate to when Go to page button is pressed.

Customizing the nodemap Even at beta-stage SpicyNodes offers a variety of skins and other customizations, which allow changing the look and feel of the node tree. Nodemap consist of 4 general items: • Center – visual look of the central focused node • Nodes – skins for level 1+ nodes • Connectors – these are connecting the nodes • Labels – the way a text information is attached to each node Take a look at (Figure 3 and 4) to see the customizations options offered. That’s it. Now the nodemap is ready and it can be integrated with the most of modern CMS.

Usage As you could already understand, SpicyNodes might be used to display any information in a specific style and colors, which will fit the style of your identity or website. SpicyNodes is not just a technology for the website organization. When using SpicyNodes users are able to scan a large quantity of information effectively. There is a common problem – users often know that particular information is available on the website, but they just cannot find it. In all places webmasters are struggling to implement the best techniques to help them in their researches. With SpicyNodes users are involved in a ‘natural’ way of walking through the information and this technology may definitely improve the conversion rate of any website.

Samples As an illustration of this technology in action you may take a look at interactive Greek Gods’ Family Tree, which is run on SpicyNodes engine: http://www.webexhibits.org/greekgods Daylight Saving Time example might be found at: http://www.webexhibits.org/daylightsaving/ nodes.html Poetry through the ages: http://www. webexhibits.org/poetry/nodes.html Try them out and I’m sure you’ll enjoy the results.

On the Net • •

http://www.spicynodes.org – official SpicyNodes website http://www.flashdaweb.com – Flash and web tutorials, tips and developments

PAUL GRITSAY Paul Gritsay is a co-founder of flashdaweb.com web resource – created to help in flash and web developments. He has an extensive experience of both system and flash software development and has written a number of flash and actionscript tutorials.

01/2009 (3)

15


For Beginners

Introducing the XMLLoader Class by Clemente Gomez The XMLLoader class hastens the process of importing xml into your flash applications. Rewriting code and constantly creating URLLoaders and functions to handle the loading of an xml file can be tedious and annoying. With the XMLLoader all that is out the window. What you will learn...

What you should know...

• How to use XMLLoader Class

• Basics of Arrays • Basics of XML • Basics of Event Handling

Level of difficulty

Y

ou will be able to load in many xml files at the same time, have only one event handler per instance of the class. Its fast and efficient and best of all, it is all done in one or two lines of code. There are two ways to create an XML Loader. The first way (Listing 1) is to pass in the xml files you want to load into the constructor. The alternative (Listing 2) is without passing anything to the constructor. When passing your xml files into

the constructor, they must be an array. To load in xml files when not passing them into the constructor, you use the loadXML() function (Listing 3). The rules for passing xml files to loadXML() i the same as in passing it to the XMLLoader constructor.

On the 'Net

Retrieving Data Once the XMLLoader is done loading all of the XML files, your are able to retrieve the data. To retrieve the data you must add a COMPLETE event listener to the XMLLoader. In the event handler to access the XML files, use the getList property. The getList property returns an array of all the loaded xml files. There are two ways to specify a specific xml file in the array (Listing 4).

• •

http://blog.kreativeking.com http://www.artbycg.com

CLEMENTE GOMEZ • • •

Freelance Flash Developer 3D Artist Student

Listing 1. Instantiating XMLLoader w/ XML files

Listing 4. Accessing Data

import com.clementegomez.utils.XMLLoader;

import com.clementegomez.utils.XMLLoader;

var myXMLLoader:XMLLoader = new XMLLoader(["file1.xml", "file2.xml"]);

Listing 2. Instantiating XMLLoader import com.clementegomez.utils.XMLLoader;

var myXMLLoader:XMLLoader = new XMLLoader();

var myXMLLoader:XMLLoader = new XMLLoader();

myXMLLoader.loadXML(["file1.xml", "file2.xml"]);

myXMLLoader.addEventListener(Event.COMPLETE, getXML); function getXML(e:Event):void {

Listing 3. Using loadXML() import com.clementegomez.utils.XMLLoader;

var myXMLLoader:XMLLoader = new XMLLoader(); myXMLLoader.loadXML(["file1.xml"]);

16

The file can be accessed by its array index or by the actual name of the file. To determine the index, it is the order in which you passed them to the constructor or the loadXML function. In this example file1.xml would be index 0 and file2.xml would be index 1. These are the basics for using the class. The developer is able to place different xml files into variables instead of typing out the whole path name all the time. I hope you find this tutorial and class useful. Have fun loading up XML files in the blink of an eye now.

}

trace(myXMLLoader.getList["file1.xml"]); trace(myXMLLoader.getList[0]);

//Output would be file1.xml data from both trace statements

01/2009 (3)



ActionScript Developement

Will You Flex? by Bernard Pineda Adobe launches Flex 4. But before you are ready to start Flex-ing, let’s take a look into what Adobe Flex is, why it is one of the leading technologies for RIA’s and how we can make simple applications with and without the Flex Builder. What you will learn...

What you should know...

• • • •

• Basic notions of conventional web applications • Basic web programming • ActionScript knowledge is useful but not compulsory for this article

What RIA's are What Adobe Flex is Basic Flex coding What's new in Flex 4

Level of difficulty

I

n order to view what’s new in Adobe Flex 4, we shall first define what Adobe Flex is. Adobe Flex is a different approach to web application development. It is used to build the front-end (visual layout) of web applications, and thus is separate from the programming of the back-end (db and data-driven functionality, etc). Flex applications are called RIA’s (Rich Internet Applications) because, besides having all the functionality of a web application, they have several desktop-like behaviors that enrich their usability. It runs using the Flash Player 9 as a virtual machine similar to the JVM (Java Virtual Machine) and can interact with Flash animations, images, and even html. It uses ActionScript 3 to do all the necessary programming and interaction with the user inside the application. Instead of using keyframes in a timeline (as Flash does), applications made in Flex use an XML-based language called MXML to create components and thus make the GUI (Graphic User Interface). Every tag and/or component inside the interface is actually an ActionScript class, and the developer can access the methods, properties and events that correspond to that class. If I was to give Flex a slang name, it would be Flash for Programmers. Whenever a non-Flash developer starts an approach towards Flash, they 18

can easily adapt to the use of ActionScript, and even appreciate the vast number of classes that Flash has now built in. But the problem they always (or almost always) run into is the use of the timeline. It’s difficult for a programmer to grasp what the timeline really is and how to benefit from its use. And that’s where Flex comes to the rescue. With Flex, you don’t have to worry about the timeline to program an interface. If you use the Flex Builder – which we will soon describe – you just drag and drop components into the canvas, save, and your application is ready to be deployed. For simple effects, you can take advantage of the builtin animations Flex has, to give an interface a more interactive look-and-feel. With just a few lines of code you can make a simple click on a button look animated. Of course, these animations are quite simple compared with a complex, customized animation that you could accomplish with Flash. Since they (both Flash and Flex) use ActionScript, you can accomplish practically the same things in Flash as in Flex. But while making animations and nice layouts are easier and faster with Flash, applications and interaction with data is so much easier with Flex. Comparing Flex and Flash is like trying to compare an SUV with a small car. The first is not better than the latter. They were just simply made for different purposes, but in the end, they will both take you to the same place. Flex has some competition in the making of RIA’s. To name a few: AJAX, Microsoft’s SilverLight, etc. The main (though not the only)

advantage that Flex has over these is that Flex will run on any web navigator that has Flash Player 9 installed (be it Internet Explorer, Firefox, Safari, etc.) on any Operating System (be it Windows, Mac or Linux). As of now, the biggest competitor is SilverLight, because of the similarities in usability and functionality with Flex. The advantage that SilverLight could have over Flex is that it’s practically married to .NET’s backend technologies (C #.NET, Visual Basic.NET, Java.NET, etc) and the support and integration with these technologies and programming tools (Visual Studio, Blend) is practically native. Flex is able to communicate with data-driven applications and databases through the use of back-end languages such as PHP, Java (through Java Server Pages and Servlets), ASP.NET, ColdFusion, Ruby, Python, etc. This connection is made with Web Services and/or Http Services. Remote Objects can also be used and make the programming so much simpler because we just need to call the remote objects, and depending on the configuration, we can have access to the methods and attributes of the remote objects. Remote Objects can facilitate the connectivity between the RIA’s and the server-side applications. To view an example of these type of platforms, refer to WebOrb. In addition to that, Flex is currently being used to create applications that use different API’s (i.e. Google’s APIs, OpenSocial, FaceBook, Hi5, etc.). So what are the advantages of RIA applications made in Flex over traditional web applications?

Figure 1. Flex builder splash

01/2009 (3)


Flex

For starters, the output of an application in Flex is a SWF (Shockwave Flash File), which pretty much behaves like any other Flash animation. You load it once, and don’t have to worry about loading it again and again once the application is running. Whereas in traditional web applications you have to load each page, in RIA’s you load every part of the application once you load the SWF with a web browser. The concept of pages inside a web application disappear. So let’s say, for example, that a “traditional” web application has an image on the top part that is 75 KB in size, and this image must be shown in every single page of the application. The application has 15 different pages. If a user was to go through every single page once, you would have downloaded the image 15 times, which would make a 1,125 KB from just one image! What if the user was using the application all day long, reloading the pages over and over? What if instead of one image, the application had 5 images? You can get a rough idea where I’m going with this. With a Flex application, an image is loaded only once into memory, and every time you want to display it, Flex simply gets it from memory, and shows it instead of downloading it again. Let’s say your Flex application is 1,000 KB in size, plus 75 KB from embedding the image inside the application. Even though at first you’d be downloading a bit more than one MB, that’s all you’d be downloading if you used the application all day. You can imagine how much bandwidth you could save. Editor’s Note: Although browser cache may minimize multiple downloads of the same image, the point remains valid: Flex saves bandwidth. Another advantage of a Flex application over traditional web applications is that it is more user friendly, since in Flex you can emulate certain desktop behaviors (such as drag-n-drop, working off-line, etc.) and your interface could be even more intuitive, depending on the GUI. The only downside of this is that you have to download/upgrade the Flash Player on the client’s computer, though nowadays practically every computer has the Flash Player already installed. One more advantage that I find important to review is that you are able to divide the user interface from the programming (using the MVC pattern). In other words, there can be changes made within the back-end of the application, without affecting the user interface as much, and vice versa. You can divide the work the designers do from the work the programmers do, so they don’t have to affect each other’s work. Another interesting addition to the Flex SDK is the launching of Adobe AIR. Code named Apollo, AIR let’s us take applications made in Flex, Flash, or JavaScript (pretty much AJAX), and turn them into desktop applications. The AIR SDK comes with several libraries so we can 01/2009 (3)

interact with the Operating System and the File System. We will make some simple applications on AIR on future articles.

Helpful Tools One of the most helpful tools for Flex development is the Flex Builder (Figure 1). You can get it as a stand-alone application or as an Eclipse Plug-in. Flex Builder is very helpful in the building of a Flex application because it automatically does a lot of tasks that otherwise we would have to manually do ourselves. Depending on the configuration, it can compile the application every time we save our work. It also gives us an idea of how the application is going to look before we compile it and run it (Figure 2). Flex Builder has different views for the programmer. In the figure shown, we have the Source View activated. We can see all the code that the Flex Builder has automatically generated for us. As we can see, we have our

MXML tags, along with the root node which is the Application node and its attributes. Once we start typing mxml code, the Code Hint can help us by suggesting input from several options (very much like the IntelliSense in Visual Studio) (Figure 3). This, along with automatic code generation, is very useful and can make our coding much faster and easier (Figure 4). The Design View gives us a pretty precise idea of how the application will look running. It also gives us the advantage of saving time by dragging components into the canvas instead of coding them. Let’s do a small example so we can grasp how easy it is to develop with the Flex Builder: On the Source View, we are going to type the following code (Listing 1). On line 5 through line 13, we embed a script with some simple code to show an alert (pretty much like an alert in JavaScript). We imported the Alert library, and created a void function called showAlert. Inside the function we called the static class Alert and its method show to display the alert. When we dragged the button into the canvas, the Flex Builder added the code on line 14. To this we add the last part where it says click=”{showAlert()}”. With this, we are telling the Flash Player that when a user clicks on the button, the ActionScript code inside the braces will be executed, in this case the function showAlert (Figure 5).

Figure 2. Flex builder src view

Figure 3. Flex Builder’s Code Hint

Figure 4. Flex builder design view

Figure 5. Sample app location

Figure 6. Sample app running

Figure 7. Sample app notepad

Figure 8. Sample app command line 1

19


ActionScript Developement Once we save this, the Flex Builder will automatically compile the code, and pack into a nice little SWF. It will also generate an html and the JavaScript to load the SWF into it. Let’s double-click on the SWF to see the small application running. Once the application is running and we click on the button, we get the alert. One of the functionalities of this alert is that it blurs everything else and you can’t click or interact with the rest of the application until you click on the buttons of the Alert. This can be helpful whenever you need to acknowledge certain actions from the user. In a future article we will discuss different kinds of alerts. This modified version of the universally known Hello World program gives us an idea of how simple it is to code in Flex with the use of Flex Builder. Unfortunately, the Flex Builder is not free (except for Educational use). You can check the price tag on the Flex Builder at http://www.adobe.com/products/flex/features/ flex_builder/. Fortunately, for those of us who don’t have a boss who will readily buy a Flex Builder license for us, there is another option. The Adobe Flex SDK (Software Development Kit) comes with a command line compiler (mxmlc.exe); all we have to do is execute it along with the name of our mxml file, and it will do the rest. Let’s try a small example to understand all this (Figure 6). The first thing we need to do is find the mxmlc.exe. I found it in: C:\Program Files\Adobe\ Flex Builder 3 Plug-in\sdks\3.0.0\bin, but beware that the location could be different for you, since the one I found on my computer is the one that comes with the Eclipse Plug-in. Also you can have different versions of the compiler since you’ll have one for Flex 2, another for Flex 3, Listing 1. Building a simple app with an Alert

and yet another one for Flex 4. Once we have the version of the compiler that we want to use, we create our source file. We can use notepad, vi, or any other editor we like. For this example I used Notepad (Figure 7). Let’s copy the code from the previous example, paste it on an empty Notepad and save it as C:\Documents and Settings\ber\My Documents\Flex\command_line_test.mxml. Let’s open a command line box in order to compile it see (Figure 8). Since we know where the mxmlc.exe is, let’s just type its location, along with the compiler’s name, and the name of the source file. C:\Program Files\Adobe\Flex Builder 3

Plug-in\sdks\3.0.0\bin\mxmlc.exe command_line_test.mxml see (Figure 9).

With this, the compiler should have generated a SWF file. Just double click it and the outcome will be the same as the previous example see (Figure 10). The Flex Builder does the same thing as we just did, but it does it in a transparent way, since it already has the locations of the compiler and the source file. One disadvantage of using the Flex Builder is that it consumes a lot of memory since it has to run on Java. One disadvantage of not using the Flex Builder is that every time you make a change on the source code, you’ll have to compile it

Figure 9. Sample app command line 2

1. <?xml version="1.0" encoding="utf2. <mx:Application

8"?>

3. xmlns:mx="http://www.adobe.com/ 4.

2006/mxml"

layout="absolute">

5. <mx:Script> 6. 7.

<![CDATA[

8.

private function

9.

{

11.

}

10.

12.

Figure 10. Command line text

import mx.controls.Alert;

]]>

showAlert():void

Alert.show("You

clicked!");

13. </mx:Script>

14. <mx:Button x="50" y="69"

label="Button"

click="{showAlert()}"/ >

15. </mx:Application>

20

Figure 11. Flex builder new project

and reload it to view the changes you made. Personally, I prefer using the Flex Builder because of the ease of use, but if it ever stopped working, it’s good to know you have other options so you don’t stay stranded. Now that we know we don’t depend on any tool to make Flex applications (except for the SDK), let’s also make a small application in which we shall see how to make a simple animation for an image. We shall create a new flex project on the Flex Builder (File>New>Flex Project), and we shall name it Simple Animation see (Figure 11). As you can see in the image above, we could make this application an AIR application, but we’ll do that on a future article. Once we click the Finish button, the Flex Builder automatically creates a main.mxml file, which is the main application and in which we will type (or paste) the following code (Listing 2). Now, let’s explain what we’re doing. We added a button to the canvas, and an image. The button will have the label Show Image and will execute the ActionScript function showImage(). The image will be embedded into the SWF, with the advantage that the image is part of the code itself, and the disadvantage that the SWF will be larger in size. The image is initially not visible. For that we have the void function showImage() on line 8, which takes the id of the image, and calls the attribute visible and changes its value to true. On line 15 we start defining the effect that we are going to apply to the image. In this case, we are going to use a Fade effect. For other available effects, refer to Flex Effects. We also have a showEffect attribute (line 30) on the image, which takes the id of the effect that it’s going to be used when the component is made visible. We could also use the hideEffect attribute and add it as a Fade out effect so if the image was to be hidden, it would also do it with the same effect that it was shown with (Fade out). After saving it, we view the SWF and we will see that when we click on the button, the image starts fading in, until the image is totally visible. So, as I mentioned before, with just a few lines of code, we animated an image. We can apply this type of animation to other Flex components, such as Canvas, TabNavigator, ViewStack, etc. It’s just a matter of playing around with the components and the effects. Now that we have a general idea of what Flex is, we can focus on what’s new, the new version of Flex, code named Gumbo. The main improvement in Flex 4 is GUI design. According to Adobe’s Ely Greenfield, the general purpose of the new SDK will be to give the designer complete control of the lookand-feel of a Flex application. Flex 4 will have, among other things, a new namespace MXML 2009 that will provide some enhancements, a new file format for vector graphics in xml, a new architecture for components and skinning, and improvements to existing features such as states, effects, transitions and layouts. 01/2009 (3)


Flex

Applications made in Flex 3 will be supported, and the current component model (called Halo) will integrate with the new functionality. Some of the improvements that will reflect directly on the developer’s productivity are the improved compiler and CSS improvements such as multiple styleNames, descendent, child, and id selectors. Integration with the Flash Player 10 deserves some attention since the player is going to have a lot of brand new text features and a new video component. Let’s take a look at a list of features for Flex 4. FXG (Graphic Interchange Format) Contains high-level graphic and text primitives that can be used to create, group, transform, and visually modify basic vector and bitmap shapes. Skinning and Skinnable Components Skin creation without having to write any ActionScript code. Listing 2. Animating an image 1. <?xml version="1.0" encoding="utf8"?>

2. <mx:Application

3. xmlns:mx="http://www.adobe.com/ 4. 5.

layout="absolute"

backgroundGradientColors="[#FFFFFF , #FFFFFF]">

6. <mx:Script> 7. 8.

<![CDATA[

private function

9.

{

10. 11. 12.

2006/mxml"

]]>

showImage():void

img_example.visible= true;

}

Enchanced States Syntax Improves experienced-oriented features such as states, effects and layout.

TextArea Component A SkinnableComponent that allows the user to enter and edit multiple lines of rich text.

Group Containter The Group class is used in Container, ListBase and individual components, providing a single consistent mechanism for all layout in an application.

ScrollBar Component An improved scroll bar component.

Items Component and Selector ItemsComponent is the base class for all skinnable components that have content. For example, Panel is a subclass of ItemsComponent that has a border, header, and footer. This is a pure model class that does not make any assumptions about the presentation or behavior of the items. Selector is a subclass of ItemsComponent that is the base class for any skinnable component that supports selection. List, TabBar, ComboBox, and RadioButtonGroup are all subclasses of Selector. Selector is also a pure model class. Application Component Gumbo's Application (flex.core.Application) is an ItemsComponent designed to be the top-level container for new Gumbo applications. The new class was needed so Application can hold graphic elements directly. Text Primitives FTE, or Flash Text Engine is the foundation of future text functionality in the Flash Player 10. Gumbo will have three text primitives: TextBox, TextGraphic, and TextView. TextInput Component A SkinnableComponent that allows the user to enter and edit a single line of single-styled text.

13. </mx:Script> 14. 15.

<mx:Fade

Partial sources:

17.

duration="1000"

16. 18. 19.

id="fadeIn"

alphaFrom="0.0"

alphaTo="1.0"/>

20. <mx:Button 21.

x="10"

23.

label="Show Image"

22. 24.

y="10"

click="{showImage()}"/>

25. <mx:Image 26.

id="img_example"

28.

x="0"

27. 29. 30.

y="40"

source="@Embed('fx.png')" showEffect="fadeIn"

31.

• • •

visible="false"/>

32. </mx:Application>

01/2009 (3)

Jacobs, Sas, De Weggheleire, Koen, Foundation Flex For Developers, Apress company, 2008. Tapper, Jeff, et.al., Adobe Flex 2: Training from the Source, Adobe Press, 2006 http://cksachdev.blogspot.com/2008/ 07/what-new-in-f le x- 4 - code-namegumbo.html http://flexorg.wip3.adobe.com/gumbo/ gumboplan.htm http://livedocs.adobe.com/flex/201/ html/wwhelp/wwhimpl/common/html/ wwhelp.htm?context=LiveDocs_Book_ Parts&file=behaviors_068_05.html http://www.mikechambers.com/blog/ 2008/08/27/everything-there-is-to-knowabout-flex-4-gumbo/ http://www.adobe.com/devnet/flex/

Range Class The Range class provides basic functionality for bounded values with maximum, minimum, and restricting the value to an increment. Track Base Class The TrackBase class subclasses Range and introduces the concepts of a thumb and a track for the thumb to move along. It also provides the basic functions to map values to positions in subclasses. Slider Component The Slider class is the base class for Slider controls. Slider provides basic functionality for Slider controls such as liveDragging, keyboard handling and track click handling. Spinner Component Spinner controls a value through its two buttons, incrementButton and decrementButton. These buttons use stepSize to increment or decrement the values. Numeric Stepper Component NumericStepper is a Spinner that has a TextInput companion. MXML 2009 Flex 4 will come with a new namespace. Users will be able to mix components on the same document. The old one (2006) will still be usable. Along with these improvements and key features, Flex 4 will also have automation support for Flex in AIR. The final release of Flex 4 is scheduled for the second half of 2009. Another important project that is parallel to the Gumbo release, but is not intrinsically related is the initiative to build a lightweight/ scalable framework for Flex RIA’s that would run on smart and mobile devices. The first version of this framework is scheduled for some time in 2010.

BERNARDO PINEDA Bernardo Pineda is a free-lance IT Consultant/ Developer at activ.com.mx. He is specialized in back-end programming (PHP, Java, .NET) and taking a plunge at front-end technologies (Flex, SilverLight). He is currently majoring in Computer Engineering. In his spare time he programs for fun, plays guitar and tennis, and skates. He loves John Grisham novels.

21


ActionScript Developement

Getting Started with Google Maps in Flash by Jassa Amir-Lang There has been a lot of hype with the release of the Google Maps API for Flash. A lot of the examples and tutorials however are aimed at Flex developers.

What you will learn…

What you should know…

• The basic steps needed to get started with GoogleMaps in the Flash IDE; • How to convert locations from text to longitude/latitude values; • Basic search functions; • Working with Routes; • Getting directions from one location to another.

• General knowledge of Flash; • A general knowledge of ActionScript 3 (AS3); • An understanding of how the Document Class works.

Level of difficulty

W

hile Flex offers some fantastic features, some projects need to be built in Flash. And let’s face it – there are some of us who just love working in Flash.

Getting started To get started you will need to grab an API key. If you head over to http://code.google.com/apis/ maps/signup.html you will be able to generate one. Copy it and save it somewhere as you will need to use this later on. Next you will need to download the Google Maps Component for Flash. Head over to http://groups.google.com/group/googlemaps-api-for-flash/files and look for the GoogleMapsComponent.mxp file. Download this and install it through Adobe Extension Manager. If you have Flash CS3 open, you will need to quit and load it up again once you’ve installed the component.

sure that it is linking up ok by clicking the little pencil to the right of the field. This should open up your actionscript file see (Figure 1).

Initial Setup Time to get stuck into some AS3. Firstly, create your GoogleMap class that extends the Sprite class see (Listing 1).

Classes timeline to Map. Create a new MovieClip and call it mapHolder. Leave it empty, and drag an instance of it on to the the Map layer. Give it an instance name of mapHolder and position it at 0 on the x axis and 150 on the y axis. Finally, go to the Components panel and drag an instance of the newly installed GoogleMapsComponent on to the stage, and then delete it. This will leave a copy of it in your library. This component contains all of the Google Maps classes we need to access and as long as it sits in your library, they will be available for import. Now we are ready to start coding. In this example I will use a Document Class so that you become familiar with the classes that we will be using. You could however, just as easily use an actions frame. Create a new actionscript file and name it GoogleMap. Save it in the same location as your FLA. If you have not saved that yet you can do that now. Next, link the actionscript file to the FLA by setting the document class definition field in the properties panel to GoogleMap. You can make

Now we will start import some additional classes. First we will import some flash classes. For this example you will need the classes found in (Listing 2). You can insert these just after the Sprite class import. Next we will import the Google classes that we will be using see (Listing 3).

Variables There are a few variables that we need to set up for this example. You can see how I have set these up in (Listing 4). The Map is the main Google Map class; the ClientGeocoder is used to convert valid address/locations from Strings to Latitude/ Longitude values; the Route, Directions and Polyline variables will all be used in our routing function. These variables should be declared between the public class and public function lines.

Creating the Map With that setup, we can jump into the main function. First we will create a new Map, declare our API key, and then add the map to our stage.

Setting up the FLA Ok, with that out the way we can get started. Create a new Flash document (ActionScript 3), set the document size to 800x600 and set the frame rate to 30fps. Rename Layer 1 in the 22

Figure 1. Basic FLA Setup

01/2009 (3)


Google Maps in Flash

We will also set the size of our map, and add an EventListener to let us know when the map has been loaded. You can find the GoogleMap function in (Listing 5). Next, underneath your GoogleMap public function create a new private function to handle the onMapLoadReady call see (Listing 6). Now jump back into your FLA and test your movie. If all has gone as planned, you should now be able to see a Google map. So far so good! Do not be alarmed if you map

has DEBUG MODE written all over it – this will disappear when you deploy the project to a webserver. Head back to your Document class and into the onMapLoadReady function. When the map has been initialized we are going to use our ClientGeocoder to position the map at a desired location – I am going to position the map over the Via Media office here in sunny Adelaide. We will need to create two functions: one to handle a failed result if the

Listing 1. Your Initial Function package { import flash.display.Sprite; public class GoogleMap extends Sprite{ public function GoogleMap():void{

location does not exist and one to handle a successful result. You can see the final function in (Listing 7).

Positioning On a successful result, we will use the setCenter method to center the map at the position created by the ClientGeocoder. The setCenter method takes three parameters: Latitude/Longitude, zoom level and map type. In our example we will set the zoom

Listing 6. Checking that the map has loaded private function onMapLoadReady(e:MapEvent):void{ }

trace("Map has been initialized");

Listing 7. Setting up a location private function onMapLoadReady(e:MapEvent):void{ trace("Map has been initialized");

Listing 2. Import the Flash classes

geocoder = new ClientGeocoder();

geocoder.addEventListener(GeocodingEvent.GEOCODING_SUCCESS,

import flash.display.Sprite;

onGeocodingSuccess);

import flash.display.MovieClip;

geocoder.addEventListener(GeocodingEvent.GEOCODING_FAILURE,

import flash.events.MouseEvent;

geocoder.geocode("283 rundle street adelaide, south

import flash.events.Event;

onGeocodingFailure);

import flash.geom.Point;

import flash.text.TextField; }

}

}

australia");

Listing 8. Handling the geocoding event private function onGeocodingSuccess(e:GeocodingEvent):void{ googleMap.setCenter(e.response.placemarks[0].point, 17,

Listing 3. Importing the Google classes import com.google.maps.Map;

}

private function onGeocodingFailure(e:GeocodingEvent):void{ trace("GoogleMaps could not locate the requested

import com.google.maps.overlays.*; import com.google.maps.controls.*;

MapType.HYBRID_MAP_TYPE);

location");

import com.google.maps.services.*;

Listing 9. The handleSearch funtion

import com.google.maps.MapType;

private function handleSearch(e:MouseEvent):void{

import com.google.maps.MapEvent; import com.google.maps.LatLng;

Listing 4. Setting up the Google variables

}

geocoder.geocode(searchTxt.text);

Listing 10. Adding the search button listener private var googleMap:Map;

private var geocoder:ClientGeocoder;

searchBtn.addEventListener(MouseEvent.CLICK, handleSearch);

private var directions:Directions;

Listing 11. Creating the directions

private var route:Route;

private var polyline:Polyline;

Listing 5. Creating the map

private function handleRoute(e:MouseEvent):void{

if(polyline) googleMap.removeOverlay(polyline);

directionsTxt.htmlText = "Calculating Route..."; directions = new Directions();

public function GoogleMap():void{ googleMap = new Map();

directions.addEventListener(DirectionsEvent.DIRECTIONS_

googleMap.key = "PASTE YOUR API KEY HERE";

SUCCESS, onDirectionsSuccess);

mapHolder.addChild(this.googleMap);

directions.addEventListener(DirectionsEvent.DIRECTIONS_

googleMap.addEventListener(MapEvent.MAP_READY,

directions.load(fromTxt.text + " to " + toTxt.text);

googleMap.setSize(new Point(800, 450)); onMapLoadReady);

01/2009 (3)

FAILURE, onDirectionsFailure);

}

23


ActionScript Developement level to 17, and the MapType to Hybrid. (for additional map types, check out the Google Maps flash documentation: http: //code.google.com/apis/maps/documentation/ flash/). On a failure result we will simply trace an error message. You can see success/ failure functions in (Listing 8). If you jump back into your FLA and test your movie you should now be positioned over the location you entered and the map type will be set to satellite.

Adding the Search function Now that the map has been set up we will add the search and route functions. To start with we will need to build the controls. Lock the Map layer and create a new layer above it called Controls. On the new layer draw a dark grey 800px by 150px rectangle. I converted mine into a MovieClip so I could add a drop shadow to it but that is up to you. On top of that create three new input text fields. Give them instance names of searchTxt, fromTxt and toTxt respectively. Put static text labels next to them so that the user knows what to enter where. From the Components panel, grab a new TextArea. Give it the instance name of directionsTxt. This will be used to display written directions. Make sure in the parameters tab make sure the VerticalScrollPolicy is set to auto. you will also need to add two buttons: One with the instance name of searchBtn, and the other with the instance name of routeBtn. Give them relevant button labels. You can see how I have arranged my MovieClip in (Figure 2). Now open up your Document class again and create a new private function called handleSearch. Set its event type to MouseEvent. we will use the ClientGeocoder to convert the address string to a valid position just like we did when we centered the map. Instead of typing an address this time however, we will use the value of the searchTxt input box. see (Listing 9). The success/failure listeners added to the ClientGeocoder earlier will handle the results. Back in the onMapLoadReady function add the handleSearch MouseEvent to the searchBtn button see (Listing 10). If you test your movie now you should be able to search for an address once the map has initialized.

Getting Directions So far we have created a google map, positioned it, and added search functionality. Already you can see how easy it is to work with the API and how quickly you can give a map some

functionality. Next we will add the ability to get directions from one place to another. Create a new function called handleRoute. Within this function we will remove any preexisting directions by getting rid of any preexisting polylines, add some success/failure listeners to our new directions, and load in our origin, and our destination as text. The load method of the Directions class takes free form text and splits the origin and destination either side of to e.g. Adelaide, SA to Melbourne, VIC. You can find the handleRoute function in (Listing 11).

Now we need to create functions to handle the success and events. First of all we need to clear out the directions TextArea. Then we create a new Array called pArray (polyline array), and a new variable called vCount (vertex count). We set the vCount to the number of vertices in a polyline object created from the directions data. Then it's simply a matter of looping through the vertex data for each point in the polyline and pushing them to our pArray. Finally we can create a Polyline object from our pArray and add it as an overlay object to our google map. The first part of

Listing 12. Creating and adding the polyline private function onDirectionsSuccess(e:DirectionsEvent):void{ directionsTxt.htmlText = "";

var pArray:Array = new Array();

var vCount = directions.createPolyline().getVertexCount(); for(var i:uint = 0; i < vCount; i ++){

var currentVertex:Object = directions.createPolyline().getVertex(i)

}

pArray.push(currentVertex);

polyline = new Polyline(pArray); googleMap.addOverlay(polyline);

Listing 13. Adding the route and written directions route = directions.getRoute(0);

for(var j:uint = 0; j < route.numSteps; j ++){

directionsTxt.htmlText += route.getStep(j).descriptionHtml; directionsTxt.htmlText += " – "

+ Math.round((route.getStep(j).distance/1000)*100)/100

+ " kms. (" + Math.round((route.getStep(j).duration/60)*10)/10 + " }

mins).<br><br>";

directionsTxt.htmlText += "Total Distance: "+ Math.round((route.distance/ 1000)*100)/100 + " kms<br>";

if(Math.round((route.duration/60)*10)/10 > 60){ directionsTxt.htmlText += "Total Time: "

+ Math.round(((Math.round((route.duration/60)*10)/10)/60)*10)/10 + " hour(s)";

}else{

} }

directionsTxt.htmlText += "Total Time: " + Math.round((route.duration/60)*10)/ 10 + " mins";

googleMap.setCenter(route.getStep(0).latLng)

Listing 14 – adding the route button listener routeBtn.addEventListener(MouseEvent.CLICK, handleRoute);

Listing 15 – declaring the zoom controls variable private var controls:ZoomControl;

Listing 16 – adding the zoom controls controls= new ZoomControl();

googleMap.addControl(controls);

Figure 2. The search/directions movieclip layout 24

01/2009 (3)


Listing 17a. The final code package { import flash.display.Sprite;

import flash.display.MovieClip; import flash.events.Event;

import flash.events.MouseEvent; import flash.geom.Point;

import flash.text.TextField; import com.google.maps.Map;

import com.google.maps.overlays.*; import com.google.maps.controls.*; import com.google.maps.services.*; import com.google.maps.MapEvent; import com.google.maps.MapType; import com.google.maps.LatLng;

public class GoogleMap extends Sprite{ private var googleMap:Map;

private var geocoder:ClientGeocoder; private var route:Route;

private var directions:Directions; private var polyline:Polyline;

private var controls:ZoomControl; public function GoogleMap():void{ googleMap = new Map();

googleMap.key = "PASTE YOUR API KEY HERE"; mapHolder.addChild(this.googleMap);

googleMap.setSize(new Point(800, 450)); }

googleMap.addEventListener(MapEvent.MAP_READY, onMapLoadReady); private function onMapLoadReady(e:MapEvent):void{ trace("Map has been initialized"); geocoder = new ClientGeocoder();

geocoder.addEventListener(GeocodingEvent.GEOCODING_SUCCESS, onGeocodingSuccess); geocoder.addEventListener(GeocodingEvent.GEOCODING_FAILURE,

a

01/2009 (3)

d

v e

r

t

i

s

e

m

e

n t


ActionScript Developement

if(polyline) googleMap.removeOverlay(polyline);

the onDirectionsSuccess function can be found in (Listing 12). Still in the same function, we need to handle the written directions. First of all we set the route by calling the getRoute method on our directions variable. The getRoute method takes the requested route index number as a parameter. Since we know we only have the one set of directions in this example, we just need to pass it 0. Then we loop through the number of steps in the route and add the directionsHtml property for each step to our description TextArea. I have also added the approximate distance in kms, and time in minutes. After the loop I have calculated the total time and distance. Finally, I set the center of the map around the first step of the route, and closed the function. The second part of the onDirectionsSuccess function can be found in (Listing 13). Once you have completed this function you can add the necessary MouseEvent to the routeBtn just after the listener for the searchBtn. see (Listing 14).

directions = new Directions();

Finishing touches

Listing 17b. The final code onGeocodingFailure);

geocoder.geocode("283 rundle street adelaide, south australia"); controls= new ZoomControl();

googleMap.addControl(controls); searchBtn.addEventListener(MouseEvent.CLICK, handleSearch); }

routeBtn.addEventListener(MouseEvent.CLICK, handleRoute);

private function onGeocodingSuccess(e:GeocodingEvent):void{

googleMap.setCenter(e.response.placemarks[0].point, 15, MapType.HYBRID_MAP_ TYPE);

}

private function onGeocodingFailure(e:GeocodingEvent):void{ }

trace("GoogleMaps could not locate the requested location");

private function handleSearch(e:MouseEvent):void{ }

geocoder.geocode(searchTxt.text);

private function handleRoute(e:MouseEvent):void{

directionsTxt.htmlText = "Calculating Route..."; directions.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, onDirectionsSuccess);

directions.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, onDirectionsFailure);

}

directions.load(fromTxt.text + " to " + toTxt.text);

private function onDirectionsSuccess(e:DirectionsEvent):void{ directionsTxt.htmlText = "";

var pArray:Array = new Array();

var vCount = directions.createPolyline().getVertexCount(); for(var i:uint = 0; i < vCount; i ++){

var currentVertex:Object = directions.createPolyline().getVertex(i)

}

pArray.push(currentVertex);

polyline = new Polyline(pArray); googleMap.addOverlay(polyline); route = directions.getRoute(0);

for(var j:uint = 0; j < route.numSteps; j ++){

directionsTxt.htmlText += route.getStep(j).descriptionHtml; directionsTxt.htmlText += " – "

+ Math.round((route.getStep(j).distance/1000)*100)/100

+ " kms. (" + Math.round((route.getStep(j).duration/60)*10)/10 + " mins).<br><br>";

}

directionsTxt.htmlText += "Total Distance: "+ Math.round((route.distance/ 1000)*100)/100 + " kms<br>";

if(Math.round((route.duration/60)*10)/10 > 60){ directionsTxt.htmlText += "Total Time: "

+ Math.round(((Math.round((route.duration/60)*10)/10)/60)*10)/10 +

}else{

" hour(s)";

directionsTxt.htmlText += "Total Time: " + Math.round((route.duration/ 60)*10)/10 +

26

So that is basically it. The only extra object I would add is a zoomControl overlay which allows the user to zoom in/out. First declare a zoomControl with the rest of your variables see (Listing 15). And then add it to the map once it has been initiated see (Listing 16). So let review what we have covered in this tutorial. Firstly we created a new google map and positioned it on the stage. Then we added a search function to it by using the same ClientGeocoder.geocode method that we used to position the map initially. On top of that we created a Route object based on the Directions returned from our text input boxes. From there we created a Polyline from the vertex points of the Directions object and grabbed the directions information about each step to add to our written directions list. I highly recommend you check out the online documentation as everything to do with the Flash API for Google Maps is there. You can read in depth about some of the methods we’ve used in this tutorial, and find out more about what the API has to offer. The online documentation can be found at http:// code.google.com/apis/maps/documentation/flash/ reference.html. To take a look at the final code for this tutorial, look at (Listing 17).

JASSA AMIRLANG Jassa Amir-Lang lives in Adelaide, South Australia. He is a Flash developer for digital agency Via Media [viamedia.com.au]. In his spare time he occasionally updates a blog at www.bangersandflash.net.

01/2009 (3)



ActionScript Developement

Visualizing GeoSpatial Data using Vector Maps by Jean-Marc Wieland and Sandra Engene

In 140 A.D. Ptolemy described cartography as an imitation through drawing of the entire known part of the world together with the things which are connected with it. Using the drawing pen of Flex, we’ll explore new methods for creating maps and visualizing the world. What you will learn...

What you should know...

• Building a map based visualization application • Customizing look and feel of map features and symbols • Creating controls and events

• • • •

Level of difficulty

G

eoSpatial visualization is the use of tools and techniques to support data analysis with graphical representations. Using ActionScript and Flex functionality, applications of geovisualization can be significantly extended beyond conventional cartography. Taking advantage of this potential, a RIA approach to presenting geospatial data is the focus of this article, and specifically the potential of using Flex/ActionScript to support the visual representation of maps and other characteristics of geographic data.

Getting Started This tutorial is based on an open source library called BirdEye and its GeoSpatial Analysis Visualization (GeoVis) component. The GeoVis component enables users to create complex data visualization interfaces for the analysis of geospatial data sets from geographic information systems (GIS) and statistical sources. The compiled GeoVis library (i.e., GeoVis.swc) can be downloaded from the project site and should be included in your Flex Project.

Basic Concepts Geospatial analysis is based on the exploration and discovery of attributes for geographic objects. 28

Create a Flex Project using external libraries Basic ActionScript Configuring mxml controls Working with XML

The common goal of these approaches is to provide visible representations to explain and enable the understanding of spatial data. Throughout this article I will demonstrate these concepts using a recent case study – the 2008 Beijing Olympics. To better understand the basis for geospatial analysis and the methods of cartographic theory, there are five basic points should be understood:

feature objects are countries, which are codified by unique identifiers based on the ISO 3166 standard. The three letter ISO codes will serve as the IDs for all our map features. Each country will have metadata (attributes), such as name and the number of gold, silver, and bronze medals. The XML sample below illustrates the basic requirements for our example map configuration: <countries>

<Country iso=”AFG” name=”Afghanistan”

gold=”0” silver=”0” bronze=”1” total=”1”>

<Country iso=”DZA” name=”Algeria” gold=”0” silver=”1” bronze=”1” total=”2”>

</countries>

Map Layout

• Map Projection: A map projection is any method used in cartography to represent the two-dimensional curved surface of the earth or other body on a plane. • Feature: A feature is an object of geometry such as a polygon, which represents a geographic concept(i.e., a country). • Symbol: A symbol is a pictographic representation used to annotate geographic data (i.e., pie chart or icon). • Choropleth: A choropleth map is a thematic map in which areas are shaded or patterned in proportion to the measurement of the statistical variable being displayed on the map. • ISO 3166: ISO 3166-1 alpha-3 is threeletter codes used as standard references for identifying countries.

The GeoVis component provides for the layout of maps using several geographic projections. The projections are determined by the mathematical models, which are based on the geometry of transforming a sphere. (Figure 1) illustrates the different projection options, which you can select from for the best fit presentation of your data. For the purposes of the tutorial, we will configure our application to use a Miller Cylindrical projection. Let’s begin by creating our main application file and adding the GeoVis component (Listing 1) (line 55), illustrates the configuration of a WorldMap instance and the parameters required. This code configures the WorldMap component, which we place like any other Flex mxml component, for example:

Data Source

<geomap:WorldMap id=”myMap” projection=

We will begin the project by defining a simple XML data source based on the 2008 Beijing Olympic Medal statistics. This data source will specify characteristics about our map features and symbols. In this example,

”Miller cylindrical” />

The WorldMap tag produces a blank map similar to the images shown in (Figure 1). We will proceed to stylize features, add symbols, 01/2009 (3)


Visualizing GeoSpatial Data

and configure controls and events to produce an end product.

Feature Styling A choropleth map is a typical mapping technique for showing comparison of values among features. For this tutorial we will build a simple choropleth map where each country will be colored based on its total Olympic medal winnings. A single feature may be configured using the feature tag such as: <features:feature foid=”FRA”

color=”0xFF0000” />

However, since our objective is to style all feature objects, a function created specifically for this purpose is used (Listing 1) (line 60) illustrates the code for creating a basic choropleth map based on the choropleth class, which serves as a repeater to stylize each country based on data parameters from the XML source. The choropleth tag automates the color coding of data values based on ColorBrewer schemes.

Color Brewer The GeoVis implementation of ColorBrewer (http://ColorBrewer.org) is derived from a web tool for selecting color schemes for thematic maps developed by the GeoVISTA Center at Penn State. ColorBrewer includes 35 basic

schemes with different numbers of classes for over 250 possible versions. Color schemes may be configured by one of three methods: • Sequential: a series with varying lightness of a single hue (i.e., grey scale. ) • Diverging: a series with a “class break” in the middle of the sequence such as the mean or median. • Qualitative: a series with contrast hues and lightness, which are used to highlight pairs and accents. Using ColorBrewer greatly simplifies the process of automating parametric styles of map features. ColorBrewer is integrated into the choropleth class with a colorScheme, step, and baseHue properties as illustrated in (listing 1), line 62.

Adding Symbols The use of symbols provides the advantage of annotating map features with multidimensional representations. In contrast to the single value of the choropleth, a symbol object such as a bubble or pie chart may be used to present multiple values. For the example, we will add a bubble plot to graph the gold medal winnings for a given country. Similar to features, symbols are placed based on ISO code references.

(Listing 1) (line 65) and (Listing 2) extend this code to illustrate the configuration of the pie chart object through the use of an item renderer. Note that when using foidField identifiers for symbols the object is placed in the center of the feature. For more specific control, latitude and longitude values may be specified.

Using Latitude and Longitude So far we have used only ISO codes as location identifiers. GeoVis also provides geocoding for latitude and longitude addressing. Similar to the Symbol class, we’ll use the LatLong class to place an icon as a capital city identifier for Beijing, the host of the 2008 Summer Olympics. <locators:LatLong lat=”39.92889”

long=”116.38833” >

With this basic declaration, a drawing object can be placed in geo-coded location. (Listing 1) (line 69), demonstrates the placement of a point annotation to mark the location of Beijing.

Controls for User Interactivity Creating a dynamic and interactive map application should include the necessary controls to navigate, zoom, and provide the means to explore, discover, and analyse data

Figure 1. Maps

01/2009 (3)

29


ActionScript Developement

Listing 1. main.mxml

1.<?xml version=”1.0” encoding=”utf-8”?>

borderStyle=”solid” borderThickness=”2”

2.<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”

52.borderColor=”#cccccc” cornerRadius=”20” paddingTop=”20” >

3.xmlns:geomap=”org.un.cava.birdeye.geovis.views.maps.world.*”

53.

5.xmlns:symbols=”org.un.cava.birdeye.geovis.symbols.*”

55.<geomap:WorldMap id=”myMap” height=”450” projection=”Miller

layout=”vertical”

4.xmlns:analysis=”org.un.cava.birdeye.geovis.analysis.*” 6.xmlns:locators=”org.un.cava.birdeye.geovis.locators.*”

54.<!-- Base Map -->

cylindrical” scaleX=”.970”

7.xmlns:controls=”org.un.cava.birdeye.geovis.controls.choropl

56.scaleY=”.970” x=”0” y=”150”

8.xmlns:viewers=”org.un.cava.birdeye.geovis.controls.viewers

58.

eth.*” .*”

9.backgroundGradientColors=”[#ffffff,#ffffff]” 10.> 11.

57.ItemClick=”getDetails(event)” > 59<!-- Choropleth -->

60.<analysis:Choropleth id=”choropleth” dataProvider=”{myWorl dMedals}”

61.foidField=”@iso” colorField=”@total”

12.<mx:Script>

62.alpha=”1” scheme=”RdBu” steps=”5” toolTipField=”@name”

13.<![CDATA[

highlighted=”true” />

14.

63.

16.

65.<symbols:Symbols id=”mySymbols” dataProvider=”{myWorldMedal

15.import org.un.cava.birdeye.geovis.events.GeoMapEvents; 17./* Get details based on feature click. */

64.<!-- Symbols -->

s}” foidField=”@iso”

18.private function getDetails(e:GeoMapEvents):void {

66.itemRenderer=”renderers.BubbleRenderer” />

20.var country:String = myWorldMedals.Country.(@iso==key).@n

67.

21.var gold:String = myWorldMedals.Country.(@iso==key).@gold;

69.<locators:LatLong lat=”39.92889” long=”116.38833” >

19.var key:String=e.key

ame;

22.var silver:String = myWorldMedals.Country.(@iso==key).@si lver;

68.<!-- Lat/Long based marker -->

70.<mx:Box width=”16” height=”16” color=”#ff0000” toolTip=”Beijing” />

23.var bronze:String = myWorldMedals.Country.(@iso==key).@br

71.</locators:LatLong>

24.var total:String = myWorldMedals.Country.(@iso==key).@tot

73.<!-- A color range slider based on color brewer and the

onze; al;

72.

choropleth -->

25.// The main application detail pane is populated with the

74.<controls:GeoAutoGauge id=”geoAutoGauge” x=”25” y=”400”

26.countryTxt.text=’Country: ‘ + country;

75.dataProvider=”{myWorldMedals}” foidField=”@iso”

28.silverTxt.text=’Silver: ‘ + silver;

76.height=”14”

30.totalTxt.text=’Total: ‘ + total;

77.startAtZero=”true” visible=”true”/>

32.

79.</geomap:WorldMap>

data

27.goldTxt.text=’Gold: ‘ + gold;

29.bronzeTxt.text=’Bronze: ‘ + bronze; 31.}

33.]]>

34.</mx:Script> 35.

target=”{myMap}”

valueField=”@total” width=”750”

scheme=”RdBu” steps=”5” geoTScale=”true”

title=”Percentage” textColor=”0x333333”

78. 80.

81.<!-- Labels for getDetails function / Zoom control -->

36.<mx:Style>

82.<mx:HBox width=”100%” height=”75” horizontalAlign=”center”

38.WorldMap {

83.<mx:Label id=”countryTxt” text=”Country:” />

40.stroke : #333333;

85.<mx:Label id=”silverTxt” text=”Silver:” />

37.

39.background-color : #ffffff; 41.} 42.

43.Choropleth{

44.strokeItem : #333333;

verticalAlign=”middle” >

84.<mx:Label id=”goldTxt” text=”Gold:” />

86.<mx:Label id=”bronzeTxt” text=”Bronze:” /> 87.<mx:Label id=”totalTxt” text=”Total:” />

88.<viewers:Zoom id=”zoom” target=”{myMap}” prompt=”Zoom

45.}

89.</mx:HBox>

47.</mx:Style>

91.</mx:VBox>

46. 48.

49.<mx:XML id=”myWorldMedals” source=”data/worldmedals.xml” /> 50.

map...” width=”250” />

90. 92.

93.</mx:Application>

51.<mx:VBox id=”mapCnvs” width=”800” height=”550”

30

01/2009 (3)


Visualizing GeoSpatial Data

from multiple views. For this purpose we will add a simple zoom control and a color range slider. Many of the necessary controls for GeoVis are included as components. For example, a zoom control is added as follows:

This is useful for adjusting the step thresholds for fine-tuning your data set.

Events

Adding a ColorBrewer range slider control is equally simple. Insert this code to your main application file as shown in (Listing 1), line 74:

It is often useful to offer a drill down of details and attributes for a specific node. We will create a basic detail pane to display some information from a feature item click event. Let’s create a getDetails function to display additional attributes from the XML data source. We will start by adding an item click event to our WorldMap component as follows:

<controls:GeoAutoGauge

<geomap:WorldMap ... ItemClick=

This control will enable users to specify the color parameters from the ColorBrewer series.

Next we will create the getDetails function that will trigger the pane data display to

<controls:Zoom id=”myZoom” target=”{myMap}” />

target=”{myMap}” />

”getDetails(event)” />

Links

The GeoVis library, source code and further information are available at: http://code.google.com/p/birdeye/

show the country name and values for medal winnings. The code for the function is shown lines 18-31. Take note of the special class GeoMapEvents invoked for the purpose.

Finishing Touches One of the advantages of Flex is the many effects and styles that can be applied to enhance feedback and interface aesthetics. Tooltips and mouse rollOvers are common examples. Line 62, illustrates the configuration of a tooltip and highlight glow effect with the tags toolTipField=”@name” highlighted=”true”. GeoVis maps can be styled using conventional CSS declarations, as shown in lines 36-47. For example, the following declarations will create a white background where map lines are drawn with grey strokes: WorldMap {

background-color : #FFFFFF;

}

stroke : #333333;

width=”{this.data.@gold}” height=”{this.data.@gold}”

Running the final application should yield a result similar to (Figure 2). This is a simple example to get you started. Use this tutorial to as a guide for your own applications. Also, check out the GeoVisExplorer example from the GeoVis site for a full demonstration of the possibilities.

cornerRadius=”25”

Next Steps

Listing 2. BubbleRenderer.mxml <?xml version=”1.0” encoding=”utf-8”?>

<mx:Button xmlns:mx=”http://www.adobe.com/2006/mxml” minWidth=”10” minHeight=”10” toolTip=”{this.data.@name}”

alpha=”.7” fillColors=”[#ffff00,#ffff00]” >

</mx:Button>

Several world, regional, and country maps are included in the core of GeoVis. Using this core architecture, users may customize and add their own maps based on SVG data. GeoVis is evolving quickly and will soon take advantage of the Flash Player 10 release offering 3D views and new controls. Stay tuned and happy mapping. Interested in the topic? Join the Google technical support group and get involved!

Acknowledgements GeoVis is based on Degrafa, the declarative graphics framework for Flex. Degrafa allows you to use MXML markup to draw shapes, make complex graphics, create skins and also includes advanced CSS support. To learn more about the project, visit http:// www.degrafa.com.

JEANMARC WIELAND AND SANDRA ENGENE

Figure 2. Final application

01/2009 (3)

Jean-Marc and Sandra are staff members of the United Nations and the lead developers of the BirdEye/GeoVis component. The United Nations Centre for Advanced Visual Analytics (CAVA) sponsors the Flex-based BirdEye visualization library and develops visualization applications for the United Nations. http://cava.unog.ch

31


ActionScript Developement

Socialbloom A Look At Flex Data Driven Applications by Walt Schlender This tutorial is designed for people with beginner to intermediate Flex experience.If you have prior programming experience, you should have no trouble following along.

What you will learn...

What you should know...

• Data driven applications • MVC (Model, View, Controller) architecture design patterns • Flex DataBinding • Some of the cool Flex visual effects

• What a class is • How events are dispatched within ActionScript 3 • How to read the Flex API reference

Level of difficulty

A

bout 2 years ago I was working as a contractor in San Francisco.One of my clients approached me and asked me to create a Social Network Map. It would show all of the users in a social network and their relationships with their friends.The project was a blast! I have always thought it would be interesting to apply something like this to say, Facebook to show who is hot, single and available in your friends networks. Since this article is on Flex, I will not actually be writing any server-side code.I will, however show you how to write an XML-powered view that can easily be connected to server-side code to visually display social networks.The basic process we will go through should help you understand how to architect and build datadriven views; the bulk of what I have done in my contracting practice.

Step 1. Build out the data model We will begin with a dummy XML dump of an imaginary database – a data driven application that takes data from a database and sends it to a client-side application running in a web browser. Data in a database is not directly available to Flash, which resides on some server a million miles away from the user’s computer.Somehow the data has to get into the Flash application. 32

One way it is commonly done is to use formatted markup languages like XML or JSON. XML and JSON are ways to format data so that data can be transmitted across the Internet from a server sitting in Timbuktu to a client’s web browser. With a bit of code it is relatively simple to take chunks of data sitting in a database, turn them into a string of text and whip them across the Internet. On the other end, Flex can take that string of text, and interpret it to figure out what information should be presented to the user. Because building server-side code is outside the scope of this article, I am going to show you how to load XML files from your hard disk. We will create the XML dummy file first. Here is what the dummy XML file looks like: see (Listing 1).

Step 2. Set up Your Project Using FlexBuilder, create a new FLEX project and save it with a name that you choose. Copy the XML from above and save it as friends.xml and place it into the bin/debug folder (which should now exist) within your Flex project. My project is titled SocialMapperII and my file SocialMapperII.mxml is the root file of the project. I will not be putting much code in there because I like to use files at the root for testing the rest of the code. This allows me to package collections of code into swcs and reuse them later. First, create a folder in the src folder called – com (right click->new in the src folder in the File Navigator). Inside of that a folder create another folder called walta and within that folder,

create another folder called socialviz. The code files, which will be placed into this folder, will have a package name of com.walta.socialviz. If you did not know, packages make it so that if there are two code files both having the same name (i.e., Loader (com.walta.Loader and flash.display.Loader) then they can both be used within this application. I am going to create another couple of folders within the socialviz folder. The first is view that will be used to store the cool visualization view files and the other, model that will hold the code, which loads the XML file. If you do not know about MVC architectures I highly recommend you learn about them. They will make you be able to build larger applications more efficiently. A good place to begin, if you are a Flex developer, is the PureMVC framework, which you can find at http://www.puremvc.org. I will split the code for this tutorial into a logical model layer and a view layer. We will start off with the XML loader.

Step 3. Build The XMLLoader and VO Objects Create a new class under the model folder called XMLLoader.

Figure 1. The end result will look something like this + will animate like the iPhone

01/2009 (3)


A Hive Full of Creativity

Listing 1. Friends.xml [Bindable]

<users>

public var name:String;

<user name="jason">

<friend name="jack">

[Bindable]

<profession>butcher</profession>

</friend>

}

public var profession:String;

<friend name="jill">

}

</friend>

Listing 4. XMLLoader.as

<profession>baker</profession>

<friend name="witch">

<profession>candlestick maker</profession>

package com.walta.socialviz.model

</friend>

{

<friend name="mark">

<profession>butcher</profession>

import flash.events.Event;

import flash.net.URLLoader;

</friend>

import flash.net.URLRequest;

<friend name="sally">

public class XMLLoader

<profession>baker</profession>

{

</friend>

<friend name="gonzales">

<profession>candlestick maker</profession>

private var xmlLoader:URLLoader; public function XMLLoader()

</friend>

{

<friend name="corey">

<profession>butcher</profession>

xmlLoader = new URLLoader();

</friend>

xmlLoader.addEventListener(Event.COMPLETE,

</user>

</users>

public function loadXML(userListURI:String):void{ }

package com.walta.socialviz.model

//When this function fires, there will be data in the xmlLoader

var data:String = xmlLoader.data;

public class UserVO [Bindable]

public var name:String;

}

[Bindable]

public var friends:ArrayCollection = new

public function addFriend(friend:FriendVO):void{

}

}

}

}

friends.addItem(friend);

trace(data);

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="absolute" creationComplete="init ()">

<mx:Script>

Listing 3. FriendVO.as

<![CDATA[

import com.walta.socialviz.model.XMLLoader;

package com.walta.socialviz.model {

private var loader:XMLLoader

public class FriendVO {

= new XMLLoader();

public function init():void{

public static const BUTCHER:String

}

= "butcher";

public static const BAKER:String

= "baker";

public static const CANDLESTICKMAKER:String "candlestick maker";

01/2009 (3)

//object

Listing 5. SocialMapperII.mxml

ArrayCollection();

}

xmlLoader.load(new URLRequest(userListURI));

private function handleLoadComplete(evt:Event):void{

import mx.collections.ArrayCollection;

{

handleLoadComplete);

}

Listing 2. UserVO.as

{

XML.ignoreWhitespace = true;

loader.loadXML("friends.xml");

]]>

=

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

33


ActionScript Developement We will treat this model class as a container for the object that represents an individual user. We will be storing the user information in a UserVO class. Create a file called UserVO within the model folder. The relationship we are trying to model looks as follows:

• Our database contains many users and a user has many friends. • Each friend has a profession. We will need to create the FriendVO class in order to accurately represent this relationship.

newFriend.name

Listing 6. XMLLoader.as Rev 2

newFriend.profession

package com.walta.socialviz.model {

}

import flash.events.Event;

import flash.net.URLLoader;

import flash.net.URLRequest; public class XMLLoader {

private var xmlLoader:URLLoader; [Bindable]

public var user:UserVO; public function XMLLoader() {

}

}

{

public class SocialMapView extends Canvas {

private function handleLoadComplete(evt:Event):void{ //When this function fires, there will //be data in the xmlLoader object var data:String = xmlLoader.data;

}

processXMLData(data);

private function processXMLData(data:String):void{ var xml:XML = new XML(data);

var users:XMLList = xml..user; //Note: This parsing routing allows for multiple users,

public function SocialMapView():void {

handleLoadComplete);

xmlLoader.load(new URLRequest(userListURI));

}

}

}

Listing 8. MapPerson.mxml <?xml version="1.0" encoding="utf-8"?>

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"> </mx:VBox>

Listing 9. SocialMapperII.mxml Rev 2 <?xml version="1.0" encoding="utf-8"?> <mx:Application

xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:view="com.walta.socialviz.view.*"

layout="absolute" creationComplete="init()">

<mx:Script>

<![CDATA[

import com.walta.socialviz.model.XMLLoader;

//in this tutorial, I'm pretending that there's only 1 user

private var loader:XMLLoader

//at a time loaded into the system so the XMLLoader //only needs to keep track of a single user.

newUser.name = users[i].@name;

var friends:XMLList = users[i]..friend;

for(var j:int = 0; j < friends.length(); j++){ var newFriend:FriendVO = new FriendVO();

34

= new XMLLoader();

public function init():void{

for(var i:int = 0; i < users.length(); i++){ var newUser:UserVO = new UserVO();

user = newUser;

import mx.containers.Canvas;

xmlLoader.addEventListener(Event.COMPLETE,

}

newUser.addFriend(newFriend);

package com.walta.socialviz.view

XML.ignoreWhitespace = true;

public function loadXML(userListURI:String):void{

}

}

= friends[j].@name;

= friends[j].profession;

Listing 7. SocialMapView.as

xmlLoader = new URLLoader();

}

If you look back at the XML above, you can see that the XML tag structure mirrors this class structure. The UserVO and FriendVO classes will be very simple. The UserVO class will require a list of FriendVO objects and each FriendVO will

}

loader.loadXML("friends.xml");

]]>

</mx:Script> <view:SocialMapView width="100%" height="100%" </mx:Application>

backgroundColor="white" />

01/2009 (3)


A Hive Full of Creativity

contain a string called profession. In addition, it will probably make sense for us to create static constants to represent the available professions. This will make changing our schema easier if we ever need to do so in the future. So the UserVO will look as follows: see (Listing 2).

Note that I added a helper function addFriend to the user. The FriendVO will look like this: see (Listing 3). Note the Bindable tag. This is one of those wonderful features the Flex framework brings to the table. We will be using it later. It will allow us to take whatever value ]]>

Listing 10. SocialMapView.as Rev 2

</mx:Script>

package com.walta.socialviz.view {

<mx:Label text="{user.name}" />

import com.walta.socialviz.model.UserVO;

</mx:VBox>

public class SocialMapView extends Canvas

Listing 13. SocialMapView.as Rev 3

import mx.containers.Canvas; {

private var _user:UserVO;

public function SocialMapView():void {

package com.walta.socialviz.view {

}

}

is stored in the profession and name variables and effortlessly connect it into our view. We now have something to load our XML data into. We have to open the XML file, read what is in it and convert it into the classes that make up our object model.

}

import com.walta.socialviz.model.UserVO;

public function set user(user:UserVO):void{

import flash.display.DisplayObject;

}

import mx.collections.ArrayCollection;

this._user = user;

import mx.containers.Canvas;

public class SocialMapView extends Canvas

Listing 11. SocialMapperII.mxml Rev 3

{

<?xml version="1.0" encoding="utf-8"?> <mx:Application

private var _user:UserVO; public function SocialMapView():void

xmlns:mx="http://www.adobe.com/2006/mxml"

{

xmlns:view="com.walta.socialviz.view.*"

}

layout="absolute" creationComplete="init()">

public function set user(user:UserVO):void{

<mx:Script>

this._user = user;

<![CDATA[

import com.walta.socialviz.model.XMLLoader;

if(this._user != null){

[Bindable]

}

private var loader:XMLLoader

= new XMLLoader();

}

public function init():void{ }

private function renderMap():void{

loader.loadXML("friends.xml");

var newPerson:MapPerson = addPerson(this._user);

}

]]>

</mx:Script>

this.removeAllChildren();

user="{loader.user}"

}

backgroundColor="white" />

private function addPerson(person:Object):MapPerson{ var newMapPerson:MapPerson = new MapPerson();

Listing 12. MapPerson.mxml Rev 2

newMapPerson.user = person;

this.addChild(newMapPerson);

<?xml version="1.0" encoding="utf-8"?>

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" <mx:Script>

}

backgroundColor="blue">

object.x = this.width / 2 – object.width / 2;

[Bindable]

public var user:Object;

return newMapPerson;

private function center(object:DisplayObject):void{

<![CDATA[

01/2009 (3)

center(newPerson);

private function clearMap():void{

<view:SocialMapView width="100%" height="100%"

</mx:Application>

renderMap();

}

}

}

object.y = this.height / 2 – object.height / 2;

35


ActionScript Developement

//To convert from degrees to radians

Listing 14. SocialMapView.as Rev 4

var radDeg:Number = (180 / Math.PI); //Circle step size

package com.walta.socialviz.view {

var thetaStep:Number = (360 / totalNumFriends + 5) * radDeg *

import com.walta.socialviz.model.UserVO;

newFriend.x = Math.cos(thetaStep) * radius + (this.width

import flash.display.DisplayObject;

/ 2);

newFriend.y = Math.sin(thetaStep) * radius + (this.height

import mx.containers.Canvas; public class SocialMapView extends Canvas {

private var _user:UserVO; public function SocialMapView():void { }

}

}

/ 2);

}

Listing 15. MapPerson.mxml Rev 3 <?xml version="1.0" encoding="utf-8"?>

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" horizontalAli

public function set user(user:UserVO):void{ this._user = user;

}

<![CDATA[

import com.walta.socialviz.model.FriendVO; import com.walta.socialviz.model.UserVO;

renderMap();

[Embed(source="assets/user.png")] [Bindable]

private var userImg:Class;

[Embed(source="assets/butcher.jpg")]

private function renderMap():void{

[Bindable]

clearMap();

private var butcher:Class;

[Embed(source="assets/baker.jpg")]

var newPerson:MapPerson = addPerson(this._user);

[Bindable]

center(newPerson);

private var baker:Class;

[Embed(source="assets/candle.jpg")]

for(var i:int = 0; i < this._user.friends.length; i++){ var newFriend:MapPerson = addPerson(this._ user.friends[i]);

}

}

positionFriend(newFriend, i, _user.friends.length);

[Bindable]

private var candle:Class;

[Bindable]

private var _user:Object;

public function set user(user:Object):void{ this._user = user;

if(user is FriendVO){

private function clearMap():void{ this.removeAllChildren();

if(user.profession == "butcher"){

}

}

private function addPerson(person:Object):MapPerson{

}

this.addChild(newMapPerson);

if(user.profession == "candlestick maker"){

return newMapPerson;

}

object.x = this.width / 2;

object.y = this.height / 2;

private function positionFriend(newFriend:

MapPerson, friendNum:int,

totalNumFriends:int):void{

36

userImg = baker;

newMapPerson.user = person;

private function center(object:DisplayObject):void{

}

userImg = butcher;

if(user.profession == "baker"){

var newMapPerson:MapPerson = new MapPerson();

}

gn="center">

<mx:Script>

if(this._user != null){

}

friendNum;

var radius:Number = 200;

}

}

userImg = candle;

]]>

</mx:Script> <mx:Image id="thumbImage" source="{userImg}" /> <mx:Label text="{_user.name}" </mx:VBox>

fontSize="20"

fontFamily="Verdana" fontWeight="normal"/>

01/2009 (3)


A Hive Full of Creativity

Go into the XMLLoader file we created earlier. You will need to create an URLLoader object, hook events to it and call load on it, passing in a URL to pull the data from. It is easier to show you in code how this works than it is to explain it in text see (Listing 4). What is going on here is I am creating an URLLoader object. These little machines are used to load the contents of a file from a remote service (in this case the local file system). The service URI will be passed in when we make a call to loadXML. The response is handled when the load operation is completed by the handleLoadComplete function. For now we are just going to trace (read print) out the contents of that text file created at the beginning of this tutorial.

Step 4. Wire the XMLLoader into the SocialMapperII class + TEST There is one more thing we need to do before we can actually see this work. We are going to need to

wire the XMLLoader class to SocialMapperII.mxml. In order to do this, the root mxml file should look like this: see (Listing 5). Mxml – that funny looking <mx:... stuff is neat. It is a way to define code structure in a tag-based (think HTML) format. It's particularly good for defining user interfaces because you can put tags inside of one another – the <mx:lung> is inside of the <mx:chest>. Code like what we have been working on though does not really have visual relationships, so you will note that I put it inside of an <mx:Script> tag. For those of you who are HTML coders, think of an <mx: Script> tag as the equivalent of a JavaScript block. Another thing to notice is that I added the creationComplete="init()" code to the <mx:Application> tag. This will cause that little function called init() to be run as soon as our application starts up. Once you have done all this, you should be able to run this application and it should print out the contents of the friends.xml file. Try

it and see if it works for you. You will see the output from the trace statement in the console window within FlexBuilder.

Step 5. Construct an object model from the XML The next thing we will be creating is constructing an object model from the contents of the xml. Go back into your XMLLoader class and add the following function after the handleLoadComplete function. Also replace the trace statement with a call to the new function. There are a couple of other changes to the XMLLoader class since it now also has to store the user information and make it accessible to the view. The new XMLLoader looks like this: see (Listing 6). We are taking the XML and loading it into our value objects. We are then storing our value objects into the XMLLoader's public user variable. This means we have a model.

Listing 16. SocialMapView.as Rev 5

}

package com.walta.socialviz.view

private function clearMap():void{

{

this.removeAllChildren();

import com.walta.socialviz.model.UserVO;

}

import flash.display.DisplayObject;

private function addPerson(person:Object):MapPerson{

import mx.containers.Canvas;

var newMapPerson:MapPerson = new MapPerson(); newMapPerson.user = person;

public class SocialMapView extends Canvas {

this.addChild(newMapPerson);

private var _user:UserVO;

return newMapPerson;

public function SocialMapView():void

}

}

private function center(object:DisplayObject):void{

{

object.x = this.width / 2 – (object.width / 2);

public function set user(user:UserVO):void{

}

}

if(this._user != null){

private function moveFriend(newFriend:MapPerson, friendNum:

}

renderMap();

int, totalNumFriends:int):void{

var radDeg:Number = (180 / Math.PI);

private function renderMap():void{

//To convert

from degrees to radians

clearMap();

var thetaStep:Number = (360 / totalNumFriends + 5) *

for(var i:int = 0; i < this._user.friends.length;

var radius:Number = 200;

radDeg * friendNum;

i++){

}

//Circle step size

var newFriend:MapPerson = addPerson(this._

var newX:Number = Math.cos(thetaStep) * radius +

center(newFriend);

var newY:Number = Math.sin(thetaStep) * radius +

user.friends[i]);

(this.width / 2 – newFriend.width / 2); (this.height / 2 – newFriend.height / 2);

moveFriend(newFriend, i, _user.friends.length);

var newPerson:MapPerson = addPerson(this._user); center(newPerson);

01/2009 (3)

object.y = this.height / 2 – (object.height / 2);

this._user = user;

}

}

}

newFriend.animateMove(newX, newY);

37


ActionScript Developement Step 6. Build a view around the model Now we can build a view around that model. This is where it starts to get fun! First create two new files in the view folder – MapPerson.mxml and SocialMapView.as. SocialMapView is the file that will represent the stage and MapPerson is the file that will represent a single person on the stage. When you create the MapPerson file, Flex will ask you for the

root tag type. In this case use a VBox. If you do not get prompted for the root tag type, do not worry. Just be sure that the source of the MapPerson file looks like what I have written below. Make SocialMapView extend Canvas – a canvas is a surface within the Flex framework which can contain child DisplayObjects (Flex visual components). A canvas can be woven into mxml code chunks. By making SocialMapView a canvas, we design it so that

Listing 17. MapPerson.as Rev 4

• SocialMapView.as: see (Listing 7). • The MapPerson.mxml file should look like this see (Listing 8).

public function animateMove(newX:Number, newY:Number):

<?xml version="1.0" encoding="utf-8"?>

void{

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" horizontalA

var move:Move = new Move();

lign="center"

move.xFrom = this.x;

rollOver="handleMouseOver()"

move.xTo = newX;

rollOut="handleMouseOut()"> <mx:Script>

move.yFrom = this.y;

<![CDATA[

move.yTo = newY;

import mx.effects.Move;

import com.walta.socialviz.model.FriendVO;

move.easingFunction = Bounce.easeOut;

import com.walta.socialviz.model.UserVO;

move.target = this;

move.duration = 1000;

import mx.effects.easing.Bounce;

move.play();

[Embed(source="assets/user.png")]

}

private var userImg:Class;

private function handleMouseOver():void{

[Embed(source="assets/butcher.jpg")]

}

private var butcher:Class;

private function handleMouseOut():void{

[Embed(source="assets/baker.jpg")]

}

private var baker:Class;

private function getBitmapFilter():BitmapFilter {

[Bindable]

[Bindable]

[Bindable]

this.filters = [getBitmapFilter()];

this.filters = [];

var color:Number = 0xFF7733;

[Embed(source="assets/candle.jpg")]

var alpha:Number = 0.8;

[Bindable]

var blurX:Number = 35;

private var candle:Class;

var blurY:Number = 35;

var strength:Number = 2;

[Bindable]

var inner:Boolean = false;

private var _user:Object;

var knockout:Boolean = false;

var quality:Number = BitmapFilterQuality.HIGH;

public function set user(user:Object):void{ this._user = user;

return new GlowFilter(color, alpha,

if(user is FriendVO){

blurX, blurY,

if(user.profession == "butcher"){ }

strength,

userImg = butcher;

quality, inner,

if(user.profession == "baker"){ }

userImg = baker;

if(user.profession == "candlestick maker"){

}

38

we can use it as a component in any of our Flex applications in the future. I will show you how to do this later in the tutorial if it is confusing at the moment. The skeleton code for the SocialMapView and MapPerson objects should look as follows:

}

}

userImg = candle;

}

knockout);

]]>

</mx:Script> <mx:Image id="thumbImage" source="{userImg}" /> <mx:Label text="{_user.name}" </mx:VBox>

fontSize="20"

fontFamily="Verdana" fontWeight="normal"/>

01/2009 (3)


A Hive Full of Creativity

Let us go ahead and tie the view into our test class so we can actually see it working. Edit the SocialMapperII.mxml file and change it look like this: see (Listing 9). The things I added are: • An mxml include called view – xmlns:vi ew=”com.walta.socialviz.view.*”

• An instance of our SocialMapView canvas that (because it is a canvas) I was able to scale to 100% of the width of the stage and 100% of the height of the stage. To make it visible, I gave it a background. Run the application. You should see a big white canvas ready to display your diagram of your social network.

Step 7. Coupling the view to the model Now we are going to make it possible to couple the model into the view. We are going to have the view observe the user object in the XMLList class. When the user object changes, the view will update. This architecture is very flexible. It is often used to show dynamically changing real-time data since the view automatically detects updates in the model. Edit the SocialMapView class and add a setter for the model. It should look something like this: see (listing 10). You will also need to modify the SocialMapperII class in order to tie the model and the view together. Make sure the SocialMapperII file looks something like this: see (Listing 11). Remember that little [Bindable] tag that I have been sprinkling all over the place? I placed it above the user variable in the XMLLoader file. I placed it above the loader variable in the SocialMapperII file and I placed it above just about everything within the UserVO value objects. Here is what it does. Without the [Bindable] tag, you could potentially be setting the UserVO for the view BEFORE it has loaded with data. Couple [Bindable] with a line like this: <view:SocialMapView width="100%"

height="100%"

user="{loader.user}" backgroundColor="white" />

Notice that I put the user=”{loader.user}” in curly braces. When you do that to a property that is Bindable it changes in the property down in the model and will automatically be pushed up to the view. Since I did that at all levels within the UserVO, we can basically just use curly braces whenever we are referring to a property on one of our UserVO objects and we are guaranteed the value the view is seeing is up to date with what is residing in the model. 01/2009 (3)

This example application is simple, but say we were doing something more complex, like a virtual world. This would be REALLY valuable. We could make a view that responds to real-time data being loaded into the model layer and whenever the model changes the view would know about it. If you code the view to respond to changes in the model data, then you never need to change the code in the view when you change code in the model.

Step 8. Rendering So let us do some rendering. Go to the MapPerson class. We are going to create a property in the MapPerson class called user and we are going to make it a generic Object. Since all things in Flex are objects, we can store both UserVO objects and FriendVO objects in this user field and use the data there to influence the view. When the model's UserVO changes, we will be creating a bunch of these MapPerson objects, assigning data objects to them and positioning them on the stage. The MapPerson class should look like this: see Listng 12. Note that we can set the label's text property to {user.name} because we will be storing UserVOs and FriendVOs in the user field. UserVOs and FriendVOs both have a name field and the name fields are Bindable, so the text field should accurately describe the underlying model. Now we are going to create a function to create a graph when the model's data changes. Edit the SocialMapView.as class to incorporate the following changes: see (Listing 13). There is quite a bit of stuff going on here. We created an addPerson, clearMap, and renderMap function and made renderMap get called whenever the UserVO in our model changes. When renderMap is called, it creates a view object (MapPerson) for the new user and adds the view to the stage. Run the application. If everything works, you will see a big white canvas with jason, the name of the user from our XML file, in the middle of the canvas.

Step 9. Plotting the friends Now, let us try to plot all of Jason's friends. Because we have worked so hard up to now, it will be easy – just loop through the friends objects from within the renderMap function, call addPerson on them and position them on the stage see (Listing 14). I decided to lay out the friends in a radial pattern. There is really not a lot of magic to this part, just simple math. I am simply using sin and cos functions to calculate points around a circle based on some angle thetaStep. Feel free to try out different layout techniques if you feel so inclined. Simply set newFriend.x and newFriend.y to some other value and the friend's image will show up somewhere else on the surface.

Step 10. Clean it up, make it pretty and make it animate Now clean up the MapPerson objects. We will add in some images to represent people, and change the font size on the labeling see (Listing 15). I have added embedded assets to the project. I just downloaded some little thumbnail images and placed them in a folder called assets within the src folder in my project. The Embed directive makes the images available to my project. I changed the way this class works so that when a user gets set we check to see whether or not the user has a profession. We can then change the image based on what the user does. Next let us animate the friends. To do this we will create one final function in the MapPerson class called animateMove. It will use a little Flex object called a Move object, which will animate our little friends across the screen. We will modify the SocialMapView class to call the animateMove function instead of directly positioning the friend objects. Then we can add a rollover glow filter to the friend objects. This will make them look cooler. You could add in click handlers or whatever you want to make this more interactive. Here is the final code for the SocialMapView and the MapPerson classes. Try it out!

Next Steps The techniques you have learned here are very flexible and powerful. They are a good starting point for understanding how to architect and build a data-driven application. I mentioned before the value of using an MVC framework. It can be difficult at first to wrap ones' head around MVC frameworks, but the productivity gains you get from them once you have mastered them are HUGE. Another thing that is worth playing with is making a model like this link to real-time data. Hook the user models to an RTMP server and for example, you can build yourself a multiplayer asteroids game. Effects can make this application look better, and the images can be replaced with MovieClips generated in Flash. Click handlers can cause info panes to pop up and animations can be made more complex. Really, it is up to you how far you want to build from this tutorial. Good luck!

WALT SCHLENDER Walt Schlender is a Flex software architect and entrepreneur located in the San Francisco Bay area. He specializes in real-time data-driven Flex applications. He is currently the co-founder and CTO of a startup company called Mousecloud, which uses Flex to create real-time, passioncentered rooms on the internet. In the past he has worked for various Bay area companies, including Ourchart, Inc., TurnHere, Inc and Precor, Inc.

39


ActionScript Developement

In bed with Flash and HTML: Embedding Flash content with SWFObject 2 by Aran Rhee SWFObject is an easy-to-use and standards-friendly method to embed Flash content. It enables Flash or Web developers to place Flash content into web pages while ensuring that even visitors without Flash Player will be able to view relevant content. What you will learn...

What you should know...

• How to embed Adobe Flash content using SWFObject 2

• HTML and JavaScript concepts

Level of difficulty

S

WFObject 2 was created by Bobby van der Sluis, Geoff Stearns, and Michael Williams who teamed up to combine the best techniques of UFO (Unobtrusive Flash Object), SWFObject 1, and the Adobe Flash Player Detection Kit. Why should you use SWFObject?

behind progressive enhancement is that you enhance the basic version of your content with additional presentation or behavior by using technologies like CSS, JavaScript, and Flash. These enhanced versions should be served only when the required browser technology support is available. STEP 1. Download the SWFObject library The SWFObject project is housed as a Google Code project: http://code.google.com/

p/swfobject/. You can download the current version of the SWFObject library (version 2.1 at the time of writing) from the following location: http://swfobject.googlecode.com/files/ swfobject_2_1.zip – It includes the required SWFObject JavaScript file as well as examples and source code if you want to look under the hood. We will use three of the files from the .zip in this tutorial – swfobject.js, test.swf, and expressInstall.swf. Save these three files in a folder on your desktop or other accessible location (Figure 1). STEP 2. Create an HTML page Using your favourite HTML or text editor; create a new HTML page in the same folder where your SWFObject files are located. The page should have valid document type

• SWFObject 2 is more optimized and flexible than any other Flash Player embed method • Breaks the cycle of being locked into vendor specific mark up and promotes the use of web standards and alternative content • Uses unobtrusive JavaScript and JavaScript best practices • Is easy to use • Adobe will be using SWFObject 2 as the standard Flash embedding method for the upcoming CS4 product suite

A Working Example This tutorial will show you show to embed Flash content into a web page utilizing the SWFObject 2 JavaScript library. We will focus on using just one of the two available methods for embedding Flash content through SWFObject which is called dynamic publishing. This method embodies a technique called progressive enhancement. The main philosophy 40

Figure 1. SWFObject Project Page

01/2009 (3)


Embedding Flash content with SWFObject 2

and include a <head> tag. In this case we are using a XHTML 1 strict doctype see (Listing 1). STEP 3. Create alternative content using standards compliant mark up SWFObject's dynamic embed method follows the principle of progressive enhancement and replaces alternative

HTML content for Flash content when enough JavaScript and Flash plug-in support is available. Alternative content is what users without the required Flash player or search engines will see when they visit the page. The alternative content should be a representation of what the Flash file would have shown to the user, and should also

Listing 1. Blank HTML page ready for mark up <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/ DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head>

<title>SWFObject – blank</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head> <body>

</body>

</html>

Listing 2. Add alternate content <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/ DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head>

<title>SWFObject – add alternative content</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head> <body>

<div id="flashContent">

<p>Search Engines or people without a valid Flash Player or JavaScript will see

</div>

this content</p>

include a link to download Flash player to encourage users to get the best experience of your content. In this case we have created a <div> element with an id of flashContent to display our alternate content. If the user has the required version of flash, this <div> and all content within will be completely replaced by SWFObject with mark up required to display a Flash file see (Listing 2). STEP 4. Include the SWFObject JavaScript library in the head of your HTML page We add the SWFObject JavaScript library by adding a reference to the swfobject.js file with a <script> tag within the <head> section of the HTML page. By including SWFObject in the <head> tag, we ensure that SWFObject is loaded before the page content is displayed, and that any code that is required to run can do so as quickly as possible. It also means SWFObject methods can be called from anywhere within the HTML page see (Listing 3). STEP 5. Embed your SWF with JavaScript We make a single call to a method of the SWFObject library to actually embed the SWF file in the page. The method is called embedSWF() and has five required and four optional arguments. For a basic example we will just concentrate on the required arguments: •

(String) – specifies the location of your SWF file

Swf URL

</body> </html>

Listing 3. Add SWFObject JavaScript library file to the page <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/ DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head>

<title>SWFObject – add swfobject library</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

Figure 2. What users with Flash will see

<script type="text/JavaScript" src="swfobject.js"></script> </head> <body>

<div id="flashContent">

<p>Search Engines or people without a valid Flash Player or JavaScript will see </div>

this content</p>

</body>

</html>

01/2009 (3)

Figure 3. What users without Flash (and search engines) will see

41


ActionScript Developement •

ID (String) – specifies the id of the HTML

element (containing your alternative content) you would like to have replaced by your Flash content • Width (String) – specifies the width of your SWF • Height (String) – specifies the height of your SWF • Version (String) – specifies the Flash player version your SWF is published for (format is: major.minor.release). For example if your Flash content requires Flash player 8 in order to display correctly, you would specify 8.0.0

to visit you page, instead of just being shown you alternative content, they would be shown a dialog like below asking to upgrade to the latest version of the Flash Player. Once installed, the idea is that the user can see your content straight away without having

to leave your original page or restart the browser (Figure 4). •

(Object) – specifies your flashvars with name:value pairs. This is the same as the flashvars param

Flashvars

Again, we add this method call within the <head> tag to ensure it will execute before the page content is fully visible to the user see (Listing 4). STEP 6. Preview the HTML page We have completed all of the steps required for basic embedding of a Flash file using SWFObject 2. If you save your HTML page and preview it in your preferred browser, you should see the below if you have Flash player 8 or above. The Flash file will display the version of your current Flash Player (Figure 2). If you preview the HTML file in a browser with no Flash player, you should see (Figure 3).

EXTRA. Customising your Flash content

Figure 5. SWFObject code generator input options

You can use the other optional arguments to add functionality or customise your Flash file. •

Swf URL (String) – specifies the URL of your express install SWF and activates Adobe express install.

ExpressInstall

Note Express install is a system designed to upgrade a user’s Flash Player to a newer version without the user having to leave the original page. This is supported by Flash Player 6.0.65 or higher on Win or Mac platforms. An example might be if you have developed content which is specific to Flash Player 9 using AS3. If a user with Flash Player 7 were

Figure 4. Express Install screen shown to update flash player version 42

Figure 6. SWFObject code generator HTML output

01/2009 (3)


Embedding Flash content with SWFObject 2

available normally, expect for the variable format. • Params (Object) – specifies your nested object element params with name:value pairs. You can specify any of the normally available <object> parameters for the Flash plug-in. • Attributes (Object) – specifies your object's attributes with name:value pairs. You can specify any of the normally available <object> attributes for the Flash plug-in. Note You can omit the optional parameters, as long as you don't break the parameter order. If you don't want to use an optional parameter,

but would like to use a following optional parameter, you can simply pass false as its value. For the flashvars, params and attributes JavaScript Objects, you can also pass an empty object instead: {}. Here is a more complex example of calling the embedSWF() method using the four optional parameters to: • Set an expressInstall swf location • Pass 3 variables into the Flash file through the flashvars object • Disable the Flash player context menu through the parameters object • Setting a custom id through the attributes object

Listing 4. Add SWFObject <script> block to display the Flash file <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/ DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head>

<title>SWFObject – embed SWF</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script type="text/JavaScript" src="swfobject.js"></script> <script type="text/JavaScript">

swfobject.embedSWF("test.swf", "flashContent", "300", "120", "8.0.0");

</script>

</head> <body>

<div id="flashContent"> <p>Search Engines or people without a valid Flash Player or JavaScript will see

EXTRA: Code Generator There is a SWFObject code generator available in order to make it quicker and easier for developers to create valid SWFObject code. There are two versions available to download – HTML, and Adobe AIR for use on the desktop: http://code.google.com/p/swfobject/downloads/list. There is also an online version of the generator available: http://www.swffix.org/swfobject/generator/ The generator only requires two steps to use: • Fill in a minimal amount of fields such as the location of your SWF and SWFObject.js files, width and height, and what publishing method you want to use see (Figure 5). • The generator will write all the code required to embed and display your Flash file. You can then copy and paste the generated code and save it as an HTML page see (Figure 6).

Where to from here We have really only gone through the basics of one embedding method available for SWFObject 2. I recommend anyone who is interested in learning more to go to the SWFObject 2 website where you will find full documentation, FAQ’s, a JavaScript API to add further capabilities, and an active developer group if you are having problems: http:// groups.google.com/group/swfobject There is also a good getting started video tutorial by Lee Brimelow of gotoAndLearn() fame: http://www.gotoandlearn.com/play?id=77

this content</p>

</div>

</body>

</html>

Listing 5. A more advanced SWFObject <script> block to customize the Flash file <script type="text/javascript"> var flashvars = {};

flashvars.name1 = "hello"; flashvars.name2 = "world";

flashvars.name3 = "foobar"; var params = {};

params.menu = "false"; var attributes = {};

attributes.id = "myDynamicContent";

attributes.name = "myDynamicContent"; swfobject.embedSWF("test.swf", "flashContent", "300", "120", "9.0.0", "expressInstall.swf",flashvars, params, attributes);

</script>

01/2009 (3)

Figure 7. www.gotoandlearn.com

ARAN RHEE Aran Rhee has been involved in the world of the Flash platform for over 10 years. He is a group manager of the SWFObject 2.0 project and currently works as a solutions architect for Qmecom, a software development company in Australia which specializes in Flash and Flex based products. When Aran is not in front of the computer screen for either work or personal projects, you might find him riding his favourite mountain bike trails.

43


ActionScript Developement

Increasing Flash and Flex Search Engine Optimization by R. Jon MacDonald, Jason McCoskery SEO, or ‘search engine optimization’, is the practice of optimizing a web site to improve both the volume and quality of traffic to the web site from search engines via organic search results for targeted keywords. In most cases, this means optimizing said website to increase the amount of traffic it receives from search results. What you will learn...

What you should know...

• • • •

• Basic knowledge of PHP • Familiarity with SWFAddress and SWFObject

Overview of SEO Issues with Flash and SEO Older solutions for Flash SEO Working solution for Flash SWFAddress and PHP

SEO

using

Level of difficulty

W

hen Adobe recently announced they were working with Google and Yahoo! to improve the searchability of Flash and Flex websites and applications, the Flash development community largely applauded the initiative. However, months after the announcement there has been minimal increase in the effective search engine rankings of Flash and Flex websites. In this article we plan to show an alternative method of achieving successful SEO for Flash and Flex websites using two open source projects, SWFObject and SWFAddress, to help you improve your SEO efforts. In this article you will learn an alternative method for achieving successful SEO for Flash and Flex websites using two open source projects, SWFObject and SWFAddress. SEO, or search engine optimization, is the practice of optimizing a web site to improve both the volume and quality of traffic to the web site from search engines via organic search results for targeted keywords. In most cases, this means optimizing said website to increase the amount of traffic it receives from search results. Since the majority of website traffic is driven by search engines such as Google, Yahoo! 44

and MSN, it is important to create a website that can be easily read and indexed by search engines so that your site can benefit from the added number of visitors that will find it through a listing in search results.

Why Flash and SEO Don’t Mix Over the past decade the Flash Platform has become a standard for everything from small websites to rich Internet applications, and everything in between. Although the content in Flash and Flex websites has become increasingly more relevant and useful to the general Internet public, the Flash SWF file format and the content that it presents to the user is still not easily read and indexed by search engines. Because of this, search engine spiders will either skip the content altogether or make an attempt to index the static textual content; but either of these solutions often results in an incomplete index of the site’s content.

Older SEO Solutions To solve the issue of search engines not being able to see within SWF files, Flash and Flex developers have typically tried one of two solutions: providing an alternative site in HTML just for search engines, or using Adobe’s publish method of placing all the static text from the Flash movie in comments above the Flash player’s HTML embed object. Most common is the practice of making a separate website with a similar look and

feel of the Flash site and then using a static HTML-based navigation to lead visitors to the Flash version of the site. Since this approach requires having a separate website it is expected that this "non-Flash" version of the website will generate most of the search engine traffic. In essence, the HTML version of the website will most certainly get indexed by search engines, but your visitors will most likely never see the Flash or Flex content. At the very least they would never be taken directly to the Flash or Flex content from the search engine results. In this case, why spend the time and money building a Flash or Flex user experience? Adobe’s generally recommended solution to this problem is to list all the static text content from the Flash movie in the HTML page containing the Flash SWF. By inserting this text content in comments above the Flash player’s HTML embed object, it allows the text to be listed in the HTML page for search engines to index, but remains hidden for normal visitors. This technique has proven to work in the past, but as search engines become more aggressive in anti-fraud measures they now tend to refuse to index any content within comments or otherwise hidden from site visitors, making this method obsolete and ineffective at best.

Adobe’s Google and Yahoo! Partnerships Adobe announced in July that they formed a partnership with Google and Yahoo! wherein Adobe has provided the search engine companies with a custom optimized version of the Flash Player that assists in discovering content that is currently undiscoverable by search engines. The official announcement, available at: http: //www.adobe.com/devnet/flashplayer/articles/ swf_searchability.html, states: 01/2009 (3)


Increasing Flash and Flex Search Engine Optimization

“Adobe has provided Flash Player technology to Google and Yahoo! that allows their search spiders to navigate through a live SWF application as if they were virtual users. The Flash Player technology, optimized for search spiders, runs a SWF file similarly to how the file would run in Adobe Flash Player in the browser, yet it returns all of the text and links that occur at any state of the application back to the search spider, which then appears in search results to the end user.” In theory, this sounds like the SEO arguments against the Flash platform has now become null and void. To test this theory, Ryan Stewart, a Platform Evangelist at Adobe, held a contest called Fleximagically Searchable (see: http://blog.digitalbackcountry. com/?p=1478). This contest asked Flex developers to try any method they believed would reveal the words Fleximagically Searchable within their sample Flex application to Google’s spiders. Almost two months later Ryan had posted an update to his blog stating the contest turned out to be a big failure due to the fact that no one could get Google to spider their content enough to index the words Fleximagically Searchable (see: http://blog.digitalbackcountry.com/?p=1617). As Ryan states in this same blog post, at the end of the day, Google appears to just not index Flash/Flex content very well. With this in mind, it is up to Flash and Flex developers to produce their own method for revealing their content to search engines. What most developers do not realize, however, is that there is a tested solution that has been proven to work and provides the added benefits of standards-compliant Flash embedding and deep-linking for your website/ application.

Overview of the SWFAddress/SWFObject Solution The solution for SEO that we will be exploring in depth is the one which can be found as part of the sample code that is included with SWFAddress. SWFAddress, written by Rostislav Hristov (http:// www.asual.com), is a small but powerful library that, among other things, provides deep-linking for both Flash and Ajax. For more information on SWFAddress and its capabilities, read the documentation and browse the samples available at http:// www.asual.com/swfaddress/. In the sample code, the approach utilizes Javascript, PHP and URL-rewriting to build a search engine-friendly Flash site by allowing Javascipt-enabled browsers to view the Flash version of the site while non Javascriptenabled browsers are presented with a slimmed-down HTML version. A working example of this is available to view at the 01/2009 (3)

SWFAddress site: http://www.asual.com/swf address/samples/seo/.

SWFAddress SEO Sample For this example, we will be walking through the SEO example that is included in the latest release of the SWFAddress library. To begin, you will need to download full source of SWFAddress from http://www.asual.com/swfaddress/. Note that this example requires the Apache web server (v. 1.3+) with PHP 4 or 5 installed. To begin, navigate to the /samples/seo/ directory of the SWFAddress.zip file that was downloaded in the previous step. We will be taking a closer look at the .htaccess and index.php files which are located in the / samples/seo/swfaddress/ directory. The first file that we will be taking a look at is the .htaccess file. An .htaccess file is

a distributed configuration file that is used by the Apache web server to make server configuration changes on a per-directory basis. In this example, the .htaccess file is being used for URL rewriting to ensure that any incoming, valid URLs are being rewritten to display the index.php file to the user. This is important in that it allows us to use the index.php file to parse these URLs to display the appropriate content to the user. (Listing 1) displays the contents of the .htaccess file (lines marked with # are comments): see (Listing 1). Next, we’ll take a closer look at the index.php file. As you will notice, this file contains a large amount of PHP code – we will be looking in depth at the parts of the code that are most relevant to the SEO process and will provide a high-level overview of the remainder of the code.

Listing 1. .htaccess file <IfModule mod_rewrite.c> # Enables mod_rewrite RewriteEngine on

# Sets the base folder of the SEO sample RewriteBase

/swfaddress/samples/seo

# Checks to see if the requested file exists, if so it displays the requested file. # If not, it displays the index.php file RewriteCond

%{REQUEST_FILENAME}

!-f

# Checks to see if the requested directory exists on the server, if so it displays the # requested requested directory. If not, it displays the index.php file RewriteCond RewriteRule

</IfModule>

%{REQUEST_FILENAME}

.* index.php

!-d

Listing 2. A closer look at index.php // SWFAddress code fully compatible with Apache HTTPD session_start();

$base = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));

$swfaddress = preg_replace('/^([^\?.]*[^\/])(\?|$)/', '$1/$2', $swfaddress, 1); ... $query_string = (strpos($swfaddress, '?')) ? substr($swfaddress, strpos($swfaddress, '?') + 1, strlen($swfaddress)) : '';

$swfaddress_path = ($query_string != '') ? substr($swfaddress, 0, strpos($swfaddress, '?')) : $swfaddress;

$swfaddress_parameters = array();

Listing 3. Strtotitle method function strtotitle($str) { }

return strtoupper(substr($str, 0, 1)) . substr($str, 1);

45


ActionScript Developement The first block of PHP that we will take a look at is the SWFAddress code that is located within the first 60 lines of the index.php file. (Listing 2) shows the beginning and end of this code (Listing 2). To oversimplify, this code is used to parse the current URL so that it can be used later to display the correct HTML content to the user. For example, if you direct your browser to http://www.asual.com/swfaddress/ samples/seo/portfolio/, the SWFAd-dress code would determine from the URL that the user is

requesting to view the ‘portfolio’ page content. The importance of this code is that it defines and sets the following variables which will be used later within this file to determine which content to display: •

– this is the base URL value. This should be the same value that was defined in the .htaccess file using the RewriteBase directive. In our case that was /swfaddress/samples/seo

$base

On the 'Net • • •

http://asual.com/swfaddress/ http://code.google.com/p/swfobject/wiki/documentation http://www.adobe.com/devnet/flashplayer/articles/swf_searchability.html

Listing 4. swfaddress_title method function swfaddress_title($title) { global $swfaddress_path;

if ($swfaddress_path != '/') {

$length = strlen($swfaddress_path);

$title .= (($length > 0) ? ' / ' . strtotitle(str_replace('/', ' / ',

substr($swfaddress_path, 1, $length – 2))) : ''); }

echo($title); } … // use of the swfaddress_title method:

<title><?php swfaddress_title('SWFAddress Website'); ?></title>

Listing 5. swfaddress_resource & swfaddress_link methods function swfaddress_resource($resource) { global $base;

echo($base . $resource); }

function swfaddress_link($link) { global $base;

echo($base . $link); }

Listing 6. swfaddress_content method function swfaddress_content() {

global $swfaddress, $swfaddress_path, $base;

$url = strtolower(array_shift(explode('/', $_SERVER['SERVER_PROTOCOL']))) . ': //';

$url .= $_SERVER['SERVER_NAME'];

$url .= $base . '/datasource.php?swfaddress=' . $swfaddress_path; $url .= (strpos($swfaddress, '?')) ? '&' . substr($swfaddress, strpos($swfaddress, '?') + 1,

strlen($swfaddress)) : ''; }

46

readfile($url);

– this is the current directory path that appears in the URL after the $base value. This is used by the SWFAddress code to determine the $query _ string, $swfaddress _ path and $swfaddress _ parameters values. • $query _ string – this is any query string value that is appended to the end of the URL string. For example, in the address http://www.asual.com/swfaddress/samples/ seo /portfolio /1/?desc =true&year=2001 the $query _ string value would be ?desc=true&year=2001. • $swfaddress _ path –this is the current directory path after the $base path. For example, in the address http: //www.asual.com /swfaddress /samples / seo /portfolio /1/?desc =true&year=2001 the $swfaddress _ path would be / portfolio/1/. • $swfaddress _ parameters – this is a PHP array containing the actual values of the $query _ string variable. Using the same URL as above, the $swfaddress _ parameters array would look like this: Array ([desc]=>true,[y ear]=>2001). $swfaddress

Next we’ll look at the remainder of the PHP code (lines 60-100 of the index.php file). This code contains several PHP methods that are being used to write the search engine-friendly HTML content to the page. The first of these methods that we’ll take a look at is the strtotitle method that is shown in (Listing 3). This method is simply used to convert a string to initial caps. For example, calling strtotitle(portfolio); would return the string Portfolio. Next, is the swfaddress_title method. This is a function that is being used to dynamically output the value of the page’s <TITLE> tag based upon the current page’s $swfaddress_ path value. This is method is important to SEO efforts because search engines, Google in particular, give the contents of the <TITLE> tag a strong weighting in their indexing and ranking of search results (Listing 4). After the swfaddress_title method, we come to two functions: swfaddress_resource and swfaddress_link which are shown together in (Listing 5). These are useful functions for this SEO example in that they take file names as arguments and then prepend the $base value to them, but they are not necessary for either SWFAddress or SEO. Next we come to the swfaddress_content method, which is shown below in (Listing 6). This is the method that writes the search engine-friendly HTML content to an HTML div layer on the page. In this example, it uses the $swfaddress, $swfaddress_path and $base variables to locate, read and print out the return value of the datasource.php file. 01/2009 (3)


Note that it is not required for you use this method for your own projects – this is just a simple example of writing out content to the page based on the current URL. Also worth noting is that this method appends a query string parameter ‘swfaddress’ to the end of the $url value, so that the file it is opening looks like this: http://asual.com/swfaddress/ samples/seo/datasource.php?swfaddress=/ about/. By doing this, we are able to use the added swfaddress parameter from within the datasource.php file to determine which HTML content to return for display on the page. To see the results, direct your browser to http://www.asual.com/swfaddress/samples/ seo/about/ and view the HTML source of the page. You will notice that at the end of the HTML source is the HTML-equivalent of what is displayed within the flash movie as well as a simple HTML-based navigation that mimics the functionality of the Flash movie’s navigation. This is the content that would be available to search spiders as well as to browsers with their Javascript functionality disabled. After the swfaddress_content method, we come across the swfaddress_optimizer method which is shown below in (Listing 7). The use of this method is similar to the swfaddress_resource and swfaddress_link

a

01/2009 (3)

methods in that it is used to add a file to the HTML page. However, to this example, the importance of this method is that it is used to add the swfaddress-optimizer.js Javascript file. This is the file that is used by Javascriptenabled browsers to re-write the browser location for use within the flash movie’s implementation of SWFAddress. For example, in a Javascript-enabled browser, this will take the following address: http://www.asual.com/ swfaddress/samples/seo/about/ and convert it to the SWFAddress-friendly URL http:// www.asual.com/swfaddress/samples/seo/#/about/ by adding the hash # symbol to the URL just after the $base value. The inclusion of this Javascript file is very important in that it allows users with Javascript-enabled browsers to view the enhanced, Flash-enabled page and users without Javascript and search engine spiders to view the trimmed-down, non-Flash version.

Conclusion While the solution for Flash SEO presented in this article requires a bit more setup than other alternatives offered by Adobe, it is also proven to be much more effective. Until the Adobe and Google/Yahoo! partnerships have resulted in clear instructions on how to make Flash platform sites and applications search engine friendly – followed by effective results – the

d

v e

r

t

i

s

e

m

e

open source solution presented in this article is your best chance as a Flash or Flex developer to expose your site’s content to search engines.

JASON MCCOSKERY Based in Portland, Oregon, Jason is an interactive developer specializing in all facets of presentationlayer programming for the web. With over ten years of experience as a developer, Jason has had the opportunity to work on projects for a varied clientele including Microsoft, Nike, the P.I.N.K. Spirits Company and AT&T.

R. JON MACDONALD A certified Adobe Flash and Web developer, Jon offers a wealth of expertise in development, design, usability and visual communication. Over the course of ten years Jon has honed his skills through a multitude of experiences. Jon works with household brands, advertising agencies and talented designers and developers across the country through JonnyMac Interactive, the interactive collective he started. Jon is an avid contributor to open source Flash Platform projects including SWX and SWFAddress, and was a contributing author to the recently released book “The Essential Guide to Open Source Flash Development”. His portfolio and blog can be found at http:// www.jonnymac.com.

n t


ActionScript Developement

Flex Application Accessing Microsoft Analysis Services to Retrieve OLAP Cube Data by Eric Ko

How does a Flex application communicate with Microsoft Analysis Services to get data from an OLAP cube? To overcome the limitations of relational databases, an OLAP cube is built to hold large amounts of data which cannot persist properly in traditional database structures. What you will learn...

What you should already know…

• The concept of an OLAP cube • How to set up Microsoft Analysis Services to allow access on a server • How to use HTTPService to access the Microsoft Analysis Services • How to access the OLAP cube data in a Flex application

• Flex and ActionScript • The Internet Information Services (IIS) Server • AdvancedDataGrid and Flex charting

Level of difficulty

I

t is now common to display and graphically present large sets of data in a Flex application. However, to connect Flex to an OLAP cube is not an easy task. This article shows you how to accomplish this. OLAP stands for Online Analytical Processing which provides fast aggregation of groups of data. In theory, for the same query of data, OLAP can respond and return data much quicker than the traditional relational database does. To bring about this fast aggregation, the OLAP has a concept of a cube that manipulates the data in terms of Measures and Dimensions. By using Measures and Dimensions, we can tackle the data sets like a tree hierarchy within which we can drill down to a particular branch’s data. To illustrate these concepts with a human readable example is a good way to analyze complicated ideas. Here we have a data grid that presents the data in an OLAP cube see (Table 1). In this example, Race and Time are the Dimensions. The rows and columns form the fact table, Immigration, which is a Measure. The Time Dimension has January, February, 48

Chinese, Indian and Japanese as the Members. For now, we can consider each of these Dimensions as an Axis. Here comes the cool part of an OLAP cube in that it can contain multiple Dimensions in an Axis which is orthogonal to the other axes. By adopting this concept, we can add two Dimensions, namely Year and Month, to the Time Axis see (Table 2). Now, we can reference the immigrantion in terms of month, year, and race. We can also add more Dimensions to the Race or even to the Measures table to populate more data and

March and April as its Members, and on the other hand the Race Dimension gets Western,

Table 1. The immigration fact table with the time and race dimensions Immigration

Race

Time

European

Chinese

Indian

Japanese

January

472

15,626

9,550

43

February

525

5,262

6,250

324

March

250

3,458

7,085

425

April

1,000

10,021

1,321

55

Table 2. The immigration fact table with the time dimensions split into years and months Immigration

Race

Time

European

Chinese

Indian

Japanese

Year

Month

January

2007

472

15,626

9,550

43

February

2007

525

5,262

6,250

324

March

2007

250

3,458

7,085

425

April

2007

1,000

10,021

1,321

55

January

2008

321

6,321

2,312

435

February

2008

453

4,222

3,442

546

March

2008

654

1,453

5,333

322

April

2008

222

4,232

2,455

556

01/2009 (3)


Flex Application Accessing Microsoft Analysis Services

Listing 1. The MDX script that queries the data set as shown in Table 3

<faultcode>XMLAnalysisError.0xc10e0002</faultcode>

<faultstring>Parser: The syntax for 'GET' is incorrect.</

SELECT {[Measures].[European],

faultstring>

[Measures].[Chinese],

[Measures].[Indian],

<detail>

[Measures].[Japanese]} ON COLUMNS,

<Error ErrorCode="3238920194" Description="Parser: The

NON EMPTY

syntax for 'GET' is incorrect."

([Race].[Race – Race].[Race – Race],

Source="Unknown" HelpFile=""/>

[Time].[Year].[Year] ,

[Time].[Month].[Month]) ON ROWS

</detail>

FROM [FFDDemo]

</soap:Fault>

Listing 2. The general pattern of a SELECT statement in both query languages SELECT ….

</soap:Body>

</soap:Envelope>

Listing 5. The expected error message returned from the server as the Analysis Services is accessed directly from a browser

FROM …..

Listing 3. The MDX query to show the data set of the European dimension only

<soap:Envelope>

SELECT {[Measures].[European]} ON COLUMNS,

<faultcode>XMLAnalysisError.0xc10e0002</faultcode>

<soap:Body>

<soap:Fault>

NON EMPTY

<faultstring>Parser: The syntax for 'GET' is incorrect.</

([Region].[Region – Region],

faultstring>

[Time].[Year].[Year] ,

[Time].[Month].[Month]) ON ROWS

<detail>

FROM [FFDDemo]

<Error ErrorCode="3238920194" Description="Parser: The syntax for 'GET' is incorrect."

Listing 4. Another example of the MDX script

Source="Unknown" HelpFile=""/>

SELECT {[Measures].[European],

</detail>

NON EMPTY

</soap:Body>

[Measures].[Japanese]} ON COLUMNS,

</soap:Fault>

([Region].[Region – Region].&[Eastern],

</soap:Envelope>

[Time].[Month].[Month]) ON ROWS

Listing 6. Source code that declares a HTTPService object

FROM [FFD Demo]

WHERE [Time].[Year].&[2008]

Listing 5. The expected error message returned from the server as the Analysis Services is accessed directly from a browser

var httpService: HttpService = new HTTPService(); httpService.method = "POST";

httpService.contentType = "application/xml"; httpService.resultFormat = "e4x";

<soap:Envelope>

httpService.headers = getHeaders();

<soap:Body>

<soap:Fault>

Table 3. The immigration fact table with the race dimensions split Immigration

Race Eastern

Western

European

Eastern

Western

Chinese

Eastern

Western

Indian

Eastern

Western

Japanese

Time Year

Month

January

2007

212

260

8,452

6,174

5,897

3,653

21

22

February

2007

225

300

3,153

2,109

4,152

2,098

199

125

March

2007

125

125

2,228

1,230

4,522

2,563

245

180

April

2007

350

650

5,236

4,785

795

526

22

33

January

2008

44

277

3,602

2,719

800

1,512

275

160

February

2008

56

397

2,639

1,583

2,916

526

81

465

March

2008

348

306

623

830

2,468

2,865

254

68

April

2008

100

122

3,338

834

1,832

623

356

200

01/2009 (3)

49


ActionScript Developement outline the relationships between the axes see (Table 3). Finally, we have the Eastern and Western Dimensions added to the Race Axis. In addition, there are 2 values in each of the cells of the Measures. By using this flat representation table, we can see how the OLAP cube can aggregate multi-

Figure 1. A conceptual representation of the above-mentioned OLAP cube

Figure 2. The path that stores the core files of the Microsoft Analysis Services

Table 4. The immediate result of the MDX in Listing 1

Eastern

2007

April

Eastern

2007

February

Eastern

2007

January

Eastern

2007

March

Eastern

2008

April

Eastern

2008

February

Eastern

2008

January

Eastern

2008

March

Western

2007

April

Western

2007

February

Western

2007

January

Western

2007

March

Western

2008

April

Western

2008

February

Western

2008

January

Western

2008

March

European

Chinese

Indian

Japanese

350

5236

795

22

225

3153

4152

199

212

8452

5897

21

125

8452

5897

21

100

3338

1832

356

56

2639

2916

81

44

3602

800

275

348

623

2468

254

650

4785

526

33

300

2109

2098

125

260

6174

3653

22

125

1230

2563

180

122

834

623

200

397

1583

526

465

277

2719

1512

160

306

830

2865

68

Table 5. The immediate result of the MDX in Listing 3 European

Figure 3. The Web Site Creation Wizard that creates a virtual directory

All

2007

April

All

2007

February

All

2007

January

All

2007

March

All

2008

April

All

2008

February

All

2008

January

All

2008

March

1000 525 472 250 222 453 321 654

Table 6. The immediate result of the MDX in Listing 4

Figure 4. The Web Site Creation Wizard to change the access permissions of the virtual directory

50

Eastern

April

Eastern

February

Eastern

January

Eastern

March

European

Japanese

100

356

56

81

44

275

348

254

01/2009 (3)


Flex Application Accessing Microsoft Analysis Services

Listing 7. The SOAP script request that is passed to the Analysis Services via the HTTPService call <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

<SOAP-ENV:Body>

<Execute xmlns="urn:schemas-microsoft-com:xml-analysis"> <Command>

<Statement>

SELECT {[Measures].[European], [Measures].[Chinese], [Measures].[Indian], [Measures].[Japanese]} ON COLUMNS, NON EMPTY

([Race].[Race – Race].[Race – Race],[Time].[Year].[Year],

dimensional datasets. Each of the axes can hold up to 128 Dimensions. Note My drawing talent is poor. If you may redraw the diagram with great graphical perception, it will be nice. Therefore, it is not necessary to use my original drawing. Here is a conceptual view that presents the OLAP cube as discussed. The data sets are slices of Measures that are confined within multiple dimension levels. We can extract data from the cube easily by referencing the coordinates of the axes.

[Time].[Month].[Month]) ON ROWS FROM [FFDDemo] </Statement>

</Command>

<Properties>

<PropertyList>

<DataSourceInfo> localhost

</DataSourceInfo> <Catalog> FFDDemo

</Catalog>

<AxisFormat>

TupleFormat

</AxisFormat> <Format>

Multidimensional

</Format>

</PropertyList>

</Properties>

</Execute>

</SOAP-ENV:Body>

Figure 5. The Windows Authentication Wizard to update the remote access settings of the virtual directory

</SOAP-ENV:Envelope>

Listing 8. The SOAP script is encapsulated in the HTTPService handle httpService.request = soapXML;

Listing 9. Send the HTTPService in an asynchronous call to the Analysis Services var atoken: AsyncToken = new AsyncToken( null );

Figure 6. The wizard to create a new application pool

aToken = service.send();

Listing 10. The event registration and event handler of the asynchronous call atoken.addEventListener(CubeEvent.CUBE_COMPLETE, serviceResultHandler); private function serviceResultHandler(event:ResultEvent):void { }

Listing 11. Populate the data from the asynchronous call to the OLAP data grid component var data:ICollectionView = new ArrayCollection(event.result.root.row); cubeGrid.dataProvider = data; cube.refresh();

01/2009 (3)

Figure 7. The settings window that allows adjustments to the properties of the virtual directory

51


ActionScript Developement SQL statements in OLAP Cube Like the traditional relational database, the OLAP cube database has a query language, called Multidimensional Expressions (MDX), that can be used to make queries to retrieve data. Using the example discussed above, if we want to retrieve the complete data set of the OLAP cube, we can use the following piece of MDX: see (Listing 1). The immediate result is shown in (Table 4). You may notice that the SELECT statement in the MDX is similar to the syntax of the query language used in relational databases. In the MDX, the difference is that we need to state the content of the rows and columns. In this example, we specify the columns as the members of the Race Dimensions. On the rows, we have the race type, year, and month Dimensions. Numeric facts about the immigrants are displayed properly within the grid. FFDDemo is the OLAP database. To extract the European immigrants from the data set, we can use this piece of MDX: see (Listing 3). The output is in (Table 5). For the sake of simplicity and content, I cannot go into all of the details of the MDX. However, by using these two examples, I can

give you an idea how to extract the desired data by adjusting the context within the ON COLUMNS and ON ROWS clauses. You can also provide a WHERE clause to filter the data. An example and the corresponding output are shown as follows.

Setting up Microsoft Analysis Services on an IIS Server After understanding the OLAP cube, we can do some real work. We will write a simple Flex application to display data from the OLAP. Microsoft Analysis Services provides a gateway to delegate data from the OLAP database. To access the OLAP database through the Analysis Services, a HTTP pump, namely the msmdpump.dll, should be made available to encapsulate the SOAP request. The easiest approach is to put the DLL on an IIS server, so that the Flex application can use the HTTPService operation to access the OLAP database. In order to run the DLL on the IIS Server, we need to make a virtual directory to host it as a website service on the server. To accomplish this, we can copy the core files (including the msmdpump.dll) of the Microsoft Analysis Services to a file folder.

Then, we turn this file folder into a virtual directory. Assuming that you have Microsoft SQL Server Enterprise Edition installed with Microsoft Analysis Services. You can copy the highlighted files to the specific folder that you wish to become a virtual directory (i.e. C:\FFDDemo) We need to complete the following three processes: • Virtual Directory • Application Pool • Web Service Extension

Virtual Directory Switch to the IIS administrative wizard. You can create a virtual directory and point the path to the folder we described in the previous step. In my example, the virtual directory is pointing to C:\FFDDemo see (Figure 3). In Flex, the HTTPService operation can access scripts like SOAP, XML, etc. Since the DLL has SOAP script involved, the access permission of the virtual directory is set to Run scripts see (Figure 4). Once the virtual directory is created, we have to allow remote access by setting the

Table 7. The output in the OLAP data grid component on the Flex application Date

(All) 2007

January February

March

Region (All)

Eastern_Eur

Western_Eu

Eastern_Chi

Western_Ch

Eastern_Ind

Western_In

Eastern_Jap

Western_Ja

93886

1460

2437

29271

20264

23382

14366

1453

1253

60667

912

1335

19069

14298

15366

8840

487

360

24691

212

260

8452

6174

5897

3653

21

22

12361

225

300

3153

2109

4152

2098

199

125

11218

125

125

2228

1230

4522

2563

245

180

12397

350

650

5236

4785

795

526

22

33

33219

548

1102

10202

5966

8016

5526

966

893

9389

44

277

3602

2719

800

1512

275

160

8663

56

397

2639

1583

2916

526

81

465

7762

348

306

623

830

2468

2865

254

68

7405

100

122

3338

834

1832

623

356

200

April 2008

January February

March April

52

01/2009 (3)


Flex Application Accessing Microsoft Analysis Services

On the 'Net • • •

http://en.wikipedia.org/wiki/OLAP_cube – OLAP Cube. Wikipedia, the free encyclopedia. March 6, 2008. http://www.microsoft.com/technet/prodtechnol/sql/2005/httpasws.mspx – Configuring HTTP Access to SQL Server 2005 Analysis Services on Microsoft Windows Server 2003. Microsoft TechNet. August 23, 2005. http://msdn.microsoft.com/en-us/library/ms145506.aspx – Multidimensional Expressions (MDX) Reference. Microsoft MSDN. 2005.

appropriate authentication method. In my situation, I disallowed anonymous remote access and instead required Integrated

Windows Authentication see (Figure 5). Next, we need to create an application pool that points to the virtual directory. Go back to IIS and right click on Application Pools to do this. Application Pool Create an application pool see (Figure 6). In the virtual directory properties, we can map the application pool to the directory that we have just created see (Figure 7). Hit the Configuration button and it will bring you to the Application Configuration wizard see (Figure 8). Add the extension as shown (Figure 9). Web Service Extension Add the web service extension and map it to the dll file that we specify in the virtual directory see (Figure 10).

Figure 8. The Application Configuration wizard that enables the addition of file extensions associated with the virtual directory

Set the status of the web service extension to Allowed see (Figure 11). Restart the IIS server. When we browse the address http://localhost/FFDDemo/ msmdpump.dll, we should see the error message as shown below. This is an indication that the IIS settings are correctly arranged.

Flex Application to Display OLAP Cube Data Now, we can program a Flex application to display the data from the OLAP cube. This simple application uses the HTTPService request to connect to the DLL hosted on the IIS server (Listing 6). First, we create an HTTPService handle. Then, we construct a SOAP script that includes the datasource name, catalog and the MDX that we would like to execute. The SOAP script is in XML form (Listing 7). We assign the SOAP script to the HTTPService handle (Listing 8). We use an asynchronous token to send out the HTTPService request to the OLAP cube database via the DLL that we set up previously (Listing 9). By registering an event listener to the asynchronous token, we can get back the query result from the OLAP cube database (Listing 10). In the event handler, we assign the result to the Flex OLAP data grid component (Listing 11). A snapshot of the data grid presents the result (Table 7)

Conclusion

Figure 9. Map the dll extension and the path of the virtual directory

In this article, we have seen how to connect Flex with Microsoft Analysis Services. We used the IIS server to host the OLAP DLL pump which encapsulates the SOAP script that accesses the OLAP database. In the presentation layer, we used an OLAP datagrid to display data in Flex. Visit http://blog.atrexis.com/demo/olap.html to check out the running demo.

ERIC KO Figure 10. Create a new web service extension

Figure 11. Enable the web service extension in the IIS administrative console

01/2009 (3)

Eric is a senior software engineer at Atrexis. He has ten years experience in the design and development of software. Over the last two years, he has specialized in Rich Internet and Mobile applications. He has built applications for most major mobile devices, including the iPhone, Blackberry, and Windows Mobile devices. He has also built several demos using the Android simulator.

53


ActionScript Developement

Contextual Awareness Parsing the Stack Trace by Christopher W. Allen-Poole There is the occasional need to have either a method or an object develop some concept of its surroundings. Often such an ability will lead to better, smarter programs. This article examines the Error object's Stack Trace value as a means towards this end and demonstrates a function which will accomplish such a goal. What you will learn...

What you should know...

• How to parse the stack trace from an error message • How to create contextual awareness in a program • How to create an additional level of encapsulation

• Object-Oriented concepts for Actionscript 3 • The Flash Event model, the Error Object, and the Function object • Flex and Flash

Level of difficulty

T

here is the occasional difficulty with encapsulation in Object Oriented programming. Most often it can be anticipated and avoided with proper techniques, but there are times when one is confronted with this situation: a property is currently private, but one needs to be able to manipulate it from outside of its owner. However, if the property is made publicly accessible, that would risk poor encapsulation. So one is often forced to choose, does he give access to this property (or method), or does he give up his ability to alter the data? An example might be this – a URLRequest object, a property of some custom class, needs to be able to have its .url property changed. Perhaps it should only be changed by external interfaces: say by a URLVariables or an XMLLoader. Yet, there is no scenario where it should be directly influenced by the UI. It would be nice to lock the property, make it inaccessible, but there is no public except in this circumstance statement to accomplish this. Someone could make a series of custom classes to try to work around this, but that can very quickly lead to bloated and cumbersome code, a worse scenario than slightly weaker encapsulation. Then there is the scenario where it would be easiest for a child class to be able to allow 54

a property to be manipulated by a member of a parent class. If, for example, there were a protected or private static property which was initialized in the constructor, one would have to re-write the constructor for each child class, unless one found a method to allow the parent access to private properties (super() will only initialize the static properties of the parent class, not the properties of the child class). There are also the circumstances where someone would like to have a method behave a certain way in certain contexts. Say one has a vector class which can either return radians or degrees. One would like to be able to have it return radians to my SineClass instance and return degrees to the UI. Unfortunately, however, Actionscript does not put a caller property in the arguments object so one is forced to complicate the interface by either creating multiple methods, or requiring some parameter to test. Either way, coupling is sacrificed to accommodate this problem.

Finally, there is the scenario where it would be best if a large amount of code were to be only accessible to one class. This code also would do well to allow for potential inheritance. One could make a single class which automatically encapsulated all functionality, but there would never be a means whereby someone could extend the classes separately (and it would likely be incredibly bloated); I could make one private class (also called a helper class) and one public class, but that would have two problems: first, it would result in just as large and cumbersome .as file, and, once again, the class not be extendable. Finally, there was the option of making the class public – something which solved the potential need to make dependent classes and the difficulties of having an Actionscript file with well over one thousand lines of code, yet it would also risk putting far too much functionality available for mis-coordination. None of these do particularly well at solving the problem at hand. In the above scenarios, there is a need to allow some form of awareness. An object which would be able to sense its surroundings would be a perfect solution.

The solution The first step to finding this method, is the realization that the stack trace of an error includes every single method and class which lead to that point. If one had a button fire a function, which caused an object to run a method which lead to an

Listing 1. The initial attem pt <code class = “as3” id = “Initial attempt”> try{

throw new Error('irrelevant');

} catch (e:Error){

if (e.getStackTrace().indexOf('Foo') < 0) throw new Error('This function cannot be

}

used unless it is called by a member of Foo');

</code>

01/2009 (3)


Contextual Awareness – Parsing the Stack Trace

error, the error's stack trace would list every single step along the course. It would not list variable or instance names, but it would make accessible the name of every class and every method. This leads to the first draft: see (Listing 1). And it works. Anytime a member of any class other than Foo tries to fire that function, it would cause an error. But there are two small problems: first, if (e.getStackTrace().iindexOf('Foo') < 0) actually returns true in two scenarios – if the current function is called by an instance of Foo directly, or if an instance of Foo called a method of a different class, which called a method, which lead to the above code (Foo could be anywhere in the stack); second, if the caller of this function is a member of a child class of Foo, that code will return false (thus causing problems with inheritance). That lead to the following: see (Listing 2). As one can see, it starts by breaking the error up by tabs into an Array. Then it looks for the regular expression which demonstrates the class package and the class which immediately called this function. Now, because this is a separate function, it requires that the first through third positions in the Array are removed – first for the error message, second for this function, and third for the function which called this function. This leaves the context of the caller in the form of a String. At this point it is important to note the next line. There are times when one may wish to use this function in a constructor. If this occurs, it can cause infinite recursion. Without this line of code, it is more than possible to crash Flex, let alone Flash. But if there is a simple test for the function name, all of this is immediately avoided. One might wonder why this does not return an actual instance, and there are several reasons for this. First, if the validation is to literally check if the caller is of a certain class, this allows it. One can simply add, if (validate() == MovieClip) to the immediate caller. Second, that means that this does not have to deal with type-casting and resulting errors, and third, this avoids problems related to parameters for the constructor and the improper instantiation of a Singleton.

etDefinitionByName('SetIntervalTimer')

will cause reference errors. Additionally, the above code generates an error with custom functions on the timelines of MovieClips (it traces 'MethodInfo-1). As this is not a class name, it will also cause an error. There needs to be a Listing 2. The core of validation function

<code class = “as3” id = “The core of the validation function”> import flash.utils.*;

01/2009 (3)

function validate():Class{

try{

throw new Error('this is irrelevant');

} catch (e:Error){

// The stack trace contains tab delineated String of every // Object and event which triggered this function. var tested:String = String(e.getStackTrace()); // Remove tabs. var arr:Array

= tested.split("\t");

// These are actually removed to ensure that the test for infinite recursion

will not look at either this or the function which called this.

arr.shift(); // arr[0] is the error message.

arr.shift(); // arr[1] is the validate function.

arr.shift(); // arr[2] is function that called validate.

// arr[3] is the String which corresponds to the immediate caller of the function.

//One may wish to add a parameter to return the caller of the caller. var value:String = arr[0];

var fakeVal:String = arr.join(',');

// This helps prevent infinite recursion.

// If the name of this function appears in the remaining trace,

// the function, somehow, is calling itself. (either directly or by proxy). if (fakeVal.indexOf('validate') >= 0) return null; // A line of the stack trace is as follows: // “at some.package::SomeClass/FuncName()” var re:RegExp

= /^at (.*?)\(\)/;

// Parse the expression. var owner:Array

= re.exec(value);

// The resulting String is in format package::classname. var tmp:Array

= owner[1].split('::');

fakeVal = tmp.join('.');

//Unless it is a constructor, the function will be defined: class/function. tmp = fakeVal.split('/');

var className:String = tmp[0];

var funtionName:String = tmp[1];

A corner case Most of the time, what is written above will suffice. Normally if something happens on the root, we know that our functions will be tracked through some event or other (Even if that Event is MouseEvent.CLICK) and when the listener hears the event, it will be able to grab context from the event.currentTarget property. There are, however, certain situations which do need to be considered. First, there is a corner-case with setTimout and setInterval. In both cases, the stack trace returns: see (Listing 3). (In case you were wondering, that website comes up as unavailable.) The validation function, as it is written above, will return the actual Function class, which is generally not useful for determining one's context. Further, getDefinitionByName('<anonymous>') and g

way to clear out both non-classes and any time that the Function class is called. Essentially, this means that the Array needs to be traversed and any value which would otherwise cause an error needs to be passed over. Now, there are many ways to do this, but it seems to make the most

// get the Class object from the name. var c:Class } }

return c;

= getDefinitionByName(className) as Class;

return null;

</code>

Listing 3. SetIntervals error <code class = “getStackTrace” id = “setInterval error”>

at Function/http://adobe.com/AS3/2006/builtin::apply() at <anonymous>()

at SetIntervalTimer/onTimer()

at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick()

</code>

55


ActionScript Developement sense to have a second, helper function which returns null in the case where an error would

occur and the actual class when everything processes correctly (Listing 4).

Listing 4. A Helper Function with the Final Form of the Validator <code class = “AS3” id = “Helper Function”> function testString(str:String):Class{ try {

// Notice, this is exactly the same as above only abstracted. var re:RegExp

= /^at (.*?)\(\)/;

var tmp:Array

= owner[1].split('::');

var owner:Array

= re.exec(str);

fakeVal = tmp.join('.');

tmp = fakeVal.split('/');

var className:String = tmp[0];

// Grab the final object to avoid problems with Function.apply var funtionName:String = tmp[tmp.length – 1]; if (className == 'Function') return null;

if (str.indexOf('MethodInfo')) className = 'MovieClip'; = getDefinitionByName(className) as Class;

var c:Class

return c; // We have successfully found a class.

} catch (e:Error){return null;} // We have not found a class.

}</code>

Then we use it in the original validator function:

<code class = “AS3” id = “Final validation function”> import flash.utils.*;

function validate():Class{ try{

throw new Error('this is irrelevant');

} catch (e:Error){

var tested:String = String(e.getStackTrace());

if (tested.indexOf('validate') >= 0) return null; var arr:Array

var i:uint = 3;

= tested.split("\t");

while(testString(arr[i]) == nul){ // All of the errors return null } } }

i++;

return testString(arr[i]);

Finally There is much more that parsing a stack trace can lead to – for example, if one has: see (Listing 5). in Flex, the resulting stack trace includes at Validator/__myButton_click(). The information following the “/” sign is two underscores, followed by the ID of the button, followed by another underscore, and finally the type of event and then parenthesis. This means that one could not only parse the String for the button's ID, one also has access to the name of the button's click function. If one were to fire the method __myButton_click(new MouseEvent('whatever')), it would be the same as clicking on the above button (only with a different message). One thing which has not been done above that could be easily accomplished is the creation of a function which returns the calling method instead of the calling class (the ground-work is already laid above). One should not deny that this code can lead to weak encapsulation and poor OOP techniques. It is relatively easy to imagine it leading to excessive spaghetti code. But, the good news is that most of the people who would use this function incorrectly would at least be talented enough to really screw things up anyway – finding something akin to the above where it is not needed will probably be the least of anyone's concerns. On the other hand, this can add something to the code. This can add dynamism which is otherwise impossible: it creates a form of contextual awareness, allowing encapsulation where it otherwise could not have happened. Code which is capable of knowing its surroundings is able to work more seamlessly, and perhaps even organically, to solve a multitude of problems.

return null;

On the 'Net

</code>

Listing 5. A Quick Flex Exam ple <code class= “mxml” id=”Flex Example”>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:

local="*">

<mx:Script>

<![CDATA[

import flash.utils.*;

public function testError():*{ try{

http://flexblog.faratasystems.com/?p=95 – This is a similar problem to the one described in my article – get dynamic access to a static class. http://geekswithblogs.net/jwhitehorn/ archive/2007/11/09/116750.aspx – .Net's ability to do the same h t t p : // b l o g . d e d r o p . o r g / 2 0 0 8 / 0 7/ restricting-method-access-in-perl.html – Something similar in PERL (Solves the problem through Decorator design pattern).

throw new Error('this is irrelevant');

} catch (e:Error){

]]>

}

}

</mx:Script>

trace(e.getStackTrace());

<mx:Button x="180" y="169" id='myButton' label="Button" click="{testError()}"/>

</mx:Application> </code>

56

CHRISTOPHER W. ALLENPOOLE Christopher W. Allen-Poole is a developer who works at a Marketing firm out of Parsippany, New Jersey. His work predominantly focuses on converting proprietary AS2-based technology into AS3 as well as maintenance and expansion of both sets of code. He is also a thrice-published author on a major Actionscript website.

01/2009 (3)



Server Side Interaction

Weather Flash Plus by Clifford Eclipse Wilson Many Web applications provide local weather information. This tutorial will walk you through programming Weather Flash Plus in ActionScript 3.0. This program can be extended to provide weather updates for public websites, intranet Web sites and mobile devices. More advanced readers can extend this program to show weather according to all geographical locations. What you will learn...

What you should know...

• Consuming XML Feeds • Displaying XML Data • Loading external images

• How to navigate the Flash IDE • Basic fundamentals of programming • Basic background of XML

Level of difficulty

C

onsuming XML feeds and SOAP based WebServices is easy with ActionScript 3.0. While there are many pay-per-WebService providers, we will be using a free XML feed provided by the US Government’s National Weather Service. You will have to locate the XML feeds in your specific state at http://www.weather.gov/xml/ current_obs/. Consuming Government XML data is free; however, if 90% of your app is based on government data then you will have to give credit to the Government resource. My local weather is for Ohio and observations are recorded at Cleveland Hopkins International Airport. I will only show observations for my local weather but in a future article I will show you how to program your ActionScript to allow users to select from any observation point within the United States. Let’s start by opening Adobe Flash CS3 Professional. Create a new ActionScript 3.0 Flash File. You can rename the existing layer to something suitable such as Actions, AS, Scripts, etc. Click on the first frame on your renamed layer and press the function key [F9] to expose the Actions pane. I will break down the following code but you should go ahead and type it in your Actions pane: see (Listing 1). 58

the addEventListener property. The final statement passes the URLRequest object into the URLLoader object through the load function. Now you can type the following function which we will modify by adding code the carries out the work of parsing the XML and displaying weather data to the users:

The first four lines import the required classes that allow us to instantiate objects for use in our code. The call to f_XMLLoader() causes our program to execute. Inside of function f_XMLLoader are 5 statements. In order to pull data from a server we need to instantiate URLLoader and URLRequest objects. The third statement is where you place the URL for your weather observation location by assigning it to the url property of the URLRequest object. We will need to assign f_XMLParser to the COMPLETE event of the URLLoader through

function f_XMLParser(event:Event):void{}

Now type the first set of code statements that will go between the left and right curly braces (Listing 2). The first five statements declare variable containers. The variable containers will be assigned values based on the returned XML data. The next statements are used to instantiate a TextArea object that will be used to hold the text or string of temperature information. I set the property wordWrap to

Listing 1. Importing ActionScript Classes import fl.controls.TextArea; import flash.display.*; import flash.text.*; import flash.xml.*; f_XMLLoader(); function f_XMLLoader():void {

var ldr_Loader:URLLoader

= new URLLoader();

var req_URLRequest:URLRequest = new URLRequest(); req_URLRequest.url = "http://www.weather.gov/xml/current_obs/KCLE.xml"; ldr_Loader.addEventListener(Event.COMPLETE, f_XMLParser); }

ldr_Loader.load(req_URLRequest);

01/2009 (3)


Weather Flash Plus

true but you can set it to false if you want to program scroll-bars for sliding left and right. Next we assign values to the x, y, width, and height properties of the TextArea object. I did not like the border so I assigned an empty sprite object to the upSkin state through the TextArea’s setStyle property. Instantiate a Loader object and an URLRequest object that so that we can dynamically load an image into display.

The XML holds a URL reference and an image filename that we will parse and concatenate for use as an absolute URL path for loading the image. Complete your code by appending the following within your f_XMLParser function: see (Listing 3). We wrap the remaining statements within try-catch blocks so that we ensure proper handling of any errors. Recall that these

On the 'Net • • •

http://www.adobe.com/devnet/actionscript http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/XML.html http://www.w3schools.com/xml

Listing 2. Variable Declaration and Initialization var xml_Weather:XML

= null;

var str_Location:String

var str_Temparature:String

= null;

= null;

var str_ImageURL:String = null; var str_ImageName:String

= null;

var ta_TextArea:TextArea

= new TextArea();

ta_TextArea.wordWrap ta_TextArea.x ta_TextArea.y

= true;

= 0;

= 60;

ta_TextArea.width

ta_TextArea.height

= 300;

= 100;

ta_TextArea.setStyle("upSkin",Sprite); addChild(ta_TextArea); var ldr_Loader:Loader

= new Loader();

var req_URLRequest:URLRequest

= new URLRequest();

Listing 3. Display Data and Image try{ xml_Weather = new XML(event.target.data); str_Location

= xml_Weather.location;

str_ImageURL

= xml_Weather.icon_url_base;

str_Temparature str_ImageName

= xml_Weather.temperature_string; = xml_Weather.icon_url_name;

ta_TextArea.htmlText

= "<b>location:</b> " + str_Location + "<br/>";

ta_TextArea.htmlText += "<b>temperature:</b> " + str_ Temparature.toString();

addChild(ldr_Loader);

req_URLRequest.url = str_ImageURL.concat(str_ImageName);

statements execute only after the XML data has been completely loaded through our URLLoader object. Refer back to the beginning of the article if you need to review URLLoader and URLRequest object instantiation. The xml_Weather object is created by use of the new keyword and the overloaded XML class constructor allows for an optional DataSource/object parameter. We pass the DataSource/object parameter the actual XML data that was returned from the weather.gov Web site. Explaining XML is beyond the scope of this article but you can read more about XML, how it is properly formatted, and how to traverse the XML Nodes using the reference links that are amended. For our purpose we only need to know the values within the XML that represent the location of the weather observance, temperature_string , icon_url_base , and the icon_url_name. We assign the values of our variable string objects to the raw XML values. Our TextArea object will only need to hold the location and temperature string so we will need to assign the htmlText property of the TextArea object. Simple html tags are used to add styling to the text. We use <b></b> to make the location and temperature labels stand out or be bold and <br/> is used to place the temperature on the next line. We will need to make sure our Loader object exists in the display in order for us to programmatically show an image using ActionScript. Adding the Loader object to the display is done by passing Loader through the addChild method of the display object container. Next we assign the url property of the URLRequest object that handles processing the image. The concat method is used to create the URL to the image that we are loading. We concatenate or add the explicit filename to the URL to make an absolute URL path of the image location. Then we pass the URLRequest object to the load method of the Loader object which processes and displays the image to the user. The remaining catch code simply displays a warning at development time. If any errors are encountered during runtime then the users will only see a block that is the color of your Flash canvas.

ldr_Loader.load( req_URLRequest ); }// end try

catch(e:TypeError){

trace("Text not parseable into XML"); trace(e.message);

}// end catch

01/2009 (3)

CLIFFORD ECLIPSE WILSON Clifford Eclipse Wilson is a Software Engineer & Web Developer with over 10 years experience in IT Project Management. Cliff’s main focus has been rich internet application RIA development and integration with Microsoft SQL-Server and Oracle Database in ASP.Net C# environments.

59


Sound and Animation

XML-based Photo Gallery & Slideshow by Chetankumar Akarte In this tutorial we are going create an XML-based photo gallery & slideshow. The gallery will show photos side-by-side and the slideshow will allow the user to move between photos using a timed animation.

What you will learn...

What you should know...

• How to create an XML-based photo gallery and slideshow

• Intermediate knowledge of component creation and data binding using Flash • Basic knowledge of XML • Flash development environment using ActionScript 2.0

Level of difficulty

C

reate a top-level directory anywhere you want to hold the files we’ll use for this demo. Within that directory, create blank xml files named gallery.xml and slideshow.xml. Create subdirectories named GalleryImg and SlideshowImg. Download photos of approximately the same size to populate the two directories as shown below. Your directory structure should look like this when you’re done: see (Listing 1). We will place our .fla and .swf files at the same level as the gallery.xml and slideshow.xml files for the sake of simplicity.

Slideshow XML XML allows us to avoid hard-coding the names of our photographs into our movie. This allows us to update only one external file when we want to change the contents of our movie. Let’s set up our data file. Copy the contents of (Listing 2) into slideshow.xml. For the sake of simplicity, the paths to our content are relative paths. This may not work when deployed on a web server, so I recommend using absolute paths to images (e.g. http://yourSite/folderName/imageName). Make note of the delay attribute in the root tag <slideshow delay="3000">. This is the 60

length of the delay between photos during our slideshow (in milliseconds).

Creating a slideshow in Flash We need to create some UI now that our data file is in place. Create a new Flash document using ActionScript 2.0. Name is Slideshow.fla. Open up the Document Property editor using Modify>Document or [Ctrl]+[J]. Change the following settings:

Your interface design should look something like (Figure 1).

Final touches Now we’ll add the code that processes slideshow.xml and displays images based on its contents. Insert a new layer called Action. Press [F9] to open the Actions Panel. Copy the code from (Listing 3) into the Action panel. In (Listing 3) we define an XML object called my_xml and load data from our external XML file slideshow.xml. We ignore white space while reading the file to avoid processing errors due to the formatting of the file.

• width=310px • height=250px • background=black. First let’s create a control to hold the images. Press [Ctrl-F8] to create a new symbol. Name it pic and set its type to Movie Clip. This adds pic to our Library pane. Name our the main layer in the timeline Images. Drag the pic symbol from the library and name the instance picture. Press [Ctrl-F8] again to create a symbol for our text. Name it Text and set its type to Graphic. We need to insert a Dynamic Text control in the Text symbol. Double-click Text in the Library pane to edit the symbol. Select the Text Tool (press [T])and draw a textbox in the center of the symbol. Set its type to Dynamic Text. Press the Scene 1 button to go back to editing the main movie. Drag the Text symbol from the Library to the Images layer near the bottom and centered.

Figure 1. Skeleton of Slideshow

Figure 2. Final Slideshow

01/2009 (3)


XML

The loadData function first counts all records and stores that number in a variable named total. The delay variable stores the delay listed in the root tag as pointed out earlier. The variable count starts at 0, so by default our first record will be displayed. Function slideshow() is then called and control is passed to it. It changes the image being displayed every 3000 milliseconds. Go to frame 10, open the Action Panel and type stop();. This stops our movie from looping. (Figure 2) shows the movie running.

The slideshow() function in more detail We used setInterval() in slideshow() to execute our function repeatedly. Here are some pointers for working with setInterval outside of this example: • Keep track of the interval ID (the return value of setInterval()) in a scope that is accessible to every function that needs it • Clear previously set intervals before starting new ones

There are multiple ways to use setInterval. In this case we’re passing in two arguments: the function we want called and the interval (in milliseconds) we want to pass between calls to this function. Another use of setInterval allows you to pass in an object and the name of a public function on that object that you’d like called after a certain interval passes. That use allows the function to reference member variables on the object using the this keyword. The return value of setInterval is essentially a handle to the

Listing 1. Directory Structure for Images

Listing 3. Process XML Structure for slideshow

GalleryImg/

// define an XML object called "my_xml"

Autumn Leaves.jpg Creek.jpg

Desert Landscape.jpg Dock.jpg

Forest Flowers.jpg Forest.jpg

Frangipani Flowers.jpg Garden.jpg

SlideshowImg/ flower.jpg

ForestFlowers.jpg

FrangipaniFlowers.jpg Garden.jpg

redRose.jpg

my_xml = new XML();

// load data from an external XML file into "my_xml" object my_xml.load("slideshow.xml");

// ignore "white spaces", text nodes that only contain white space are discarded my_xml.ignoreWhite = 1;

// what to do when data is loaded ... Call a function ("loadData" in this case) my_xml.onLoad = loadData; count = 0;

// function contents function loadData() {

total = my_xml.firstChild.childNodes.length;

whiteRose.jpg

delay = my_xml.firstChild.attributes.delay;

gallery.xml slideshow.xml

// take the data from the XML lines (line 0,1,2) and place that data inside text fields

txtImgInfo.text=my_xml.firstChild.childNodes[count].childNode

Listing 2. XML Structure for Slideshow

s[1].firstChild.nodeValue;

picture.loadMovie(my_xml.firstChild.childNodes[count].childNo

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <slideshow delay="3000"> <image>

<location>SlideshowImg/redRose.jpg</location>

</image>

<caption>A beautiful flower</caption>

}

gotoAndPlay(2);

txtImgInfo.text=my_xml.firstChild.childNodes[count].childNode

<location>SlideshowImg/whiteRose.jpg</location>

s[1].firstChild.nodeValue;

<caption>Snow White Beauty</caption>

picture.loadMovie(my_xml.firstChild.childNodes[count].childNo

</image>

<location>SlideshowImg/flower.jpg</location> <caption>Another flower</caption>

</image> <image>

}

slideshow();

myInterval = setInterval(pause_slideshow, delay); function pause_slideshow() {

<caption>Forest Flowers Beauty</caption>

clearInterval(myInterval); if (count<(total-1)) {

</image>

count++;

<image>

<location>SlideshowImg/FrangipaniFlowers.jpg</location>

loadNextRecord();

<caption>Frangipani Flowers</caption>

}else{

count=0;

</image> <image>

<location>SlideshowImg/Garden.jpg</location>

</image>

</slideshow>

01/2009 (3)

des[0].firstChild.nodeValue, 1);

function slideshow() {

<location>SlideshowImg/ForestFlowers.jpg</location>

<caption>Garden Beauty</caption>

des[0].firstChild.nodeValue, 1);

function loadNextRecord() {

<image>

<image>

slideshow()

}

}

}

loadNextRecord();

61


Sound and Animation interval. It’s used by clearInterval to stop the repeated calls from continuing every time that interval elapses. If you do not catch the return value (interval ID) of setInterval and eventually use it to call clearInterval, the interval will continue to operate as long as your movie is running. If you’re using the object-centric call to setInterval, you can assign the return value of

setInterval to a member variable on the object. In this way, the function being called can locate the interval identifier at this.intervalId. You can have multiple intervals going, but if you’re using the same variable to store the interval ID, you will want to call clearInterval() before calling setInterval(). To call clearInterval() prior to calling setInterval(), both the initiating script and

Listing 4. XML Structure for Gallery <?xml version="1.0" encoding="utf-8" standalone="yes"?> <gallery>

<image>

<location>GalleryImg/Autumn Leaves.jpg</location>

// function contents function loadData() {

total = my_xml.firstChild.childNodes.length;

// take the data from the XML lines (line 0,1,2) and place that data inside text fields

<image>

txtImgInfo.text=my_xml.firstChild.childNodes[count].childNod

<location>GalleryImg/Forest Flowers.jpg</location>

es[1].firstChild.nodeValue;

<caption>Garden Beauty</caption>

<location>GalleryImg/Creek.jpg</location> <caption>A beautiful flower</caption>

</image>

picture.loadMovie(my_xml.firstChild.childNodes[count].childN odes[0].firstChild.nodeValue, 1);

}

this.onEnterFrame = function() {

filesize = picture.getBytesTotal();

<image>

loaded = picture.getBytesLoaded();

<location>GalleryImg/Dock.jpg</location>

preloader._visible = true;

<caption>Snow White Beauty</caption>

txtLoder._visible = true; if (loaded != filesize) {

</image> <image>

preloader._width = 100*loaded/filesize;

<location>GalleryImg/Forest.jpg</location>

txtLoder.text=Math.round((loaded/filesize)*100)+"%";

} else {

<caption>Another flower</caption>

</image>

preloader._visible = false;

<image>

txtLoder._visible = false; if (picture._alpha<100) {

<location>GalleryImg/Garden.jpg</location> <caption>Forest Flowers Beauty</caption>

</image> <image>

<location>GalleryImg/Desert Landscape.jpg</location> <caption>Frangipani Flowers</caption>

</image> <image>

}

}

}

picture._alpha += 10;

btnNext.onRelease = function() { if (count<(total-1)) {

<location>GalleryImg/Frangipani Flowers.jpg</location>

count++;

<caption>Garden Beauty</caption>

loadData();

</image>

}else{

</gallery>

count=0;

Listing 5. Process XML Structure for Gallery // define an XML object called "my_xml" my_xml = new XML();

// load data from an external XML file into "my_xml" object

}

}

if (count>0) { count--;

loadData();

// ignore "white spaces", text nodes that only contain white

}else{

space are discarded

count=total-1;

my_xml.ignoreWhite = 1;

// what to do when data is loaded ... Call a function ("loadData" in this case)

loadData();

btnBack.onRelease = function() {

my_xml.load("gallery.xml");

62

Now that we’ve successfully implemented a slideshow, let’s use similar techniques to create an image galler. Copy the contents of (Listing 2) stored into gallery.xml. We are going to allow users to browse our images by clicking next

count = 0;

</image>

<image>

Gallery XML

my_xml.onLoad = loadData;

<caption>Frangipani Flowers</caption>

</image>

the script being executed must have access to the intervalId, as shown in the function’s code.

}

}

loadData();

01/2009 (3)


Further reading XML Integration With Flash – http://www.tech-funda.com/?p=8 Flash-Based Galleries For Your Images – http://www.smashingmagazine.com/2007/10/12/ flash-based-galleries-for-your-images/ • XML In Flash – http://www.communitymx.com/content/article.cfm?cid=D1CB3 • Photo Slideshow Using XML and Flash – http://www.kirupa.com/developer/mx2004/xml_ slideshow.htm • XML Flash Slideshow v2.1 – http://www.flashnifties.com/xml_slideshow.php • setInterval function: http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/ actionscript_dictionary646.html • •

and previous buttons. We are going to use a Pre loader which will show us progress of loading image.

Creating an image gallery in Flash Create new document with dimensions 510 X 400 pixel. Create Movie Clip pic as you did for the slideshow. Insert new layer (Photo) and drag pic to it and give the instance the name picture. I have added a frame on my gallery. Just import frame image to library and add new layer (Base) and drag it there also add a dynamic textbox with <Instance Name> as txtImgInfo which will show more information about image. We have to add a pre loader for that creates a movie clip as loaderBar. Select it and draw a box of 100 x 3 with Rectangular Tool. Insert new layer named Preloder and drag loaderBar to it and give <Instance Name> as preloader. And below it add a dynamic textbox with <Instance Name> as txtLoder which will show progress of loading image in percentage.

Insert a new layer named Buttons. Now we have to add two buttons so that we can switch between images, next or previous. Use buttons from Flash’s common library through Windows>Common Libraries>Buttons. Drag both buttons from Library to the Buttons layer and give them instance names btnBack and btnNext as shown in (Figure 3).

Final touches Our gallery.xml file holds a new list of images to display. Insert a new layer named Action and copy (Listing 5) into it. (Listing 5) is a modified version of (listing 3). The code is modified to allow switching between images when the click events of btnNext and btnBack are dispatched. We also added ActionScript to manage the Preloader. The variable filesize gets the size of an image and the variable ‘loaded’ holds number of bytes loaded. We update filesize and loaded on every animation frame until the image is loaded and we use those values to determine the width of the preLoader and the value of txtLoder. With that, our gallery is finished! (Figure 4) shows the gallery movie running.

Conclusion

Figure 3. Skeleton of Gallery

XML opens up broad possibilities for functionality. Flash allowed us to use XML and some simple scripting to quickly create a slideshow and a gallery. With some quick scripts we were able to manage a library of images, and give the user some useful UI feedback using a preloader. We also got to play with Flash’s built-in functions setInterval() and clearInterval() to execute functions repeatedly over time.

CHETANKUMAR AKARTE

Figure 4. Final Gallery

01/2009 (3)

Chetankumar Akarte (chetan.akarte@gmail.com) is an Electronics Engineer and he loves programming. He is working on PHP, MySQL, CSS, XHTML, JavaScript, Flash and PhotoShop. His interests are reading books and magazines as well as writing. He has been working on several projects (www.xfunda.com or www.tech-funda.com). Currently, he is working on a Software Developer at Green Point Technology Services, Navi Mumbai, India.

63


BILL VOLPE Level of difficulty

Bill Volpe is a Mobile Web Marketing Manager in New York City. He spends half of his time in front of his PC and the other half of time in front of mobile devices. In his spare time Bill enjoys developing applications for mobile, playing Texas Hold’em, and hiking the Hudson Valley. You can contact Bill directly via email: (b.volpe@gmail.com).

How to Develop Flash Games for the Nintendo Wii by Bill Volpe

Flash games, good. Nintendo Wii, good. And what happens when you put two good things together? Well, in this case, you get an excellent opportunity to develop your own Flash games for the Nintendo Wii.

I

t all starts with the Wiimote. The Wiimote gives Nintendo a distinct leg up over its competitors when it comes to surfing the Internet. Via Opera Powered internet browser on the Wii, users have the opportunity to access email, websites, and most importantly utilize the built in Flash Player. Since the Wiimote acts as a typical mouse when navigating websites, it also acts as a mouse within Flash applications. Therefore you can manipulate Flash games by using the Wiimote in place of your typical computer 64

mouse. So how do I create a Flash game and play it on my Wii, you ask? Well, it’s actually quite simple. Once your game is uploaded to the web you can access via Wii Browser. Simply navigate to the appropriate URL that you uploaded your game, or navigate to http://www.wiicade.com if you are utilizing Wiicade’s web server. Enjoy, and please feel free to send me a link to any cool games that you may develop!

01/2009 (3)


Nintendo Wii

01

Downloading the Opera Browser Download the Opera Browser from the Wii Shop Channel. Yes, I know it costs 500 Wii Points, but

02 Downloading Adobe Flash CS3 You will need a copy of Adobe Flash CS3 (or any version capable of ActionScript 2.0 or higher) in order to create Flash files. You can download a free 30 day trial of Flash CS3 from Softpedia: http:// www.softpedia.com/get/Internet/WEB-Design/ Flash/Adobe-Flash.shtml. In addition Adobe has just released a trial version of Adobe Flash CS4 which can be found here http:// www.adobe.com/go/tryflash.

03

Creating a New Document Open up Flash CS3, and create a new Flash Document with the following settings: Set the height to 800px, set the width to 500px. Frame rate 12fps. 01/2009 (3)

65


Sound and Animation

04

Editing Publish Settings Now we need to change some of the publish settings. Click on File>Publish Settings>Flash Tab> Choose Flash Player 7, Choose ActionScript 2.0. We also need to make a few changes in the HTML Tab>Dimensions to Percent>Width 100% x Height 100%. Change the Flash alignment to horizontal center and vertical center.

05

Creating the Background and Clouds Create a background layer with any colors you like. I created a simple blue to white gradiant to clouds. Now, create a cloud movie clip. Once created, drag the movie clip from the library onto the stage.

06

Creating the Balloon Movie Clip I am creating a balloon, which will serve as the interactive piece of this game. After you create this graphic, you can add a motion tween if you like. I added in a motion tween which makes the balloons float up toward the sky. After creating the graphic, let’s create another layer in the balloon movie clip, and call it actions. Make sure this layer is on top. This is where we will insert some simple ActionScript code. Now click on the first frame of the actions layer and let’s add the code. Simply press [F9] on Windows, and [Option-F9] on a Mac to bring up the ActionScript menu. Add the following code: this.onRelease = function():Void {

This.unloadMovie();

}

66

01/2009 (3)


Nintendo Wii

07

Adding the Balloon Movie Clip to the Stage Click on Scene 1 to get back to the stage. Let’s create a new layer on the stage called balloons. Now, drag a few balloons from the library to the stage on the balloon layer.

08 Testing the Game Now, let’s test our game. Press Ctrl-Enter to open the clip. The balloons should go up (if you added in a motion tween), and when you click them they disappear. Success! You created your first simple Flash game ready for the Wii. Granted, we can add in a lot more to this such as sound effects, background music, score boards, etc. However, for the sake of simplicity I left the movie as is.

09 Editing Publish Settings and Uploading So now that we have a finished product and something playable on the Wii, let’s get it online! Click File>Publish Settings>Choose Formats>Select .swf & .html>Click Publish. Now you can upload these files to a web server of your choice. If you don’t have your own domain to publish these files, or you are simply unsure how to upload the game via FTP, take a look at http://www.wiicade.com. This site lets users upload their Flash games for the Wii, which provides access to millions of other users around the globe! Take a good look at this site, as you can check out what other developers are creating. 01/2009 (3)

67


SUBSCRIBE AND SAVE! Subscribe to Flash & Flex from just $39 Free shipping


$39

only for 4 issues □ Yes, I’d like to subscribe to Flash & Flex magazine from issue □ □ □ □ / 2009 1

2

3

4

□ Yes, I’d like to order archive □1 □1 □2 / 2008 Order information (□ individual user/ □ company) Title Name and surname address postcode tel no. email Date

3 EASY WAYS to subscribe: 1.

Phone

Order by phone:

1-917-338-3631 2.

Online

Order via credit card:

www.buyitpress.com 3.

Post or e-mail

Complete and post the form to:

Software Media LLC 1521 Concord Pike, Suite 301 Brandywine Executive Center Wilmington, DE 19803 USA or scan and e-mail the form to: subscription@software.com.pl

Company name Tax Identification Number Office position

Payment details: □ USA $39,99 □ Europe 29,99€ □ World 29,99€ I understand that I will receive 4 issues over the next 12 months. Credit card: □ Master Card □ Visa □ JCB □ POLCARD □ DINERS CLUB

□□□□ □□□□ □□□□ □□□□ □□□□ □□□□ Issue number □□ □□□

Card no. Expiry date Security number

□ I pay by transfer: Nordea Bank

IBAN: PL 49144012990000000005233698 SWIFT: NDEAPLP2 Cheque:

□ I enclose a cheque for $ ____________________ (made payable to Software Media LLC)

Signed Terms and conditions: Your subscription will start with the next available issue. You will receive 4 issues a year.


Column

Adobe Genesis: AIR Refreshes The Desktop T

oday's Web 2.0 frenzy has led me to predict that Web 2.1 will be focused on reducing the noise and clutter by continuing to aggregate and connect wonderful web services to really show people a personalized larger picture of their work and lives. Its not going to surprise everyone that this personal funneling (or aggregation) may not come directly from the next hip web site, but instead from a Desktop application. Below I outline some arguments, but for a moment let's remember the power in client Desktops cannot be forgotten nor ignored. Desktop nodes and very powerful devices and for us Flex/Flash developers we know that our Desktop answer is Adobe AIR. So, maybe I'm biased in saying we'll see AIR applications gain respect in numbers. Adobe doesn't plan to miss the next Desktop wave as is evident with the release of Adobe AIR. Now, a project codenamed Genesis, which uses AIR, brings Flex developers a new market for their ActionScript genius. Here are some points to help show how an Adobe Air application could rule all desktops. • Adobe Air is currently distributed on three major desktop platforms: Windows, Mac, and Linux. With the history of flash player technology this triple play will not be overlooked by businesses. Imagine, office staff can use open-source Linux desktops and desktop software that can be the same as their Mac and Windows co-workers, reducing web virus threats from the work place. • Both ActionScript and Javascript programmers can play, so the innovation can come from anywhere. As we'll read in a moment, Flex programmers can join the Adobe Genesis project. • AIR can be connected to web apps, resulting in applications beyond the web browser. In all honesty, with HD video support in Flash Player we could see a trampling of Quicktime as an HD web delivery medium from Adobe platform designers and developers. • AIR contains a built-in web browser engine (Webkit) and a database engine (SQLlite) – that's a power combo.

• 3D is now a part of the new Flash Player (out now), and 3D engines are super popular with Flash Player 9 all year long. We have yet to see the impact on the entire world when 3D ActionScript applications add an official 3rd dimension to our browsing experiences. In getting back to refreshing of desktops, take note that with AIR being cross-platform (Windows, Mac, Linux) that absolves all platform concerns and the conversation of the desktop changes from questioning the platform to questioning what users will use the application and how. Who will use a desktop application? Business users, developers, artists & designers, chefs, moms, dads, kids, medical staff, field electricians.....I think you get the picture. As AIR developers we have the power and platform to not only impress users, but stay with users on their desktops. We need to make sure we cater to that. Adobe's project Genesis is aimed at initially companies looking to organize and mash-up the Desktop with Flex and AIR. Genesis, a codename for now, is not a new technology like AIR, but is instead built using AIR and Flex to provide harmonious desktop applications. If you would prefer to build on top of an existing projects because now at days you know someone on the web started a project before you thought of it. Anyway, Adobe Genesis is that very project providing more than a starting point for custom dashboard style desktop apps that has Adobe's fine design touch to help keep a cohesive look and feel. Essentially, Adobe is bringing that award winning design and software magic to a customizable AIR playground. Genesis is not a design method, nor a set of graphics and code, but instead is an application shell and may have its own API in the future because it can install and run custom Flex components (known as Panes in Genesis), and imagine you don't even have to maintain the shell just your components. Now, imagine you mix your components with other awesome Genesis Panes. That way you can create, save, and share custom Workspaces. How would your office or business function with a custom AIR application catered to your work? Would you build an AIR app for the biz-dev team? How about an AIR app for the help desk team that loads customer browser windows and Panes with popular sites/URL's or issue tickets and their status? Those sound good, right? Now, imagine you have to make all those AIR apps, maintain them, and they're all separated by department and desktops which is so 1990's. Let's consider Adobe Genesis as we can save Workspaces for each department that may or may share Flex components. With that we can distribute common desktops and even train staff quicker since people would be learning Panes over entire software interfaces. For some, a custom office dashboard seems like overkill, but I assure you that this is one of those moments where you can't see how big of an impact it can have on companies until its there being used. Imagine custom workspaces on every desk. by Chris Charlton

70

01/2009 (3)



ZMAGS

Flex Framework Takes e-publishing to the Next Level

I

n the UK, the Association of Online Publishers recently found what many other countries are also experiencing – namely that Flash online magazines are easier to access, faster for locating desired content and are more convenient. However, within that same survey, it also found that half of all respondents rated the print version as overall more satisfying from a point of user satisfaction. So how can Flash developers make an online magazine as easy and enjoyable to read as the offline equivalent? Market-leading epublishing provider, Zmags, has just released the world’s most customizable tool for creating and viewing online publications. Based on the Flex framework Zmags 3.0 takes e-publishing to the next level. Esben Krag Hansen, Chief Architect at Zmags guides you through the programming innovations and sums up the current status within the e-publishing industry.

All Zmags e-publishing tools are made using Flash technologies. What are the biggest advantages from the developer’s point of view?

interface with much more functionality. Magazine publishers for instance can customize to a very detailed level now and layout styles and skinning to adapt to the magazine’s style. Used cleverly, readers will benefit from the higher degree of customization as well. functionality that you would normally need to build from scratch if you just used Flash without Flex. So using the Flex framework made us able to create a very rich user interface with advanced capabilities such as built-in skinning and a very high degree of customization options for the user. We use the Flex framework extensively as all our components are based on this technology. In the earlier version we implemented a lot of user interface controls on our own. That was a lot of work. Now we get most of the controls directly from Flex which releases resources to focus on the most important things, namely, building the functionality of the viewer for online publications.

Zmags publishing software seems quite revolutionary. One of the most ground-breaking features is the ability to integrate third party plugins in online magazines. How can software developers integrate plugins?

Switching from AS2 to AS3 – how does this impact the reader’s experience when viewing online magazines?

We provide an open API, so third party developers can build and integrate their own plugins. It’s a straight forward and open API, where developers can build anything such as exposing forum threads directly in the online magazine. Another possibility could be to display if a selected offer in an ad is still in stock by building a plugin that captures data from a warehouse management system. It is sort of similar to what you can do in Facebook, where anyone can build third party applications. All it takes is some Flash and Flex programming skills.

In short they get a much better reading experience. Using AS3 and Flex we created a more pleasant and faster loading user

Do you read online magazines yourself?

Flash is definitely the state-of-the-art technology for building rich user interfaces. It creates graphically superior user interfaces and Flash is simply the only technology capable of achieving such advanced interfaces at this point. We did not even consider using any other technologies which is a testament to the strength of Flash.

You created a complete rewrite of the Zmags platform for viewing online publications. This was made using the Flex framework. What are the biggest advantages of using Flex? Flex is a very rich and good user interface toolkit. It provides a lot of built-in 72

ZMAGS

01/2009 (3)


zmags

I do – a lot, actually. They are very useful. They are always available and you don’t have to bring them with you. However, from my standpoint working in the online publishing industry, I see a lot of difference in the quality of the viewers for online magazines. Some of them fail to provide a good reader experience, due to lack of features or loading capacity. Other providers seem to leave the magazine publisher shorthanded when it comes to offering layout customization capabilities and adding relevant features.

is one of our top priorities at Zmags. Our philosophy is to provide a viewer to support this while adding features that do not disturb the reader when viewing online. Navigation should also be as easy as reading a printed version.

will face a hard time, simply because usability matters and providing flexible and easy-touse online magazine viewers are not done overnight.

To what extent does usability count for reading online magazines?

Publishers can customize their online magazines to a much higher degree now. Is there a risk that too much customization can have a negative impact on the usability? No, and certainly not with Zmags epublishing software. No matter what you change, the basic user experience will remain unaffected. The customization does not really affect the user experience and will just add something extra like new features or a look-and-feel that matches the layout of the online magazine.

How long have you got (*laughs*)?! This is a momentous time for publishing and there are so many changes it’s difficult to keep track. Take newspapers – circulations around the world are falling and the former City Editor of The New York Post came out publicly this summer and said that the only way the newspaper industry can save itself is via ‘an aggressive expansion to the web’. It’s the same with catalogues. In May this year, Bloomingdales (one of America’s most famous retailers) announced that it would close its postal mail order catalogue business in 2009 in order to focus on web sales. This move is magnified by the fact that Bloomingdale’s is owned by Macy’s, the second largest retailer in the States with over 1,000 stores and $30 billion in annual sales. Print inflation is high – ink is up 40%, paper starch 40%, raw pulp 24% – and this is compounded by transport and distribution costs that are closely linked with oil prices. Many, many different types of publications are now moving online and Zmags is focused on providing an online solution that is as satisfying to use as the offline version. That’s the challenge and we feel that Zmags Version 3.0 is our best effort yet.

It’s very important. You are basically comparing it to the experience you have when flipping through a printed version – that’s the benchmark. The online experience should therefore be pleasant and easy-to-use. That

Looking ahead, what is the future for online flash publications? Are we facing de-facto standards or will we see different types of technologies and platforms on the market for a long time? I think we will see a lot of evolution and most of this will be based on Flash technologies. A few key players who provide both the best user experiences and the best customization support will dominate the market. This is hard to do, so only the best will survive here. The minor players that only offer the basics 01/2009 (3)

ZMAGS

Finally, what’s your prognosis for the future of online publishing?

73


KING BEE

KING BEE Animation by KING BEE King Bee Animation is a creative hive of talented animators, designers and story tellers that work in a multi-disciplined way to create extremely cutting-edge animation.

K

ing Bee pride themselves on creating animations with more visual distinction – in other words more STING. In practice this means that King Bee pushes the boundaries when it comes to animation styles in order to differentiate the production, whether a TV Commercial, Music Video or any other corporate animation to really get it noticed in an ever fiercer market place. Due to King Bee Animation’s strong knowledge of campaign advertising – King Bee takes ideas extremely seriously in all the animations they produce so that the end goal is the focus for the style and story of every animation/design.

Style with STING We have created a unique website within our own site www.kingbee.co.uk called Animation Styles.com which show cases hundreds of unique animation styles to help clients and animators find that unique style that has extra Sting. For example – An Ad Agency from California headed by talented creative director Michael Sperry contacted King Bee having found a style of animation that would be perfect for the identity of a new website they were producing for famous Urologist Dr. Turek. The loose hand drawn feeling of Kieran Slack’s style on AnimationStyles.com caught Michael’s eye in mind for his clients branding

Figure 1. Bling Loud Commercial

74

and flash website. Kevin Baldwin – King Bee’s head 2D Animation Director along with Kieran headed up the production of 5 flash animated sequences as refreshable banners for the website www.theturekclinic.com. f0 King Bee endeavour to add loads more styles to AnimationStyles.com in the coming months – Watch this space.. Commercial Case Study One: Bling Loud King Bee was approached by New York based Ring tones company ‘Bling Loud’ in to create a funky 3d advert to promote their ringtones download portal. They spotted one of King Bee’s short films called ‘Play Dead’ and fell in love with the 2 quirky animated dogs and asked for a TV advert to feature them promoting their site. King Bee were given the brief to both come up with a cool idea that sold the product and could be a downloadable fun sketch that teens would text a number to get the movie. Jamie and Martyn Niman (King Bee’s creative and animation directors) conceived the idea of the 2 dogs grooving to the music of the ring tones and the smaller dog enjoying it so much

that he breaks wind – the client loved it and Jamie and Martyn directed the animation of this quirky 3d commercial with extra text effects animated in flash (Figure 1).. 2D Animated Character Case Study : ACDC The Metropolis Group head-hunted several animation companies to create the 2d flash animation for the best hits DVD for legendary hard rock band ACDC. King Bee successfully pitched for the work by creating a variety of different cartoon illustrations to capture the heroic timeless personality of the band’s legend Angus Young. King Bee created 4 flash animated cartoon animations of Angus acting as a matador fighting a 3d bull with a live action girl on top. The 4 DVD menus were turned around within a few weeks under a tight deadline but pulled off in good time – Phew! (Figure 2) Music Video Case Study : My Boy Lollipop Purple Lion Entertainment’s director Esther Jones approached King Bee looking for an

Figure 2. ACDC

KING BEE

01/2009 (3)


A Hive Full of Creativity

animation studio to create the character, identity and music video for a new animated female artist that’s debut single is called My Boy Lollipop (A new version of an international hit song by Millie Small). King Bee created the character calling her Fizzy to get across her offbeat fun personality. The idea for the music video was again in the hands of King Bee’s directors Jamie and Martyn Niman. The idea was to appeal to teenagers, parents and anyone who fondly remembers the original song. The concept of an unrequited love of a waitress in a boring day job was chosen as a setting anyone could relate to. Fizzy’s fantasies could be supercolourful and elaborate whilst the real world would be an exaggerated dull monochrome setting. King Bee mixed flash 2d overlay sweet effects over the 3d animated video with the rap sequence at the end including a fully animated flash 2d sequence full of sweets and rainbows! (Figure 3) Cartoon Illustration Case Study : Disney Enchanted Momentum Worldwide Group got in touch with King Bee close to the release of Disney’s Enchanted on DVD. Disney were looking to get the film’s six directors illustrated in the

style of the 2d sequences from the movie and Momentum head-hunted King Bee to capture the Disney style whilst capturing the real look of the directors. King Bee flash illustrated the 6 directors complete with film lighting effects ready to be each framed and put up for the DVD’s release. Event Animation Case Study : Madness Birthday Animation Event Management company Launch Pad Events got in touch with King Bee with a very unusual brief. A wealthy CEO of a London Investment banking company’s business partner was throwing a surprise 40th birthday party for the company’s director. As part of a huge birthday event – Madness the band (the client’s favourite band) were to play live. The client wanted a day in the life of the director in a Terry Gilliam Monty Python flash animated cut-out collage style. The end result headed up by Kevin Baldwin – King Bee’s 2D animation director was an 8 and a half minute film with the hilarious script co written between King Bee and the client that included a professional voice actor playing the director as an Ali G type of character along with the improvised humour from the directors’ family and friends. The last line in the animation had the director’s wife exclaim, Madness! and the director responded No – This is Madness! and Madness started playing from behind a curtain – Quite a party! DVD Animation Case Study : British Parliament Animation Worthwhile TV’s director Jeremy Wootliff was producing a live-action documentary for the British Parliament and was in strong need of some animation to both fill gaps in history that had no archive footage as well as to liven up the existing documentary visually. King Bee animated a variety of styles from different historical periods in flash including a Bayeux

Figure 3. Fizzy my Boy Lollypop Music Video

01/2009 (3)

Tapestry style as well as a cut-out animated style for some more up-to-date periods that had no footage or needed more life. The DVD will be given out shortly to members of British Parliament (Figure 4).

KING BEE Entertainment Website: www.greatcartoons.tv. As well as a full service animation production studio, King Bee also works on a variety of series productions through their other company King Bee Entertainment. The slogan story with sting captures their mission in creating extremely memorable animated series productions that will stand the test of time. King Bee is focusing on the prime time animated market with 3 animated series in development. One of which is being co-produced with Fawlty Towers director Bob Spiers. King Bee are also producing 2 exciting new properties called Soap City and the Non Stop Cartoon Sketch show – All made in flash. The sketch show will be a fully interactive website full of sketch downloads and more.. As well as King Bee’s prime time flash series – King Bee also have 2 children’s toons underway including a flash animated series called Wheelie Wednesdays all about talking dustbins and recycling. King Bee’s plans for the future? King Bee are very positive about the future – They plan on continuing to innovate both in terms of stylistic and story originality and aim to make an even more lasting impression on the world of TV and cross-media flash animation production – give us a buzz if you’d like to get in touch.

KING BEE ANIMATION The Studio 23 Eagle Terrace Woodford Green Essex IG8 9AT Give us a buzz: (+44)(0) 845-601-6424 e-mail us: info@kingbee.co.uk

Figure 4. British Parliament

KING BEE

75


OMNISDATA

Adobe Flash as the engine in geospatial applications

T

oday Adobe Flash technology is mostly used for games and multimedia applications. At the same time the technology has a great potential as a visualization component for GIS and CAD systems. It can

render anti-aliased vector and raster graphics and it has widespread compatibility. Adobe Flash runs on most operating systems and it can be used for both web and desktop applications. The mobile version of Flash, Flash Lite, brings

development of Flash applications for mobile devices. Flash utilizes a vector file format (SWF) and this makes it great for GIS and CAD applications. The format is also optimized considering size which makes it great for environments like the Internet. FlashNavigator is a rapid development framework, used for publishing GIS and CAD data through Adobe Flash technology in web, desktop and mobile applications. It has been in active development for over two years. Unlike other solutions it provides tiled vector

Figure 1. Implementation diagram of flashNavigator viewer

76

OMNISDATA

01/2009 (3)


flashNavigator

target applications. FlashNavigator can be used in simple (lite) projects with basic functionality, but it can also be used in enterprise projects which require full GIS functionality. It can be integrated into any current and upcoming web, desktop and mobile technology that supports Adobe Flash or Flash Lite. FlashNavigator features: Figure 2. www.flashnavigator.net

to vector conversion of GIS and CAD file and database formats to Adobe Flash. FlashNavigator supports conversion from multiple vector and raster formats: ESRI Shapefile, PostgreSQL (PostGIS), Oracle Spatial, Mapinfo mid/mif, GeoTIFF, GRASS, OGDI, OCAD, AutoCAD DWG/ DXF, Adobe Flash (SWF), Raster images (GIF, PNG, JPEG, …), Custom SQL format, etc. FlashNavigator viewer is a Flash component that is optimized regarding file size. The viewer core has a total size of around 20 KB with a preloader of just 4 KB. The core engine can be extended with custom plugins, which make the entire solution very flexible regarding usage in

1. conversion of numerous vector and raster formats to Adobe Flash 2. fast and fluid pan and zoom 3. API (Application Programming Interface): JavaScript, .NET, Adobe Air, etc. 4. modularity (plug-in structure for additional functionality, e.g. slider, canvas, interaction with various databases, …) 5. cross-platform and cross-device GIS/CAD support 6. multiple projection support and conversion 7. reduced development costs 8. spatial analysis 9. highly customizable 10. visually attractive 11. display of POI (Point Of Interest)

Regarding web applications the principle is similar. Using ExternalInterface it’s possible to control flashNavigator from JavaScript. Of course it’s possible to use it in Flash and Flex applications as well. Recently Flash for mobile phones, Flash Lite, has gotten some important improvements which enabled flashNavigator to be ported to the Adobe Flash Lite platform. First Adobe Flash Lite mobile location application, powered by NAVTEQ maps, was created by integrating flashNavigator with Symbian OS. More information about flashNavigator can be found at: http://www.flashnavigator.net/. About Omnisdata: Website: http://www.omnisdata.com/ Omnisdata is a geoinformatics company headquartered in Zagreb, Croatia. Core business is focused on proprietary geospatial technology flashNavigator. Omnisdata performs geospatial services for the end clients but also it cooperates with various worldwide geospatial companies as technology partner. Company has leading local mapping project in Croatia: www.karte.hr.

Figure 3. FlashNavigator technology diagram

01/2009 (3)

OMNISDATA

77


Interview

Interview with Justin Everett-Church Justin Everett-Church is a senior product manager for Designer/Developer Relations for Flash at Adobe, and has co-authored four books on game development in Flash. Justin is a frequent speaker at conferences on the topics of Flash for mobile and devices and Flash outside the browser. What is your role at Adobe and how long have you worked there? My name is Justin Everett-Church and I’m a senior product manager for Adobe Flash Player. I’ve worked at Adobe since 2006. Previously I worked at Yahoo! as rich media evangelist and manager in the platform workin on Flash content.

Have the makeup of the next CS4 suites been decided and if so, will they include Flex builder? Well, Adobe does not discuss product specifics before they launch so that’s something your readers will have to wait for !

Have the complaints about the Flash IDE been taken on board and can we hope to see improvements in the near future? Adobe is committed to creating innovative products and technologies with features and functionality based on valuable customer feedback. Customer requests are play a huge role in determining how the product team will enhance future product versions.

Is there a tentative release date for Flash CS4? We haven’t announced the date for Flash CS4. However, Adobe Flash Player 10 is in public beta on Adobe Labs and developers can already start developing SWFs using the new features with the compiler available on our open source site along with the documentation for the new ActioonScript features.

Do you think that many companies are taking the RIA market seriously at the moment or do you think it'll take more time for them to embrace the technology? 78

Rich content, in general, and RIAs, in particular, are an increasingly important part of today's Web experience. In many ways, the growing acceptance of RIAs represents a natural progression of the Web. Given the power and potential of RIAs, it’s not surprising that the Gartner Group, for example, predicts that by 2010 at least 60 percent of new application development will include RIA technology. Successful RIA development depends on the flexibility to meet a wide range of application requirements, whether it is simply extending capabilities in existing Web applications or creating full client-side applications running in browsers. And, of course, it’s important to consider where RIAs should run – in a browser, on the desktop or a combination of both. Much like the familiarity of today's Web applications, RIAs will become increasingly common given their current surge in growth. Developers will be asked to build more sophisticated applications and users will regularly access services filled with real-time updates, data manipulation, quality presentation and printing, blended video and documents, and other capabilities once limited to costly desktop applications. Already, the impact of RIAs is evident on Web sites and corporate intranets worldwide – with even the simplest RIAs helping to reshape users' expectations and experiences of what is possible with Web services.

Do you think Thermo will help designers who feel intimidated by Flex? Thermo complements traditional Flex development with a workflow that is intuitive to designers. While there is WYSIWYG capabilities in FlexBuilder, Thermo will give designers the tools they need to take the experience in RIAs in new directions. Applications created in Thermo are Flex applications that can be loaded directly into Flex Builder, providing a great roundtrip workflow for designers collaborating with developers. The

designer's work can be incorporated directly into the production application with no loss of fidelity, and designers can continue to refine the design throughout the iterative development process. (http://labs.adobe.com/wiki/index.php/Thermo)

The migration from AS2 to AS3 has proved a stumbling block for some creatives. Again, they feel intimidated. What do you think that Adobe could have done to make the transition a little easier? Colin Moock's 'From the Ground Up' Tour was definitely a move in the right direction but possibly a little late in the game? Anytime we release a new version of ActionScript, we know that there will always be a hurdle for some users. The same was true in the transition from Flash 4 syntax to ActionScript and ActionScript 1.0 to ActionScript 2.0. We try to make the change as easy as possible and support it with information like the ActionScript migration guide, Adobe Developer Connection articles and a variety of tutorials. The reason for changing ActionScript at all is really about making development easier. Previous versions of ActionScript had a lot of exceptions. It was becoming difficult for new users to learn because too many rules had exceptions. In ActionScript 3, we changed the APIs to become more consistent, but also to come inline with the proposed ECMAScript standard which will also provide guidance to users about how the language will evolve from here. The other major reason for ActionScript 3 is that it provides significant performance enhancement. Along with ActionScript 3.0, we introduced a new virtual machine that lets designers and developers express their creativity in ways that the previous VM would not have allowed. From here we can continue to make better, faster Flash Players that keep up with the demands of all of our users. 01/2009 (3)



Books review

Review: Learning Flex 3: Getting up to Speed with Rich Internet Applications

Authors: Alaric Cole Publisher: O'Reilly Media, Inc. Language: English Paperback: 304 pages (15 chapters) ISBN 10: 0-596-51732-7 ISBN 13: 9780596517328 Website: http://oreilly.com/catalog/ 9780596517328/

F

lex 3, open source technologies released by Adobe Systems for the development and deployment of cross platform rich Internet applications, is based on and runs on the Adobe Flash platform. Since Adobe released the Flex 3 SDK under the open source Mozilla Public License more and more people are attracted towards it and want to learn it. Are you a beginner, or an experienced web developer, or coming to Flex from another platform want to enjoy this technology and want to learn more? Learning Flex 3: Getting up to Speed with Rich Internet Applications by Alaric Cole is a good practical and outstanding book to start your journey to learning Flex 3. This book is quite different from other black and white books. This book has colorful images, an attractive layout and colored tips, scripts and lots more... which keep the mind refreshed during reading. The book is divided into 15 chapter which allowing you to learn and apply key concepts by building applications progressively. Learning Flex 3 provides a step-by-step tutorial for learning Flex development with basic features of ActionScript and MXML. If you don't know anything about Flex development this book begins with the first step towards it. This book introduce new user with Flex, AIR and discusses how to set up Flex Builder or Eclipse for flex development to run his first flex application. Then more information is given on Common Components and the properties to Layout a Flex application in design mode and modifying it in source mode with Adobe’s Flex Builder. ActionScript and MXML add life to Flex application. Here we get introduced to the basics of scripting and topics like assignment,

80

variables, data types, objects, classes, ActionScript’s Relationship with MXML, Events, Events Handling, scripting and Debugging for the events. Then we moves towards advanced topics like handling user input with rich forms and building a flexible user interface, data binding to develop complete applications such as connecting to data and building a flexible user interface, gathering information and displaying it, controlling flow and visibility, learning about MXML and ActionScript to create reusable components with MXML, adding effects, filters, and transitions, style applications with CSS, and deploying applications to the Web, or to the desktop using Adobe AIR. The colored tips will help you to understood the topic very well and you will experience it like you are working on PC. This book is excellent for people with no experience with Flash IDE, web design, or programming in general and it will help them feel comfortable jumping right in world of Flex. I have really enjoyed the book, and I hope you do, too. It’s a good start to build some great applications with this powerful Flex technology.

Conclusion: This is a great beginner’s book for those looking to start up with Flex 3. The book offers you plenty of practical and useful examples that are a good introduction into a lot of aspects of Flex. The possibilities with Flex 3 are nearly limitless. The book describes real-time example that can be reused. This book also teaches you how to build components with MXML and ActionScript 3.0 in practical way. by Chetankumar Akarte

01/2009 (3)


Recommended Companies Adobe

mod7

Adobe Systems Inc. is a diversified software company, which offers a line of business and mobile software and services for creating, managing, delivering and engaging with compelling content and experiences. Adobe added Flash to its technology portfolio after acquisition of Macromedia in 2005.

mod7 is a visual communications and interaction design agency specializing in interactive media, web design and motion graphics. A broad range of clients – from Electronic Arts to CBC – have been rocked by our passion for making killer interactive experiences. We can do the same for you.

www.adobe.com

www.mod7.com

Digicrafts

Kindisoft

Digicrafts Flash Components is the leading company on developing Flash/Flex extension and related products. With years of experiences on the design industry and expertise on multimedia design. We can create the most suitable products for designer to maximum their creativity.

Kindisoft started out as a vision; a vision to ensure the security of designers’ code, creativity, and intellectual property. These days, the Internet is becoming a more dynamic and interactive medium of communication, giving designers the freedom to express their selves in any way they want.

www.digicrafts.com.hk

www.kindisoft.com

Advitor

Powerflasher

The Advitor is a highly creative, innovation and expertise of interactive design, motion graphics, film production, music & audio, rich media, animation and technology specializing in all fields of high-end design, film, music & audio and animation. www.advitor.com

Powerflasher has become since its foundation in 1997 Europe’s leading multimedia agency specializing in Flash. Forty passionate coders, graphic artists and animators develop more than 1.000 interactive stunning yet user-friendly on- and offline human interface experiences for prestigious clients all over the globe. www.powerflasher.com


Books review

Foundation Flash CS4 for Designers

Authors: Tom Green, David Stiller Language: English Paperback: 650 Pages ISBN-10: 1-4302-1093-1 ISBN-13: 978-1-4302-1093-1 Website: www.friendsofed.com Publisher: Apress company

I

f you’re a Flash designer looking for a solid overview of Flash CS4, this book is for you. Through the use of solid and practical exercises, you will soon master the fundamentals of this latest edition of the Adobe Flash authoring tool. Using a series of carefully developed tutorials, you will be led from basic Flash CS4 techniques to the point where you can create animations, MP3 players, and customized Flash video players in no time. Each chapter focuses on a major aspect of Flash, and then lets you take the reins in a „Your Turn” exercise to create something amazing with what you’ve learned. This book focuses on the core skill set you need to feel at home with Flash CS4, and also introduces you to some of the biggest names in today’s Flash community through interviews and actual “How To” examples, so you can learn from the masters. You will start by studying the Flash CS4 interface, and while you’re at it, you’ll be guided toward mastery of the fundamentals, such as movieclips, text, and graphics, which will lead you into some of the more fascinating aspects of Flash, including audio, video, animation, and 3D transformations. By the time you finish, you will have created an MP3 player and a Flash video player, been introduced to the basics of ActionScript 3.0, learned how to combine Flash with XML,

82

styled Flash text with CSS, created animated scenes, and worked your way through a host of additional projects. All of these exercises are designed to give you the knowledge necessary to master Flash CS4 from the ground up. If you’re already a seasoned Flash designer, this book will get you up to speed with the latest version in relatively short order. This book covers all of the new Flash CS4 features, such as the new animation and 3D tools, the new Adobe Media Encoder, and a pair of the coolest new additions to the Tools panel: a Spray Brush tool and a Deco tool. In this book, you’ll learn: • How to create effective animations using the new Motion Editor and animation tools • How to use the new 3D features to animate objects in 3D space • Best-practice tips and techniques from some of the top Flash practitioners on the planet • How to create captioned video and full-screen video, and deploy HD video using Flash • Techniques for using the Flash UI components as well as XML documents to create stunning,interactive presentations

01/2009 (3)




Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.