visualizing your data with birt and flash ffd 08 2010

Upload: binbinle

Post on 29-Oct-2015

25 views

Category:

Documents


0 download

TRANSCRIPT

  • 4Editors Note

    08/2010 (16)

    What we can achieve together ...My answer is everything :). And I hope that we can do this together. We can create the best mag for Flash developers. It is my aim for this year. Ive started from the final thought but what we need is to have fresh and new ideas to prepare an interesting issue for you each month. I know that the new ideas exist and you need to be made aware of them to finally use them constructively or creatively. We want to show you what has been perhaps hidden so far from you.

    I hope that our FFD achieves in helping and supporting you with your daily tasks. We always aim at providing the most up to date issue by presenting modern techniques often required and sought out by everyone in the respected areas.

    In this issue our lead article on Visualizing your Data with BIRT and Flash (p. 14) discusses how Actuate has combined these technologies in a way that takes advantage of Flash and Web based skill sets to produce some very impressive interactive applications.

    For all of you who want to learn about actionscript development, please go on page 24 and 28 to read articles written by Grzegorz Mirek and Huw Collingbourne.

    I would like to add that Huw will be our regular columnist. Thank you very much Huw and all FFD contributors for your support.

    If you want to check what is the best model for developer when it comes to monetizing a web game. Definitvely you shoudl read the 3rd part of article series by Chris Hughes on page 20.

    Moreover, if you have any ideas for topics that you would like to see us cover in up coming issues, please let us know. So keep the mails coming in!

    Kind RegardsFFD Team

    [email protected]

    Editor in Chief: Ewa Dudzic [email protected]: Betsy Irvine, Patrick French

    DTP Team: Ireneusz Pogroszewski [email protected] Director: Ireneusz Pogroszewski [email protected]

    Senior Consultant/Publisher: Pawe Marciniak

    Publisher: Software Press Sp. z o.o. SKul. Bokserska 1 02-682 Warszawa Poland Worldwide Publishing

    Software Press Sp. z o.o. SK is looking for partners from all over the World.If you are interested in cooperating with us,please contact us by e-mail: [email protected]

    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.

    Thanks to the most active and helping beta testers:Russell TangChoon, Lee Graham, Jassa Amir Lang, Ed Werzyn, Yann Smith-Kielland, Justus, Csomk Gbor, Kevin Martin, Charles Wong, Ali Raza, Almog Koren, Izcoatl Armando Estanol Fuentes, Lionel Low, Michael J. Iriarte, Paula R. Mould, Rosarin Adulseranee, Sidney de Koning

    To create graphs and diagrams we used program by company.

    The editors use automatic DTP system Mathematical formulas created by Design Science MathType

    ATTENTION!Distributing current or past issues of this magazine without permission of the publisher is harmful activity and will result in judicial liability.

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

  • 608/2010 (16)

    CONTENTS

    Tip of the issueFlash Error with Flickering TweensTom Rassweiler Manager of Game Development Sometimes when a ash movie is compiled some of the animated tweens will become corrupted in the .swf. This is a very strange problem and results in animations seeming to icker, displaying only the keyframes and not the tweened frames. This is made more difficult because the compiler does not give you any warning of this corruption. You will only see it when you play the movie.

    The bug is easily xed by going into the library of the a and opening the corrupted movie clip, and then recompiling. No actual adjustment of the code is required.

    However, it is still time consuming and irritating, so it is possible to create a JSFL command that will go through the process of opening and looking at each movie clip before compiling. Using this preventative measure, you can avoid this error entirely.

    doc = fl.getDocumentDOM(); lib = doc.library; it = lib.items; for(var i in it){ if(it[i].itemType == movie clip){ lib.editItem(it[i].name); } }

    Special Report

    08 Is Apple Getting The Big Picture?

    BY JOHN MARX

    InBrief

    10 News

    BY CSOMK GBOR

    Tools

    12 Sothink SWF Decompiler

    BY ALI RAZASuppose you watched a video presentation online and want to save it on your system to enjoy it later offline. Maybe you are thrilled with a cartoon animation and you want to create a wallpaper out of it using few assets from the movie. Or you could be a student with a curious mind who wants to learn the behind the scene stuff.

    BUSINESS

    14 Visualizing your Data with BIRT and Flash

    BY DAN MELCHER AND JASON WEATHERSBYFlash is an industry standard when producing professional interactive content for data analysis. BIRT is a widely popular open source reporting technology that offers a great set of web based analytic features. Combine these two technologies and you can produce some very compelling applications that will amaze and dazzle. This article discusses how Actuate has combined these technologies in a way that takes advantage of Flash and Web based skill sets to produce some very impressive interactive applications.

    GAMES

    20 Monetizing Your Web Game

    BY CHRIS HUGHESCurrently there are many choices when it comes to monetizing a web game. It can be daunting to decide which model is best for a developer. On top of this, there are conflicting reports as to which ones are truly lucrative. The 3rd part of article series by Chris Hughes.

    ACTIONSCRIPT IN ACTION

    24 Objects and Associative Arrays. There Is More To The Actionscript Object Class Than Meets The EyesBY HUW COLLINGBOURNEIn this series, Huw will be at a variety of topics related to ActionScript programming. In this article,

  • 708/2009 (16)

    Influxis www.influxis.com ............................................. 2-3 Digicraftswww.digicrafts.com.hk ...................................... 5

    Erainwww.erain.com ..................................................13

    Exsyswww.exsys.com ................................................ 19

    Flash and Mathwww.flashandmath.com ....................................21

    Gamersafewww.gamersafe.com .........................................23

    gate2shopwww.gate2shop.com .........................................27

    Flexerwww.flexer.info ...................................................33

    ActionScriptJobs.comhttp://actionscriptjobs.com/ .............................. 39

    FusionMaps for Flexwww.fusioncharts.com/flex ............................... 41

    Kevin Ruse + Associatess Inc.www.kevinruse.com .......................................... 49

    Actuatewww.actuate.com .............................................. 51

    The Jumpeye Frameworkwww.jumpeye.com ............................................ 53

    The issue 8/2010 sponsored by Advertisers:

    CONTENTS

    Huw wants to begin at the very beginning with the Object class, which is the root of the ActionScript class hierarchy from which all other classes descend. In many object oriented languages, the root class is very simple.

    ACTIONSCRIPT DEVELOPMENT

    28 Loading External Assets Using the Open-source BulkLoader Class BY GRZEGORZ MIREKFlash offers great built-in solutions for loading several types of external content into SWF applications. However, that doesnt help you much when it comes to loading numerous units of different kind of data at the same time. Thankfully, there are some third-party utilities that can take care of the job. In this article you will see how to make use of the open-source BulkLoader class.

    FLEX DEVELOPMENT

    34 Adobe AlchemyA Comparative ExampleBY MARCO CASARIOAdobe Alchemy is an Adobe project that allows users to compile C and C++ code to be run on the Actionscript Virtual Machine (AVM2). With this possibility developers can take advantages of hundreds of powerful C and C++ libraries on the Flash Platform. These libraries will be compiled as a SWF or SWC files that run on Adobe Flash Player 10 (as well as Adobe AIR 1.5).

    SERVER-SIDE INTERACTION

    38 How to Test Upload Bandwidth to a FMSBY MARC CASARIOFlash Media Server has a native method to check download bandwitdh of the client, a feature that becomes very useful when you are going to stream multi bitrate content.

    FLASH GAME CONFERENCE

    42 Flash GAMM!

    BY VALERIYA MALLAYEVAA story of enthusiasm and love of the Flash platform which turned a small meeting into one of the brightest events in the Flash industry.

    INTERVIEW

    46 Interview with Sean Carey, President HD Interactive, a Premium Provider of Branded Games, Rich Internet Applications, Social Media & Memorable Online Experiences

    BOOKS REVIEW

    50 Flex 4 in Action

    BY PAUL BRZEK

  • 08/2010 (16)8 08/2010 (16) 9

    As Adobe developers we may not like Steve Jobs but we should respect him. Seeing the turnaround of Apple Computer upon his return and the stellar growth of companies such as Pixar Animation Studios should lead any of us to deduce he is a man with a plan. Just a few short years ago we had never heard of i-devices and now none of us can sit and enjoy our latte without seeing at least one.

    So in April when developers using Adobes Packager For iPhone were shut out of the iOS application market, most of us would deduce that Apples decision was final. After all, when was the last time you saw a $200 Billion company waffle on critical policy decisions. Yet just four months after Jobs now infamous letter titled Thoughts On Flash was posted for all to see we hear that Adobe is back in the game.

    A recent blog post by Adobe Communications titled Great News For Developers on the Adobe Blog Site demonstrates that it is a good thing we communicate digitally because the news we must follow doesnt allow time for ink to dry. But why the change? Surely Steve Jobs has a reputation to protect. With shareholders and a board to answer to there must have been compelling reasons to waffle.

    As I pondered the news I first thought that the recent numbers showing sales of Android based phones might be the kicker. We now see that Android is in the number two spot behind Symbian and Apple is running in third place in the smart phone race. This cant be good for Apples new iAd offering launched in April. And if the iPhone follows the Mac in a head-to-head technology war similar to the PC war in the 80s, Steve doesnt want to relive the history that led to his resignation as Apples CEO in 1985. Steve is too old for another Next.

    But with one home run after another starting with the iPod Apples throngs of strategists and planners surely knew of Googles impending threat. I began to ask myself, what else is Apple up to? Might this be bigger than phones?

    There is no doubt that Googles business model has changed the way leaders in the computer industry

    think. Google has shown that advertising revenue is much more profitable than either hardware or services and with its $150 Billion plus market cap, achieved just six years since its IPO, the established technology companies have to take notice. Hence, when Apple announced iAd their share price jumped 8% in one day.

    And I guess that is the point. We are no longer speaking of the computer industry and while most of us sit at keyboards and flat panel screens all day, most of the world doesnt. In fact, the real world is sitting in front of flat screens but most dont have keyboards. The now famous Nielsen Company popularized for its Nielsen Ratings published for television advertisers enabled airtime to be priced and targeted to certain markets. Nielsen now publishes a report called the

    Is Apple Getting The Big Picture?

  • 08/2010 (16)8 08/2010 (16) 9

    Three Screen Report. A review of this report shed a great deal of light on Apples decision regarding Flash.

    In their Q1 report Nielsen writes Each week the typical American continues to increase his/her media time, watching over 35 hours of TV, 2 hours of which is timeshifted TV, 20 minutes of online video and 4 minutes of mobile video, while also spending nearly 4 hours on the Internet. In addition, 59% of Americans surf the Internet and watch TV at the same time. Hmmm? If Nielsen is telling advertisers that people are using the Internet and phones more and TVs less, what does that say about advertising investment?

    Onstream Media Corp, specialists in webcasting and digital media reported in their investors conference call that There is going to be billions of dollars shifted from the traditional media and television to the internet. eMarket has predicted that this emerging market [online video advertising] will grow from nearly $600 million in 2008 to more than $3 billion by 2012 and $4.6 billion by 2013. This represents 800% growth in USA alone over the

    next 5 years. So if advertisers are shifting away from television and toward new media, what does that mean for Apple and even more importantly Adobe Flash and Flex?

    On September 20th, 2010 an SEC Filing known as an 8-K was filed by a company called Rovi Corporation. Filed under paragraph 8.01 titled Other Events they

    report, Rovi Corporation (the Company) announced today that it has entered into a multi-year agreement

    with Apple Inc. whereby Apple shall license intellectual property from the Company. The specific terms of the license agreement are confidential.

    A quick look at Rovis web site demonstrates that not only do they use

    Flash but they also catalog digital video content and seem to

    have a technology answer to a 10,000 channel world. Im certain a great deal

    of that video is .flv! Granted I am no Search Engine

    Optimization (SEO) buff but it would appear that Apple may

    be looking to trump YouTube and take iTunes beyond its

    lame $1.99 offerings of the same video content we enjoy from Netflix and Hulu.And that is when it hit me!

    If we had to name something Apple has not hit out of the

    park it would be AppleTV. In fact, the recent revised hardware

    offering taking the price point of its HDTV connected hardware from $299 to $99 is a pretty clear indication that things are not headed in the right

    direction. That reality combined with Googles CEO Forum held in May at Google-IO announced GoogleTV with CEOs of Sony, Best Buy, Echostar, Logitech, and yes, the CEO of Adobe!

    Flash and Flex Friends, I have a prediction. We are about to become programmers. Not in the sense of computer programmers but more in the sense of television programmers. Content will become programming and our craft will be in even higher demand than it is today. The iOS verses Android race will stretch far beyond smart phones and is about to invade our living rooms. I think Rovi and Apple will not only prove to be our

    patrons, but I believe what Steve Jobs learned from Disney may be a boon for us all. Stay tuned for more Toy Story!

    JOHN D MARX

  • 10

    IN BRIEF

    08/2010 (16)

    iOS Applications and FlashOn September 9th Apple announced that they have removed the restriction on 3rd-party development tools for creating applications for iOS devices.

    What this Means:This theoretically allows developers to use the Flash CS5 iPhone packager to create applications for the iPhone and iPad. Adobe also announced that they will resume development work on the packager.

    What this Does NOT Mean:This does not mean that the Flash Player will be coming to iOS as part of Mobile Safari. It also doesnt mean that AIR will be natively supported as it will be on Android.

    So this is great news for Flash developers who want to target iOS devices with their applications.

    Source: TheFlashBlog.com

    Flash Media Server 4 Released at IBCAdobe have just launched the new version of Flash Media Server at IBC conference in three different versions: Streaming, Interactive and Enterprise.

    The features to be most excited about are:

    64-bit support, which brings tremendous streaming power!

    P2P/RTMFP support with a server-side API... you get the same access to the P2P networks like the Flash Player client, plus you can create a stable point from the server, very useful for distributed objects and databases. Next to that, you dont need to use Adobe Stratus rendezvous-server and you can start building your own commercial P2P apps.

    Multicast support stream multicast in H.264/on2 VP6 right from the Flash Media Live Encoder as well as control and manage multicast streams from the server. This also brings new possibilities to IP only multicast and multicast fusion (combination of application-level multicast and IP-only multicast).

    CentOS support Absolute timecode to sync audio and video from

    different channels + combined with multibitrate streaming

    HTTP streaming new delivery choice

    and more

    Source: FlashRealtime.com

    Yahoo and Baidu Using Flash for Handwritten QueriesYahoo Taiwan and Hong Kong just rolled out a new feature for their search box. A new Flash based application allows you to hand-write your search queries.

    Typing search queries in Chinese can be challenging especially for new computer users because it requires memorizing Chinese character mapping rules. Even experienced computer users dont remember the mapping for all Chinese characters. The handwriting feature lowers the hurdle for people searching on Yahoo! Taiwan and Yahoo! Hong Kong.

    This is another great example of how powerful Flash has become and how Flash has become so much more than a video player or animation tool! More info on Yahoos Search Blog.

  • 11

    IN BRIEF

    08/2010 (16)

    Baidu (the most popular search engine in the Chinese language) already added the same feature a few months ago. Baidu also uses Flash.

    Source: webkitchen.be

    Update on Flex SDK HeroOn the official Adobe Blog, Deepa Subramaniam was pleased to announce that we have made the first build of Flex SDK Hero already available on the Adobe Open Source site.

    The Hero release development practices have changed somewhat from the Flex 4 release the biggest change is that Hero is built atop the latest (and as of yet, unreleased) Flash Player and AIR runtimes. Because of this tight coupling, Adobe have been unable to provide nightly builds that showcase in-development Flash Player and AIR features. Once the current in-development Flash Player and AIR runtimes are showcased in a public release, nightly builds will resume. In the interim, we are releasing semi-regular stable builds that showcase Hero feature work not dependent on features under development in the latest Flash Player and AIR runtimes the first of these builds has now been posted!

    This build showcases in-development work like the Spark DataGrid (Tier 1), Spark Image, Spark Form, enhancements to RSLs, OSMF 1.0 integration and the SWF Size Report compiler option.

    Source: blogs.adobe.com

    Demand for Flash Developers is IncreasingThe Wall Street Journal recently put out an article describing how the demand for Flash developers has been increasing as of late. While this is no surprise to most of us in the community, it is a refreshing reminder that those who have marked Flash as a dying technology

    are quite wrong indeed. The article states that the increase in online Flash gaming is a large reason for the spike. Maybe it also has something to do with all of the anticipation surrounding Flash on mobile devices.

    The article also includes a quote about the salaries that top Flash developers are getting these days:

    Top full-time Flash engineers can now command more than $150,000 a year in salary, says Stuart Liroff, a headhunter at GreeneSearch recruiting firm. That compares with $50,000 to $80,000 a year three years ago.

    Source: TheFlashBlog.com

    Adobe MAX 2010 is ComingThe MAX 2010 is coming. A short preview what inside this years MAX: If you are working on mobile applications, you definitely cant miss this event. This year Adobe will focus on developing multiscreen content with Flash and HTML.

    Also, a hot topic in the industry is the creation of e-book publications. At this years MAX, Adobe will focus on the digital publishing workflow.

    This years conference will focus on three emerging trends: the explosion of content across multiple screens and devices, new technologies that enable integrated designer and developer workflows, and innovative ways to monetize content. MAX 2010 will give you the skills, insight, and contacts to take advantage of these opportunities as they transform our industry.

    For more information about MAX 2010, you can visit the link below.

    http://max.adobe.com/

    Source: FlashEnabledBlog

    News selected by Gbor Csomk

  • 08/2010 (16)12

    TOOLS

    There is a great possibility that you are a flash/flex developer who wishes to know the security level of his application, or a worse situation is that you have lost your portfolio, or an application which you are supposed to present today. Scary! Isnt it?

    So? What would you need to solve all the above problems? A swf downloader? extractor? decompiler? A fla converter?

    Luckily, there is an all-in-one application I am presenting Sothink SWF Decompiler.

    Sothink SWF Decompiler is a Windows 7 compatible, multi-lingual eye-catching application that provides features from capturing swf files to magical swf-to-fla/flex conversion. Its top bar gives quick access to various important actions from interacting with the selected content to finally getting the desired results. It has panes such as explorer, information, and export that give it a professional look. Other than its Office 2007 inspired theme, it comes with a built-in flash player capable of playing swf, flv and f4v files.

    I came to know about SWF Decompiler when I was in my college. At that time, there was no other equivalent technology. Still, in 2010, Sothink SWF Decompiler takes the lead due to its rich set of features, especially for Flash CS5 support.

    This incredible application works in 3 fundamental steps. First it lets you capture the swf files using SWF Catcher from either IE or Firefox. It also lets you get

    SWFs from IE history. In the second step, it lets you interact with

    the selected swf, browse resources along with preview, ActionScript searching, and finally let you select how would you want to export the swf.

    In the last step you either export a SWF to a Flash/Flex project or export only selected resources such as sprites, text, actionscript code, flv videos, sound files etc. It also supports batch exporting. A great feature is that it lets you convert a flash projector (.exe) into fla file.

    My only concern with Sothink SWF Decompiler is that there is no official support for Adobe AIR based applications, although Im quite hopeful that this is in their plans as well.

    Here is the link to the product. http://www.sothink.com/product/flashdecompiler/index.htm

    Sothink SWF Decompiler

    Suppose you watched a video presentation online and want to save it on your system to enjoy it later offline. Maybe you are thrilled with a cartoon animation and you want to create a wallpaper out of it using few assets from the movie. Or you could be a student with a curious mind who wants to learn the behind the scene stuff.

    An all-in-one Magical Flash Utility

    ALI RAZAAdobe Certied InstructorSun Certied Java ProgrammerZend Certied Engineerwww.manofspirit.com

  • 08/2010 (16)14

    BUSINESS Visualizing your Data with BIRT and Flash

    08/2010 (16) 15

    Combining Best of Breed Technologies Flash is an industry standard when producing professional interactive content for data analysis. BIRT is a widely popular open source reporting technology

    that offers a great set of web based analytic features. Combine these two technologies and you can produce some very compelling applications that will amaze and dazzle. This article discusses how Actuate has

    Visualizing your Data

    Understanding how Actuate is using data driven BIRT reporting in combination with Flash presentations to create highly interactive business applications.

    What you will learn How Actuate is leveraging both technologies to produce a

    better Web based BI Solution Flash Development Features available to the BIRT designer How BIRT and Flash can be combined

    What you should know Should have a general understanding of basic web based re-

    porting

    with BIRT and Flash

    Figure 1. BIRT Flash Examples

  • 08/2010 (16)14

    BUSINESS Visualizing your Data with BIRT and Flash

    08/2010 (16) 15

    popular Eclipse IDE and is used to build and deploy business intelligence applications in a Java/J2EE environment.

    The goal of the project is to create a set of tools for data analysis and reporting, with simplicity and ease of use as key motivating drivers. Currently the main tool is a report designer built on top of the Eclipse platform that generates XML based reports designs. These designs allow accessing many data sources which can be joined, cubed, or mined for data. This designer is easy to use, yet offers many advanced features, such as crosstabs, data cubes, and extensive charting capabilities.

    Additionally, BIRT supports an event model that allows report customization based on JavaScript or Java. Once reports are complete they can be deployed using the BIRT APIs or using the AJAX based Servlet Viewer. The reports can be rendered in HTML, paginated HTML, XLS, DOC, PPT, PS and PDF formats, all from the same design. The BIRT project had its first major release in the summer of 2005 and has garnered millions of downloads since its inception.

    combined these technologies in a way that takes advantage of Flash and Web based skill sets to produce some very impressive interactive applications (see Figure 1).

    What is BIRT?The Business Intelligence and Reporting Tools (BIRT) project is an open source project based on the

    Figure 2. Actuate BIRT Palette

    Figure 3. Actuate BIRT Flash Chart Editor

    Figure 4. Actuate BIRT Flash Chart Effects Editor

    Figure 5. Flash Chart Events

  • 08/2010 (16)16

    BUSINESS Visualizing your Data with BIRT and Flash

    08/2010 (16) 17

    To learn more about the BIRT project see http://www.eclipse.org/birt, which includes an introduction, tutorials, downloads and examples of using BIRT.

    The BIRT products are very extensible providing extension points that can be used to add to or modify the product without rebuilding any of the core source code. Actuate Corporation, the primary sponsor of the project, extends virtually every area of the open source tool to provide enhancements and features that are geared toward providing valuable business intelligence in the commercial arena. For example, Actuate provides an extended designer with new report components, an interactive viewer that allows customizing reports by end users on the fly, an AJAX based API to include report content in virtually any front end, improved emitters for XLS and PDF, and a set of highly scalable backend deployment infrastructures to meet throughput demands.

    This article discusses how the Actuate BIRT Designer, which is extended from the open source designer, has been improved to support Flash content.

    Extending BIRT to Provide Flash ContentAs stated earlier, BIRT provides many extension points to enhance the product. One set of extension points allows the creation of new report items that can be placed on the report canvas from within the designer. Actuate BIRT uses these extension points to provide three new Flash based components to the report palette (see Figure 2).

    Flash Chart Report ItemWhile BIRT provides a charting palette item, Actuate provides this additional chart component to allow certain chart types to be rendered in Flash. Using this component, a report developer can create very dynamic and aesthetically pleasing charts. Much like the existing

    Figure 6. Flash Chart Client Side Interactivity

    Figure 7. Actuate BIRT Flash Gadget Editor

    Figure 8. Flash Chart Data Bound Example

    Figure 9. Flash Object Library

  • 08/2010 (16)16

    BUSINESS Visualizing your Data with BIRT and Flash

    08/2010 (16) 17

    Chart report item, this report item retrieves its data from

    BIRT data sources and is constructed using the same three tabbed chart wizard from within the designer (see Figure 3).

    Currently this component supports Column, Bar, Line, Pie and Doughnut chart types. Each chart type also provides addition configurations to customize the chart, such as changing the dimensions to support 2D with depth, custom animation, beveling, blurring, glowing, shadowing and dynamic font manipulation (see Figure 4).

    Additionally the Flash Chart report item supports both client and server side event management. Server side event management is implemented using a set of event handlers that are triggered as the Flash chart is being generated. Currently the developer has fourteen events that can be hooked and used to modify the data and presentation of the chart (see Figure 5).

    Client side events can be hooked using the interactivity editor for the chart. Using this feature allows a developer to support custom drill through to details, custom script functions, and hyper-linking (see Figure 6).

    Flash Gadget Report ItemBIRT Flash Gadget report items are used to display data in a unique dynamic graphic. Currently Actuate BIRT supports thermometer, cylinder, bullet, spark line, meter

    Figure 10. Flash Object Gantt Example Design

    Figure 11. Flash Object Gantt Example Output

    Figure 12. Flash Object World Map Example Design

  • 08/2010 (16)18

    BUSINESS

    gauge or linear gauge gadgets. These gadgets are constructed in a similar fashion as Flash Charts. Actuates Flash Gadgets also support server and client side event management (see Listing 7).

    As with all the new Flash components, gadgets can be embedded in existing BIRT report items to display and interact with data retrieved from BIRT data sources. For example a BIRT table can use a Flash object to represent a column value (see Figure 8).

    Flash Object Report ItemThe Flash Object report item allows a developer to incorporate existing swf files into a BIRT report design. These objects can be retrieved from a URI, a predefined resource folder, embedded directly into the report, or from a supplied library of Flash objects. The location can also be dynamic, meaning the actual swf file or location can be changed based report parameters, data retrieved from a database, or based on an event script (see Figure 9).

    Any third-party Flash Object in the form of a .swf file can be used in a BIRT design. The Actuate BIRT Report Designer ships with a library of almost 400 .swf designs that can be used to further enhance the visualizations within your BIRT report. The concept of hooking up the data from the BIRT Data Source to the .swf file is an easy concept. Just create a hidden BIRT table that collects the data from a Data Set into a global variable and format it as needed by the .swf file requirements. This format is XML-based, and will be different for each specific .swf file. The global variable can then be referenced by the Flash Object in your design by setting the dataXML Flash variable to it. For example, using the supplied Gantt.swf file is as follows: see Figure 10.

    This example uses two hidden BIRT tables to collect the data for the Gantt flash object. One is used collect process data while the other is used to collect task data. The resulting report is presented Figure 11.

    As another example, a supplied world map flash object is tied to a BIRT table (see Figure 12).

    The output for this design is presented Figure 13.

    ConclusionWhile Flash components are only one part of the Actuate BIRT designer, they offer very significant enhancements to the whole product. Using these new components with the existing Actuate BIRT interactive Viewer allows a user to customize his or her view of critical business data in the form of dynamic dashboards, scorecards and reports that can be saved, shared and manipulated.

    If you want to know more about BIRT take a look at www.birt-exchange.org/org/new-to-birt/. You can download the Actuate BIRT designer here www.birt-exchange.com/be/downloads.

    DAN MELCHER Dan Melcher is a Sr. RIA Architect for Actuate Corporation. He has over 24 years of experience in the software industry in various roles including: project lead, web developer, senior programmer, technical sales, technical alliance manager and RIA architect. Dan joined Actuate in October 1999 and has been responsible for providing technical assistance in presales situations, technical certications and architecting applications. Prior to joining Actuate, Dan created diverse applications for companies including LTV Aerospace and Morningstar, Inc.

    JASON WEATHERSBYJason Weathersby is the BIRT Evangelist at Actuate Corporation and a member of the Eclipse Business Intelligence and Reporting Tools (BIRT) Project Management Committee (PMC). Jason has over 15 years experience in the software development eld, ranging from real time process control to business intelligence software. At Actuate, Jason is currently responsible for educating the Open Source community on BIRT and encouraging its adoption, and is responsible for managing the Eclipse BIRT newsgroup and website. Jason has co-authored two BIRT books and written many articles that discuss the BIRT technology. Figure 13. Flash Object World Map Example Output

  • 08/2010 (16)20

    GAMES

    08/2010 (16)

    The hope of this series of articles is to shine a light on many of the monetization methods to choose from by presenting hard facts based on case studies from a number of developers as well as statistics we have been tracking at FlashGameLicense.com and GamerSafe.com.

    Part 3: Micro-transactionsIm not going to go into much detail explaining micro-transactions since there is a ton of information about this elsewhere. Instead, I am going to focus on micro-transactions in the web games that Ive helped with. Mainly short form web games made by independent developers. In this niche, micro-transactions are relatively new.

    In brief, micro-transactions are small transactions that players make to buy something in a game. In reality, this term micro-transaction has come to cover a very broad spectrum. In almost every case what it actually means is a user pays for something in a game. Ive even seen the term used for sums of money in excess of $100 not very micro in my opinion, but this is still accepted as a proper use of the term by most. Also, many times, what the player is actually buying is another form of currency that they can then use to buy something in a game. This is what happens in GamerSafe. A user buys GamerGold that they can then spend in all the games in the GamerSafe network. I will go over the reasons for this in more detail a little later, but the point here is to show that micro-transaction is a very general term and I will be using it pretty loosely in this article.

    Currently there are two popular models for monetizing a web game with micro-transactions. One is distributing the game and monetizing users on thousands of sites, and the other is making the game stationary and growing a community around the game at a destination site. Both of these models can be used on a single game, of course, but I will split them up in order to describe the plusses and minuses of each.

    Before I split things up, though, I want to define some universal rules you need to follow to get the most out of your web game when monetizing using micro-transactions:

    Your monetization strategy should be intertwined with your game design strategy.

    Do not undervalue what you sell. Make sure to fully monetize your dedicated players.

    If at all possible there should be no limit to the amount a single player can spend in your game.

    Learn from your game.

    I want to note that I am being very strict when defining the universal rules. The reason for this is because of the first rule above. What you are selling, why you are selling it, and how much you are selling it for are going to vary wildly depending on your game. I could easily make this list much longer by including almost universal rules such as making your game more social and adding a component of competition, but in reality these things arent necessary though they have been proven to increase the amount of revenue a game makes in most cases.

    So, now armed with these core rules, lets take a look at how things are a little different between a distributed game and a stationary game.

    Micro-transactions in Distributed GamesThe biggest benefit to distributing a game that is monetizing through in game purchases is the extremely large audience the game will be exposed to. Great games will reach millions of players in weeks. Obviously, if a games conversion rate from player to payer is significant in any way this can be very lucrative.

    However, the main problem with this model is that the conversions, very often, are NOT significant. Most games see a conversion rate below 1%. So, if a game

    Monetizing Your Web Game

    Currently there are many choices when it comes to monetizing a web game. It can be daunting to decide which model is best for a developer. On top of this, there are conflicting reports as to which ones are truly lucrative.

    Part 3

  • 08/2010 (16)20

    GAMES

    08/2010 (16)

    gets 500,000 plays and converts 1% of the players, that would be 5,000 purchases. Now, this is where one of our universal rules comes in. In this scenario, setting a price point at $20 or $1 is a difference of $95,000. Of course, if what you are selling isnt worth $20 to the player then it hardly matters. I also want to stress the third universal rule here: we have found at GamerSafe that most users are willing to spend AT LEAST $20. So, if the player doesnt have the ability to spend $20 or more in your game then you are missing out on that additional revenue. However, I should note, in most cases players see more value in buying many things that add up as opposed to one item that costs $20. Our most popular buy in is $20, but many players also buy multiple $5 packages of GamerGold (usually totaling $20 or more).

    Another problem with this model is that game portals, which are the sole source of the massive traffic, have a very high turnover rate. This means your game will most likely have a very short lifespan of having high traffic since portals will eventually drop the game from their front pages and featured spots for new games. For great games traffic can still be significant for a time, and there is almost always a consistent flow of traffic for years, but not at the massive numbers of the initial release. If you have made a short form game a game with a relatively short play time and limited replay value this may work out fine. Some developers business models are based on making several games a year and earning the development costs back on the initial surge of traffic on release, and profiting on the long tail of the multiple games they release, creating a passive revenue stream over several games.

    Yet another issue with this business model is that the audience for these games who are used to games being completely free and monetized by ads (or nothing at all) are not yet fully accepting of the micro-transaction (freemium) model. The reason this is especially important is because a distributed web game will live or die by its ratings on sites and the feedback of the player communities on the web. If your game does not find a great balance between what is free and what is not, and how the free and paid content is presented your game will most likely be rated down and hidden on most sites. However, this trend against games charging for anything is a trend that is slowly changing. As more games monetize this way it becomes more acceptable to players. And this is not to say that there are not a ton of players that are already willing to pay, because it has been proven that there are an extremely large number of players who have already been willing to whip out their wallets. But it is a hurdle that currently exists and should be thought about and accounted for.

    Monetizing Your Web Game Part 3

  • 08/2010 (16)22

    GAMES

    Micro-transactions in Stationary Games Stationary games have the opposite problem of distributed games. Getting users to stick around and convert to paying customers is a bit easier. But building the customer base is much harder. The reason that converting players to payers is easier is due to many factors, but the main one is that players feel more comfortable spending money in a game that has a destination and a community. If a game is part of a site with forums and a place to interact with developers of the game (or anyone officially associated with the game) players are going to be much more likely to spend money. Especially when compared to players playing on a miscellaneous site where they are surrounded by a sea of games, none of which they know how to get a hold of anyone associated with the game if they have questions.

    This is a big reason why games on social networks have been so successful. Places like Facebook provide a slew of community features that are great for getting users more engaged in games. Another big reason that these social networks are such a good fit for games is they help in combating the issue of how to drive traffic to the game. The specifics of exactly how to best capitalize on this is outside the scope of this article, but it is an undeniable reality now that integrating with one or many social networks can be extremely lucrative if done right.

    After learning about these two models the astute reader will realize there is a great opportunity here. Why not utilize both models? The pros and cons of each complement the other quite nicely. In fact, this is exactly what should be done. It is not an easy task to balance the two models, for sure. Should the distributed version emphasize selling items, just like the stationary version? Or should it emphasize driving traffic to the stationary version? Should the distributed version be a light version, or the full version of the game? How will each of these decisions affect the amount of distribution you see? All of these questions, and many more, are ones you should think about and come to your own conclusions based on your game and your business model. In the end, though, there is no down side to both distributing your game (or a version of it) AND hosting it on a destination site. In fact, I would take this a step further and say that you should take this opportunity to achieve things that were not possible before. For example, we have tried several tests with games that use GamerSafe where we see how we can influence players. One test that we tried was with a game called Mechanical Commando 2 developed by Berzerk Studio. In this game users can earn or buy various things that they can equip to their character, a combat mech. One of the items we offer is a gun slightly more powerful than the guns

    you can earn by merely playing the game that you can only get if you play a different game (in this case, a spot the difference mini-game) to its end. Not only that, but you first have to install a Facebook app to play the mini-game. What we found is that 90% of the users who achieved the first Mechanical Commando 2 GamerSafe achievement went on to install the Facebook app and complete the mini-game. This was quite a shock to us. Conversion levels this high are unheard of. However, it does make some sense. Getting the first GamerSafe achievement signifies a level of engagement in the game. Once a user is engaged and presented with something they want it makes sense that they would take the effort to get it especially when it is free. This is where learning from your game is important. Trying out new things and tracking how users play and interact with your game will allow for innovations in the industry and hopefully lead to games being more fun for players and more lucrative for us developers.

    This article is merely an introduction to the world of micro-transactions in web games, and is not meant to be all encompassing or definitive. I invite all readers to visit our sites: FlashGameLicense.com and GamerSafe.com to find out more. GamerSafe is a game enhancing platform that can be used to, among many other things; monetize users through micro-transactions. I encourage you to check it out.

    As a final note I want to stress that the Micro-transaction model and all of the models that are covered in the articles in this series are not mutually exclusive of each other. Developers can, and should, take advantage of all of them. I am merely presenting them individually as to make them less confusing to understand. The final article in this series will cover the best ways to combine as many of these monetization models as possible to maximize the revenue generated by your game.

    CHRIS HUGHESChris Hughes FlashGameLicense.com

  • 08/2010 (16)24

    ACTIONSCRIPT IN ACTION Objects and Associative Arrays

    08/2010 (16) 25

    In this series, Ill be looking at a variety of topics related to ActionScript programming. In this article, I want to begin at the very beginning with the Object class, which is the root of the ActionScript class hierarchy from which all other classes descend. In many object oriented languages, the root class is very simple. Often, its only real purpose is to provide a mechanism for the construction of new objects. More specialized behaviour is added in its descendent classes.

    In fact, the Object class in ActionScript is a lot more complex than it may at first appear. Any objects created from the Object class may contain a (potentially quite large) collection of two-element items.

    The first element in each of these items is the key and the second element is a value. In ActionScript terminology, this data structure is known as an associative array. The key of each element in an associative array must always be a string but the value may be an object of any type. In other languages, similar data structures may be called Hashes or Dictionaries.

    Slightly confusingly, ActionScript 3 also has a Dictionary class which is a variant of an associative array that can use any type of object as a key rather than just strings. I wont be discussing the Dictionary class in this article and, to avoid confusion, I will generally use the term associative array when referring to the data structure of the Object class.

    How to Create an Associative ArrayAn associative array is, in a sense, similar to a standard array apart from the fact that the index of each element is given by its key rather than by its numerical position (see Figure 1). In fact, the elements of an associative array are not sequentially ordered and cannot be accessed by an index.

    The code below shows how to create both a normal (numerically indexed) array and an associative (keyed) array. For the sake of comparison, both the array and the associative array have been assigned three strings: "apples", "oranges" and "pears". The code accesses the string orange from each data structure and assigns it to a string variable:

    var anArray:Array = ["apples","oranges","pears"];

    var anAssociativeArray:Object = {crunchy:"apples",tangy:

    "oranges",juicy:"pears"};

    var s1:String = anArray[1];

    var s2:String = anAssociativeArray["tangy"];

    The result of the above is that s1 is assigned the value at index 1 from the array (in ActionScript, arrays are indexed from 0) and s2 is assigned the value associated with the key tangy from the associative array. In other words, both s1 and s2 are assigned the string, oranges.

    Notice that in the above example, I did not create either the Object or the Array by using the new

    Objects and Associative Arrays

    There is more to the ActionScript Object class than meets the eye. In the first of a new series, Huw Collingbourne looks at associative arrays

    What you will learn The internal structure of the Object Class How to create dynamic classes How to manipulate associative arrays

    What you should know The fundamentals of object orientation How to construct objects from classes The basics of the ActionScript class hierarchy

    Why an ActionScript Object is Like a Dictionary

  • 08/2010 (16)24

    ACTIONSCRIPT IN ACTION Objects and Associative Arrays

    08/2010 (16) 25

    Why is an Object so Complex?Associate array structures have many uses but why, you may wonder, would they be provided in the base class rather than in some specialized type of descendant class? That is something that puzzled me when I started working with ActionScript. In fact, it makes a bit more sense when you understand how the members (the methods, constants, variables and properties) of a class are implemented.

    It turns out that the names of the members are keys in an associative array. You are no doubt used to accessing properties using dot notation. For example, this is how you would access the x and y properties of a TextArea named ta:

    ta.x;

    ta.y;

    In fact, however, you can also access those properties using their names as keys, just as you would access the values of the associative array of an Object:

    ta["x"];

    ta["y"];

    In effect, the normal type of dot notation is just an alternative syntax to indexing into an associative array using a key. Once you understand that, the otherwise eccentric-sounding decision to make the

    keyword to call the classs constructor. Instead, I declared the variables and immediately assigned values to them. Objects (just like Arrays and Strings) may be created and initialized at the same time by assigning literal values. A string literal is a series of characters between quotes such as "abc". An array literal is a series of comma delimited values between square brackets such as ["a", "b", "c"]. An Object literal is a series of comma-delimited paired values (each pair divided by a colon) such as {"a":1, "b":2, "c":3}. String delimiters around the keys are optional; if omitted, the key will be treated as a string. The following code snippets show three ways of creating objects, each of which is initialized with an associative array containing two key-values pairs: the strings "a" and "b" are the keys, and the integers 1 and 2 are the values:

    var o : Object= new Object ();

    o["a"]=1;

    o["b"]=2;

    var o2 : Object={a:1, b:2};

    var o3 : Object={"a":1, "b":2};

    Object literals can only be used to initialize instances of the Object class but not of descendent classes. You cannot, for example, assign an object literal to a Dictionary:

    var d: Dictionary={"a":1, "b":2}; // This wont work!

    Figure 1. Key-Value PairsUsing the debugger of the Amethyst IDE we can look inside Arrays and Objects. You can see that the strings stored in the Array (shown in the Watch window at the bottom of the screen) are indexed numerically; for example, arr[1] indexes the string arr: two. The associative array in the Object (shown in the hovering debug tip) is indexed with a string key; for example, myOb[b] indexes the string myOb: two.

  • 08/2010 (16)26

    ACTIONSCRIPT IN ACTION

    Object class an associative array should make more sense.

    The descendent classes of Object all need to have various members (properties, variables etc.) and, in ActionScript, a class maintains a lookup list of those members in the form of key-value pairs: the key is the members name, the value is its data.

    Lets take an example. Lets assume that you have created this class:

    package

    {

    public dynamic class MyClass

    {

    public static const XXX:int = 100;

    public var greeting:String;

    public function MyClass()

    {

    greeting = "hello world";

    }

    }

    }

    Some piece of code that uses this class needs to access the static (that is, the class-level) constant, XXX. This may be done using either dot syntax or key-indexing in the following ways:

    MyClass.XXX; // dot-syntax access

    MyClass["XXX"]; // key-indexing

    Adding PropertiesYou can even create new properties for an object (or an array) using dot-syntax or square-bracket syntax:

    arr2["a"] = "arr2: one";

    arr2["b"] = "arr2: two";

    arr2.c = "arr2: three";

    You might think that, since all classes descend from Object, you should be able to create new properties for objects of all types. Not so! This wont work with most objects (try it with a Button, for example, and you will get nowhere).

    It turns out that most classes are sealed meaning that their properties and methods are limited to those that were available at compile-time and no more can be added subsequently. Object and Array are both dynamic classes, however, which means that new properties can be added. If you want to add more properties to an existing class you need to create a dynamic descendent by preceding the class definition with the keyword dynamic. You will see that

    the MyClass class was declared to be dynamic so I can add new properties for this, using the square-bracket or dot-notation syntax (but I cannot do so by assigning an object literal which is only available with instances of the Object class). The code below gives an example:

    public var myOb:MyClass = new MyClass();

    myOb["a"] = "one";

    myOb["b"] = "two";

    myOb.c = "three";

    In fact, I can even add properties to quite complex objects such as a Flex Button as long as I make it dynamic. I could, for example, create this MyButton class:

    public dynamic class MyButton extends Button

    {

    public function MyButton()

    {

    }

    }

    The following code works fine with the dynamic MyButton class:

    public var myBtn:MyButton = new MyButton();

    myBtn["a"] = "btn: one";

    myBtn["b"] = "btn: two";

    myBtn.c = "btn: three";

    However, if myBtn had been created as a regular (non-dynamic) Button, any attempts to add new properties would fail.

    Deleting PropertiesOne more piece needs to be fitted into this puzzle. Having created new properties, how can I delete them? Associative arrays, perhaps due to the fact that they exist at the base of the entire class hierarchy, are not very intelligent objects: they dont have a whole load of methods with which they can be manipulated.

    There is not, for example, a delete() method that lets you remove a specific key-value pair. Instead, ActionScript provides a brute-force way of doing this using the delete keyword.

    This is how to delete an item with the key (the property name) "b":

    delete myOb["b"];

    Note that you can also delete items from a specific index in a normal array in the same way:

  • Objects and Associative Arrays

    delete arr[1];

    When you delete an item in this way, the behaviour is different for an Array and an Object. With an Object, the element is destroyed so that the associative array will contain one fewer item. With an Array, the element is not destroyed, the array value is merely cleared at the specific index but the length of the array is not changed. This is because delete removes an object at a given position in the Array and replaces it with the special value undefined. So, for example, if the string "oranges" were at index 1 in an array of 3 items, when you execute the code delete arr[1] you would replace the string with the undefined value at the same index. However, the length of the array would still be 3. Note that the Array class has other ways of performing deletion the methods pop(), shift(), and splice(). When deleting Object items, however, the delete keyword is required.

    In summary, then, you can see that the ActionScript Object class is a bit like an Array and a bit like a Dictionary but is not quite the same as either. The relative complexity of the Object class has some benefits and some disadvantages. On the plus side, it is easy to create an object and assign values or in the form of key-value pairs in an associative array. Having created an associative array, it is easy to access its values using either dot notation or square-bracket indexing using a string key.

    HUW COLLINGBOURNEHuw Collingbourne is Director of Technology at SapphireSteel Software. For more than 20 years, he has programmed in languages ranging from Ruby to C# and has been a technical columnist for computer magazines such as PC Pro and PC Plus. He is the software lead of the Amethyst Designer, the Flex user interface design environment of the Amethyst IDE for Visual Studio. SapphireSteel Software: http://www.sapphiresteel.com/

    The main problem with the Object class is that, for something so complex, it is poorly supplied with methods for manipulating its own data structure. There are no built-in methods to return all the keys or all the values of an Objects associative array, for instance. There is no method to return the size of an associative array (that is, there is nothing comparable to the length property of a normal Array). Nor are there methods to test if a key or a value already exists. If you need methods of this sort, you will have to write them yourself. Ill explain how to do this in next months article.

    a d v e r t i s e m e n t

  • 08/2010 (16)28

    ACTIONSCRIPT DEVELOPMENT Loading external assets using the open-source BulkLoader class

    08/2010 (16) 29

    BulkLoader is very handy when it comes to loading lots of different elements. It allows one to track the individual loading progress of many items independently of each other. It also serves as a container for the loaded data.

    Of course, one could just use the built-in functionality to successfully load all the data, but that route can be very tricky (consider 20 images, 10 sounds, 5 XML documents and some SWFs). While working on complex projects, a clear and simple method to acquire all the assets and later use them becomes a necessity. The BulkLoader class provides a unified and convenient approach for this task. Additionally, it is absolutely free.

    BulkLoader can be used in many situations, having all the functionality to serve as a loader in any application. Countless scenarios abound: websites, dynamic image galleries, business apps, music and video players (together with playlists) or games. At the end of the article we're going to create simple XML driven slideshow.

    InstallationYou can download the library files from the project's site at code.google.com/p/bulk-loader/. Within the archive there is a src folder. Make sure to copy the contents to the directory of your Flash project. After that, we're ready to go further.

    Using BulkLoaderFirst of all, you have to import the library into your code. With the BulkLoader folder added to your project directory use the following instruction:

    import br.com.stimuli.loading.*;

    The next step is to create a BulkLoader object which will handle all loading operations:

    var loader : BulkLoader = new BulkLoader("loaderID");

    A parameter passed into the constructor will be the name of our loader. Later in the article you'll see when it becomes handy. There are other arguments you can pass to the constructor, but they're not that important. After the object is created, we can start adding assets to load. The BulkLoader add method takes care of that. Its general signature looks like this:

    public function add(url:*, props:Object = null):

    LoadingItem

    The first parameter here is the URL of the file we want to load. It can be passed as a String or URLRequest. The second one (props) is an object with key-value pairs inside it, defining how to load the asset. The following table shows possible properties.

    Loading External Assets

    Flash offers great built-in solutions for loading several types of external content into SWF applications. However, that doesn't help you much when it comes to loading numerous units of different kind of data at the same time. Thankfully, there are some third-party utilities that can take care of the job. In this article you will see how to make use of the open-source BulkLoader class.

    What you will learn BulkLoader class overview How to load different type of assets at the same time

    What you should know ActionScript 3.0 basics How to use events How to create simple preloaders

    Using the open-source BulkLoader Class

  • 08/2010 (16)28

    ACTIONSCRIPT DEVELOPMENT Loading external assets using the open-source BulkLoader class

    08/2010 (16) 29

    the main SWF loaded successfully by listening for loaderInfo's Event.COMPLETE event. Keep in mind that it is not for the main preloader but external assets only. So to keep things simple we're not showing the progress of the major SWF being loaded. Next, we're creating a Shape object to act as a preloader progress bar, constructing a BulkLoader instance, adding an image to it and attaching event listeners. The doneLoading and errorLoading methods behave the same as in the case of a basic preloader and both are a using pure Event class. The most important method, loadingProgress, differs a bit as it takes BulkProgressEvent as an argument instead of ProgressEvent. Besides that, everything is the same. There's not a lot to explain, but we can look deeper at the BulkProgressEvent class and what it does offer.

    BulkProgressEventAs you can see in the code ahead, handling progress events from BulkLoader looks exactly the same as with any other loading class. It holds bytesLoaded and bytesTotal properties which you already know. Nevertheless, there are some other BulkProgressEvent members you can take advantage of. To begin with, you should realize that using bytesLoaded/bytesTotal is not the best solution every time. BulkLoader maintains a limited number of connections while loading data (set via constructor or within a call to the start method). If the number of loading assets exceeds the available connections, the bytesTotal value is set to 0 until all components begin to load. But if you have 24 components and only 12 connections, then the first 12 elements will load simultaneously and the last 12 will have to wait for empty connections. The bytesTotal value will stay 0 before last element starts to

    There's no need to a pass second parameter as it's optional. However, doing so can be very practical. Here are few lines showing the use of add method:

    loader.add("12.jpg", { id : "miniature" });

    loader.add("getDesc.php", { id : "description", type :

    "xml" });

    loader.add(new URLRequest("my.jpg"), { id : "photo",

    maxTries : 10 });

    As you can see here, the convenient way to pass an object into the function is to type it as a literal. You may also have noticed that sometimes there is a type property present and sometimes not. BulkLoader has some nice abilities to recognize item types by extension. So, if you pass it an URL having xml at the end, it will assume you're requesting an XML document. Otherwise, if there isn't any way to determine file type, you should use the type property to remove any ambiguity.

    When we're done increasing the number of elements, it's time to add some event listeners. BulkLoader dispatches three main types of events: BulkLoader.COMPLETE, BulkLoader.PROGRESS and BulkLoader.ERROR. Their names are self-explanatory.

    loader.addEventListener(BulkLoader.COMPLETE,

    doneLoading);

    loader.addEventListener(BulkLoader.PROGRESS,

    loadingProgress);

    loader.addEventListener(BulkLoader.ERROR, errorLoading);

    The final step is to start BulkLoader by simply calling:

    loader.start();

    Now that we know how to get BulkLoader up and running, you'll agree it's time for some real examples. In the next section you'll also discover how to get loaded assets out of a BulkLoader instance.

    Creating a Simple PreloaderYou should be familiar with making basic preloaders with Flash. The good news for you is that with BulkLoader creating preloaders for external content is very similar. Loading many different components looks just the same as loading one thing with Flash's build-in Loader class. All you have to do is decide what to load and deal with events. The only difference is that you're retrieving more than one piece of content.

    Create a new Flash project, add the BulkLoader library to it, and start with the following document class (see Listing 1).

    Most of the code should be clear to you if you know the basics of ActionScript. First we're making sure that

    Table 1. Item properties used with add function

    Property Description

    id A string identier for the asset which later allows it to be acquired from BulkLoader.

    type A string specifying the type of added le. It can be one of these values: binary, image, movieclip, sound, text, xml and video.

    priority A number dening the loading priority. The higher the value, the higher the priority for an item.

    maxTries Max number of attempts when loading fails.

    weight The approximate size of the le in kilobytes.

    preventCache A boolean value specifying if there is a need to prevent the browser from caching the item. If set to true, BulkLoader will append the query string with some random text.

    headers An array of RequestHeader objects to use with request.

    context LoaderContext or SoundLoaderContext object for loading operation.

  • 08/2010 (16)30

    ACTIONSCRIPT DEVELOPMENT Loading external assets using the open-source BulkLoader class

    08/2010 (16) 31

    load (and that will happen only when some are finished loading). So, when bytesTotal gains actual value of total bytes, it may be after half of them already loaded. That's not the proper behavior for any preloader. We would like to see progress from the beginning (not from halfway)

    to the end. Generally, bytesTotal is satisfying when the number of elements don't exceed the sum of loader connections.

    BulkLoader offers three alternatives. First one is bytesTotalCurrent variable. It keeps the amount of

    Listing 1. Basic external assets preloader

    package

    {

    import flash.display.Sprite;

    import flash.display.Bitmap;

    import flash.display.Shape;

    import flash.events.Event;

    import br.com.stimuli.loading.*;

    public class SimplePreloader extends Sprite

    {

    private const BAR_WIDTH : int = 100;

    private const BAR_HEIGHT : int = 10;

    private var _loader : BulkLoader;

    private var _progressBar : Shape;

    public function SimplePreloader()

    {

    loaderInfo.addEventListener(Event.COMPLETE,

    initPreloader);

    }

    private function initPreloader(evt : Event)

    {

    _progressBar = new Shape();

    _progressBar.x = stage.stageWidth / 2

    BAR_WIDTH / 2;

    _progressBar.y = stage.stageHeight / 2

    BAR_HEIGHT / 2;

    addChild(_progressBar);

    _loader = new BulkLoader("preloader");

    _loader.add("assets/ffdmag_1.png", { id :

    "logo" });

    _loader.addEventListener(BulkLoader.COMPLET

    E, doneLoading);

    _loader.addEventListener(BulkLoader.PROGRES

    S, loadingProgress);

    _loader.addEventListener(BulkLoader.ERROR,

    errorLoading);

    _loader.start();

    }

    private function doneLoading(evt : Event) : void

    {

    }

    private function loadingProgress(evt :

    BulkProgressEvent) : void

    {

    var ratio : Number = evt.bytesLoaded /

    evt.bytesTotal;

    _progressBar.graphics.clear();

    _progressBar.graphics.beginFill(0x000000);

    _progressBar.graphics.drawRect(0, 0, ratio

    * BAR_WIDTH, BAR_HEIGHT);

    _progressBar.graphics.endFill();

    }

    private function errorLoading(evt : Event) :

    void

    {

    trace(evt.toString());

    }

    }

    }

    Listing 2. Getting bitmap out of BulkLoader

    removeChild(_progressBar);

    var bmp : Bitmap = _loader.getBitmap("logo");

    bmp.x = stage.stageWidth / 2 bmp.width / 2;

    bmp.y = stage.stageHeight / 2 bmp.height / 2;

    addChild(bmp);

  • 08/2010 (16)30

    ACTIONSCRIPT DEVELOPMENT Loading external assets using the open-source BulkLoader class

    08/2010 (16) 31

    bytes of elements which already started loading. Therefore, if you have 12 assets being loaded it will hold the size of those 12 assets. At the time loader reaches 4 more, bytesTotalCurrent value will be equal to the size of 16 assets, and so on. Thus, it changes over time. If you don't want to see your progress bar acting like the one from the old Internet Explorer's download window, consider another option. You can measure progress in terms of items instead of bytes. There are itemsLoaded and itemsTotal properties meaning already acquired assets and the total number of them. It's a less accurate approach but very reliable as the itemsTotal value is always known. It's good when loading many items of a similar size. The last method to track loading progress is to use the weightPercent value. As you maybe remember from the beginning of the article, when adding an element to BulkLoader, you may specify its weight property. If you do that, later you can use the weightPercent property to achieve a smooth looking progress bar omitting drawbacks from bytesTotal or bytesTotalCurrent. You should make use of it when you know the approximate size of your assets. weightPercent is a value in range from 0 to 1.

    Getting Assets out of BulkLoaderAfter preloading, what we have to describe is how to get an asset out of a loader instance. BulkLoader provides plenty of methods for that and the use of them is trivial. The most general one is called getContent and requires an asset id to pass it:

    loader.getContent("id");

    Instead of id, you can also use the URL of the component (the same you sent to the add method) or URLRequest object if you prefer. The function returns a reference to the loaded object which you can assign to anything. That's all. The important note is that getContent can return any type of object, so sometimes you may have to cast from it. To free yourself from that activity use several methods BulkLoader supplies for getting particular types of assets. Some examples of them are: getBitmap, getBitmapData, getSound, getXML, getMovieClip and so on. To see full list of them visit BulkLoader's project site.

    In the preloader's code listing, doneLoading method was empty. Now we can complete it with instructions which will show the loaded image on the screen. Here it is (see Listing 2).

    First we're removing the progress bar and then creating a Bitmap object based on the result of the getBitmap method. It's then positioned at the center of the stage and added to the display list.

    Adding More ItemsIf you need to enrich your application with new items to load, all you have to do is write some more add method calls. That's all there is to it. The rest of the code remains the same. After that, you can get them using getContent or other related methods.

    Getting a Loader Instance from the BulkLoader ClassMost of the time, when using BulkLoader you have direct access to its instance. However if you don't, it's still possible to refer to it by calling the BulkLoader getLoader static method. It requires a loader id (set when constructing it) as an argument and returns the BulkLoader object:

    var loader : BulkLoader = BulkLoader.getLoader("preloader");

    From then on you can use it as you normally would.

    Building a Preloaded SlideshowYou've just made it through the article to the point where we're going to create an image slideshow. It's main functions will include an XML image list which will

    Listing 3. Initializing slideshow preloader

    private function initPreloader(evt : Event)

    {

    var configLoader : URLLoader = new URLLoader(new

    URLRequest("config.xml"));

    configLoader.addEventListener(Event.COMPLETE,

    function(evt : Event) : void

    {

    _config = new XML(configLoader.data);

    // creating progress bar object

    // ...

    _loader = new BulkLoader("preloader");

    for(var i : int = 0; i < _config.image.length();

    i++)

    _loader.add(_config.image[i][email protected](), {

    id : "image" + i });

    // adding event listeners and starting

    // ...

    });

    }

  • 08/2010 (16)32

    ACTIONSCRIPT DEVELOPMENT

    08/2010 (16)

    be fully preloaded (all pictures will be loaded at start and none during watching). Remember, that's not an article about how to design photo slideshows, but only an example of BulkLoader use. Hence it's going to be extremely simple one.

    Frontend DesignThe user interface for a slideshow shouldn't be very complicated. It's all about the pictures. Let's just say we'll make the background black and leave it at that. There won't be any buttons or other stuff. When images are loaded, it will display them on the whole stage one by one. After the last picture shows up it will return back to the first one, so everything will stay looped.

    Create a new Flash project and set the size of the stage to something panoramic, say 800x480. Set the background color to black, and we can begin.

    Creating XML File with ImagesOur XML document has to store URLs of images to load and display. It will be as simple as possible, supplying no other information. Its basic structure looks look like this:

    There's a main node named slideshow and inside it we'll be placing image nodes containing URLs in the url attribute. Following is the file I made.

    Keeping to the structure you can add your own URLs. Save it as config.xml and put in your project's directory.

    Using BulkLoader to Load XML and all of the ImagesOur image slideshow document class will be based on that from the Creating simple preloader section. All we have to do is modify the initPreloader and doneLoading methods. Within the initPreloader procedure we have to load the configuration file and accordingly fill BulkLoader with items. The doneLoading function in turn should be able to initialize the slideshow mechanism. Here's the code for the first one (I've shown only new instructions and removed the rest of the code for simplicity) (see Listing 3).

    As you can see, there's the URLLoader object used to load the XML configuration. After it's been loaded, we assign a new XML object to the _config property, which is now a member of the document class. Next, the progress bar is created, and after that, we construct the BulkLoader, adding some elements based on the XML file. Finally, we attach event listeners. The ID of each item added to the loader's instance will be prefixed by an image phrase and followed by its index (number from 0, increasing).

    Displaying SlideshowNow that the BulkLoader is set up, we can go ahead to the doneLoading method. Here it is (see Listing 4).

    In this code we use two additional class members, _images and _imageIndex. The first one is the array to store references to all of the images and the latter is the index of pictures being currently displayed. Inside the for loop, we get items out of BulkLoader and add them to the array. There's also the resizeAndPosition function used to adjust the images to fit the stage. I'm not going to explain it in detail as it's beyond the scope of this article. You can look at its body in the sources attached to the magazine issue. After that, the first image from the list is added to the display list and the _imageIndex gains a value of 0. In the end we create a Timer instance which will be rotates all the images in 5 second intervals. Following is the timer's code (see Listing 5).

    Listing 4. Starting slideshow

    private function doneLoading(evt : Event) : void

    {

    // removing progress bar

    // ...

    _images = new Array();

    for(var i : int = 0; i < _config.image.length();

    i++)

    {

    _images.push(_loader.getBitmap("image" + i));

    resizeAndPosition(_images[i]);

    }

    addChild(_images[0]);

    _imageIndex = 0;

    _timer = new Timer(5000);

    _timer.addEventListener(TimerEvent.TIMER,

    changeImage);

    _timer.start();

    }

  • 08/2010 (16)32

    ACTIONSCRIPT DEVELOPMENT

    08/2010 (16)

    This removes the current image and displays the one after it. If _imageIndex exceeds a maximum value, it is assigned back to 0.

    That's all there is to the image slideshow. Besides what I mentioned here, I've also changed the preloader bar color to white and used BulkProgressEvent's itemsLoaded/itemsTotal instead of bytesLoaded/bytesTotal. You can test it and see how it works.

    How to Extend the Preceding ExampleAt this point the slideshow example is working, but it's very simple. If you would like, you can take your time to improve it with some more functionality. For example, one could add an XML attribute to the main node indicating a time interval to change the images. One could add some animated transitions between each of the pictures. You could also consider adding sound to each image, played when the image appears (it's not that complicated when using BulkLoader).

    SummaryThis article described most of the principles belonging to BulkLoader, but it's not the last word on the subject. I suggest you peruse the project's page at code.google.com/p/bulk-loader/. There you will find copious articles and documentation from which you can learn more about BulkLoader use.

    GRZEGORZ MIREKGrzegorz Mirek is currently studying IT at Jagiellonian University and freelancing in free time - mainly using Flash. Also he is interested in Java and C++. And he likes to write. To contact the author: [email protected]

    Listing 5. Rotating images

    private function changeImage(evt : TimerEvent) : void

    {

    removeChild(_images[_imageIndex]);

    _imageIndex++;

    if(_imageIndex >= _images.length) _imageIndex =

    0;

    addChild(_images[_imageIndex]);

    }

  • 08/2010 (16)34

    FLEX DEVELOPMENT Adobe Alchemy: a Comparative Example

    08/2010 (16) 35

    Today I'll go deeper and talk about Alchemy through a comparative example: Alchemy aimes to allow users to take advantage of efficient C/C++ (existing or not) designed to accomplish very cpu-intensive tasks. The performance improvements of flex applications can

    Adobe Alchemy

    Adobe Alchemy is an Adobe project that allows users to compile C and C++ code to be run on the Actionscript Virtual Machine (AVM2). With this possibility developers can take advantages of hundreds of powerful C and C++ libraries on the Flash Platform. These libraries will be compiled as a SWF or SWC files that run on Adobe Flash Player 10 (as well as Adobe AIR 1.5).

    What you will learn Implementing the Bubble sort algorithm Use the C++ Bubble sort algorithm Use the ActionScript Bubble sort algorithm Compare the two Bubble sort algorithms

    What you should know Getting started with Aclhemy (you can read this http://

    blog.comtaste.com/2010/04/alchemy_compiling_cc_code_into_1.html)

    a Comparative Example

    Listing 1. The Actionscript implementation

    01 public function bubbleSort(array:Array):void

    02 {

    03 var temp:int = 0;

    04 var alto:int = array.length;

    05 while(alto > 0)

    06 {

    07 for(var i:int = 0; i array[i+1])

    10 {

    11 temp = array[i];

    12 array[i] = array[i+1];

    13 array[i+1] = temp;

    14 }

    15 }

    16 alto--;

    17 }

    18

    }

    Listing 2. The C implementation view source

    01 void BubbleSort(int *array, int array_size)

    02 {

    03

    04 int i, tmp;

    05 int bound = array_size;

    06

    07 while (bound > 1)

    08 {

    09 for (i=0; i array[i+1])

    12 {

    13 tmp = array[i];

    14 array[i] = array[i+1];

    15 array[i+1] = tmp;

    16 }

    17 }

    18 bound--;

    19 }

    20 }

  • 08/2010 (16)34

    FLEX DEVELOPMENT Adobe Alchemy: a Comparative Example

    08/2010 (16) 35

    Listing 3. The translation of the Actionscript array to the C integer array data structure

    01 #include

    02 #include

    03

    04 //Header file for AS3 interop APIs

    05 //this is linked in by the compiler (when using flaccon)

    06 #include "AS3.h"

    07

    08 //INSERT HERE THE C IMPLEMENTATION OF THE BUBBLESORT

    ALGORITHM

    09

    10 static AS3_Val orderArray(void* self, AS3_Val args)

    11 {

    12 //Creating a C representation of the Actionscript

    Array object

    13 AS3_Val actionscript_array = NULL;

    14 AS3_ArrayValue( args, "AS3ValType", &actionscript_array );

    15

    16 /*

    17 * Translation process from Actionscript

    to C in 4 steps:

    18 */

    19 //STEP 1 : calculating the dimension of the

    Actionscript array

    20 AS3_Val actionscript_array_size = AS3_

    GetS(actionscript_array, "length");

    21 int array_size = AS3_IntValue(actionscript_array_size);

    22

    23 //STEP 2: declaring the C array to use with BubbleSort

    24 int array_c[array_size];

    25

    26 //STEP 3 : ActionScript function pop() of Array Class

    27 AS3_Val pop_function = AS3_GetS(actionscript_array, "pop");

    28 AS3_Val emptyParams = AS3_Array("");

    29

    30 //STEP 4(iterative): Extracting the actionscript

    integer values from the actionscript array

    31 //and storing them into the c array

    32 int i = 0;

    33 for(i = array_size-1; i >= 0 ; i--)

    34 {

    35 AS3_Val temp_actionscript_Int = AS3_Call(pop_

    function, actionscript_array, emptyParams);

    36 int tmp = AS3_IntValue(temp_actionscript_Int);

    37 array_c[i] = tmp;

    38 AS3_Release(temp_actionscript_Int);

    39 }

    40 AS3_Release(pop_function);

    41 /*

    42 * END of Translation process from actionscript to C

    43 */

    44

    45 /*

    46 * Ordering operations: invoking the Bubble

    Sort on the c array of integers

    47 */

    48 BubbleSort(array_c, array_size);

    49

    50 /*

    51 * Translation process from C to actionscript:

    52 */

    53

    54 //ActionScript function push() of Array Class

    55 AS3_Val push_function = AS3_GetS(actionscript_

    array, "push");

    56

    57 //Storing the ordered integer values into a new

    actionscript array object

    58 int j;

    59 for( j = 0; j < array_size ; j++)

    60 {

    61 AS3_Val int_to_push = AS3_Array("IntType",

    array_c[j]);

    62 AS3_Call(push_function, actionscript_array,

    int_to_push );

    63 AS3_Release(int_to_push);

    64 }

    65 AS3_Release(push_function);

    66

    67 return actionscript_array;

    68 /*

    69 * END of Translation process from C to actionscript

    70 */

    71 }

    72

    73 //entry point for code

    74 int main()

    75 {

    76 //define the methods exposed to ActionScript

    77 //typed as an ActionScript Function instance

    78 AS3_Val orderArrayMethod = AS3_Function( NULL, orderArray );

    79

    80 // construct an object that holds references to the functions

    81 AS3_Val result = AS3_Object( "orderArray:

    AS3ValType", orderArrayMethod );

    82

    83 // Release

    84 AS3_Release( orderArrayMethod );

    85

    86 // notify that we initialized -- THIS DOES NOT RETURN!

    87 AS3_LibInit( result );

    88

    89 // should never get here!

    90 return 0;

    91 }

  • 08/2010 (16)36

    FLEX DEVELOPMENT Adobe Alchemy: a Comparative Example

    08/2010 (16) 37

    Listing 4. The code of ex test application

    01

    02

    03

    04

    05 06 import mx.collections.ArrayCollection;

    07

    08 import cmodule.bubblesort.CLibInit;

    09

    10 private var startDate:Date;

    11 private var stopDate:Date;

    12

    13 private function init():void

    14 {

    15

    16 this.addEventListener("actionscriptS

    ortComplete",handler);

    17 this.addEventListener("cSortComplete

    ",handler);

    18 var intArray:Array = new Array();

    19 var intArray2:Array = new Array();

    20 for(var i:int = 20000; i > 0; i--)

    21 {

    22 intArray.push(i);

    23 intArray2.push(i);

    24 }

    25 list.dataProvider = intArray;

    26 list2.dataProvider = intArray2;

    27 }

    28

    29

    30 //INSERT HERE THE CODE OF THE ACTIONSCRIPT

    IMPLEMENTATION OF BUBBLESORT ALGORTHM

    31

    32 public function orderArray(event:Event):void

    33 {

    34 startDate = new Date;

    35

    36 if(event.target.id == "actionscriptO

    rderingButton" )

    37 {

    38 var source1:Array = (list.dataProvider

    as ArrayCollection).source;

    39 bubbleSort(source1);

    40 this.dispatchEvent(new Event("act

    ionscriptSortComplete"));

    41 }

    42 else

    43 {

    44 var loader:CLibInit = new CLibInit();

    45 var lib:Object = loader.init();

    46 var source2:Array = (list2.dataProvider

    as ArrayCollection).source;

    47 list2.dataProvider =

    lib.orderArray(source2);

    48 this.dispatchEvent(new

    Event("cSortComplete"));

    49 }

    50

    51

    52 }

    53

    54 public function handler(event:Event):void

    55 {

    56 stopDate = new Date();

    57 var diff:Number = stopDate.getTime()

    startDate.getTime();

    58 if(event.type == "actionscriptSortComplete")

    59 {

    60 timeLabel.text = "time elapsed :

    "+diff/1000+" sec!";

    61 (list.dataProvider as ArrayColle

    ction).refresh();

    62 }

    63 else

    64 {

    65 timeLabel2.text = "time elapsed

    :"+diff/1000+"sec!";

    66 (list2.dataProvider as ArrayColl

    ection).refresh();

    67 }

    68