Table of contents : Cover......Page 1 Contents......Page 6 Introduction......Page 20 Part I: Getting Started with AIR......Page 24 What Is the Adobe Integrated Runtime?......Page 26 Who Benefits from AIR?......Page 28 A Short History Lesson—From the Adobe Apollo Camp to AIR 1.5......Page 29 Workshop......Page 31 Safety Considerations for the AIR Runtime......Page 34 Differences for Your Operating System: Windows, Mac OS X, and Linux......Page 37 Installing the AIR Runtime......Page 39 Installing the AIR SDK......Page 41 Finishing the Job......Page 43 Workshop......Page 44 Using the Adobe AIR Debug Launcher......Page 48 Using the Adobe AIR Developer Tool......Page 50 Creating a Badge (Seamless) Installer......Page 54 Workshop......Page 59 How to Use Flex Builder 3 for AIR Development......Page 64 How to Use Flash CS3 Pro for AIR Development......Page 68 How to Use Dreamweaver CS3 for AIR Development......Page 71 Workshop......Page 73 Creating the Flex Project—Desktop AIR Application......Page 76 Meet the AIR Application Descriptor......Page 79 The Code, Test, and Repeat Process......Page 92 Packaging a Release Build......Page 106 Workshop......Page 109 Creating a Desktop AIR Application with HTML......Page 112 Accessing the AIR Classes with JavaScript......Page 121 A Few Cautionary Words About Security......Page 127 Workshop......Page 130 Choosing the Right IDE for the Job......Page 132 Creating a Desktop AIR Application with Flash CS3......Page 135 Creating a Desktop AIR Application with Dreamweaver CS3......Page 141 Workshop......Page 148 PDF Capability Detection in an AIR Application......Page 152 Loading PDF Content into an AIR Application......Page 154 Limitations for PDF Content in an AIR Application......Page 158 Workshop......Page 160 Using the Adobe Flex Builder Debugger......Page 162 Using the Adobe AIR Debug Launcher to Debug......Page 170 Using Third-Party Tools to Debug......Page 172 Using the Adobe AIR HTML Introspector......Page 174 Workshop......Page 177 Installing an AIR Application in a One-Off Approach......Page 180 Installing AIR Applications Seamlessly from a Web Page......Page 185 Digitally Signing and Creating an AIR Installation File......Page 190 Workshop......Page 197 Part II: Using the AIR APIs......Page 200 Creating Windows Using the NativeWindow Class......Page 202 Creating Windows Using the mx.core.Window Class......Page 206 Creating Custom Windows......Page 209 Workshop......Page 214 Introduction to Working with Screens......Page 218 Determining Screen Resolution......Page 223 Positioning Screens Programmatically......Page 225 Workshop......Page 229 Introduction to the AIR File API......Page 232 Meet the File Class......Page 235 Meet Some Other Class Members......Page 241 Working with Directories......Page 244 Reading and Writing Files......Page 247 Workshop......Page 250 Introduction to the Drag-and-Drop API......Page 254 Meet the Drag Event......Page 255 Meet the Drop Event......Page 262 Introduction to the Copy-and-Paste API......Page 265 Meet the Copy Event......Page 266 Meet the Paste Event......Page 268 Workshop......Page 271 Introduction to the NativeMenu Class......Page 276 Working with Application Menus......Page 278 Working with Window Menus......Page 281 Creating Dock Icon Menus......Page 283 Creating System Tray Icon Menus......Page 285 Creating Context Menus......Page 286 Creating Pop-up Menus......Page 287 Workshop......Page 288 Introduction to Connectivity......Page 292 Meet the HTTPStatusEvent Class......Page 293 Meet the NetStatusEvent Class......Page 295 Meet the Loader Class......Page 296 Meet the ServiceMonitor Class......Page 299 Meet the URLMonitor Class......Page 301 Workshop......Page 303 Introduction to Local Data Concepts......Page 306 Writing Data to the File System......Page 307 Meet the Local Shared Object......Page 308 Meet the Local SQL Database......Page 311 Workshop......Page 317 Storing Encrypted Data......Page 320 Timestamping Your AIR Code......Page 327 Signing with a Digital Certificate......Page 328 Workshop......Page 330 Creating Status Bar Notifications......Page 334 Creating Taskbar Highlighting......Page 337 Creating Toast Messages......Page 338 Creating a System Tray Icon......Page 342 Bouncing the Mac OS Dock Icon......Page 344 Workshop......Page 346 Part III: Developing AIR Applications......Page 350 Leveraging Remoting......Page 352 Leveraging Web Services......Page 355 Leveraging HTTP Communication......Page 356 Leveraging Messaging......Page 358 Workshop......Page 359 Deciding on an Application......Page 362 Architecting Your Application......Page 364 Coding Your Application......Page 366 Workshop......Page 384 Meet the Certificate Authorities......Page 386 Obtaining a Certificate......Page 387 Leveraging a Publisher Identifier......Page 391 Using a Timestamping Server......Page 392 Workshop......Page 393 Using the Updater Class......Page 396 Updating an AIR application......Page 399 Updating AIR Applications Remotely......Page 401 Workshop......Page 403 Using the AIR Documentation......Page 406 Meet the Adobe Developer Connection......Page 407 Meet the Adobe XML News Aggregator for AIR......Page 409 Meet the Adobe AIR Marketplace......Page 410 Workshop......Page 411 Part IV: Appendixes......Page 412 APPENDIX A: AIR and Flex 3 API Reference......Page 414 APPENDIX B: Additional Resources for AIR Developers......Page 416 A......Page 418 C......Page 420 E–F......Page 421 I......Page 423 O–P......Page 424 S......Page 425 U......Page 426 X–Z......Page 427
Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Adobe is a registered trademark of Adobe Systems, Inc. AIR is a trademark of Adobe Systems, Inc.
Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.
Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419 [email protected] For sales outside the United States, please contact International Sales [email protected]
Associate Publisher Greg Wiegand Acquisitions Editor Laura Norman Development Editor Todd Brakke Managing Editor Patrick Kanouse Senior Project Editor Tonya Simpson Copy Editor Heather Wilkins Indexer Ken Johnson Proofreader Dan Knott Technical Editor Alexander Tsoukias Publishing Coordinator Cindy Teeters Book Designer Gary Adair Composition Nonie Ratcliff
Part IV: Appendixes APPENDIX A: AIR and Flex 3 API Reference
395
APPENDIX B: Additional Resources for AIR Developers
397
Index
399
About the Author Michael Givens is the CTO of U Saw It Enterprises, a Web technology consulting firm based in Spring, Texas. He is an Adobe Community Expert and an Adobe Corporate Champion known to share his experience and evangelism of all things Adobe. Certified in both ColdFusion 5 and as an Advanced CFMX Developer, he has been using ColdFusion since the days of Allaire Spectra and Flex since it was known as Royale. He is the co-author of Adobe AIR Programming Unleashed (Sams Publishing) and has written articles for the ColdFusion Developer’s Journal and the Flex Developer’s Journal. He also wrote a digital Short Cut titled Apollo in Flight for Sams Publishing. Michael blogs regularly at www.flexination.info.
Dedication This book is dedicated to my sweet wife, Leny Dayrit Givens; Li Yi, a very special woman in my life; our wonderful, bright daughter, Han Ye Givens (Go Bears); my new family in the Philippines (Nicanor Dayrit, Leticia Rivera Dayrit, Chariza Dayrit, Allen Pangilinan, Michael Dayrit, Haidee Rivera, Rico Policarpio, and Rebecca Rivera); and my parents, Floyd and Nila. Thanks for all the encouragement and inspiration along the way.
Acknowledgments I’d like to offer special thanks to my father, Floyd, who always encouraged me to write. Even at a young age, it was too late to run from the example he set. Thanks to the best mom, Nila Jean, a son could ever hope to have. Send money now, Mom. To my brother, Pat, who sets a fine example in the way he lives his life. Thanks for that immigration help. Thanks to my new friend in the Philippines, Melanie Dela Peña, for her caring ways and the inspirational example she sets for her students. Thanks to the stranger I met in San Fernando for having the courage and taking the time to return my passport and other important documents. Thank you, thank you, thank you, sir. You are the living example of a good Samaritan. Thanks to my technical editor, Alexander Tsoukias, for the great attention to detail and the advice along the way. Special thanks to Laura Norman, with whom I have worked before and will again. I would also like to thank Todd Brakke for his advice along the way. Thanks to Heather Wilkins for her assistance in getting the writing refined and polished along the way. Thanks to Tonya Simpson and Patrick Kanouse for their guidance in getting the final waxing and polishing of this title completed on time. —Michael
We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book’s title and author as well as your name and phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book. E-mail: Mail:
[email protected] Greg Wiegand Associate Publisher Sams Publishing 800 East 96th Street Indianapolis, IN 46240 USA
Reader Services Visit our website and register this book at informit.com/register for convenient access to any updates, downloads, or errata that might be available for this book.
This page intentionally left blank
Introduction The Adobe Integrated Runtime (AIR) is a new product from Adobe, released in the spring of 2008. It allows web developers and web designers to use the skills they already have to build rich desktop applications. Revolutionary in many ways, AIR is a cross-operating system runtime that is light-weight yet powerful. Many naysayers might comment that AIR gives you a capability that is already covered in competing products (you can build desktop applications with other tools). But AIR excels in its easy-to-learn application programming interface (API) and in its capability to take existing web applications and add powerful desktop features that are either impossible to do from a browser or prone to browser differences, making them difficult to code. AIR applications, often called rich desktop applications, are springing up all over the Internet. Take a moment and use your favorite search engine to search “Adobe AIR applications”. As of this writing, more than 159,000 results come back with these search keywords (double-quoted) on Google. AIR applications can be written in Adobe Flex, Adobe Flash, HTML, in a combination of HTML/JavaScript, or AJAX—the same skills you use today. In the next 24 hours, after reading Sams Teach Yourself Adobe AIR Programming in 24 Hours, you can start building for the desktop today. It’s that easy. This book gives you the knowledge, from a professional developer’s perspective, of just how easy it is to program for AIR. From installing the AIR runtime to leveraging popular integrated development environments (IDEs), from creating your AIR applications to packaging and deploying them to end users, from debugging AIR applications to profiling them for improving performance, each hour presents you with new, important concepts, reinforced with a workshop, hands-on section at the end of each chapter. The first 10 hours of chapters introduce you to getting started with AIR, and include the following topics:
. In Hour 1, “Taking in a Deep Breath of AIR,” you’ll learn about the pieces that make up AIR, who benefits from AIR’s easy-to-grasp learning curve, a short history lesson about AIR, and just how big AIR is expected to be.
. In Hour 2, “Ready to Install AIR,” safety considerations for the AIR runtime are discussed, along with differences for your operating system (Windows, Mac OS X, and Linux), and how to install the AIR runtime on the different operating systems.
. In Hour 3, “Harnessing the AIR SDK,” you learn about the AIR software development kit (AIR SDK), including using the Adobe AIR Debug Launcher (ADL), using the Adobe AIR Developer Tool (ADT), and creating a badge (seamless) installer for AIR application deployment.
2
Sams Teach Yourself Adobe AIR Programming in 24 Hours
. In Hour 4, “Preparing to Build Your First AIR Application,” you learn about the Adobe suite of tools recommended for building AIR applications, including Flex Builder 3, Flash CS3 Professional, and Dreamweaver CS3, as well as a third-party IDE, Aptana Studio.
. In Hour 5, “Writing Your First AIR Application with Flex 3,” you see how to use Flex Builder 3 to build an AIR application. You will walk through building a Hello AIR World application, testing it, and packaging it for deployment.
. In Hour 6, “Writing an AIR Application with HTML,” you see how HTML and HTML/JavaScript or AJAX can be used to build AIR applications.
. In Hour 7, “Writing an AIR Application with Flash CS3 or Dreamweaver CS3,” you see how to use Flash CS3 Professional and Dreamweaver CS3 to build AIR applications, test them, and package them for deployment.
. In Hour 8, “Writing an AIR Application with PDF Integration,” you learn how to add PDFs to your AIR applications and how these integrated PDFs can be controlled within the AIR API.
. In Hour 9, “Debugging AIR Applications,” you learn about debugging your AIR applications, including debugging with the Flex Builder Debugger, the Flash Debugger, the AIR HTML Introspector, and even some third-party debugging tools.
. In Hour 10, “Distributing Your AIR Application,” you see additional information about packaging and distributing your AIR applications, including suggestions on where to distribute them. The next nine chapters introduce you to the AIR APIs and include the following topics:
. In Hour 11, “Opening Doors with AIR,” you discover how to open one or more windows for your AIR application’s user interface.
. In Hour 12, “Screening an AIR Application,” you learn how to control the screens and the screen real estate that your AIR applications utilize.
. In Hour 13, “File This API with AIR,” you get a first-hand look at the AIR File API and how you can interact with the files and folders on the end user’s file system.
. In Hour 14, “Drag and Drop, Copy and Paste in AIR,” you learn the capabilities of the AIR API related to drag and drop and copy and paste, two must-have capabilities for a professional desktop application.
. In Hour 15, “AIR and the Natives,” you see how to build native menus on Windows and the Mac OS.
Introduction
. In Hour 16, “Connectivity with AIR Networking,” you learn how to detect an end user’s connectivity to a network or the Internet and how to transition from a connected to a non-connected state in your AIR applications.
. In Hour 17, “Local Data in an AIR Application,” you discover how you can leverage a SQLite local database as an AIR application’s data repository.
. In Hour 18, “Encryption and Security in AIR,” you learn about AIR’s encryption and security features.
. In Hour 19, “AIR and User Notifications,” you see how AIR can access the operating system’s notification capabilities to build a full-featured desktop application. The final five chapters discuss some important development-related topics for many AIR applications as follows:
. In Hour 20, “Leveraging Server-Side Features for AIR,” you see examples of connecting an AIR desktop application to a server-side infrastructure.
. In Hour 21, “Building an AIR Application,” you see a step-by-step walkthrough of building an AIR application that can help you continue learning more about the AIR API.
. In Hour 22, “Signing AIR Applications,” you learn more about the digital code-signing of AIR applications.
. In Hour 23, “Updating AIR Applications After Deployment,” you discover strategies for updating AIR applications, including suggestions for dynamic updates using a form of pull technology.
. In Hour 24, “Where Do I Go from Here?” you read some suggestions on how to continue learning about and improving your understanding of AIR. Appendix A includes details about downloading an AIR Flex 3 API as an AIR application and how to re-create the most recent AIR Flex 3 API as an AIR application. Appendix B includes a compilation of useful AIR-related links to help you continue to learn and improve your AIR applications.
3
This page intentionally left blank
PART I
Getting Started with AIR HOUR 1
Taking in a Deep Breath of AIR
HOUR 2
Ready to Install AIR
15
HOUR 3
Harnessing the AIR SDK
29
HOUR 4
Preparing to Build Your First AIR Application
45
HOUR 5
Writing Your First AIR Application with Flex 3
57
HOUR 6
Writing an AIR Application with HTML
93
HOUR 7
Writing an AIR Application with Flash CS3 or Dreamweaver CS3
113
HOUR 8
Writing an AIR Application with PDF Integration
133
HOUR 9
Debugging AIR Applications
143
HOUR 10
Distributing Your AIR Application
7
161
This page intentionally left blank
CurrentH1
7
HOUR 1
Taking in a Deep Breath of AIR In this hour, you’ll learn . . . .
What the Adobe Integrated Runtime is Who benefits from AIR A short history lesson, from the Adobe Apollo Camp to AIR 1.5 Just how big AIR is going to be
What Is the Adobe Integrated Runtime? The Adobe Integrated Runtime (AIR) is a new offering from Adobe that allows the development of rich desktop applications (RDA), a term that is coined here but that is similar to the rich Internet application (RIA) that Macromedia and Adobe’s Flex have popularized.
RIAs are web applications that have the features and functionality resembling that of desktop applications. RIAs typically maintain all the necessary features for the user interface on the web client (for Adobe Flex–based RIA applications or Adobe Flash–based RIA applications, the web client is the Adobe Flash Player running inside the browser). However, they keep the bulk of the application’s data on the server-side’s application server.
By the Way
RDAs are AIR applications that have the features and functionality of desktop applications and, unless the developer specifically added server-side data transfer, all the features reside and operate exclusively on the user’s desktop.
The latest AIR 1.5 runtime was made available during the Adobe MAX conference, held in San Francisco the week of November 16, 2008.
By the Way
8
HOUR 1: Taking in a Deep Breath of AIR
AIR 1.0 was released on February 25, 2008 and is already extremely popular thanks to the comprehensive feature set included in the product. AIR, as defined by Adobe, is a runtime that allows a desktop application created by combining the existing web technologies you already know (Flex, AJAX, HTML/JavaScript, PDF, and others) to be an engaging, rich desktop experience. One of the major differentiators and compelling benefits of AIR from other competing products is the ease with which you are able to build a comprehensive and full-featured desktop application. Instead of spending all your time and energy learning the intricacies of developing for Windows and then developing for Mac OS X, you can take your existing web development skills and build an AIR application that can run on both operating systems within the first hour of your hands-on learning from this book. (AIR for Linux is currently available as an alpha version and allows AIR applications to be deployed on the Linux operating system.) Forget the learning curves of traditional desktop development tools because there’s a new kid on the block. Let’s get started. AIR 1.5 includes the application programming interfaces (APIs) for all of the important desktop features that you and your users have come to expect in a desktop application. These features include drag and drop, the clipboard’s copy and paste, network communication, local database connections and usage, file system interactions (crud), precise windowing (multiple windows) and window positioning (screen positioning), system tray access (Windows) or docking (Mac OS X), service monitoring, encryption capabilities, HTML and JavaScript features, and even digital signing for securing AIR application distributions. It is also easy to combine any existing web-based, server-side components with AIR applications to yield a powerful desktop application with full access to web-based application benefits. AIR 1.5 is available as an integrated part of Adobe Flex Builder 3 and separately as the AIR SDK. The AIR SDK provides you with the tools you need to package and distribute your AIR applications. AIR contains tools that can be simply run from the command line or that can be integrated with Flash CS3 Professional and Dreamweaver CS3. Keep in mind that no matter what tools and methodology you are currently using to build your web applications, you do not need to learn a new web technology to build AIR applications. Depending on your background, certain tools might make more sense to you and work best for your experience level. For HTML/AJAX developers, the Adobe AIR Dreamweaver extension might make the most sense, especially if you are already using Dreamweaver. If your background is Flash, the Adobe AIR update for Flash CS3 Professional would be a practical way to go. If Adobe Flex is your cup of tea, the benefits of Adobe Flex Builder 3 would be a great choice. Whatever your choice of tools, building an AIR application is so easy a fifth-grader can do it.
Who Benefits from AIR?
Who Benefits from AIR? The benefactors for the AIR runtime and AIR applications are both the developers and the end users. The developers have a powerful, full-featured runtime that is easy to program and develop against, leveraging the knowledge that they already have with a very small learning curve. Simply learn the AIR Framework’s APIs and build your applications in Flex, Flash, or HTML/JavaScript just like you do already. In a simplified example using Flex, you can literally replace a Flex-based Application tag with the corresponding AIR tag, WindowedApplication, and you have an AIR application.
Beginning in Hour 5, “Writing Your First AIR Application with Flex 3,” you will see that in most cases, porting your web-based application to an AIR desktop application involves more than this simplified example suggests. The point is that AIR developers are going to benefit from this rapid development environment because of its ease of use. The end users benefit by virtue of a stable runtime, a wide base of developers that can deliver features quickly by virtue of the easy-to-learn AIR APIs, an easy-toupdate distribution capability for AIR applications (via what is termed the seamless install), and version monitoring that can be added. Imagine a desktop application that you are using while waiting for a flight at the airport, where you are able to communicate through an AIR application to a backend database at your office (wirelessly via the airport’s hotspot). Suddenly you hear the announcement that it is time to board your flight. Do you need to worry about your data? No, not with this AIR application, because it was written to detect network connectivity and to seamlessly switch over to a local database repository installed on your laptop when network connectivity is lost. You board your flight, and until you have to close the laptop for the actual departure, you can continue to work on whatever you were doing. Are there complicated synchronization steps you need to perform when you get back to your office or regain wireless network connectivity? Again, no, as the AIR application detects that you are online again and the local database synchronizes with the server-based database. This might seem similar to some client-server applications from the late 1990s or early 2000s, but the big difference here is how easy this is to
9
10
HOUR 1: Taking in a Deep Breath of AIR
code and the simplicity in the synchronization of the data. Who benefits? Again, both the developer that builds this functionality and the end users that reap the hassle-free data integrity of this AIR application are the benefactors.
A Short History Lesson—From the Adobe Apollo Camp to AIR 1.5 AIR first became a blip on the radar during the spring of 2007 when its alpha release, code-named Apollo, was first introduced. The amount of interest in this alpha was high. On March 16, 2007, an unprecedented event was held at the Adobe San Francisco office on Townsend Street. The Adobe Apollo Camp, as it was called, was not only unique in its originality, but it was also free. I attended this event and received first-hand knowledge about what has now become AIR 1.5, a cool Apollo Camp T-shirt and Apollo sticker, a free copy of Adobe Flex Builder 2, and the first book on the alpha release of software ever sold to my recollection. The Apollo for Adobe Flex Developers Pocket Guide is still an interesting read because it explains the justification for today’s AIR. You can still buy copies of this title if you are interested, or download a free PDF version (http://download.macromedia.com/pub/labs/apollo/ documentation/apollo_for_flex_pocketguide_031907.pdf). For a bit more nostalgia, the Apollo Camp feeds are still available on the Adobe XML News Aggregator. Finally, while writing this chapter I came across a blog post I made from my hotel room, immediately after the Apollo Camp: “Apollo Camp was tons of fun, and the speakers provided some great presentations that got my wheels turning. I see great things associated with Apollo and Apollo’s File I/O and multi-windows capabilities. I took a prototype of a Flex 2 web application that I am working on and ported it to an Apollo desktop application in a matter of minutes.” Figure 1.1 shows this Apollo application. Apollo was a great name for this new offering from Adobe and developers liked it. The first iteration of the present O2Apps.com site, an early adopter of what would become AIR, was ApolloApps.net. This was a great site for those curious about Apollo. The successful [email protected] now had a new brother, the [email protected] mail list that is still operational today. The problem with the name Apollo was that the name could not be used for the final product, according to several Adobe employees whose names remain anonymous. Whatever the actual reason for changing the popular Apollo name to AIR, the Adobe Integrated Runtime (AIR) name was relayed to the rest of us at midnight on June 11, 2007. The Apollo alpha was pushed forward and reintroduced as the AIR beta.
A Short History Lesson—From the Adobe Apollo Camp to AIR 1.5
11
FIGURE 1.1 The Apollo Holdem application prototype.
One of the first things you would have noticed is all your Apollo applications would not run against the AIR runtime without tweaking the AIR Descriptor file a bit (the XML-based file that contains versioning, naming, copyright, and icon-related information inside it) and recompiling your Apollo, ahem, AIR, application. There were a few new APIs to explore, most notably, the SQLite local database capability and some new PDF-related capabilities. Increased HTML/AJAX developmental improvements came out about this time, too. The summer of 2007 is remembered by some as the cross-country on AIR Bus Tour (http://onair.adobe.com/schedule/na2007.php) that culminated at the Adobe MAX gathering in Chicago during the first week of October 2007.
It should be noted that the Apollo alpha installation file was compiled as an .air file, so it was not a complete surprise that AIR became the final product name.
The beta 2 of AIR was released on October 1, 2007 and beta 3 was released on December 12, 2007. The APIs continued to evolve and the XML-based application Descriptor file mutated in both betas, requiring some minor tweaks in Flex-based AIR applications. There were some fast changes taking place as the Adobe engineers were perfecting their new product, and AIR 1.0 was turned out on February 25, 2008. Not guilty of resting on their laurels, Adobe released the latest AIR 1.5 runtime during the Adobe MAX 2008 conference, held in San Francisco the week of November 16, 2008.
By the Way
12
HOUR 1: Taking in a Deep Breath of AIR
Just How Big Is AIR Going To Be? Adobe has released the 1.5 version of AIR to developers across the world, and the tools to build AIR applications are either free or almost free. The AIR SDK is free and all the tools necessary to build your AIR applications are a part of the SDK if you do not need the features that Flex Builder 3 offers. As mentioned earlier in this chapter, if you already own Flash CS3 Professional or Dreamweaver CS3, free extensions are available to assist you in AIR application packaging and distribution.
By the Way
As of this writing, Flex Builder 3 Professional is now free to all students, faculty, and staff of eligible education institutions (www.flexregistration.com/). For new purchasers, the cost is less than $700 (US). Upgrades from Flex Builder 2 are available at a substantial savings—less than $300 (US).
All of this—the ease of creating AIR applications, the power of those applications, and the amount of visibility for AIR from all the various camps and tours—leads one to believe that AIR is already immensely popular.
By the Way
As of this writing, the Air Europe 2008 Tour is well underway, with stops in selected cities through June 2008 (http://onair.adobe.com/schedule/).
Just how big will AIR become? The fact that you are reading this book and possibly others related to this topic shows your commitment to learning more about AIR and what it can do. The time and effort that you and others are taking to learn and use AIR in what you create leads me to believe that AIR will continue to grow and evolve with additional capabilities. You can easily see Adobe’s commitment to AIR and its Flex development platforms by taking a look at its corporate website. Not only does the home page immediately mention both AIR and Flex, but the Developers section under Communities covers both topics with a rabid fervor. AIR is going to be huge.
Workshop The workshop contains a Q&A section and an exercise to help reinforce what you’ve learned in this hour.
Workshop
Q&A Q. What does the acronym AIR stand for? A. AIR is the Adobe Integrated Runtime. Q. What was the alpha code name for AIR? A. Apollo was the alpha version of the Adobe Integrated Runtime. Q. What web technologies can you use to build an AIR application? A. Flex, AJAX, HTML/JavaScript, and PDF. Q. What is the AIR SDK comprised of? A. The AIR SDK includes the AIR Framework of APIs and the tools you need to package and distribute your AIR applications.
Q. Can you run any beta version of Apollo or AIR applications, as is, with the AIR
1.5 runtime? A. No. Because of the API changes between betas and the XML-based application Descriptor changes, previous versions of Apollo alpha or AIR betas will not run with the AIR 1.5 runtime.
Exercises 1. Download the AIR 1.5 release, the AIR SDK, and the trial version of Flex Builder 3 (if you do not already have it). Install Flex Builder 3. Do not install either the AIR 1.5 runtime or the AIR SDK, as you will do this in Hour 2, “Ready to Install AIR.” The downloads are available at
2. Download the AIR 1.5/Flex 3 API application from www.airination.info/ airtraining/airflex3api/AIRFlex3API_v1.air, but wait until the next hour to install it (requires the AIR 1.5 runtime).
13
This page intentionally left blank
CurrentH1
HOUR 2
Ready to Install AIR In this hour, you’ll learn . Safety considerations for the AIR runtime . Differences for your operating system . How to install the AIR runtime
Safety Considerations for the AIR Runtime The Adobe AIR runtime, as alluded to in Hour 1, “Taking in a Deep Breath of AIR,” is a cross-platform runtime that allows much tighter and more access to the desktop operating system than traditional web applications. This wider reach equates to a more intimate relationship with the operating system, so by inference, this increases security concerns. Just as in personal relationships that end up in the therapist’s office, trust can be broken quite easily, and your operating system can end up needing some of its own mending if a rogue AIR application takes advantage of the AIR runtime’s closeness to the desktop OS. An AIR application is no longer trapped in the browser environment. An AIR application is running in a security model the same as other desktop applications and not as a web application. With this said, will the end users of AIR applications accept this increased risk? It was a very important consideration Adobe engineers had to factor in during the development of AIR 1.5. As with any desktop application, there are risks when you install any commercial, freeware, or shareware applications. Some of the same mechanisms that have been added to commercial applications, such as code-signing and encryption, are also available in AIR applications. Hour 22, “Signing AIR Applications,” shows you that an AIR application cannot be packaged for distribution unless it has been signed (at the very least, self-signed).
15
16
HOUR 2: Ready to Install AIR
The AIR security model operates in what are called AIR sandboxes, of which there are only two.
. The application sandbox is the root level of an AIR application. The application sandbox has access to a higher level of privileges in the AIR APIs, but this higher level of access is granted only in a restricted manner. For example, only content loaded directly from the AIR application’s home directory (the app:/ URI scheme) can be placed in the application sandbox. Loading an image that is contained in the same root (or subroot) level of the AIR application is shown in the following code. The AIR application contains an icons subfolder and an AIRApp_128.png image. This image exists in the application sandbox as
described earlier. var sysTrayImageURL:String = ”app:/icons/AIRApp_128.png”;
. A non-application sandbox includes all other types of content that are not loaded directly into the application sandbox. Local and remote content are included in this case, and as such, both types of content behave just as they would in the web browser.
Do you feel safer? Maybe you are not quite safe, just yet. Another part of an AIR application is the installer and its warning dialog. Figure 2.1 depicts the warning dialog for a signed Adobe AIR application, and Figure 2.2 depicts the warning dialog for a signed but unknown AIR application publisher.
FIGURE 2.1 Adobe-signed AIR application installation dialog.
Just as when installing a commercial desktop application, the end user is in control of what gets installed and what does not. You probably would feel much better about installing the AIR application shown in Figure 2.1 versus that shown in Figure 2.2.
Safety Considerations for the AIR Runtime
17
In fact, they are the same AIR applications; the second one was simply recompiled locally without benefit of the Adobe code-signing certificate. This introduces a concept that you should understand—tampering with existing and well-recognized AIR applications is possible.
FIGURE 2.2 AIR application installation dialog for a signed but unknown publisher.
Are you nervous again? Fortunately, mechanisms are built in during the packaging or repackaging of an AIR application that would protect, in this case, Adobe’s reputation related to this application. There is that pesky (only to bad people) requirement that the AIR application must be signed during the packaging process. Because the tampering party does not normally have access to Adobe’s code-signing certificate, end users immediately see the installation dialog shown in Figure 2.2. This should be a red alert to the end user that something is amiss. Feel better now? Wait a minute. What if the tampering is done inside the Adobe office with full access to the code-signing certificate (perhaps by a disgruntled engineer)? Another defense system is in place that might help with this hypothetical situation—the timestamping that Adobe recommends for all commercial AIR applications. During the code-signing steps, a Timestamp checkbox is available, as shown in Figure 2.3. During the packaging of an AIR application, this timestamping feature adds a timestamp from a timestamp authority (Adobe selected GeoTrust) during the code-signing process. The timestamp on the pilfered or rogue AIR application would be different (or all together missing if the culprit had unchecked the timestamp feature).
18
HOUR 2: Ready to Install AIR
FIGURE 2.3 AIR application packaging and leveraging the timestamp feature.
By the Way
GeoTrust is part of VeriSign, a name with which you might be familiar. One of the services that GeoTrust offers is timestamping. How does it work? When you sign your Adobe AIR application and have it timestamped, an encrypted hash of the AIR code is sent to GeoTrust to be timestamped. As a result, when your AIR application is downloaded and an installation is started, end users are able to distinguish between a signed AIR application with an expired certificate (not trustworthy) and an AIR application signed with a certificate that was valid at the time the application was signed, but which has subsequently expired (trustworthy) .
Differences for Your Operating System: Windows, Mac OS X, and Linux This section briefly discusses minor or idiosyncratic differences between the two (or three, if you count the Linux alpha version) versions of the AIR runtime. Of course, each operating system has suggested minimum hardware requirements, shown here. For Windows, the suggested minimum configuration is
. Intel Pentium 1GHz or faster processor . Microsoft Windows 2000 (Service Pack 4), Windows XP (Service Pack 2), or Windows Vista (with the exception of Home Basic)
. 512MB of RAM For Mac OS X, the suggested minimum configuration is
. PowerPC G4 1GHz or faster processor, or Intel Core Duo 1.83GHz or faster processor
Differences for Your Operating System: Windows, Mac OS X, and Linux
19
. Mac OS X v10.4.910 or 10.5.1 (PowerPC), Mac OS X v10.4.9 or later, 10.5.1 (Intel) . 512MB of RAM For the alpha version for Linux, numerous release notes that include the hardware and software requirements are currently on the Adobe Labs website (http://labs. adobe.com/wiki/index.php/AIR_for_Linux:Release_Notes). As previously mentioned, there are other quirks where one operating system behaves differently from another. For example, AIR notifications, a valuable feature that allows close interaction with an operating system’s notifications (such as blinking a minimized application’s) delivers AIR system tray icons on a Windows OS, but dock icons on a Mac OS X. Figure 2.4 shows an example of an AIR application with a system tray icon on a Windows OS, and Figure 2.5 shows that same icon on the Mac OS X dock.
FIGURE 2.4 AIR system tray icon on the Windows OS. The AIR Icon
FIGURE 2.5 AIR dock icon on the Mac OS X.
The AIR Icon
Distinct methods in the AIR API allow you, the developer, to determine what OS the end user of your AIR application is running and then programmatically support that OS feature. To test for Windows OS, use NativeApplication.supportsSystemTrayIcon. To test for Mac OS X, use NativeApplication.supportsDockIcon.
Another example of the AIR runtime’s OS differences is in the AIR Menu API. The Windows OS includes a type of menu called a Window Menu, but the Mac OS X does not. The Mac OS X includes a type of menu called an Application Menu, but the Windows OS does not. The Linux alpha version of AIR, as of this writing, only shows the publisher as “Unknown,” so after the discussion in this chapter’s first section, you should probably install these AIR applications only from trusted sources.
By the Way
20
HOUR 2: Ready to Install AIR
There are surely other minor differences when running the AIR runtime on the different operating systems. One of the promises of AIR to developers was to finally obtain that evasive, land of nirvana, “write once, run everywhere” paradigm. Adobe worked extremely hard to minimize what a developer would need to do to distribute AIR applications to any end user, regardless of the OS. I believe it has achieved this goal with AIR 1.5. In the next section you will install AIR 1.5 and continue to learn more about AIR in detail.
Installing the AIR Runtime In the Exercises in last hour’s chapter, you should have downloaded the current installer for the AIR 1.5 runtime. The version number you downloaded might vary from the one described in Hour 1 if Adobe has released any revisions to the runtime since this book was released (a likely possibility). If you chose to skip the Exercise at the end of the previous chapter, please download the AIR runtime now (http://get. adobe.com/air/), saving it to your favorite download location on your PC or laptop.
Watch Out!
If you have any issues installing the AIR runtime on Windows or the Mac OS X, you may consult the TechNote on the Adobe website (http://kb.adobe.com/ selfservice/viewContent.do?externalId=kb403150&sliceId=2).
AIR Runtime Installation for Windows For Windows, install the AIR runtime as follows:
1. Double-click the AdobeAIRInstaller.exe file. If your operating system asks for your permission to continue running the AIR runtime application, you should allow it to continue.
2. The first screen of the installation dialog appears, revealing the license agreement. Click the I Agree button to continue.
3. The installation dialog changes to a progress bar that shows the installation process and rapidly moves to 100% complete.
4. The final dialog confirms that AIR is installed. Click the Finish button to exit the installer. You are now ready to write AIR applications.
Note that if you had a previous version of the AIR runtime already installed, especially AIR 1.0, the dialog screens mentioned here could be a bit different. When I
Installing the AIR Runtime
21
installed version 1.5 over my existing 1.0 installation, for example, the first dialog screen I was presented with noted my current version of the runtime and the new version of the runtime, and asked me if I wanted to update the runtime to the newer version (see Figure 2.6).
FIGURE 2.6 The AIR runtime installation upgrade dialog.
If for some reason you already have the latest version of the AIR runtime installed, the dialog tells you that you already have the current version installed.
AIR Runtime Installation for Mac OS X Installing the AIR Runtime on Mac OS X is a nearly identical process to the Windows installation. However, on Mac OS X, you’ll need to run the AdobeAIR.dmg file. If the installer presents an authenticate dialog box, enter your Mac OS X credentials to continue installing the AIR runtime application. From here, the installation proceeds just as it does when installing under the Windows OS.
AIR Runtime Installation for Linux For one of the Linux operating systems described on the Adobe Labs website, install the AIR runtime as follows:
1. Follow the instructions outlined on the Adobe Labs website at http:// labs.adobe.com/wiki/index.php/AIR_for_Linux:Release_Notes#Installing_ Adobe_AIR.
2. Review the known issues for the use of AIR on Linux at http://labs.adobe.com/ wiki/index.php/AIR_for_Linux:Release_Notes#Known_Issues_for_AIR_on_ Linux.
22
HOUR 2: Ready to Install AIR
Installing the AIR SDK Are you ready to write your first AIR application? Whoa! Not so fast. Remember that the Exercises in the first chapter had another download—the AIR SDK? If you did not download it yet, you should do so now: www.adobe.com/products/air/tools/sdk/.
AIR SDK Installation for Windows For Windows, install the AIR SDK by following these steps:
1. Double-click the AdobeAIRSDK.zip file and extract the entire archive to your folder of choice, paying careful attention to maintaining the folder structure. For this discussion, the archive was extracted to C:\Program Files\AIRSDK.
2. Open the Environment Variables setting for the Windows OS (if you need help in locating these settings, the most common location for these environment variables is found via the classic Control Panel, System, Advanced, Environment Variables).
3. Add the following path entry to the system variable: C:\Program Files\ AIRSDK\bin.
Watch Out!
Make sure you separate existing path entries and this new entry with a semicolon (for example, %SystemRoot%\system32;C:\Program Files\AIRSDK\bin).
4. To test the AIR SDK and the new path system variable, open a new command prompt, type adl, and press Enter. You should see a response similar to that shown in Figure 2.7: a message that says “application descriptor file not specified.”
FIGURE 2.7 The AIR SDK installed and path variable set properly.
AIR SDK Installation for Mac OS X For the Mac OS X, install the AIR SDK by following these steps:
1. Mount the AdobeAIRSDK.dmg file.
Installing the AIR SDK
2. Copy the contents of the SDK to your system. 3. Place the /bin directory into your system path so you can execute the command-line applications from anywhere on your system. On the Mac, you can add the path to the AIR SDK to your system path in a number of ways, depending on which shell you are using and how you specify user environment variables. The following instructions explain how to modify your path environment variable if you are using the bash shell:
a. Open the Terminal program (Applications, Utilities, Terminal). Make sure you’re in your home directory by typing cd and pressing Enter.
b. Check to see whether one of two files is present. Enter the command ls -la.
c. Look for a file named either .profile or .bashrc. d. If you have neither file, create the .profile file with the command touch .profile.
e. Open the .profile or .bashrc file with a text editor. f. Look for a line that looks similar to this: export PATH=$PATH:/usr/local/bin.
g. Add the path to the /bin directory to the end of this line. For example, if /bin is at /airsdk/bin, the export path should look something like this: export PATH=$PATH:/usr/local/bin;/ airsdk/bin. Make sure you separate the entries with a colon.
h. If the file is empty, add the following line: export PATH=$PATH:/ airsdk/bin.
i. Save and close the file and restart your Mac. (If you do not restart your Mac, the Terminal program will not recognize the changes.)
j. Run the command . .profile to load the new settings (or . .bashrc, if that is the file you edited).
k. Confirm that the new settings have taken effect by typing echo $PATH and pressing Enter. Make sure the /bin path is included in the output.
l. To test the installation, open a Terminal window and type adt. You should see the following (meaning the SDK is configured correctly): Too few arguments. Usage: adt -package air_file app_xml [ file_or_dir | -C dir file_or_dir ... ]
23
24
HOUR 2: Ready to Install AIR
AIR SDK Installation for Linux For Linux, install the AIR SDK by following these steps:
1. According to the documentation from the Adobe Labs website, the AIR SDK is available in .tbz2 format.
2. Issue the command tar -jxvf .
Note that because Linux development is an ever-evolving process, you should look for the most up-to-date information for the AIR SDK and the Linux OS at http://labs.adobe.com/downloads/air_linux.html for online versions of this book.
Watch Out!
There are known issues with the AIR Developer Tool (ADT) for the Linux alpha. The ADT does not work with GNU Java. Unfortunately, GNU Java comes as a standard with many Linux distributions. To make it work, add Sun Java to your path. You can use the command java -version in the terminal to figure out which version of Java is being used. The minimum required version of Sun’s Java/JRE is 1.4.2.
Components of the AIR SDK The AIR SDK includes the AIR Framework of APIs and the tools you need to package and distribute your AIR applications. Looking in the Runtime folder’s subfolders, you will find the AIR runtime, Adobe AIR.dll. The HTML engine, WebKit.dll, is also here. The bin folder has two important tools you will use in later chapters—the adl.exe and the adt.bat. The AIR Debug Launcher (ADL), adl.exe, is used to test
your AIR applications from a command prompt during development. The AIR Developer Tool (ADT), adt.bat, is used to package your AIR applications from a command prompt. A Samples folder contains a Badge folder with the basic tools for creating a badge or seamless installer for your AIR applications. All of these tools from the AIR SDK will be examined in subsequent chapters.
Finishing the Job Are we there yet? If you guessed no, you are correct because a few more steps are remaining from the first chapter’s Exercises. You should install Flex Builder 3 if you have not already installed it. The installation steps are outside the scope of this book, but there is plenty of help available on the Adobe website. You now need to download and install the AIR 1.5 and Flex 3 API documentation running in an AIR application.
Workshop
25
You might find this to be a handy application as you continue to explore the AIR APIs in the remainder of this book. If you have not already downloaded it, go get it here: www.airination.info/airtraining/airflex3api/AIRFlex3API_v1.air.
This is a large download because it contains the complete documentation set for the AIR 1.5 and Flex 3 APIs. The file size is approximately 41.9 MB, so maybe this is a good time to go get a fresh cup of coffee or other beverage of your choice.
After the download is complete, simply double-click on the .air file and install the AIR application. I used a self-signed certificate, so the publisher is listed as “Unknown.” Do you trust me? I hope you will trust this application because it really is a big help when looking up the AIR and Flex 3 APIs. You accomplished a lot in this hour and are poised to prepare to build your first AIR application. Before starting the next chapter, review what you have learned in the following workshop.
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. As the developer, how can you prevent the publisher from being flagged as
“Unknown” during the AIR installation? A. AIR applications must be signed by a publisher with a digital certificate recognized as a commercial certificate from a trusted Certificate Authority (CA); otherwise, the publisher is flagged as “Unknown” during the AIR installation dialog.
Q. What are some differences in the AIR runtime for Windows and the Mac OS X? A. AIR on Windows recognizes a type of menu called a Window Menu in the AIR API, and the Mac OS X does not. AIR on the Mac OS X recognizes the type of menu called an Application Menu, and the Windows OS does not. The AIR runtime understands that Windows contains a system tray icon, while the Mac OS X contains a dock icon.
Watch Out!
26
HOUR 2: Ready to Install AIR
Q. Although not specifically addressed in the text, how is the AIR runtime differ-
ent from the AIR SDK? A. The AIR SDK includes all the tools necessary to build an AIR application as well as the AIR runtime, whereas the AIR runtime is the framework of APIs that allows the cool AIR applications that you build to run on Windows, Mac OS X, and on Linux operating systems.
Q. What is the AIR SDK comprised of? A. The AIR SDK includes the AIR Framework of APIs and the tools you need to package and distribute your AIR applications. Looking in the Runtime folder’s subfolders, you will find the AIR runtime, Adobe AIR.dll. The HTML engine, WebKit.dll, is also here. The bin folder has two important tools you will use in
later chapters—the adl.exe and the adt.bat. The AIR Debug Launcher (ADL), adl.exe, is used to test your AIR applications from a command prompt during
development. The AIR Developer Tool (ADT), adt.bat, is used to package your AIR applications from a command prompt. A Samples folder contains a Badge folder with the basic tools for creating a badge or seamless installer for your AIR applications. All of these tools from the AIR SDK will be examined in subsequent chapters.
Quiz 1. In what ways were the safe packaging and distribution of AIR applications made a primary concern for Adobe’s engineers?
2. The current Linux alpha has a known safety concern. What is it? 3. If an AIR application is packaged with a self-signed certificate, what is shown as the publisher’s name during the AIR installation dialog?
4. What is the ADL used for? 5. What is the ADT used for?
Answers 1. AIR applications must be signed by the publisher before they can be distributed, and unknown publishers (those without a recognized CA certificate) are flagged as “Unknown” during the AIR installation dialog. This allows the end user to be better informed as to the source of an AIR application. Specifically, the publisher can be identified during the packaging of the AIR application, so
Workshop
an end user can decide if he trusts that publisher. AIR applications can also be timestamped during the code-signing process for an added level of safety. Additionally, AIR applications operate in sandboxes that help protect access to the AIR APIs that have the most power and privileges.
2. The Linux alpha version of AIR only shows the publisher as “Unknown,” so you should probably only install these AIR applications from trusted sources.
3. The publisher’s name is shown as “Unknown.” 4. The AIR Debug Launcher (ADL) is the adl.exe file located in the AIR SDK bin folder that allows the developer to test AIR applications from a command prompt.
5. The AIR Developer Tool (ADT) allows the developer to package an AIR application (including installing a certificate and timestamping) from a command prompt.
Exercises 1. Use the ADL to run the following AIR application: a. Save the following HTML-based code as hello_world.html in C:\testSite:
Hello World
Hello World
b. Save the following XML-based code as hello_world-app.xml in C:\testSite:
testSite 2008 Hello World from DW CS3 false Hello World
27
28
HOUR 2: Ready to Install AIR
testSite 3
hello_world.html 600 800 standard false true
01fig10.png
c. Open a command prompt and enter the following command: adl C:\testSite\hello_world-app.xml
Figure 2.8 shows this simple AIR application tested with the ADL.
FIGURE 2.8 The AIR application tested with the ADL.
CurrentH1
HOUR 3
Harnessing the AIR SDK In this hour, you’ll learn . How to use the Adobe AIR Debug Launcher . How to use the Adobe AIR Developer Tool . How to create a badge (seamless) installer
Using the Adobe AIR Debug Launcher The downloaded and installed Adobe AIR SDK allows you, the developer, to build and test your AIR applications with command prompt–style tools (Windows) or terminal window–style tools (Mac OS X and Linux). Whatever developer tools you currently use to build websites, by simply adding the AIR SDK and its tools, you have everything you need to build this new breed of rich desktop applications. The Adobe AIR Debug Launcher (ADL) allows you to test the AIR applications that you build as unobtrusively as possible. This is important because you can perform quick tests to see what your application looks like and how it performs without having to take the extra time and effort to package it, install it, and then find out whether it is behaving in some way contrary to your goals for it. It also saves you from having to uninstall it before correcting and testing the next set of development corrections or additions. Depending on its complexity, an AIR application might have many files that make up its functionality, but at a minimum there are always at least two files: a main application file and an application descriptor file. The main application file can be created in MXML (introduced by Macromedia during the creation of Flex) or even ActionScript 3 (AS3) if it is a Flex-based AIR application; it can be created in simple HTML and JavaScript or as an AJAX application (commonly, Dreamweaver CS3); it can be created in Flash CS3 Professional; in fact, it can be created with any text editor.
29
30
HOUR 3: Harnessing the AIR SDK
The application descriptor file is written in XML and can be created with any text editor of your choice. Without worrying about the specifics of the actual code in the main application file and the contents and structure of the application descriptor file (these topics are for another hour), an example should help make these concepts a bit clearer. Listing 3.1 shows a simple, Flex-based code sample for the main application file of an AIR application.
LISTING 3.1
Hello World Flex-based Adobe AIR Application
1: 2: 7:
8:
The second required file, the application descriptor, for this AIR application is shown in Listing 3.2.
LISTING 3.2
Hello World Flex-based Adobe AIR Application Descriptor
1: 2: 3: HelloWorld 4: 2008 5: Hello World from Flex 6: false 7: Hello World 8: com.sams.TYAIR24.HelloWorld 9: v1 10:
1. Download the zip archive from www.airination.info/airtraining/tyairin24/ HelloWorld.zip and extract it to a directory of your choice.
2. Open a command prompt or terminal window (depending on your OS) and change to the directory where you extracted the two files in the zip archive. In the example for this book, the location is C:\testSite, so a quick cd\ followed by a cd testSite is enough to get to the correct location.
Using the Adobe AIR Developer Tool
31
3. Type adl HelloWorld-app.xml and press Enter. You can see the command prompt of this in Figure 3.1. Figure 3.2 shows the resulting AIR application that the ADL tests.
FIGURE 3.1 The ADL from a Windows command prompt.
FIGURE 3.2 The AIR application run from the ADL and a Windows command prompt.
If your example application does not run from the ADL, please review Hour 2, “Ready to Install AIR,” and the section “Installing the AIR SDK,” about setting the environment variables path to include the location of your AIRSDK\bin folder (where the ADL tool resides).
After your AIR application is fully tested and you are satisfied with it, you are ready for the next step, packaging it for distribution. The Adobe AIR Developer Tool (ADT) is the perfect tool for speeding this along.
Using the Adobe AIR Developer Tool The next tool you examine from the AIR SDK tool belt is the Adobe AIR Developer Tool (ADT). The ADT allows you to package your AIR application for distribution. Packaging includes compiling, code-signing, optionally timestamping, and creating the .air file that the end user’s AIR runtime recognizes as an AIR application installer. Like the ADL, the ADT is run from a command prompt (Windows) or a terminal window (Mac OS X or Linux). You can examine the ADT internals by opening the adt.bat file (found in the \bin folder; for example, C:\Program Files\AIRSDK\bin). The content of the file is @java -jar “%~dp0\..\lib\adt.jar” %*
As you might have noticed, the ADT is a Java jar file (a collection of Java classes, many of which are security related). You don’t need to understand any of the inner
Did you Know?
32
HOUR 3: Harnessing the AIR SDK
workings of these classes to be able to use the ADT, so this is only mentioned as a point for the curious. Using the ADT is a bit more tedious than the ADL in that many optional parameters are available. Entering all the required parameters leaves you subject to typos in the command prompt (terminal window), so take care when entering the directives. To get an idea of the possible parameters, just remember the command in Listing 3.3, adt -help.
For the example application discussed in the ADL section, you will keep things as simple as possible for packaging the first AIR application. Try the following command (the -prepare statement creates an intermediate, unsigned airi package that will need to be signed later before distribution): adt -prepare HelloWorld.airi HelloWorld-app.xml HelloWorld.swf
The HelloWorld.airi file is created, as shown in Figure 3.3. You should note that trying to run an intermediate airi file does not install the AIR application. You must sign the intermediate airi file before you have a distributable AIR application installer. You might have noticed the -prepare parameter in the adt command in Listing 3.3. You can create an intermediate, unsigned package with the -prepare command. To create an actual package .air file, use -package. You must also add two additional parameters, -storetype and -keystore. Recall that a requirement to creating an .air file ready for distribution is that you must code-sign the AIR application with
either a Class 3 certificate or a self-signed certificate. This example uses a self-signed certificate.
Using the Adobe AIR Developer Tool
33
FIGURE 3.3 The HelloWorld. airi file
created.
To try this example out, follow these steps:
1. Download the zip archive from www.airination.info/airtraining/tyairin24/ HelloWorldplusCert.zip and extract it to a directory of your choice.
2. Open a command prompt or terminal window and change to the directory where you extracted the file. In the example for this book, the location is C:\testSite, so a quick cd/ followed by a cd testSite is enough to get to
the correct location.
3. Type the following command and press Enter: adt -package -storetype pkcs12 -keystore myCert.p12 -tsa none HelloWorld.air HelloWorld-app.xml HelloWorld.swf
You can see the command prompt of this in Figure 3.4, and Figure 3.5 shows the resulting .air installer file. Note that you will be challenged with the password created during the certificate creation (for this example, the self-signed certificate’s password is michelle).
FIGURE 3.4 The ADT from a Windows command prompt.
34
HOUR 3: Harnessing the AIR SDK
FIGURE 3.5 The .air file created with the ADT from a command prompt.
Watch Out!
One additional parameter, -tsa none, might be required if your development machine cannot access the GeoTrust timestamping service. This command tells the ADT to not timestamp the .air file.
4. You can install the resulting AIR application by double-clicking the HelloWorld.air file. You will see that the publisher is “Unknown” because the
myCert.p12 is a self-signed certificate created specifically for this example. Figure 3.6 shows the installation dialog.
FIGURE 3.6 The HelloWorld AIR application initial installer dialog.
5. Click the Install button to continue the installation of this HelloWorld AIR application. Figure 3.7 shows the next dialog screen that displays the application name, the description, choices about installation preferences (shortcut
Creating a Badge (Seamless) Installer
35
creation and whether to start the application after installation), and installation location.
FIGURE 3.7 The HelloWorld AIR application installation choices.
6. Click the Continue button to begin the installation. 7. The installation completes, and because the Start Application After Installation checkbox was checked, the AIR application starts automatically (if the checkbox was not checked, your end user will need to locate the shortcut for the AIR application and double-click it to start the application).
Many scenarios are possible when it comes to using the ADT to package your AIR application. For more information or more examples of using the ADT, please refer to the Adobe help documentation at http://livedocs.adobe.com/air/1/devappshtml/ help.html?content=CommandLineTools_3.html.
Creating a Badge (Seamless) Installer The badge, or seamless installer as some call it, allows you as the developer to deploy an AIR application from a website. A highly customized page can be created so your end user can easily obtain your fancy, new AIR application. In fact, with the badge installer, you can detect if the end user does not have the AIR runtime installed, transfer him to the AIR runtime installer first and then back to your AIR application installer, all seamlessly. A sample badge installer is in both the AIR SDK and the Flex 3 SDK (Flex Builder 3 also contains the sample badge installer files). Figure 3.8 shows the badge-related files contained in the AIR SDK.
36
HOUR 3: Harnessing the AIR SDK
FIGURE 3.8 The badge files in the AIR SDK.
The way the badge installer works is a bit more complex than first appearances indicate, but keeping things as simple as possible, you can copy the files (badge.swf, default_badge.html, and AC_RunActiveContent.js) provided in the Adobe AIR
SDK to your web server. Figure 3.9 shows these files added to a folder, tyairin24, on a web server (C:\inetpub\wwwroot\tyairin24 for this book).
FIGURE 3.9 The three badge files copied to your web server.
Creating a Badge (Seamless) Installer
37
To try this badge installer, follow these steps:
1. Download and extract the archive file, tyairin24_badge.zip, to your web server’s root directory, maintaining the tyairin24 folder structure. The archive is available at http://www.airination.info/airtraining/tyairin24/ tyairin24_badge.zip.
2. Open the page http://localhost/tyairin24/default_badge.html and click the badge installer’s Install Now button, as shown in Figure 3.10.
For an actual website deployment, you need to add a new mime type to your web server’s configuration, so it will know what an Adobe .air file is. According to Adobe, you should add the mime type application/vnd.adobe.air-installpackage associated with the .air extension. For the Apache HTTP Server, adding the following to your httpd conf file works well: AddType application/vnd.adobe.air-install-package .air.
By the Way
FIGURE 3.10 The badge installer on a website.
If you do not have the AIR runtime installed, you are automatically directed to the appropriate AIR runtime installer because an OS-detection feature is built into the badge installer. After the AIR runtime installation dialog is completed, the HelloWorld AIR application installer initiates.
Figure 3.11 shows the resulting badge installer dialog to begin the AIR installation.
3. The end user can click the Open button to immediately begin the AIR application installation, the Save button to simply save the .air file to their local PC (or Mac), or the Cancel button if they choose to not install the application.
By the Way
38
HOUR 3: Harnessing the AIR SDK
FIGURE 3.11 Open or save the .air file.
As mentioned earlier in this section, the badge installer can be modified extensively to provide a customized, seamless installation routine for your AIR application. Even the badge.fla file is included, so by using Flash CS3 you could modify the badge.swf file. You can also open the default_badge.html file with your code edi-
tor of choice and then look in the AC_FL_RunContent() JavaScript function shown in Listing 3.4.
Note the appurl parameter in Listing 3.4. It is http://localhost/tyairin24/ HelloWorld.air. If you simply list the AIR application name, HelloWorld.air, you get “Installation Error #2032.” This error is a stream error and means the .air file cannot be accessed from this relative location.
Adjust the flashvars parameters for the customization you desire based on Table 3.1.
Creating a Badge (Seamless) Installer
TABLE 3.1
39
flashvars Parameters You May Customize
Parameter
Description
appname
The name of the application, displayed by the SWF file when the runtime is not installed.
appurl (required)
The URL of the .air file to be downloaded. You must use an absolute, not relative, URL.
airversion (required)
For the 1.5 version of the runtime, set this to 1.5.
imageurl
The URL of the image (optional) to display in the badge.
buttoncolor
The color of the download button (specified as a hex value, such as FFCC00).
messagecolor
The color of the text message displayed below the button when the runtime is not installed (specified as a hex value, such as FFCC00).
The minimum size for the badge.swf is 217 pixels wide by 180 pixels high. You can adjust the values of the width and height parameters found in the AC_FL_RunContent() function to suit your user-interface requirements.
Watch Out!
Figure 3.12 shows a highly customized badge installer.
FIGURE 3.12 A highly customized badge installer on a website.
You covered a great deal of material in this hour. You saw three of the most important tools found in the AIR SDK: the Adobe AIR Debug Launcher, the tool to test your AIR applications during development; the AIR Developer Tool, the tool to package your .air file for distribution; and the badge or seamless installer that allows you to build a custom deployment strategy for your AIR applications. Before starting the next chapter, you should review what you have learned in the workshop.
40
HOUR 3: Harnessing the AIR SDK
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. What are the key features found in the AIR SDK? A. The AIR SDK contains a tool to test your AIR applications (the Adobe AIR Debug Launcher), to package your .air file for distribution (the AIR Developer Tool), and the badge or seamless installer samples to build a custom deployment strategy for your AIR applications.
Q. What makes the ADL so compelling for developers? A. The ADL allows the developer to test AIR applications without having to spend extra time packaging, installing, and un-installing an .air file during the development cycle. This speedy way of testing the work in progress is a useful capability that the ADL provides for free.
Q. What are the ways in which the ADT can be run, and what sets them apart? A. The most comprehensive command, the ADT -package command, can package and sign an AIR file in a single step. adt -package -storetype pkcs12 -keystore myCert.p12 air_file app_xml ➥[file_or_dir | -C dir file_or_dir | -e file dir ...] ...
The -prepare command can also create an intermediate, unsigned package. adt -prepare unsignedMyApp.airi unsignedMyApp-app.xml unsignedMyApp.html
The -sign command allows you to sign the intermediate package in a separate step. adt -sign -storetype pkcs12 -keystore myCert.p12 airi_file air_file
Q. What makes the badge or seamless installation so great? The badge or seamless installer provides the developer the means to enhance the end user experience by customizing an improved way to obtain an AIR application. It is one of the best ways to mass distribute an AIR application, as deployment from the badge installer’s web page can reach a world-wide audience in a much more effective manner than a “one-off” distribution through a CD-ROM or DVD, or even a simple website that forces the end user to download the .air file to her desktop before installation of the AIR application.
Workshop
Quiz 1. To package an AIR application from a terminal window on a Mac OS X, what tool from the AIR SDK should you use?
2. To test a development version of an AIR application from a command prompt on a Windows OS, what tool from the AIR SDK should you use to streamline the iterative develop-test process?
3. To create an intermediate .airi file, what ADT parameter would you use? 4. Can the badge or seamless installer detect the absence of the AIR runtime? 5. What advantages does a badge or seamless type of installer have over a simple “one-off” approach?
Answers 1. The AIR Developer Tool (ADT) is the tool that you use to package an AIR application in a terminal window (or command prompt).
2. The Adobe AIR Debug Launcher (ADL) is the tool that you use to test an AIR application in a streamlined manner from a command prompt (or terminal window).
3. To create an intermediate .airi file for an AIR application named myUnsignedApp, you would use the following command: adt -prepare myUnsignedApp.airi myUnsignedApp-app.xml myUnsignedApp
Afterward, you could sign the intermediate myUnsignedApp.airi file by using the following command: adt -sign -storetype pkcs12 -keystore myCert.p12 myUnsignedApp.airi ➥myUnsignedApp.air
4. Yes, the badge or seamless installer can detect the presence or absence of the AIR runtime and proceed to the logical next step. If the AIR runtime is missing, the end user is prompted to first install the runtime and then the AIR application; otherwise, the AIR application dialog prompts the end user through the installation steps.
5. One of the most important advantages of the badge or seamless installer is the capability to widely distribute an AIR application. Additionally, the improved experience that is possible by customization of the badge installer allows branding and personalization for a more professional end user installation experience.
41
42
HOUR 3: Harnessing the AIR SDK
Exercises 1. Use the ADT to create an intermediate .airi file for the AIR application shown below.
a. Save the following HTML-based code as hello_world.html in C:\testSite:
Hello World
Hello ➥World
b. Save the following XML-based code as hello_world-app.xml in C:\testSite:
testSite 2008 Hello World from DW CS3 false Hello World testSite 3
hello_world.html 600 800 standard false true
01fig10.png
c. Open a command prompt and enter the following command: adt -prepare hello_world.airi hello_world-app.xml hello_world.html ➥01fig10.png
Figure 3.13 shows the hello_world.airi file created with the -prepare parameter and the ADT.
Workshop
43
FIGURE 3.13 The .airi intermediate file created with the ADT.
2. Use the ADT to sign the intermediate .airi file you just created. Open a command prompt and enter the following command: adt -sign -storetype pkcs12 -keystore myCert.p12 -tsa none hello_world.airi ➥hello_world.air
Figure 3.14 shows the hello_world.airi file signed with the sign parameter and the ADT.
FIGURE 3.14 The .airi intermediate file signed with the ADT.
This page intentionally left blank
CurrentH1
45
HOUR 4
Preparing to Build Your First AIR Application In this hour, you’ll learn . How to use Flex Builder 3 for AIR development . How to use Flash CS3 Pro for AIR development . How to use Dreamweaver CS3 for AIR development
How to Use Flex Builder 3 for AIR Development Setting up Flex Builder 3 for AIR development is a simple matter because everything you need to develop AIR applications is included. Why would anyone want to use another development tool? One possible reason is that Flex Builder 3 might not be free and for smaller, cost-conscious firms, the relatively low upgrade cost might be too much.
If you are a student, a faculty member, or staff member of eligible education institutions, you might qualify for a free license for Flex Builder 3. Check for the requirements at www.flexregistration.com. Other considerations might make Flex Builder 3 a poor choice. If you are not planning to leverage Flex as your development language for your AIR applications, Flex Builder 3 is not the best choice for you. If you are a Flash developer, you should take a look at the Adobe AIR Update for Flash CS3 Professional. If you are a fan of Dreamweaver, give the Adobe AIR Extension for Dreamweaver a try. The next two sections in this hour discuss both of these alternatives to Flex Builder 3.
By the Way
46
HOUR 4: Preparing to Build Your First AIR Application
Okay, so you are still here and want to create your AIR applications with Flex-based code. Without a doubt, Flex Builder 3 is the de facto tool for quickly building Flexbased AIR applications. You should have already downloaded and installed the trial version of Flex Builder 3 (during the Exercises found at the end of Hour 1, “Taking a Deep Breath of AIR”). If not, do so now from www.adobe.com/cfusion/entitlement/ index.cfm?e=flex3email.
Did you Know?
Feel free to download and install the Eclipse plug-in version if you already have Eclipse installed. Otherwise, the stand-alone version works just as well. As mentioned in Hour 2, “Ready to Install AIR,” the installation steps are outside the scope of this book. The goal for this section is to familiarize you with the AIR-related parts of Flex Builder 3 and not how to install the tool. With Flex Builder 3 installed, fire it up and you see a main screen that looks like Figure 4.1. This screen is the Flex Start Page.
FIGURE 4.1 The Flex Start Page.
You can always get to this screen by looking under the Help menu and selecting Flex Start Page. The Flex Start Page is a great place to start learning more about building web-based, rich Internet applications, so you can spend some time here later if you like. In the meantime, take a look at the built-in AIR development features found in Flex Builder 3. With Flex Builder 3 you can perform all of the following:
. Create a Flex-based project for coding your AIR application using a wizard-style user interface (UI). Figure 4.2 shows the first step of this wizard-style UI. The rest of the steps are covered in Hour 5, “Writing Your First AIR Application with Flex 3.”
How to Use Flex Builder 3 for AIR Development
47
FIGURE 4.2 Step one of a new Flex project for building an AIR application.
. Automatically create the AIR application descriptor, an Extensible Markup Language (XML)–based file that contains metadata information about how the AIR application is handled. This file is automatically generated and named according to the following convention: the AIR main application filename (sans the .mxml extension) plus -app.xml (for example, HelloWorld-app.xml), as shown in Figure 4.3. AIR Application Descriptor
FIGURE 4.3 The AIR application XML-based descriptor filename.
48
HOUR 4: Preparing to Build Your First AIR Application
. Test your AIR application from the toolbar to ensure that you are satisfied with the functioning of your AIR application. Figure 4.4 shows this capability.
FIGURE 4.4 Testing an AIR application from a Flex Builder 3 menu.
.
Use the Debug toolbar button to debug your AIR applications from within Flex Builder 3. Hour 9, “Debugging AIR Applications,” covers debugging in detail.
.
Profile the performance of your AIR application by clicking the Profile toolbar button.
. Package your AIR application for distribution from a wizard-style tool. Hour 10, “Distributing Your AIR Application,” covers packaging and distribution in detail.
. Access abundant help within the Flex Builder 3 application. Figure 4.5 shows an example of searching for help for the topic, AIR.
FIGURE 4.5 Help for developing an AIR application from Flex Builder 3.
As you can see, if you are going to use Flex-based code to build your AIR applications, the price of the Flex Builder 3 integrated development environment (IDE) might well be worth the expense.
How to Use Flash CS3 Pro for AIR Development
49
How to Use Flash CS3 Pro for AIR Development If you are a Flash developer and would like to continue building AIR applications in the familiar Flash IDE, you might best be served by downloading and installing the Adobe AIR update for Flash CS3 Professional. Versions for Flash CS3 Professional for Windows and for Flash CS3 Professional for Macintosh are currently available. You can find either version at www.adobe.com/support/flash/downloads.html. Installing the AIR update for Flash CS3 Professional is not covered in this book. Please consult the Adobe website for information about the installation steps. As with the Flex Builder 3 discussion in the previous section, the purpose for this section is to discuss the AIR-related features that are enabled with this update. So what does this Flash update provide you? With the AIR update for Flash CS3 Professional you can perform all of the following:
. When you first start Flash CS3 Professional, you can now choose the Flash File (Adobe AIR) option (see Figure 4.6).
New Menu Option
FIGURE 4.6 The new Flash File (Adobe AIR) choice.
Figure 4.7 shows an introductory screen about authoring AIR applications with Flash CS3 Professional. It tells you where the AIR-specific menus are located, how to test and debug your AIR applications, and where you can find more help about authoring for an AIR application.
50
HOUR 4: Preparing to Build Your First AIR Application
FIGURE 4.7 Screen splash about authoring for Adobe AIR.
. Automatically create the AIR application descriptor, an Extensible Markup Language (XML)–based file that contains metadata information about how the AIR application is handled. This file is automatically generated and named according to the following convention: the AIR main application filename (sans the .mxml extension) plus -app.xml (for example, HelloWorld-app.xml), as shown in Listing 4.1.
10: HelloWorld.swf 11: standard 12: false 13: true 14:
15:
16: false 17: false 18:
. Two new menu choices are available from the Commands menu: AIR - Application and Installer Settings, which is used to make changes to the AIR application descriptor file via a graphical user interface [GUI] and AIR - Create AIR
How to Use Flash CS3 Pro for AIR Development
51
File, which is used to physically create the .air file for your AIR application. The use of these menu choices is discussed fully in Hour 7, “Writing an AIR Application with Flash CS3 or Dreamweaver CS3.”
. Access a new publish profile, Adobe AIR 1.5. This profile is found by selecting Publish Settings within the File menu, or by using the keyboard shortcut, Ctrl+Shift+F12, and then choosing the Flash tab, as depicted in Figure 4.8.
FIGURE 4.8 Adobe AIR 1.0 publish profile.
. Receive abundant help within the Flash CS3 Pro application. Figure 4.9 shows an example of searching for help for the topic, CS3 for Adobe AIR. As you can tell, if you are going to use the Flash IDE to build your AIR applications, the Adobe AIR update for CS3 Professional is an excellent tool for the job.
52
HOUR 4: Preparing to Build Your First AIR Application
FIGURE 4.9 Help for developing an AIR application from Flash CS3 Pro.
How to Use Dreamweaver CS3 for AIR Development If you are an HTML, JavaScript, or AJAX developer, the Adobe AIR extension for Dreamweaver CS3 allows you to develop, test, and package your AIR applications directly within Adobe Dreamweaver CS3. The Adobe AIR extension is an MXP file and you use the Adobe Extension Manager to install it. The MXP file is available at www.adobe.com/products/air/tools/ajax/. Installing the Adobe AIR extension for Dreamweaver CS3 is not covered in this book. Please consult the Adobe website for information if you have questions about the installation. You can access documentation for this extension at www.adobe.com/go/ learn_dw_air. As with the two previous sections, the purpose for this section is to discuss the AIRrelated features that are enabled with this extension. With the Adobe AIR extension for Dreamweaver CS3, you can perform all of the following:
. Automatically create the AIR application descriptor, an XML–based file that contains metadata information about how the AIR application is handled. This file is automatically generated and named according to the following
How to Use Dreamweaver CS3 for AIR Development
convention: the AIR main application filename (sans the .mxml extension) plus -app.xml (for example, hello_world-app.xml), as shown in Listing 4.2.
LISTING 4.2
The hello_world-app.xml Created by Dreamweaver CS3
1: 2: 3: testSite 4: 2008 5: Hello World from DW CS3 6: false 7: Hello World 8: testSite 9: 3 10:
. Access two new Site menu options, AIR Application Settings (used to make changes to the AIR application descriptor file via a GUI and Create AIR File (used to physically create the .air file for your AIR application).
.
Choose a new preview by clicking the Preview toolbar icon and selecting Preview in Adobe AIR. This allows you to test your AIR application from within Dreamweaver CS3.
. Access help within the Dreamweaver CS3 application. Figure 4.10 shows an example. As you have seen, if you plan to develop AIR applications with HTML and JavaScript or AJAX and are currently using Dreamweaver CS3, the Adobe AIR extension for Dreamweaver CS3 might just be a perfect match for you. Another busy hour and you saw three of the IDEs for leveraging your current skills to build AIR applications. Other choices are available in this arena, but with Flex Builder 3, Flash CS3 Pro, and Dreamweaver CS3, you will be using the tools that the creator of the AIR runtime, Adobe, built precisely for you to create AIR applications.
53
54
HOUR 4: Preparing to Build Your First AIR Application
FIGURE 4.10 Help for developing an AIR application with Dreamweaver CS3.
Did you Know?
Aptana Studio is an alternative to Dreamweaver CS3, available at www.aptana.com/ air.
Before starting the next chapter, you should review what you have learned in the following workshop.
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. Why would you select one IDE over the other? A. Depending on your experience level, one IDE might just fit your developer hand better. Flex Builder 3 is a likely IDE for Flex developers who want to build AIR applications; Flash CS3 Pro is the best choice for Flash developers who want to build AIR applications; Dreamweaver CS3 and Aptana Studio are two choices for HTML/JavaScript or AJAX-style AIR development.
Workshop
Q. Which IDE is ready to go out of the box (without needing any updates or
extensions)? A. Flex Builder 3 was designed from the ground up to be the de facto standard for building Flex-based AIR applications. Flash CS3 Pro requires an update and Dreamweaver CS3 requires an extension to be able to leverage AIR development features.
Q. Can I use the Flex Builder 3 Eclipse plug-in version to build AIR applications,
or do you need the Flex Builder 3 standalone version? A. You can build AIR applications with either version of the Flex Builder 3 software. There are no differences in the AIR development features (or any other Flex features for that matter) in either version.
Q. Can I name the application descriptor file differently? A. The AIR application descriptor created automatically by all three of the Adobe IDEs is named after the main application name (without any file extension) plus -app.xml (for example, for a main application named hello_world. html, the AIR application descriptor is named hello_world-app.xml).
Quiz 1. What does an AIR application descriptor file contain? 2. The Adobe AIR extension for Dreamweaver CS3 is used for what type of AIR applications?
3. How do you create the AIR application descriptor file? 4. What version of AIR are the three Adobe IDEs targeted for?
Answers 1. The AIR application descriptor contains metadata that describes the AIR application and includes such things as the application name, the description, copyright, application version, AIR runtime version, system chrome, window size and initial position, and in some cases application icon information. Listing 4.3 shows the application descriptor created by completing the Dreamweaver CS3 AIR Application Settings GUI.
55
56
HOUR 4: Preparing to Build Your First AIR Application
LISTING 4.3
The hello_world-app.xml Created by Dreamweaver CS3
1: 2: 3: testSite 4: 2008 5: Hello World from DW CS3 6: false 7: Hello World 8: testSite 9: 3 10:
2. The Adobe AIR extension for Dreamweaver CS3 is used to build HTML, HTML/JavaScript, or AJAX-based AIR applications.
3. You do need to create the AIR application descriptor file. All three of the Adobe IDEs automatically generate this file. You can certainly modify it with any text editor, but creating it from scratch is not necessary.
4. All three Adobe IDEs are targeted, as of this writing, at the AIR 1.5 runtime.
By the Way
The AIR runtime, as of this writing, is at version 1.5.
Exercises Take a look at Aptana Studio. You should explore what it offers because you might find that it is a better fit for you over what Dreamweaver CS3 offers. You can download it at www.aptana.com/studio.
CurrentH1
HOUR 5
Writing Your First AIR Application with Flex 3 In this hour, you’ll learn . . . .
How to create a Flex project About the AIR application descriptor The process of code, test, and repeat The steps for packaging a release build
Creating the Flex Project—Desktop AIR Application In Hour 4, “Preparing to Build Your First AIR Application,” you saw the built-in benefits of using Flex Builder 3. Flex Builder 3 should be installed, but if you missed that install, refer to Hour 4’s section, “How to use Flex Builder 3 for AIR development” for assistance. When you have Flex Builder 3 installed, you are ready to create a new Flex project, a desktop application that runs in Adobe AIR. Use the following steps to begin this process:
1. Start up Flex Builder 3 by navigating to the Adobe Flex Builder 3 shortcut and clicking (or double-clicking if necessary) the shortcut icon.
2. After Flex Builder 3 is started, select New, Flex Project from the File menu. This initiates the New Flex Project Wizard.
3. The first step of the New Flex Project Wizard is the Create a Flex Project screen. Enter a project name (you can enter TYAIRin24Hours to match the name used in this book), configure the project location (you can simply enable the Use Default Location checkbox), select the application type (in this case, you should select the Desktop Application [Runs in Adobe AIR] radio button), and
57
58
HOUR 5: Writing Your First AIR Application with Flex 3
choose the server technology (for this AIR application, you do not need a server technology, so simply leave the Application Server Type drop-down list to the default choice of None). All these selections are depicted in Figure 5.1. Click Next to continue.
FIGURE 5.1 The completed Create a Flex Project screen.
4. Complete the Configure Output screen by filling in the output folder (see Figure 5.2). Normally you can click the Browse button and navigate to any output folder of your choice, but for this chapter, you can simply leave the default value, bin-debug, as the entry. Click Next to continue.
FIGURE 5.2 The completed Configure Output screen.
5. Complete the wizard’s final step by filling in the main source folder (the default src folder works well), the main application file (in this case, you can
Creating the Flex Project—Desktop AIR Application
59
enter HelloWorld.mxml), and the application ID (enter info.airination. AIR.HelloWorld). Figure 5.3 shows this final step. Click the Finish button to
complete the wizard.
FIGURE 5.3 The completed final step for the Create a Flex Project wizard.
The application ID should uniquely identify your application. It is common practice to use the URL (in reverse) of the deployment site in the ID (for example, com.informit.AIR.HelloWorld).
You now see the default code for your HelloWorld.mxml as shown in Listing 5.1.
LISTING 5.1 Builder 3
The Default HelloWorld.mxml Created by Flex
1. 2. 3.
Figure 5.4 shows the default HelloWorld.mxml and the default HelloWorld-app.xml (the AIR application descriptor file) in the Flex Navigator. It also shows the default source code for the HelloWorld.mxml file. You have just created your first AIR application without writing a single line of code. No one will be too impressed with this new AIR application because it won’t do much at this point. Figure 5.5 shows a screen capture of the resulting default AIR application. As impressive as this all is, let’s continue on in your reading to learn how to create an AIR application that is a bit more... useful.
By the Way
60
HOUR 5: Writing Your First AIR Application with Flex 3
FIGURE 5.4 The default HelloWorld.mxml
and the default HelloWorldapp.xml.
FIGURE 5.5 A default AIR application.
Meet the AIR Application Descriptor The AIR application descriptor file is an XML-based file that contains metadata for an AIR application. Metadata might sound like a catch phrase for some minor or trivial kind of data, but at least for an AIR application, this metadata-containing file is not trivial at all. In fact, you cannot test or package an AIR application without this critical file. Taking a look at the AIR application descriptor file shown in Listing 5.2, you can see it contains quite a lot of information about an AIR application. Reviewing the comments inside this file is a worthwhile exercise, so you will see the contents described in detail following the code listing.
First you should note that this file is XML based, and as such, must be well-formed XML.
For more information about well-formed XML, consult http://www.w3.org/TR/ REC-xml/#sec-well-formed.
By the Way
If during editing you unintentionally break this valid XML, you will no longer be able to test or package your AIR application. Figure 5.6 shows the symptom you will see during testing the AIR application if the application descriptor is not well-formed XML. Figure 5.7 shows you the symptom you would see during packaging of the AIR application if the application descriptor is not well-formed XML.
FIGURE 5.6 Error symptom during testing with a broken HelloWorldapp.xml.
64
HOUR 5: Writing Your First AIR Application with Flex 3
FIGURE 5.7 Error symptom during packaging with a broken HelloWorldapp.xml.
Now, let’s examine each part of this descriptor file and what its purpose is.
Assigning the Basic Application Descriptor Information In Listing 5.2, line 2 of the descriptor file, the xmlns attribute identifies the version of the AIR runtime that the AIR application requires (currently 1.5). An optional attribute (referred to in line 9 of the code) is the minimumPatchLevel. This is the minimum patch level of the AIR runtime required to run the application. The xmlns attribute or the namespace does not change for patch releases because patch releases contain only a limited number of fixes and no API changes. In most situations AIR applications do not specify which patch release they require. However, if a fix in a patch release corrects an issue in an application, you can specify a value for the minimumPatchLevel attribute to ensure that patch is applied before the application is installed. The application id comes next, as shown line 12. This should be a unique identifier that allows the AIR runtime to easily distinguish between different AIR applications.
By the Way
The id string typically uses a dot-notation hierarchy, similar to a reversed DNS domain address. Keep in mind that the reversed notation (DNS-like form) is not enforced, and the AIR runtime does not actually test the match of the id and any actual DNS domain.
The next five application XML nodes are filename (line 14), name (line 16), version (line 18), description (line 20), and copyright (line 22).
. The filename node contains a string to use as the filename for the application (without the file extension) when the AIR application is installed. If the optional
Meet the AIR Application Descriptor
name node is left empty, the filename is also used as the name of the installa-
tion folder. The filename is required.
. The name node is optional but Adobe recommends that it be entered and becomes the name or title displayed by the AIR application installer. The AIR 1.1 runtime supports the name being configured in multiple languages (English, German, and Spanish, in the code shown here).
Hello AIR World Hallo Luft Welt Hola Mundo del AIR
. The version node specifies the version information for the application. (It has no correlation to the version of the runtime, and the runtime does not interpret the version string in any way.) The version string is still useful to the developer because you can read the version from the AIR application installed and compare it to a new version that you wish to roll out with code similar to the following: var appDescriptor:XML = ➥NativeApplication.nativeApplication.applicationDescriptor; var ns:Namespace = appDescriptor.namespace(); var appVersion:String = appDescriptor.ns::version; var updateVersion:String = “v2”; if (appVersion != updateVersion) { // add update code as AIR app should be upgraded } else { Alert.show(“AIR App is already version “ + appVersion, “Note”); }
. Although the description node is optional, it is displayed in the AIR application installer if it is completed. Just as with the name node, the description node for AIR 1.1 can contain multiple language elements.
This is an AIR application. Il s’agit d’une application AIR. Se trata de una aplicación AIR.
. The copyright node (optional) provides copyright information for the AIR application. On the Mac OS, the copyright text appears in the About dialog box for the installed AIR application. There does not seem to be a hook into the copyright information for the Windows OS, so although you may have the information in the copyright node, it is not found in the properties information of the installed AIR application for the AIR 1.1 runtime.
65
66
HOUR 5: Writing Your First AIR Application with Flex 3
Assigning the Properties of the Initial AIR Application Window The next set of settings control the AIR application’s initial window. These settings include
. content: The value specified for the content element, line 27, is the URL for the main content file of the AIR application. This may be either a Shockwave Flash File (SWF) file or an HTML file.
By the Way
A Flex-based AIR application results in a SWF file being generated with what is known as an HTML wrapper that points to the SWF. When running an AIR application with the ADL, the content URL is relative to the folder containing the application descriptor file.
. title: The optional title in line 29, shown in the main application window (see Figure 5.8).
FIGURE 5.8 The title tag used in the HelloWorldapp.xml and
resulting AIR application.
. systemChrome: The optional type of system chrome, line 31, uses standard or none. Figure 5.8 shows using the default standard system chrome. Figure 5.9
shows using the none setting.
FIGURE 5.9 The systemChrome
tag used in the HelloWorldapp.xml and
resulting AIR application.
. transparent: This setting (line 33) determines whether the window is transparent (it only affects an application window when the system Chrome is set to none). This node is optional.
Meet the AIR Application Descriptor
67
. visible: Determines whether the initial application window is visible, line 35. The default value is false, so this node is optional.
In case you are wondering why you might want an AIR application to be initially invisible, imagine a case where you wanted an application to launch but become visible only at a certain time of the day or at certain intervals of time. The visible setting makes this possible.
By the Way
. minimizable: Determines whether the window can be minimized (line 37). . maximizable: Determines whether the window can be maximized (line 39). . resizable: Determines whether the window can be resized (line 41). . width: Determines the initial width of the window (line 43). Figure 5.10 shows using 250 for the width setting.
FIGURE 5.10 The width (250) tag used in the HelloWorldapp.xml and
resulting AIR application.
. height: Determines the initial height of the window (line 45). Figure 5.11 shows using 250 for the height setting.
FIGURE 5.11 The height (250) tag used in the HelloWorldapp.xml and
resulting AIR application.
. x: Determines the x-coordinate for the window’s position (line 47). . y: Determines the y-coordinate for the window’s position (line 49).
68
HOUR 5: Writing Your First AIR Application with Flex 3
. minSize: Determines the minimum size to which a window can be resized (line 51).
. maxSize: Determines the maximum size to which a window can be resized (line 53). Lines 23 to 54 of Listing 5.2 show the complete XML nodes for the initial window section.
Assigning the Installation Folder and Program Menu Folder The next two settings, lines 56–58 in Listing 5.2, control the AIR application’s default installation folder and, for Windows, the Start, Programs menu to which the AIR application is added. Lines 60–65 is where you, the developer, can select the icons that are used for the shortcut or dock icon associated with the AIR application. You can supply four sizes for the icons (16×16, 32×32, 48×48, and 128×128). The supported image files are PNG, GIF, and JPEG.
Defining a Custom User Interface for Application Updates Defining a custom user interface in the descriptor file allows the developer to create and use a customized AIR user interface for updates in lieu of the default AIR installer handling the update. Line 68 of Listing 5.2 shows this node, customUpdateUI.
Toggling the Browser Invocation of the AIR Application Line 71 in Listing 5.2 toggles the badge or seamless installation capability on or off for the AIR application. A true setting allows the AIR application to be installed from a browser and a false setting prevents it.
Registering New File Type Associations for Your AIR Application Lines 73–92 in Listing 5.2, the final section of the AIR descriptor file, allows the AIR application to be registered with one or more applications of the developer’s choice. When an AIR application is installed, any declared file type is registered with the operating system and, if these file types are not already associated with another
Meet the AIR Application Descriptor
69
application, they are associated with the AIR application. This allows the developer to create a custom file extension of their own choosing to be associated with the AIR runtime. As the saying goes, a picture is worth a thousand words. In Figure 5.12, an AIR shortcut with the filename myTest.airmg has been registered as an AIR application. A custom icon (double-clicking starts the AIR application) has also been registered. This allows you, the developer, to create your own unique file extension (in this case, the new file extension is .airmg) and register it as an AIR application, so the AIR runtime is triggered anytime the application is run.
FIGURE 5.12 The myTest.airmg
AIR application.
You can see the details about the file and new custom file extension in Figure 5.13. The new file extension in the myTest.airmg file (.airmg) is registered in the application descriptor, so now any file with this new file extension will run as an AIR application. Looking at the properties of this file, you see the name and the type (My custom new AIR file type) are those found in the application descriptor, as well as the custom icon used for this file. Amazingly, the actual contents of the myTest.airmg file are very simple—a single line containing a single word, Howdy, makes up the entire content of the AIR application—and yet you have a viable AIR application. That’s it, you say? Yes, because the .airmg extension has been registered in the AIR descriptor as an AIR application. The file’s contents are immaterial—it simply fires up the HelloWorld application. The point is, because of the new extension being registered, the file’s content is immaterial because the AIR runtime simply triggers the AIR application, HelloWorld, no matter whether the contents of the registered file for the extension contains the word Howdy. The complete, modified HelloWorldapp.xml descriptor file is shown in Listing 5.3. The changes from the default applica-
tion descriptor are depicted in the boldfaced font (lines 21, 23, 30, 44, 46, 48, 51, 81, 83, 85, 87, and 93).
70
HOUR 5: Writing Your First AIR Application with Flex 3
The tag positions other Flex-based UI controls. The tag is the image placeholder for the animated images controlled in the ActionScript 3 code. An tag displays content in a horizontal layout. Finally, there are two buttons, the Play Again button and the Exit button. The click event for the Exit button runs the code, this.nativeWindow.close(), and this simply closes the main application window. Because it is the only window open, the AIR application exits, too. The final image is the smiling or frowning smiley, which is dependent on the availability of an Internet connection.
Did you Know?
If you come from a Flash background, you are probably aware of this scripting shortcut: toolTip=”{(blnPlayEnabled)?’Click to play the sound effects again...’:’Button is currently inactive...’}”. toolTip contains an inline conditional shortcut, and the logic follows like this: If the blnPlayEnabled is true, the string for the ToolTip follows the ’?’; if the blnPlayEnabled is false, the string for the ToolTip follows the ’:’.
Packaging a Release Build
To test this application from Flex Builder 3, simply press and hold the Ctrl key and press the F11 function key. Now that you have competed the walk through and this AIR application is fully tested and ready to distribute, the next section explains the steps you can perform to package a release build.
Packaging a Release Build Packaging a release build in Flex Builder 3 is quite easy because there is a built-in wizard for stepping through the process. The steps are as follows:
1. From the Flex Builder 3 menu, select Project, Export Release Build. 2. Complete the Export Release Build Wizard as shown in Figure 5.17. Click Next to continue.
87
88
HOUR 5: Writing Your First AIR Application with Flex 3
FIGURE 5.17 The completed Export Release Build step.
3. Complete the Digital Signature screen by selecting the first radio button, Export and Sign an AIR File with a Digital Certificate.
a. Browse to your certificate by clicking on the Browse button and selecting the certificate. If you do not have a digital certificate, you can create a self-signed one by clicking the Create button and completing the form shown in Figure 5.18.
FIGURE 5.18 The self-signed certificate form.
Packaging a Release Build
89
b. Enter the password for your certificate. You can enable the Remember Password for this Session and Timestamp checkboxes. Enabling these checkboxes ensures that your password will not have to be reentered while this session of Flex Builder 3 is running and that your AIR application’s digital signature will get a timestamp from GeoTrust, the organization that Adobe selected for timestamping services. Click Next to continue.
4. Complete the AIR File Contents screen by selecting the files that you want included in your AIR application package (see Figure 5.19). You will see that some of the files are marked as required and cannot be unchecked.
FIGURE 5.19 The completed AIR File Contents screen.
5. Click the Finish button. The HelloWorld.air file is created as shown in Figure 5.20.
FIGURE 5.20 The Flex Navigator showing the HelloWorld.air
file.
90
HOUR 5: Writing Your First AIR Application with Flex 3
In Hour 10, “Distributing Your AIR Application,” you will see how you can deploy your cool new AIR application. You have just completed a long and busy hour, but hopefully you saw firsthand how Flex Builder 3 gives you a powerful assist in building, testing, and deploying your Flex-based AIR applications. Before starting the next chapter, you should review what you have learned in the following workshop.
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. What are two of the types of Flex projects that you can build with Flex
Builder 3? A. Flex Builder 3 can build Flex-based web applications that run in the Flash Player and Flex-based desktop applications that run in the AIR runtime. During the first step of creating a new Flex project, you can select either a web application (runs in Flash Player) or a desktop application (runs in Adobe AIR).
Q. How important is the AIR application ID and how should you name it? A. The application ID should uniquely identify your application from all other AIR applications. It is common practice to use the URL (in reverse) of the deployment site in the ID (for example, com.informit.AIR.HelloWorld).
Q. What is the importance of the AIR application’s descriptor file? A. The AIR application descriptor file is an XML-based file that contains metadata for an AIR application. The capabilities contained within this metadata can enhance the AIR applications that you build and provide a richer desktop experience for your end users. You cannot test or package an AIR application without this critical file.
Workshop
Q. Can I name the AIR application descriptor file anything I like?. A. Attempting to rename this file, for example in Flex Builder 3, yields an error: “Adobe AIR application is missing the corresponding HelloWorld-app.xml.” The AIR application descriptor created automatically by all three of the Adobe IDEs is named after the main application name (without any file extension) plus -app.xml. For example, for a main application named hello_world.html, the AIR application descriptor is named hello_world-app.xml.
Quiz 1. What does an AIR application descriptor file contain? 2. The world’s smallest AIR application could contain how many lines of code? 3. Can you package an AIR application without supplying a digital certificate? 4. How do you monitor events in Flex-based (or Flash-based) code?
Answers 1. The AIR application descriptor file contains metadata that describes the AIR application and includes such things as the application name, the description, copyright, application version, AIR runtime version, system chrome, window size and initial position, and in some cases application icon information.
2. The default AIR application that Flex Builder 3 builds upon completing the New Flex Project Wizard contains four lines of code (one blank line) as shown in the following code:
3. Adobe is so concerned with safely deploying AIR applications that you cannot build an AIR package for distribution without adding a digital certificate to the generated .air file. You can test the packaging process with a self-signed certificate (that you create in Flex Builder 3), but Adobe does not recommend doing this for the final version you will distribute.
91
92
HOUR 5: Writing Your First AIR Application with Flex 3
4. You should add event listeners to the objects that you want to monitor. The addEventListener() function is a very important concept that you must
understand to code effectively in Flex (or Flash). /* add a timer event listener: Listens for a 12 second interval; onTimer2() function is called once after 12 seconds */ myTimer2.addEventListener(“timer”, onTimer2);
Exercises Take a look at the URLMonitor AIR class in the AIRFlex3API application. The URLMonitor class monitors availability of an HTTP- or HTTPS-based service. In fact,
the URLMonitor class could be leveraged to rebuild the HelloWorld AIR application to use it instead of the Flash-based NetStatusEvent class that was shown in this hour.
CurrentH1
93
HOUR 6
Writing an AIR Application with HTML In this hour, you’ll learn . Creating a desktop AIR application with HTML . Accessing the AIR classes with JavaScript . A few cautionary words about security
Creating a Desktop AIR Application with HTML In Hour 2, “Ready to Install AIR,” you saw the results of a simple HTML-based AIR application run from the AIR Debug Launcher (ADL) (refer to Figure 2.12). Figure 6.1 shows another simple AIR application loaded in Aptana Studio.
FIGURE 6.1 An HTML-based AIR application inside Aptana Studio.
94
HOUR 6: Writing an AIR Application with HTML
In this section you see how you can build, test, and package an HTML/JavaScriptbased AIR application leveraging Aptana Studio. If you have not already downloaded Aptana Studio during the Exercises at the end of Hour 4, “Preparing to Build Your First AIR Application,” do so now (www.aptana.com/air). Ensure that you have the Aptana Studio plug-in for Adobe AIR 1.0 (by the time this is published, you might see that the Aptana Studio plug-in is targeted to the AIR 1.5 runtime) application development installed (http://update.aptana.com/install/air/3.2/). Now follow these steps to build your HTML-based AIR application:
1. Open Aptana Studio and create a new project by opening the File menu and selecting New. This launches the New Project Wizard.
2. Select AIR Project from the Select a Wizard dialog, as shown in Figure 6.2. Click Next to continue.
FIGURE 6.2 Selecting the AIR Project from the Select a Wizard dialog.
3. Complete the Create an Adobe AIR Project screen by entering a project name (feel free to use the examples shown in Figure 6.3), configuring the location (you can simply check the Use Default Location checkbox), completing the main HTML file entry in the Application Options section, and selecting the Application and Non-application Sandbox radio button in the Included Sandbox Code Sample section. Use the default choices for the Jaxer Options section. Figure 6.3 shows a screen capture of this completed dialog. Click Next to continue.
4. Complete the Application XML Properties screen by filling in the ID, the name, the filename, the version, the description, the copyright, and the imported icons by browsing/selecting any of the image sizes that you want to include with your AIR application. Figure 6.4 shows the completed screen. Click Next to continue.
Creating a Desktop AIR Application with HTML
95
FIGURE 6.3 Completed Create an Adobe AIR Project screen.
FIGURE 6.4 Completed Application XML Properties screen.
96
By the Way
HOUR 6: Writing an AIR Application with HTML
The application ID should uniquely identify your application. It is common practice to use the URL (in reverse) of the deployment site in the ID (for example, com.adobe.example.HelloAIRWorldFromHTML).
5. Complete the fourth wizard step, also labeled Application XML Properties, by selecting the windows options, such as the window style, sizing options, and the dimension options of the main window (the default size and position). Figure 6.5 shows this fourth step. Click Next to continue.
FIGURE 6.5 Completed fourth wizard step.
6. Select any third-party JavaScript library of your choice from the Import JavaScript Library screen. Figure 6.6 shows that the Adobe Spry 1.6 library is selected. Click the Finish button to complete the wizard.
For more information about JavaScript libraries, take a look at the following URL: http://javascriptlibraries.com/.
You now see the default code for your HelloWorld.html as shown in Listing 6.1.
LISTING 6.1
The Default HelloWorld.html Created by Aptana Studio
Two security sandboxes sample
Application Sandbox Content
Has access to AIR APIs:
Use of eval() and other string-to-code techniques are ➥limited. — the following throws an exception:
Read more about these restrictions: ➥http://www.adobe.com/go/airhtmlsecurityfaq.
Can only load JavaScript files from the application resource ➥directory.
XMLHttpRequest object can reach into remote domains — the ➥following loads http://www.adobe.com:
Can expose functions to the non-application sandbox using the ➥sandbox bridge (the parentSandboxBridge property of the iframe window ➥object).
Can call functions from the non-application sandbox exposed via the ➥sandbox bridge (the childSandboxBridge property of the iframe window ➥object):
Read more about developing AIR Applications with HTML and Ajax: ➥ ➥http://www.adobe.com/go/learn_air_html.
Run the AIR application and press the F12 key. Examine the resulting application that is displayed (it is a nice UI to introspect the application), the Adobe AIR HTML/JS Application Introspector. You learn more about this topic in Hour 9, “Debugging AIR Applications.”
CurrentH1
HOUR 7
Writing an AIR Application with Flash CS3 or Dreamweaver CS3 In this hour, you’ll learn . The right IDE for the job . How to create a desktop AIR application with Flash CS3 or Dreamweaver CS3
Choosing the Right IDE for the Job In Hour 1, “Taking in a Deep Breath of AIR,” you might recall this statement: Depending on your background, certain tools might make more sense to you and work best for your experience level. For HTML/AJAX developers, the Adobe AIR Dreamweaver extension might make the most sense, especially if you are already using Dreamweaver. If your background is Flash, the Adobe AIR update for Flash CS3 Professional is a practical way to go. Although you could certainly build AIR applications with low-level (fewer features) text editors, test and debug from the AIR Debug Launcher (ADL), and package with the AIR Developer Tool (ADT), it might be speedier to select an integrated development environment (IDE) to handle the full cycle of AIR development. In other words, selecting the IDE or tool that fits your developer hand is important for a number of reasons (speedier development time, possibly a lower cost of the IDE, built-in help content, and so on). Part of that decision can be best determined by exploring as many IDEs as you are willing to give a try (for example, I had never tried Aptana Studio before writing this book, and now I use it quite a bit). Figure 7.1 shows the Dreamweaver CS3 IDE and the Preview in Adobe AIR menu choice. Figure 7.2 shows the Flash CS3 Professional IDE and the AIR - Create AIR File menu choice.
113
114
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
FIGURE 7.1 A peek inside the Dreamweaver CS3 IDE.
FIGURE 7.2 A peek inside the Flash CS3 Professional IDE.
Figure 7.3 shows an application open in a simple text editor, TextPad. Comparing it to the Dreamweaver CS3 IDE and the Flash CS3 Professional IDE, you see the tradeoff between simplicity and features. There are no AIR-related menus in TextPad at all, so you are on your own as far as testing, debugging, and packaging goes. You can, of course, use the ADL to test and
Choosing the Right IDE for the Job
115
debug. Note the trace statement has been added to the tag’s initialize property shown in the following code snippet.
FIGURE 7.3 A peek inside the TextPad IDE.
As you saw in Hour 6, “Writing an AIR Application with HTML,” Aptana Studio might be a great choice if you are not already hooked on Dreamweaver CS3 and if you plan to write most of your AIR applications with HTML and JavaScript. Figure 7.4 shows the Aptana Studio IDE with the Export Adobe AIR Package wizard selected.
FIGURE 7.4 A peek inside the Aptana Studio IDE.
116
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
As time progresses, more IDEs will support AIR applications, so you should keep a watchful eye open for any new front runners as you read this hour. In fact, the Exercises for this hour contain a suggestion to search for “Adobe AIR IDEs.” Select the tool that fits your developer hand best and you will have the best coding advantage at your disposal—an IDE that fits you perfectly and that you like and trust to rapidly build the AIR applications that you dream up. If you come from a Flash background, however, the next section in this hour is for you.
Creating a Desktop AIR Application with Flash CS3 As shown in Hour 4, “Preparing to Build Your First AIR Application,” Flash CS3 Professional provides an excellent IDE for building AIR applications if you are already a Flash developer. All that is needed is the Adobe AIR update for Flash CS3 Professional, an update that you probably already have downloaded and installed from www.adobe.com/support/flash/downloads.html. If not, do so now. Follow these steps to build the Hello AIR World Flash-based AIR application:
1. Start Flash CS3 Professional. 2. From the Create New section in the middle of the splash screen shown after the Flash IDE is started, click on the Flash File (Adobe AIR) choice as shown in Figure 7.5.
By the Way
If your splash screen is not displayed, you can turn it back on by choosing Show Welcome Screen from the General category in the Preferences dialog. You need to restart the Flash IDE after changing the On Launch setting to Welcome Screen. 3. Click OK to clear the About Authoring for Adobe AIR message. 4. Select the Text tool from the Tools palette. 5. Drag the Text tool across the Flash stage and create a text placeholder, of Static Text type, about 300 pixels in width. Type Hello AIR World from Flash in a red, Verdana, 12pt font. Figure 7.6 shows a screen capture of this.
6. Save your Flash file as HelloWorld.fla to a location of your choice. 7. You can test your Flash file by selecting Test Movie from the Control menu.
Creating a Desktop AIR Application with Flash CS3
117
FIGURE 7.5 Selecting the Flash File (Adobe AIR) choice.
The Text Tool
FIGURE 7.6 Hello AIR World from Flash text.
Possibly without realizing it, you have already created a new Flash-based AIR application. The Flash CS3 Professional IDE with the Adobe AIR update for Flash CS3 Professional automatically creates the two files required for an AIR
118
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
application (the main application, a Shockwave Flash file [SWF], and the application descriptor) just by virtue of testing the movie noted in step 7.
8. Adjust the AIR application descriptor by selecting AIR - Application and Installer Settings from the Command menu. You can modify all the Application settings, such as filename, name, ID, description, copyright, and window style, as shown in Figure 7.7.
FIGURE 7.7 Modifying the Application settings.
Additionally, you can modify the icon by clicking the Select Icon Images button and selecting one or more of the icons you want to use for your AIR application, as shown in Figure 7.8. Click OK if you made some icon changes; otherwise, click Cancel. You also can click the Advanced Settings button and modify associated file types, initial window settings, and other settings, such as install folder and program menu folder. You also can enable the Use Custom UI for Updates checkbox. A screen capture of this dialog window is shown in Figure 7.9. Click OK if you made some advanced setting changes; otherwise, click Cancel.
Creating a Desktop AIR Application with Flash CS3
119
FIGURE 7.8 Modifying the icons used in the AIR application.
FIGURE 7.9 The Advanced Settings dialog window.
120
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
9. Click the Publish AIR File button after you complete the AIR - Application and Installer Settings. Figure 7.10 shows the resulting Digital Signature dialog.
FIGURE 7.10 The Digital Signature dialog.
10. Just as with Flex Builder 3 and Aptana Studio, the Flash Professional IDE allows you to either browse to a certificate or create a self-signed certificate. After you choose your certificate, enter the password associated with it, and disable the Timestamp checkbox if you do not want the certificate timestamped. Review Figure 7.10 to see a screen capture of the completed dialog window.
11. If you disable the Timestamp checkbox, you see a warning which reminds you that an AIR application that is not timestamped will fail to install after the certificate expires; a timestamped AIR application is still considered safe after the certificate expires and can still be installed. Click OK to continue.
By the Way
You also can change the default radio button selection from Sign the AIR File with a Digital Certificate to the selection Prepare an AIR Intermediate (AIRI) File That Will Be Signed Later. 12. Click the Publish AIR File button again, and you see the success message, AIR File Has Been Created.
13. Install the AIR application by locating and double-clicking the HelloWorld.air file. Step through the installation steps and you will see the
Flash-based AIR application shown in Figure 7.11.
Creating a Desktop AIR Application with Flash CS3
121
FIGURE 7.11 The Flash-based AIR application, HelloWorld.
If you are curious about the contents of an .air file versus an .airi file, you can open both files with a zip archive utility. When the HelloWorld.air file is opened, you see an extra file, signature.xml. This is the result of digital signing the AIR application (for the .air file). The .airi file has not been signed, so the signature.xml file is not included in it.
You can also create the HelloWorld.air file for your AIR application by following these steps:
1. Select the AIR - Create AIR File menu choice from the Commands menu. 2. Complete the Digital Signature dialog by selecting your certificate, supplying the password for it, and making the timestamp choice (refer to Figure 7.10).
3. Click OK and the HelloWorld.air file is created. You see the message in Figure 7.12.
As you have seen, the Flash CS3 Professional IDE with the Adobe AIR update is a fullfeatured tool enabling you to create Flash-based AIR applications. If you would like to experiment more, the HelloWorld.fla and supporting files are available at www. airination.info/airtraining/tyairin24/HelloWorldFlashCS3.zip.
122
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
FIGURE 7.12 The HelloWorld. air file is
created.
Creating a Desktop AIR Application with Dreamweaver CS3 So you are a Dreamweaver CS3 fan and you would like to take your HTML, HTML/JavaScript, or Spry web applications to the desktop. You are at the right place in this hour because you will see an example AIR application built with Dreamweaver CS3 upgraded with the Adobe AIR Dreamweaver extension. If you have not previously downloaded and installed the extension, please do so now (www.adobe. com/products/air/tools/ajax/#section-2).
Creating a Site with Dreamweaver CS3 After you have the Adobe AIR Dreamweaver extension installed, open Dreamweaver CS3 and follow these steps:
1. Select New Site from the Site menu in Dreamweaver CS3. 2. Switch to the Basic tab by clicking on it. 3. Complete the first dialog window by entering HelloWorld in the What Would You Like to Name Your Site? text box. Click Next to continue.
4. Select the No, I Do Not Want to Use a Server Technology radio button. Click Next to continue.
5. You can leave the default settings as they are in the Editing Files, Part 3 section. Click Next to continue.
6. Select None from the How Do You Connect to Your Remote Server? combo box. Click Next to continue.
By the Way
If you plan to use a server-side technology to supplement your AIR desktop application, you can select the technology from the How Do You Connect to Your Remote Server? combo box. Possible server-side technology choices include ASP, ASP.NET, ColdFusion, JSP, or PHP. 7. Review the site definition summary. Click Done.
Creating a Desktop AIR Application with Dreamweaver CS3
123
Creating the Main Application with Dreamweaver CS3 Next you will create the actual main application file (in this case, it is an HTML file) that will become the code behind the AIR application. Recall that an AIR application has at least two files, the main application file and the application descriptor file. To create the main application file, follow these steps:
1. Right-click your new HelloWorld site under the Files panel group and the Files tab—on either the left or right side of the screen, depending on your Dreamweaver CS3 IDE layout—and select New File at the top of the menu, as shown in Figure 7.13.
FIGURE 7.13 Selecting New File at the top of the context menu.
2. Rename the new default untitled.html file as HelloWorld.html by clicking the filename and typing the new one.
3. Double-click the HelloWorld.html file to open it in the main Dreamweaver CS3 viewing area. You can switch to the code view, if necessary, to see the default code shown in Figure 7.14.
124
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
FIGURE 7.14 Opening the HelloWorld. html file and
viewing the default code.
4. Modify the code as shown in Listing 7.1.
LISTING 7.1
The Modified HelloWorld.html Code
1. 2. 3. 4. 5. Hello AIR World from Dreamweaver CS3 6. 7. 8.
9. Hello AIR World from Dreamweaver CS3
10. 11.
5. Save the changes. 6. Click the Preview in Adobe AIR selection from the menu: File, Preview in Browser/Preview in AIR Adobe, or use the shortcut key combination Ctrl+Shift+F12. A screen capture of the resulting preview is shown in Figure 7.15.
Creating a Desktop AIR Application with Dreamweaver CS3
125
FIGURE 7.15 The resulting preview of HelloWorld.
Modifying the Application Descriptor Next you will modify the application descriptor with Dreamweaver CS3 AIR Application Settings menu as follows:
1. Select Site, AIR Application Settings from the menu. 2. Fill in the name, ID, initial content, description, copyright, window style, and window size (500 × 500), and click the Select Icon Images button, as shown in Figure 7.16.
3. Select one or more of the icons you would like to be associated with your AIR application, and then click OK. Figure 7.15 shows four icon images selected.
4. Click the Set button to begin the digital signature steps (refer to Figure 7.16). 5. Either browse to your certificate by clicking the Browse button, or create a selfsigned certificate by clicking the Create button.
6. To create a self-signed certificate, fill in the dialog similar to the example shown in Figure 7.17, and click OK. The self-signed certificate is created and acknowledged in a brief confirmation dialog message.
126
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
FIGURE 7.16 Clicking the Select Icon Images button.
FIGURE 7.17 Creating a self-signed certificate.
7. Clear the acknowledgment message by clicking OK, and you are returned to the Digital Signature dialog window. Enter your certificate’s password, select the Remember Password for This Session checkbox (if you want to avoid having to reenter it each time you create the HelloWorld.air file), select the Timestamp checkbox (if you want to timestamp your HelloWorld.air file), and click OK as shown in Figure 7.18.
Creating a Desktop AIR Application with Dreamweaver CS3
127
FIGURE 7.18 Completing the Digital Signature dialog.
8. Click the Save button when you are back at the AIR Application and Installer Settings dialog window.
9. Next, click the Create AIR File button, located just beneath the Save button. You see the message Creating ‘HelloWorld’ AIR file. Please Wait. If you are unable to connect to the Timestamp server, you see a warning message. An operation succeeded message is displayed after the HelloWorld.air file is created, as shown in Figure 7.19. If the HelloWorld.air file already exists, you get a warning about this fact, as shown in Figure 7.20. Figure 7.21 shows the newly created HelloWorld.air file.
FIGURE 7.19 The operation has succeeded.
An optional way to create the HelloWorld.air file is to select the Create AIR File from the Site menu.
By the Way
128
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
FIGURE 7.20 A warning that the HelloWorld. air file already
exists.
FIGURE 7.21 The HelloWorld. air file.
Newly Created File
10. Double-click the HelloWorld.air file and step through the AIR installation dialog. The AIR application is shown in Figure 7.22.
You accomplished a lot in this hour, and you should now be able to use Flash CS3 Professional and Dreamweaver CS3 to build, test, and package your AIR applications. Before starting the next chapter, you should review what you have learned in the following workshop.
Workshop
129
FIGURE 7.22 The HelloWorld AIR application created with Dreamweaver CS3.
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. How can you choose the best IDE for developing AIR applications? A. Select the tool that fits your developer hand best and you will have the best coding advantage at your disposal—an IDE that fits you perfectly and that you like and trust to rapidly build the AIR applications that you dream up. If you are a Flash developer, Flash CS3 Professional makes the most sense. If you are a Dreamweaver developer, Dreamweaver CS3 is the tool that you should use.
Q. Can you develop an AIR application with a primitive text editor? Although you could certainly build AIR applications with low-level (fewer features) text editors, test and debug from the ADL, and package with the ADT, it might be speedier to select an IDE to handle the full cycle of AIR development.
130
HOUR 7: Writing an AIR Application with Flash CS3 or Dreamweaver CS3
Q. In addition to Flash CS3 Professional, do you need anything else to use the
IDE to build AIR applications? A. All that is needed is the Adobe AIR update for Flash CS3 Professional. Q. In addition to Dreamweaver CS3, do you need anything else to use the IDE to
build AIR applications? A. All that is needed is the Adobe AIR Dreamweaver extension.
Quiz 1. How can you redisplay the Flash CS3 Pro splash screen if it is not displayed? 2. What sort of things can you modify, as far as the application descriptor is concerned, with the Flash CS3 IDE?
3. What sort of things can you modify, as far as the application descriptor is concerned, with the Dreamweaver CS3 IDE?
4. What is the difference between an .air and an .airi file?
Answers 1. If your Flash CS3 Pro splash screen is not displayed, you can turn it back on by choosing Show Welcome Screen from the General category in the Preferences dialog. You need to restart the Flash IDE after changing the On Launch setting to Welcome Screen.
2. You can modify all the Application settings, such as filename, name, ID, description, copyright, and window style. Additionally, you can modify the AIR application’s icons and associated file types, initial window settings, and other settings, such as install folder and program menu folder.
3. You can modify all of the Application settings, such as filename, name, ID, description, copyright, and window style. Additionally, you can modify the AIR application’s icons and associated file types, initial window settings, and other settings, such as install folder and program menu folder.
4. You can open both with an archive utility such as WinZip. When you open an .air file, you see one extra file, signature.xml, versus the intermediate .airi file.
Workshop
Exercises Using your favorite search engine, search for “Adobe AIR IDEs.” Spend some time evaluating any new ones that you find. If you find any of interest, send an email with the details to [email protected].
131
This page intentionally left blank
CurrentH1
HOUR 8
Writing an AIR Application with PDF Integration In this hour, you’ll learn . PDF capability detection in an AIR application . Loading PDF content into an AIR application . Limitations for PDF content in an AIR application
PDF Capability Detection in an AIR Application PDF integration is yet another important AIR runtime capability, but it does require that the end user has Adobe Acrobat Reader 8.1, at a minimum, installed. Fortunately, the AIR application programming interface (API) includes the AIR-only class, HTMLPDFCapability. When it is used with the HTMLLoader class, you as the devel-
oper have a way to programmatically add the PDF feature if the end user’s PC fits the requirement. If you examine the HTMLPDFCapability class, you will see that there are five possible scenarios as far as PDF capability is concerned. Each scenario relates back to one of five constants shown in Table 8.1.
TABLE 8.1
HTMLPDFCapability Class Constants
Constant
Code
Description
STATUS_OK
0
A sufficient version (8.1 or later) of Adobe Reader is detected and PDF content can be loaded in an HTMLLoader object.
ERROR_INSTALLED_READER_ NOT_FOUND
3201
No version of the Adobe Reader is detected.
ERROR_INSTALLED_READER_ TOO_OLD
3202
Adobe Reader is detected, but the version is too old.
133
134
HOUR 8: Writing an AIR Application with PDF Integration
TABLE 8.1
HTMLPDFCapability Class Constants
Constant
Code
Description
ERROR_PREFERRED_READER_ TOO_OLD
3203
A sufficient version (8.1 or later) of Adobe Reader or Acrobat is detected, but the version of Adobe Reader that is set up to handle PDF content is older than version 8.1.
ERROR_CANNOT_LOAD_READER
3204
An error was returned by the OS when trying to load the Adobe Reader or Acrobat application or one of its necessary libraries.
As the developer, you should code your AIR application to test for PDF capability similar to the following example.
LISTING 8.1
A Flex-Based Example HTMLLoader.pdfCapability Test
import mx.controls.Alert; import flash.html.HTMLLoader; import flash.html.HTMLPDFCapability; private function init():void { if (HTMLLoader.pdfCapability == HTMLPDFCapability.STATUS_OK) { Alert.show(“PDF content can be displayed”); // add code to display the PDF } else { Alert.show(“PDF cannot be displayed. Error code: “ + ➥HTMLLoader.pdfCapability); } }
Figure 8.1 shows the result of this test. An alert is displayed depending on your PDF capability—in this case, Acrobat 8.1 is available. In Flex 3, and particularly ActionScript 3, you will appreciate the switch/case conditional. It is a clean way to avoid a long and seemingly unending if/else conditional that you might have seen before. It is important to remember that each case statement must include a break; statement or you will get unexpected and incorrect results. switch (condition) { case 0: // do something if condition is 0 break; case 1: // do something if condition is 1
Loading PDF Content into an AIR Application
break; case 2: // do something break; case 3: // do something break; case 4: // do something break; default: // do something break;
135
if condition is 2
if condition is 3
if condition is 4
if none of the conditions are met
}
FIGURE 8.1 The PDFcapability test is passed.
A special case for PDF integration on the Windows OS exists, and you should decide how you want to handle this possible scenario. The special case is as follows: If Adobe Acrobat Reader 7.x or above is already running on your end user’s system, that opened version is used even if version 8.1, which supports loading PDF content, is installed. In this case, if the value of the pdfCapability property is HTMLPDFCapability.STATUS_OK, the older version of Acrobat Reader displays an
alert when your AIR application attempts to load the PDF content. You may choose to display a warning about closing other Acrobat Reader instances before running your AIR application if you think you will be affected.
Loading PDF Content into an AIR Application In the next code example (also Flex-based), you see how to load PDF content into an AIR application. An explanation of the code will help make your understanding complete.
136
HOUR 8: Writing an AIR Application with PDF Integration
1. First, the tag’s property, applicationComplete, calls the init() function.
2. A tag contains the required import classes necessary for the example (Alert, HTMLLoader, and HTMLPDFCapability).
0 statusLb.text += “ OK”; var PDFContainer:HTMLLoader = new HTMLLoader(); PDFContainer.width = htmlContainer.width; PDFContainer.height = htmlContainer.height; PDFContainer.load(new ➥URLRequest(“assets/PDFs/AIRinFlightPreview.PDF”)); htmlContainer.addChild(PDFContainer); break; case 3201: // HTMLPDFCapability.ERROR_INSTALLED_READER_NOT_FOUND--> ➥3201 statusLb.text += “ Unable to load PDF files. No version of Adobe ➥Reader is detected.”; return; break; case 3202: // HTMLPDFCapability.ERROR_INSTALLED_READER_TOO_OLD--> 3202 statusLb.text += “ Unable to load PDF files. Adobe Reader is ➥detected, but the version is too old.”; return; break;
Loading PDF Content into an AIR Application
case 3203: // HTMLPDFCapability.ERROR_PREFERRED_READER_TOO_OLD--> 3203 statusLb.text += “ Unable to load PDF files. A sufficient version ➥(8.1 or later) of Adobe Reader or Acrobat is detected, but the the ➥version of Adobe Reader that is set up to handle PDF content is ➥older than Adobe Reader or Acrobat 8.1.”; return; break; case 3204: // HTMLPDFCapability.ERROR_CANNOT_LOAD_READER --> 3204 statusLb.text += “ Unable to load PDF files. An error was returned by ➥the OS when trying to load the Adobe Reader or Acrobat application ➥or one of its necessary libraries.”; return; break; } }
4. Finally, the AIR UI is coded to include a for visual feedback, if Acrobat 8.1 is not installed on the end user’s PC. If Acrobat 8.1 is installed, a control displays the PDF.
Listing 8.2 shows the complete code.
LISTING 8.2
PDF Integration in an AIR Application
0 statusLb.text += “ OK”; var pdfContainer:HTMLLoader = new HTMLLoader(); pdfContainer.width = htmlContainer.width; pdfContainer.height = htmlContainer.height; pdfContainer.load(new ➥URLRequest(“assets/pdfs/AIRinFlightPreview.pdf”)); htmlContainer.addChild(pdfContainer);
137
138
HOUR 8: Writing an AIR Application with PDF Integration
break; case 3201: // ➥HTMLPDFCapability.ERROR_INSTALLED_READER_NOT_FOUND --> 3201 statusLb.text += “ Unable to load PDF files.No version ➥of Adobe Reader is detected.”; return; break; case 3202: // ➥HTMLPDFCapability.ERROR_INSTALLED_READER_TOO_OLD --> 3202 statusLb.text += “ Unable to load PDF files. Adobe ➥Reader is detected, but the version is too old.”; return; break; case 3203: // ➥HTMLPDFCapability.ERROR_PREFERRED_READER_TOO_OLD --> 3203 statusLb.text += “ Unable to load PDF files. A ➥sufficient version (8.1 or later) of Adobe Reader or ➥Acrobat is detected, but the the version of Adobe ➥Reader that is set up to handle PDF content is older ➥than Adobe Reader or Acrobat 8.1.”; return; break; case 3204: // HTMLPDFCapability.ERROR_CANNOT_LOAD_READER --> ➥3204 statusLb.text += “ Unable to load PDF files. An error ➥was returned by the OS when trying to load the Adobe ➥Reader or Acrobat application or one of its necessary ➥libraries.”; return; break; } } ]]>
Figure 8.2 shows the resulting AIR application. You can download the Flex-based project code from http://www.airination.info/airtraining/tyairin24/ AIRPDFIntegration.zip.
Limitations for PDF Content in an AIR Application
139
FIGURE 8.2 PDF integration is complete.
Limitations for PDF Content in an AIR Application You should be aware of some limitations concerning loading PDF content into your AIR applications:
. PDF content does not display in an AIR application that has a transparent window (meaning the transparent property is set to true and the systemChrome is set to none in the AIR application descriptor file). If you change the application descriptor in the example shown in the previous section to a transparent window, the PDF is no longer visible, as Figure 8.3 shows.
FIGURE 8.3 PDF content and a transparent window.
140
HOUR 8: Writing an AIR Application with PDF Integration
. The display order of a PDF file operates differently than other display objects in an AIR application. PDF content always sits on top of the content in the AIR application’s display order. You can see this by setting the HTML control’s visible property to false. The OK label is now displayed. With the visible
property set to true, the label is beneath the PDF and cannot be seen. Figure 8.4 shows the HTML control with the visible property set to false.
FIGURE 8.4 PDF content and display order.
. Full-screen mode renders PDF content invisible. You enable full-screen mode when the displayState property of the Stage is set to either StageDisplayState.FULL_SCREEN or StageDisplayState.FULL_SCREEN_INTERACTIVE.
. The visual properties, such as filters, alpha, rotation, or scaling, of an HTMLLoader object that contains a PDF file cannot be changed, or the PDF file
will become invisible until the properties are reset.
. A Stage object’s scaleMode property of the NativeWindow object containing the PDF content must be set to StageScaleMode.NO_SCALE.
. Hyperlinks within an integrated PDF file in the AIR application act a bit strange when clicked and in some cases do not work at all. You now have another hour in the knowledge bank, and you should be able to integrate PDFs into your AIR applications. Before starting the next hour, you should review what you have learned in the following Workshop.
Workshop
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. Why is my PDF invisible in My AIR application? A. The transparent property in the AIR application descriptor if set to true (along with a systemChrome setting of none) causes a PDF to not be displayed.
Q. What pdfCapability should you check for at a minimum? A. There are five possible results for the HTMLLoader.pdfCapability property, but only one that results in a PDF displayed in your AIR application.
Q. Why should end users be warned about closing older versions of Acrobat
Reader before running your PDF-integrated AIR application? A. If Adobe Acrobat Reader 7.x or above is already running on your end user’s system, that opened version is used even if version 8.1, which supports loading PDF content, is installed. In this case, if the value of the pdfCapability property is HTMLPDFCapability.STATUS_OK, the older version of Acrobat Reader displays an alert when your AIR application attempts to load the PDF content.
Q. Why do changes to an HTMLLoader object’s filters, alpha, rotation, or scaling properties seem to break the display of a PDF?
A. The visual properties of an HTMLLoader object that contains a PDF file cannot be changed. Changing an HTMLLoader object’s filters, alpha, rotation, or scaling properties render the PDF file invisible until the properties are reset.
Quiz 1. What is the success code for Acrobat or Acrobat Reader being at the appropriate level (8.1) to display a PDF in an AIR application?
2. What is the significance of the HTMLPDFCapability class? 3. How is a PDF added to the display of an AIR application? 4. Describe the scaleMode property setting that works for PDF integration.
141
142
HOUR 8: Writing an AIR Application with PDF Integration
Answers 1. Zero (0) STATUS_OK means a sufficient version (8.1 or later) of Adobe Reader is detected and PDF content can be loaded in an HTMLLoader object.
2. If you examine the HTMLPDFCapability class, you see that there are five possible scenarios as far as PDF capability is concerned. A zero (0) means a sufficient version of Acrobat or Acrobat Reader is present and PDF content can be displayed.
3. A PDF is displayed by passing an HTMLLoader (with the PDF) via the addChild method to an HTML control.
4. The scaleMode property of the Stage object of the NativeWindow object containing the PDF content must be set to StageScaleMode.NO_SCALE.
Exercises Review adding JavaScript to an Acrobat PDF, and then integrate the resulting PDF in an AIR application. See the following link for more information: http://www.adobe.com/devnet/acrobat/javascript.html.
CurrentH1
143
HOUR 9
Debugging AIR Applications In this hour, you’ll learn . . . .
Using Using Using Using
the Adobe the Adobe third-party the Adobe
Flex Builder Debugger AIR Debug Launcher (ADL) to debug tools to debug AIR HTML Introspector
Using the Adobe Flex Builder Debugger As an AIR developer, you should always strive to create your AIR applications free from bugs and performing at a reliable level. Fortunately, with the tools that Adobe provides, you can accomplish this with a minimum of hassle. If you are developing your AIR applications by coding them with Flex, you are in luck, as Flex Builder 3 has a full-featured debugger. With the Flex Builder Debugger, you can do all of the following:
. Set and manage breakpoints . Step into and over code . Watch variables . Evaluate expressions . Trace network traffic Free videos about debugging with Flex Builder are available from Lynda.com (http://movielibrary.lynda.com/html/modPage.asp?ID=290).
Did you Know?
144
HOUR 9: Debugging AIR Applications
To get started debugging with the Flex Builder Debugger, follow these instructions:
1. Open Flex Builder 3 and, after it is open, open your Flex project (AIR application) and the main application file. In the example shown in Figure 9.1, you see the Open Project menu choice. This allows you to begin working with the project’s code.
FIGURE 9.1 Selecting the Open Project menu choice.
The main application file, AIRPDFIntegration.mxml, is shown opened in Figure 9.2.
2. Set and manage breakpoints by double-clicking in the left gutter while in the Source view. A blue dot appears. Double-click again, and the blue dot toggles off. During a mouseover, the text “Line breakpoint: AIRPDFIntegration.mxml [line: 11]” is displayed, as shown in Figure 9.2.
By the Way
A breakpoint is a point in a program at which operation may be interrupted for manual intervention or inspection. 3. Click the Debug icon (it looks like a bug) beneath the Navigate menu to begin debugging your AIR application. Because you set breakpoints in the application, your application will run until the first breakpoint, and then pause for your intervention, allowing you see the inner workings of your application as the variables come into and out of focus.
Using the Adobe Flex Builder Debugger
145
FIGURE 9.2 The file AIRPDFIntegration.mxml is
open.
4. You receive an alert questioning whether you want to open the Flex Debugging perspective. You should allow this perspective to open so you can inspect the code in a line-by-line manner. You see the Flex Debugging perspective as shown in Figure 9.3.
FIGURE 9.3 The Flex Debugging perspective.
146
HOUR 9: Debugging AIR Applications
5. Step over the code down to line 13. If you mouseover text in the statusLb.text variable, you see statusLb.text = ““. This shows you an
example of the value of a variable before it is used.
6. Step over the code one additional line to line 14. Now if you mouseover text in the statusLb.text variable, you see statusLb.text = “ OK”, as shown in Figure 9.4. This shows you an example of the value of a variable after it is used.
FIGURE 9.4 Line 14 from the Flex Debugging perspective.
7. Look in the Console tab, located beneath the Source view area, and you see HTMLPDFCapability.STATUS_OK --> 0 from the trace statement at line 13.
This shows the power of using the trace statement in your code as a form of debugging. A screen capture of this is shown in Figure 9.5.
8. Double-click the Variables tab, located above and slightly to the right of the Source view. Look at the statusLb variable and you will see the text (statusLb.text) value is ”OK”, as shown in Figure 9.6.
9. Right-click the statusLb.text variable, and choose Watch “statusLb.text” from the menu, as shown in Figure 9.7. You see the value of statusLb.text in the Expressions tab.
Using the Adobe Flex Builder Debugger
147
FIGURE 9.5 The Console view from the Flex Debugging perspective.
FIGURE 9.6 The Variables tab from the Flex Debugging perspective.
148
HOUR 9: Debugging AIR Applications
FIGURE 9.7 Watching the statusLb.text
expression from the Flex Debugging perspective.
10. Click the red Stop button to terminate the debugging session). 11. Scroll to the top of the code in the AIRPDFIntegration.mxml file and add the following code (see Figure 9.8). Save the change.
12. Start a new debugging session as you did in step 3. You see a new line in the Console, as shown in Figure 9.9. The tag traces network traffic and provides a logger target that uses the global trace() method to output log messages. It displays ’629C7AC4-FB62-32BC-627E-AED09C36CDFB’ producer set destination to ‘DefaultHTTP’ (see the highlighted output in the Console tab in Figure 9.9).
Using the Adobe Flex Builder Debugger
149
FIGURE 9.8 New code added to the AIRPDFIntegration.mxml file.
FIGURE 9.9 The Flex Builder Debugger Console with trace output.
150
HOUR 9: Debugging AIR Applications
The complete code for this debugging example is shown in Listing 9.1.
LISTING 9.1
A Flex-Based Example Used for the Debugging Sessions
0 trace(“HTMLPDFCapability.STATUS_OK --> “ + HTMLLoader.pdfCapability); statusLb.text += “ OK”; var pdfContainer:HTMLLoader = new HTMLLoader(); pdfContainer.width = htmlContainer.width; pdfContainer.height = htmlContainer.height; pdfContainer.load(new ➥URLRequest(“assets/pdfs/AIRinFlightPreview.pdf”)); htmlContainer.addChild(pdfContainer); break; case 3201: // HTMLPDFCapability.ERROR_INSTALLED_READER_NOT_FOUND -➥>3201 trace(“HTMLPDFCapability.ERROR_INSTALLED_READER_NOT_FOUND --> “ + ➥HTMLLoader.pdfCapability); statusLb.text += “ Unable to load PDF files. No version of Adobe ➥Reader is detected.”; return; break; case 3202: // HTMLPDFCapability.ERROR_INSTALLED_READER_TOO_OLD --> 3202 trace(“HTMLPDFCapability.ERROR_INSTALLED_READER_TOO_OLD --> “ + ➥HTMLLoader.pdfCapability); statusLb.text += “ Unable to load PDF files. Adobe Reader is ➥detected, but the version is too old.”; return; break; case 3203: // HTMLPDFCapability.ERROR_PREFERRED_READER_TOO_OLD --> 3203 trace(“HTMLPDFCapability.ERROR_PREFERRED_READER_TOO_OLD --> “ + ➥HTMLLoader.pdfCapability); statusLb.text += “ Unable to load PDF files. A sufficient version ➥(8.1 or later) of Adobe Reader or Acrobat is detected, but the the ➥version of Adobe Reader that is set up to handle PDF content is ➥older than Adobe Reader or Acrobat 8.1.”; return; break; case 3204: // HTMLPDFCapability.ERROR_CANNOT_LOAD_READER --> 3204 trace(“HTMLPDFCapability.ERROR_CANNOT_LOAD_READER --> “+ ➥HTMLLoader.pdfCapability);
Using the Adobe AIR Debug Launcher to Debug
151
statusLb.text += “ Unable to load PDF files. An error was returned by ➥the OS when trying to load the Adobe Reader or Acrobat application ➥or one of its necessary libraries.”; return; break; } } ]]>
As you have seen, the Flex Builder Debugger is a powerful tool you have in your arsenal to build reliable Flex-based AIR applications. Further information about the Adobe Flex Builder debugger can be found at http://livedocs.adobe.com/flex/3/html/ compile_debug_1.html.
Using the Adobe AIR Debug Launcher to Debug If you do not use Flex Builder 3 or your AIR applications are not Flex-based (the Flex Builder 3 Debugger can only be used for Flex-based projects), you can use the Adobe AIR Debug Launcher (ADL). With the ADL, you can debug either Flex-based or HTML-based applications during the development phase of your AIR project. Using the ADL, you can debug without first packaging and installing the AIR application, saving you some time and effort during the development phase of your project.
You should note that the ADL can print trace statements and runtime errors to the standard output log or console, but it does not support breakpoints or other debugging features.
Watch Out!
From the previous section, the same code can be run through the ADL with the following command: adl AIRPDFIntegration-app.xml
When running the ADL, if you see the “Initial content not found” error in the Command Prompt, the initial content is specified in AIRPDFIntegration-app.xml. If you are using the AIRPDFIntegration-app.xml file in the Flex src directory, the file content is not actually specified—instead, you will see [This value will be overwritten by Flex Builder in the output app.xml].
Watch Out!
152
HOUR 9: Debugging AIR Applications
In this case, run the ADL for the AIRPDFIntegration-app.xml file that Flex Builder autogenerates in the bin-debug directory. It has the correct value: AIRPDFIntegration.swf. With the trace statement and the tag present in the code, the Command Prompt window contains the following output. The trace statement is responsible for a single line, HTMLPDFCapability.STATUS_OK --> 0. The rest of the output is from the tag and includes the communication handshake and the data returned from the URL, http://localhost, called with the tag (in the third line of Listing 9.1). The data is simply a listing
of the files and folders on the webserver.
Watch Out!
This http://localhost happens to be the local webserver on my laptop, so your output will be different. ’A95C668B-2933-118D-7A35-AF7DBF521B71’ producer set destination to ‘DefaultHTTP’ . HTMLPDFCapability.STATUS_OK --> 0 ‘direct_http_channel’ channel endpoint set to http: ‘A95C668B-2933-118D-7A35-AF7DBF521B71’ producer sending message ‘BD696984-E57E-F B54-9881-AF7DBFD6D242’ ‘direct_http_channel’ channel sending message: (mx.messaging.messages::HTTPRequestMessage)#0 body = (Object)#1 clientId = (null) contentType = “application/x-www-form-urlencoded” destination = “DefaultHTTP” headers = (Object)#2 httpHeaders = (Object)#3 messageId = “BD696984-E57E-FB54-9881-AF7DBFD6D242” method = “GET” recordHeaders = false timestamp = 0 timeToLive = 0 url = “http://localhost” ‘A95C668B-2933-118D-7A35-AF7DBF521B71’ producer connected. ‘A95C668B-2933-118D-7A35-AF7DBF521B71’ producer acknowledge of ‘BD696984-E57E-FB 54-9881-AF7DBFD6D242’. Decoding HTTPService response Processing HTTPService response message: (mx.messaging.messages::AcknowledgeMessage)#0 body = “
As you can see, ADL debugging, although not as user friendly as the Flex Builder Debugger, can still provide some valuable debugging output. For more information, you can review http://livedocs.adobe.com/flex/3/html/CommandLineTools_4. html#1033678. In some cases, you might want to debug network traffic to and from your AIR application, where the tag is not enough to suit your needs. In the next section, you see some third-party tools that you can add to your tool belt for such occasions.
Using Third-Party Tools to Debug Third-party tools, such as ServiceCapture, Charles, and Ethereal/Wireshark, allow you to capture the network traffic (using Flash Remoting) or data flow between an AIR application and any server-side infrastructure.
Flash Remoting provides a communication connection for data transfer between a Flash SWF and a web application server. Flash Remoting is available for Adobe ColdFusion, .NET, and PHP server-side technologies (natively for ColdFusion).
By the Way
154
HOUR 9: Debugging AIR Applications
Additionally, as you have seen, for a Flex-based Adobe AIR application, the tag can be placed anywhere in the Adobe Flex code. During
debugging, the network traffic data (Flash Remoting type) is displayed in the Console window. These tools can prove valuable when you get stuck in a corner trying to figure out why your data seems to be missing. To clarify this a bit further, these tools are not in place of the Flex Builder 3 Debugger or the ADL (used for Flex-based coding logic debugging) because the tag and these third-party tools are specifically for debugging the data transferred between the AIR application and a server-side entity; the Flex Builder 3 Debugger and the ADL are of little use for this type of debugging. Syntax case-sensitivity issues are readily solved with this sort of debugging. In Figure 9.10, the data transferred between an AIR application and a ColdFusion server is shown using ServiceCapture.
FIGURE 9.10 An AIR application and ServiceCapture.
Another third-party tool, Charles, shows an issue with connecting to a crossdomain.xml file in Figure 9.11. Instead of spending wasted time trying to deter-
mine an issue with the code for this AIR application, you would see immediately that it is simply a connectivity issue.
Using the Adobe AIR HTML Introspector
155
FIGURE 9.11 A crossdomain. xml connection issue found with Charles.
Using the Adobe AIR HTML Introspector To debug HTML or AJAX-based AIR applications, you will use either the ADL or another IDE’s debugger for your AIR applications. Unfortunately, the current IDEs on the market are not AIR-aware and will not be that useful. Fortunately, the AIR SDK includes an AIRIntrospector.js JavaScript file (called the AIR HTML Introspector) that you can include in your application to help debug HTML-based or AJAX-based AIR applications. If you recall, you also saw that this file was included (yet commented out by default) in Aptana Studio, as the following code shows:
Figure 9.12 shows the AIRIntrospector.js file included in Aptana Studio. The AIR HTML Introspector includes the following features:
. A console that allows the developer to point to user interface (UI) elements in an application and see their properties.
. A console for sending object references for introspection. You can adjust property values, execute JavaScript code, and serialize objects to the console. You can also copy and save text from the console.
. A tree-based view for DOM properties and functions. . An edit capability for the attributes and text nodes of the DOM elements. . A list of links, CSS styles, images, and JavaScript files loaded in your application.
156
HOUR 9: Debugging AIR Applications
FIGURE 9.12 The AIRIntrospector. js file included in
Aptana Studio.
. A view of the initial HTML source and the current source code for the UI. . A view of the files in the application directory. This feature is only available for the AIR HTML Introspector console opened in the application sandbox and is not available for consoles open for non-application sandbox content.
. A viewer for XMLHttpRequest objects and their properties, including responseText and responseXML properties (when available).
. A way to search for matching text in the source code and files.
Watch Out!
Include the AIRIntrospector.js file only when developing and debugging the application. Remove it in the packaged Adobe AIR application that you distribute. Listing 9.2 shows a sample HTML-based application that includes the AIRIntrospector.js reference and a call to the log method.
Using the Adobe AIR HTML Introspector
LISTING 9.2
157
A Sample HTML-Based Application That Includes
AIRIntrospector.js
Source Viewer Sample
Click to view the button object in the Console.
Running this application with the ADL and clicking on the Log button reveals the application shown in Figure 9.13. This Adobe AIR HTML/JS Application Introspector contains tabs that allow you, the developer, to see different views of the application’s structure, such as the HTML elements, the Document Object Model (DOM), the assets referenced in the application, and the source code. This information can be very useful during the debugging sessions for your AJAX or HTML/JavaScript-based AIR supplication development.
FIGURE 9.13 The Adobe AIR HTML/JS Application Introspector.
158
HOUR 9: Debugging AIR Applications
For more information about the Introspector, see the details at http:// livedocs.adobe.com/air/1/devappshtml/AIR_Introspector_1.html#1050347. Once again you have been busy this hour, and you should now be able to debug your AIR applications. Before starting the next hour, you should review what you have learned in the following Workshop.
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. List the debug features included with the Flex Builder Debugger. A. With the Flex Builder Debugger, you can do all of the following:
. . . . .
Set and manage breakpoints Step into and over code Watch variables Evaluate expressions Trace network traffic
Q. How can you trace network traffic? A. The tag can be placed anywhere in the Adobe Flex code. During debugging, it displays network traffic data (Flash Remoting type) in the console window.
Q. How can you debug HTML/JavaScript-based AIR applications? A. To debug HTML or AJAX-based AIR applications, the AIR SDK includes an AIRIntrospector.js JavaScript file (called the AIR HTML Introspector) that
you can include in your application to help debug HTML-based or AJAX-based AIR applications.
Q. Why would you want to use third-party tools suggested in this hour? A. Third-party tools, such as ServiceCapture, Charles, and Ethereal/Wireshark, allow you to capture the network traffic (using Flash Remoting) or data flow between an AIR application and any server-side infrastructure, possibly saving you hours of frustration with network communication.
Workshop
Quiz 1. Flex Builder 3 includes what perspective that is useful for debugging? 2. What useful debugging statement is used to debug Flex-based AIR applications?
3. What should you do if you see this error in the Command Prompt while testing your AIR application with the ADL: “Initial content not found”?
4. What should you remember to do with the AIRIntrospector.js file included for debugging purposes before you package and distribute your AIR application?
Answers 1. The Flex Debugging perspective is used during Flex Debugging sessions. 2. The trace statement is useful in both the Flex Builder Debugger and the ADL. 3. In this case, run the ADL for the application descriptor file that Flex Builder autogenerates in the bin-debug directory. It has the correct value: YourAIRApp.swf.
4. Include the AIRIntrospector.js file only when developing and debugging the application. Remove it in the packaged Adobe AIR application that you distribute.
Exercises Explore the other third-party tools useful for network (Flash Remoting) traffic monitoring, such as Ethereal/Wireshark. If you find any of interest, send an email with the details to [email protected].
159
This page intentionally left blank
CurrentH1
161
HOUR 10
Distributing Your AIR Application In this hour, you’ll learn . Installing an AIR application in a one-off approach . Installing AIR applications seamlessly from a web page . Digitally signing and creating an AIR installation file
Installing an AIR Application in a One-Off Approach The “one-off approach” might sound like a strange name to call downloading an .air file, double-clicking it, and stepping through the installation process, but if you
think about it, the term actually fits quite well. Each end user that wants to install your AIR application is a single installation or a one-off installation. For this approach you need either a website from which the end users can download your .air file or some distribution media, such as a CD or DVD.
For a website deployment, you need to add a new mime type to your web server’s configuration, so it will know what an Adobe .air file is. According to Adobe, you should add the application/vnd.adobe.air-install-package mime type, associated with the .air extension. For the Apache HTTP Server, adding AddType application/vnd.adobe.air-install-package .air to your httpd conf file works well.
Watch Out!
162
HOUR 10: Distributing Your AIR Application
Your end users should be advised of the requirement for the AIR runtime to be installed first. You can provide the link to the Adobe website, http://get.adobe.com/ air/, with the textual explanation about its requirement. An example website is shown in Figure 10.1.
FIGURE 10.1 A website example for downloading an .air file and the runtime.
Mass distribution of the AIR runtime might be available depending on your specific circumstances. You can review the license requirements and apply for a distribution license at http://www.adobe.com/products/air/runtime_distribution1.html. Distribution through such sites as O2Apps.com: http://www.o2apps.com and the Adobe AIR Marketplace: http://www.adobe.com/cfusion/exchange/ index.cfm?event=productHome&exc=24&loc=en_us are also viable channels for distribution of your AIR applications. After an end user has your AIR application’s .air file, she needs to understand an important requirement—she needs adequate administrative-type privileges on her PC or Mac to be able to install the AIR runtime or an AIR application. The nature and power of this type of application requires elevated privileges to the native OS over the typical web application with which she is likely more familiar. These elevated privileges could, in the wrong hands, be dangerous to the OS. Part of the distribution process is to educate and comfort the end user into accepting the risks because of the great benefits the AIR runtime and your AIR application provides. Whatever the vehicle of delivery is for your AIR application, you should prominently list these precautions (for example, on your website surrounding your AIR application, in a read-me file on a CD-ROM or DVD, and so on). After the user has been informed, the installation process is as follows:
Installing an AIR Application in a One-Off Approach
163
1. Obtain the Adobe AIR runtime from http://get.adobe.com/air/. 2. Install the runtime by double-clicking on the runtime and follow the installation steps.
3. Click the I Agree button. The installer proceeds and you see the Installation Completed dialog. If you have an earlier version of the AIR runtime already installed, you see the installation step shown in Figure 10.2. If you attempt to install the same version of the AIR runtime, you see the dialog shown in Figure 10.3.
FIGURE 10.2 The Updated Adobe AIR dialog.
FIGURE 10.3 The Adobe AIR Already Installed dialog.
4. Next, obtain the .air file from the website. 5. Double-click the .air file to launch the installation process. See Figure 10.4 for a screen capture of an example of an .air file installer.
FIGURE 10.4 An example .air file installer.
164
HOUR 10: Distributing Your AIR Application
You see the Getting Ready to Install this Application... progress meter.
6. After you see the Are You Sure You Want to Install this Application to Your Computer dialog step, click the Install button, as shown in Figure 10.5.
FIGURE 10.5 Clicking the Install button.
7. Select the installation preferences you want. Your choices are Add Shortcut Icon to My Desktop, Start Application After Installation, and the Installation Location.
8. Click the Continue button. You see the Installing Application... progress dialog. If you selected the Start Application After Installation checkbox, the AIR application automatically starts after the installation is complete, as shown in Figure 10.6. If you selected the Add Shortcut Icon to My Desktop checkbox, the AIR application shortcut is automatically added to your desktop. The shortcut icon is also added to the OS menu. On the Mac OS, the application is added to the Applications directory.
9. When the installation is complete, the end user should click the Finish button.
If the AIR application is already installed and is the same version, the installer gives the end user the choice of opening the existing version of the application, uninstalling the application, or cancelling. The installer identifies the application using the application ID and publisher ID found in the .air file. Figure 10.7 shows this scenario.
Installing an AIR Application in a One-Off Approach
165
FIGURE 10.6 The installed AIR application.
FIGURE 10.7 The AIR Application Is Already Installed dialog.
If the AIR application is already installed and is an older version, the installer gives the end user the choice of replacing the version on his OS, cancelling the installation, uninstalling the current version, or running the existing application. Figure 10.8 shows this scenario. After the AIR application is installed on a Windows OS, double-click the AIR application’s icon (which is either installed on the desktop or in a folder) or select the application from the Start menu. On the Mac OS, double-click the AIR application in the folder in which it is installed. The default installation directory is the /Applications directory.
166
HOUR 10: Distributing Your AIR Application
FIGURE 10.8 An Older Version of the AIR Application Is Already Installed dialog.
Installing AIR Applications Seamlessly from a Web Page Installing an AIR application from a web page is an attractive alternative to the oneoff approach. The badge install or seamless install method, as it is called, is what you will use to accomplish this. The seamless install feature lets you embed a special Shockwave Flash (SWF) file in a web page that lets the user install an AIR application from the browser. Additionally, if the AIR runtime is not installed (and the user allows it), the seamless install feature can install the AIR runtime and then the actual AIR application. The seamless install feature allows an end user to install the AIR application directly from his browser, or if an end user desires, the .air file can still be saved to his PC and run manually at a later time (just like a one-off installation). The choice still resides with the end user, as it should, so remember that the user interface (UI) of your website and textual explanation of the process should support and comfort your potential AIR application clients if you want the highest adoption rates for the work you produce. A sample badge installer is available in the AIR SDK, the Flex 3 SDK, and Flex Builder 3. Figure 10.9 shows the badge-related files contained in the AIR SDK. As mentioned in Hour 3, “Harnessing the AIR SDK,” the badge installer can be modified extensively to provide a customized, seamless installation routine for your AIR application. With badge.fla included and by using Flash CS3, you could even modify the badge.swf file for your custom web deployment page, as shown in Figure 10.10.
Installing AIR Applications Seamlessly from a Web Page
167
FIGURE 10.9 The badge files in the AIR SDK.
FIGURE 10.10 A customized badge.swf in a web page.
You might recall from Hour 5, “Writing Your First AIR Application with Flex 3,” that to allow the badge installer to work, you must toggle on the badge or seamless installation capability for the AIR application. A true setting in the AIR application descriptor file node, , allows the AIR application to be installed from a browser, while a false setting prevents it.
AIRRemotingmxCoreWindow
v1
none
true
191
192
HOUR 11: Opening Doors with AIR
Creating Custom Windows
Next, you can use code similar to the complete MXML code listed in Listing 11.6. You should note that custom Minimize and Close icons have been added to the UI, and event listeners and their corresponding functions handle the minimizing and the closing of the AIR application. Additionally, this AIR application has a non-rectangular UI.
The complete Flex-based project code for this hour is available at http:// www.airination.info/airtraining/tyairin24/AIRWindows.zip. There you have it: You can now create windows in several ways and open the door to building a nice UI for your AIR applications. As always, you covered a great deal of material in this hour. Before starting the next hour, you should review what you have learned in the following Workshop.
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. How do I display a native window? A. The first way is to call the activate() method. The second way is to set the visible property to true (newWindow.visible = true;). Invoking the activate() method on the NativeWindow instance will
. Make the window visible . Bring the window to the front . Give the window keyboard and mouse focus
195
196
HOUR 11: Opening Doors with AIR
The visible property simply specifies whether the window is visible on the desktop. It only affects visibility and does not give the window focus or bring it to the front.
Q. What can I do with the initialization properties of the NativeWindowInitOptions class?
A. The properties are systemChrome
Specifies the type of system chrome used by the window.
type
Specifies the type of the window to be created.
maximizable
Specifies whether the window can be maximized.
minimizable
Specifies whether the window can be minimized.
resizable
Specifies whether the window can be resized.
transparent
Specifies whether the window supports transparency and alpha blending against the desktop.
Q. What can I do with the NativeWindowInitOptions systemChrome choices? A. The systemChrome choices are STANDARD and NONE. The STANDARD option creates a standard-looking native window based on the OS. The transparent property of the window must be set to false (which is the default value) or the end user will not see a window. The NONE option specifies that the window should not display any system chrome. Creating a native window with no chrome yields a rectangle on the screen without any controls.
Q. Can I change the NativeWindowInitOptions after a native window has been
created? A. No. Although all NativeWindowInitOptions properties have default values, they cannot be changed after the native window is created.
Quiz 1. To create a custom window, what properties in the AIR application descriptor file must be modified?
2. How do you create a new window with the mx.core.Window class? 3. Is there an ordering rule when moving a window created with the mx.core.Window class?
4. How can you close a window?
Workshop
Answers 1. The node must be modified in the AIR application’s descriptor file, specifically these three settings:
true
2 3
5 [This value will be overwritten by Flex Builder in the output ➥app.xml] 6
8
11 true 12 false
false
100
650
You see another user notification type, the system tray icon ToolTips, in the next section.
Creating a System Tray Icon System tray icons are another one of the Windows-only types of notifications. This notification relies on the NativeApplication class, specifically its icon property (NativeApplication.nativeApplication.icon) and the SystemTrayIcon class. The tricky detail you need to remember when working with this notification strategy is that an instance of the SystemTrayIcon class cannot be created directly. Instead, you should create a variable of type Object to hold NativeApplication. nativeApplication.icon.
You need to remember another important rule when working with system tray icons in your AIR applications. You might recall that if you try to use other notification types with operating systems that do recognize them, no compile-time or run-time errors are triggered. With system tray icon code, however, attempting to call a SystemTrayIcon class method on the NativeApplication.icon object on an oper-
ating system that does not support system tray icons will generate a run-time exception. So it is imperative that you test your applications and check the value of the NativeApplication.supportsSystemTrayIcon Boolean value to determine whether
system tray icons are supported on the end user’s system. Figure 19.5 shows a screen capture of this type of AIR application.
323
324
HOUR 19: AIR and User Notifications
FIGURE 19.5 An AIR system tray icon notification example application.
As with many AIR applications, the applicationComplete event triggers a custom function that kicks things off; the init() function is called in Listing 19.7, line 4. In line 10, you see the test for the Boolean value for NativeApplication. supportsSystemTrayIcon. If the value is true, a string variable, sysTrayImageURL,
is created (in line 12) to hold the URL of the system tray icon. A 16 × 16 pixel icon is just the ticket for a Windows system tray icon. Line 13 declares a Loader object as the variable loader. In line 14, an event listener, Event.COMPLETE, is added to the loader object. Line 15 calls the load method and passes a URLRequest object that
contains the URL held in the sysTrayImageURL variable. In line 16, the status bar is updated to provide a visual cue for the end user (it shows the result of the NativeApplication.supportsSystemTrayIcon Boolean value). The handler, iconLoaded, for Event.COMPLETE is shown in lines 23–27. In line 24, bitmapData is
added to the nativeApplication.icon.bitmaps property. In line 25, a systray object (a variable of type Object) is declared and set equal to the nativeApplication.icon. Finally, in line 26, a ToolTip is added to the systray
object. You will notice that there is an else clause in lines 17–20 to cleanly handle the NativeApplication.supportsSystemTrayIcon evaluating to a false value.
LISTING 19.7
Application Code that Demonstrates a System Tray Icon
1 2 6
7
Last but not least, you will see another user notification type—bouncing the Mac OS dock icon.
Bouncing the Mac OS Dock Icon The last type of AIR operating system notification you will examine in this hour is a Mac-only one—bouncing the Mac OS dock icon. Figure 19.6 shows a screen capture of a sample AIR application that bounces the Mac OS dock icon.
FIGURE 19.6 An AIR bouncing the Mac OS dock icon sample application.
As you saw with highlighting the taskbar for the Windows operating system, you can use the native window notifyUser() method to communicate visually with the Mac OS end user by bouncing the docked icon. You can also bounce the Dock icon by calling the NativeApplication.nativeApplication.icon.bounce() method. Setting
326
HOUR 19: AIR and User Notifications
the bounce() priority parameter to informational bounces the icon once. Setting this priority parameter to critical bounces the icon until the user interacts with the AIR application. As you have seen before, constants for the priority parameter are defined in the NotificationType class. As you might have guessed, you can test for this property
to determine if the OS can handle Dock icons. The property supportsDockIcon of the NativeApplication class is useful for this purpose. Listing 19.8 is an example of the type of code you need to write. As with many AIR applications, the applicationComplete event triggers a custom function that kicks things off; the init() function is called in Listing 19.8, line 4. In line 10, you see the test for the Boolean value for the NativeApplication. supportsDockIcon. If the value is true, a DockIcon variable, dockIcon, is created in
line 12 to hold the icon property of nativeApplication. In line 13, the bounce method, NotificationType.CRITICAL, bounces the Mac OS Dock icon (if the NotificationType is set to CRITICAL, the icon bounces until the user interacts with
the AIR application). In line 14, the status bar is updated to provide a visual cue for the end user, showing the result of the NativeApplication.supportsDockIcon Boolean value.
LISTING 19.8 Application Code that Demonstrates Bouncing the Mac OS Dock Icon 1 2 6
7
21
Workshop
22
23 24
You covered a great deal of material in this hour, and you should now understand how to create user notifications for your AIR applications. Before starting the next hour, you should review what you have learned in the following Workshop.
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. Can I code all the notification types generically without worrying about
whether a notification type is supported? A. That is almost the case, but the system tray icon notification will throw a runtime error on a Mac OS if you fail to protect the false evaluation of the Boolean test for NativeApplication.supportsSystemTrayIcon.
Q. Are there any other notification types that this hour did not discuss? A. Yes, although they would need to be custom coded without benefit of built-in AIR classes. Leveraging the Alert class (mx.controls.Alert), you can notify the end user if a particular event takes place. Additionally, you can use the visible or enabled properties on the Flex-based controls to provide visual cues throughout your AIR application. Recall that the connectivity icon toggling the smiley-faced icon from a smile to a frown is an example of a user notification (see Hour 16, “Connectivity with AIR Networking”).
Q. Can you bounce a system tray icon on Windows? A. Yes, with a bit of custom code you can simulate this effect. Hint: One way is to use the Timer class. See the “Exercises” section.
327
328
HOUR 19: AIR and User Notifications
Q. Which type of user notification is considered the least invasive to the user
experience? A. Although this is subject to further discussion, the toast type of notification is a nice way to present information or critical alerts to an end user without forcing him to click on anything to be able to continue working with your AIR application. It is a nice non-invasive technique that you should consider.
Quiz 1. List the types of user notifications discussed in this hour. 2. What are the two types of notifications that use the NotificationType class, and what are the two values of this class?
3. What is the user notification type that will throw a run-time error if you attempt to use the wrong OS?
4. Which notification type uses the concept of an idle time?
Answers 1. The user notification types seen in this hour were
. Status bar notifications . Taskbar highlighting . Toast messages . System tray icons . Dock icons 2. The taskbar and the Dock icon leverage the NotificationType class. The values defined in the NotificationType class are
.
NotificationType.INFORMATIONAL
.
NotificationType.CRITICAL
Workshop
3. With the system tray icon notification type, attempting to call a SystemTrayIcon class method on the NativeApplication.icon object on an
operating system that does not support system tray icons will generate a runtime exception.
4. Toast messages leverage the NativeApplication class. Use the NativeApplication events userIdle (the constant is User_Idle) and userPresent (the constant is User_Present) to implement the toast notifica-
tions that rise up from the lower right of the screen, pause briefly, and then lower back down out of sight.
Exercises Create a system tray icon for Windows that bounces in an example AIR application. Email the zipped archive to [email protected]. Your AIR application will be considered for inclusion in future revisions of this title.
329
This page intentionally left blank
PART III
Developing AIR Applications HOUR 20
Leveraging Server-Side Features for AIR
333
HOUR 21
Building an AIR Application
343
HOUR 22
Signing AIR Applications
367
HOUR 23
Updating AIR Applications After Deployment
377
HOUR 24
Where Do I Go from Here?
387
This page intentionally left blank
Leveraging Remoting
HOUR 20
Leveraging Server-Side Features for AIR In this hour, you’ll learn . . . .
Leveraging remoting Getting the most out of web services Using HTTP communication Taking advantage of messaging
Leveraging Remoting In this hour, you will see how your AIR applications can communicate with an enterprise’s server-side infrastructure. You will learn about
. Remoting: The shortened name for remote object access service, it is available for ASP.NET, ColdFusion, J2EE, and PHP.
. Web services: Can be programmed with the Flex frameworks tag.
. HTTP communication: Leverages the tag. . Messaging: Publish/subscribe messaging collaboration with BlazeDS. Regardless of your choice in the communication protocol, AIR desktop applications can easily leverage many of the server-side technologies that are tried and true and have substantial investments in an enterprise. Up front, you should realize that the highest performance and fastest communication is via the remoting technique using the Flex-based tag.
333
334
By the Way
HOUR 20: Leveraging Server-Side Features for AIR
Flash remoting, since Adobe Flex 2, is a binary format called AMF3. It is inherently better performing than the other Remote Procedure Call (RPC) types, HTTPService and WebService. Given the choice, you should always choose remoting when performance matters. From the very beginning, Adobe Flex and Adobe ColdFusion have been best friends. If you have the option of providing server-side functionality with ColdFusion, you are very lucky and should take full advantage of ColdFusion components (CFC). A CFC is easy to code and just as easy to connect remotely to. In the following example, you will see just how easy it is to communicate between an AIR application and a CFC stored on a remote server. Listing 20.1 shows two of the three files for this example—AIRCFRemoting.mxml and airinfo.cfc that is deployed on the ColdFusion application server. (Recall that an
XML-based application descriptor file is always needed, but it is not shown here because the automatically generated default file is used.) The Flex-based click event for the Button control in line 26 calls the getVisitorIP() method of the RemoteObject tag (line 8).
By the Way
The RemoteObject class gives you access to classes on a remote application server. You should note that the tag, in line 8, includes two events: a result event and, in case of a communication error, a fault event. The result event is passed to the getVisitorIPHandler handler. This handler is shown in lines 17–20 and simply pushes event.result.toString() into the text property of the Flexbased Label control (the id property is lbl). If there is a communication error, the fault handler, the roFaultHandler function, displays the contents of event.fault.
Of course, in a release version of an AIR application, you would handle a communication error in a more user-friendly manner.
LISTING 20.1 AIRCFRemoting.mxml Application Code That Leverages Remoting to a CFC 1 2 3
The CFC airinfo.cfc is a very simple single function ColdFusion component. In the following code, line 3 sets a string variable, sIP, equal to the ColdFusion environment variable of the remote IP address, CGI.REMOTE_ADDR. In line 4, the sIP value is returned back through flex2gateway (line 5 in the AIRCFRemoting.mxml file shown in Listing 20.1).
To use a CFC with Flash remoting, the access attribute in the cffunction tag must be set to remote. 1 2 3
4
5 6
Figure 20.1 shows this simple example application. Clicking on the Get Remote IP Address button makes a remote call to the CFC and a server-side script returns the IP address of the end user. In the next section, you will see the same CFC function, getVisitorIP(), called with the tag.
Watch Out!
336
HOUR 20: Leveraging Server-Side Features for AIR
FIGURE 20.1 AIR remoting to a CFC returns the IP Address.
Leveraging Web Services Web services are another server-side data provider or source that a Flex-based AIR application can leverage. The tag gives you access to the operations of SOAP-compliant web services (SOAP is a protocol for exchanging XML-based messages over computer networks, normally using HTTP/HTTPS) deployed on a web server. Unlike the small, speedy footprint that is remoting, a web service is slower performing; however, web services may be the best choice if your server-side infrastructure already has web services deployed and available. If you take a look at Listing 20.2, you will see how to code the tag. The Flex-based button control in line 22 calls the WebService, whose id is wsAIRInfo, getVisitorIP operation (line 4). Just as in the method tag for RemoteObject, there is a result event and a fault event. The result event calls the getVisitorIPHandler handler function (lines 13–16), which pushes event.result.toString() into the text property of the Flex-based Label control in line 15 (the id property is lbl). If
there is a communication error, the fault handler (wsFaultHandler) displays the contents of event.fault. As in the previous example, the release version of an AIR application would handle a communication error in a more user-friendly manner.
By the Way
The WebService class provides access to SOAP-based web services on remote servers.
LISTING 20.2 AIRCFWebService.mxml Application Code That Leverages a Web Service Call to a CFC 1 2 3
4
5
6
Leveraging HTTP Communication
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
23 24
The CFC is not listed again because no changes are necessary for its usage with the WebService tag.
In the next section, you will see the same CFC function, getVisitorIP(), called with the tag.
Leveraging HTTP Communication You can use the tag by calling the HTTPService object’s send() method. It makes an HTTP request to a specified URL, and an HTTP response is returned. Optionally, you can pass parameters to the specified URL. When you do not go through a server-based proxy service, you can use only the HTTP GET or POST methods. However, when you set the useProxy property to true and you use a serverbased proxy service, you can also use the HTTP HEAD, OPTIONS, TRACE, and DELETE methods. If you take a look at Listing 20.3, you will see how to code the tag. The Flex-based button control in line 26 calls the send() method for HTTPService, whose id is set as httpAIRInfo. Just as in the remote object’s method
tag and the web service’s operation tag, there is a result event and a fault event. The result event calls the getVisitorIPHandler handler function in lines 16–20, which pushes xmlResult.data.string[0] into the text property of the Flex-based label control in line 19 (the id property is set to lbl).
337
338
By the Way
HOUR 20: Leveraging Server-Side Features for AIR
In line 5 of Listing 20.3, the resultFormat=”e4x” property slightly changes the way the handler function, getVisitorIPHandler, works. The event.result is returned as XML, so the lbl.txt equals xmlResult.data.string[0].
If there is a communication error, the httpFaultHandler function will display the contents of event.fault. As in the previous two examples, the release version of an AIR application would handle a communication error in a more user-friendly manner.
LISTING 20.3 AIRCFHTTPService.mxml Application Code that Leverages a HTTPService Call to a CFC 1 2 3
9
10
25
26 27 28
The CFC is not listed again because no changes are necessary for its usage with the HTTPService tag.
In the next section, you will see an example of messaging with BlazeDS.
Leveraging Messaging
339
Leveraging Messaging BlazeDS is a free, open source, JAVA-based messaging technology that can be leveraged to handle the communication of messages between AIR desktop applications and a server-side infrastructure or Web-based applications built in Flex or HTML/JavaScript. A sample AIR application that would benefit from the BlazeDS technology is a desktop chat application that must publish (send) and subscribe (receive) instant messages between the chat application’s end users. The AIR application communicates through BlazeDS messaging to handle both the publish and subscribe messaging requirements.
For more information about BlazeDS, review http://opensource.adobe.com/wiki/ display/blazeds/BlazeDS.
Did you Know?
Installation of BlazeDS is beyond the scope of this book, so please refer to http://opensource.adobe.com/wiki/display/blazeds/Installation+Guide for specific details about the installation steps.
The install instructions for BlazeDS assumes you have a properly configured JAVA environment on your machine, including having a JAVA_HOME environmental variable set and the JRE bin directory added to your system path.
After you have BlazeDS installed, try these steps:
1. Start the sample database by changing the directory, in a command prompt, to {BlazeDS root}/sampledb.
2. Run startdb.bat on Windows. 3. After the sample database has been started, open a new command prompt and navigate to {BlazeDS root}/tomcat/bin by changing the directory.
4. From the Windows command prompt, type catalina run. To test your installation, browse to http://localhost:8400/samples/.
5. Scroll down to the Other Samples section and click the Trader Desktop link (http://localhost:8400/samples/#traderdesktop).
6. Click the link in the Click Here to Start the Feed text, or go to http:// localhost:8400/samples/traderdesktop/startfeed.jsp.
By the Way
340
HOUR 20: Leveraging Server-Side Features for AIR
7. Finally, click the link in the Click Here to Start the Trader Desktop Application text, or go to http://localhost:8400/samples/traderdesktop/index.html.
Figure 20.2 shows the Trader Desktop application so you can get an idea of the realtime messaging capability. Every four seconds the stock prices are sent, via BlazeDS, as a message to all subscribed end-user client applications.
FIGURE 20.2 A BlazeDS messaging sample from the Trader Desktop application.
You covered a great deal of material in this hour, and you should now understand how to leverage a server-side infrastructure for your AIR applications. Before starting the next hour, you should review what you have learned in the following Workshop.
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. Can I use other server-side technologies with AIR applications? A. Yes. You can perform remoting to an ASP.NET, a ColdFusion, a J2EE, or a PHP server-side infrastructure.
Workshop
Q. I am unable to return any data from my CFC function to my AIR application.
What is wrong? A. You should ensure that the cffunction tag that you are calling has the access variable set equal to remote. Additionally, you can leverage either the
Flex-based tag or a third-party application, such as ServiceCapture or Charles, to see if you are remoting successfully or simply not referencing the returned data properly. For example, a case sensitivity issue can prevent your AIR application from working as you expect.
Q. What is the preferred remoting technique to use with an AIR application? A. If you are able to use the Flex-based tag, you should always select this technique because it is the fastest of the Remote Procedure Call (RPC) methods.
Q. How can I pass variables to a CFC function with a Flex-based WebService or HTTPService tag call?
A. The Flex-based WebService tag allows you to place the variables you want to pass inside the operation call. For example, in the following code a single variable, tiFlight.text, is passed to the getFlightDetails operation of the wsFlight web service: wsFlight.getFlightDetails(tiFlight.text);
The Flex-based HTTPService tag is coded a bit different than the WebService tag: httpFlight.url = “http://localhost/AIRRemoting➥debug/info/airination/cfcs/flight.cfc?method=getFlightDetails& ➥flightnumber=”+ tiFlight.text; httpFlight.send();
Quiz 1. What attribute in a CFC’s cffunction tag is vital to the success for Flash remoting?
2. What are the three types of sub tags used with the three RPC data services? 3. How can you, the developer, handle remoting communication failures? 4. What capability can BlazeDS give you over the three RPC data services?
341
342
HOUR 20: Leveraging Server-Side Features for AIR
Answers 1. The access attribute must be set to remote to enable Flash remoting. 2. The RemoteObject tag uses the method sub tag; the WebService tag uses the operation sub tag; the HTTPService tag uses the request sub tag.
3. Each of the RPC data services has the fault event, allowing you to write custom communication fault handlers to notify the end user that a server-side communication issue exists.
4. BlazeDS can bring real-time messaging capabilities to AIR applications that the other RPC data services cannot.
Exercises Create a BlazeDS-based example AIR application. Email the zipped archive to [email protected]. Your AIR application will be considered for inclusion in future revisions of this title.
Deciding on an Application
HOUR 21
Building an AIR Application In this hour, you’ll learn . . . .
Deciding on an application Selecting application features Architecting your application Coding your application
Deciding on an Application In this hour you will see my approach to building an example application. I guess you can say that this chapter is a bit one-sided. To make up for that, I welcome your feedback in the “Exercises” section at the end of the hour. Deciding on an application can be easy in many cases, as your target audience might actually dictate what the application requirements are and even the time frame for the development cycle. At other times, I have been in the situation where I stumble across a topic that interests me. For example, I enjoy traveling and always spend time looking for flight information, such as arrival times, departure times, and likelihood of on-time arrivals in the city of destination. A year or so ago, I found a nice online site called FlightAware (http://flightaware.com/about/) that allows you to track real-time flight data (the site updates the flight data about once every six minutes). It includes a cool feature—the approximate flight path shown visually on the website. Also available is data such as altitude, air speed, time since departure, and estimated arrival time. There is a fee-based commercial feature (http://flightaware.com/commercial/), but I opted for a free path to the data I wanted to leverage. The free path means you need to know the ColdFusion Markup Language (CFML) cfhttp tag.
343
344
HOUR 21: Building an AIR Application
A quick browse to http://flightaware.com/live/flight/COA1444 shows you an example of the data available. Depending on the time of day you go to the site, the daily flight from San Francisco to Houston might be in progress. If it is in flight, you see a plane icon showing its current location. Figure 21.1 shows this flight as it was in progress on August 12, 2008.
FIGURE 21.1 Continental Air Lines Inc. flight #1444 August 12, 2008.
When I first stumbled across the FlightAware site, AIR was not even available. At the time, I was simply evaluating the site’s capabilities for a possible Flex 2 application. After the Apollo alpha was available, I quickly decided that I would build an Apollo desktop application that would display the flight information in the new HTMLControl. You might quickly recognize that the alpha Apollo HTMLControl is no
longer available in AIR, although the HTML control that replaced it serves the same purpose.
By the Way
The HTML control lets you display HTML content in your application.
So there you have it. My decision to create an AIR application I call Go Fly was prompted by a personal interest and hobby. For you, it might be an end user request, a business requirement, or something that simply tweaks your creative juices. You might even decide that you would like to port one of your existing web applications to the desktop. Whatever the spark is for you, I hope you enjoy working with AIR as much as I do. In the next section, you will see how I selected the features I wanted to include in my Go Fly AIR application.
Architecting Your Application
Selecting Application Features As with deciding on what application to build, selecting what features your application will contain might also be dictated by the end user or the business enterprise. In my case, I was on my own—the sky was the limit. Part of the immediate feature ideas was based on my desire to learn about the new features baked into Apollo and later the AIR release.
. Use the HTML control to display the retrieved flight data. . Use the Flex-based validation classes to ensure that the end user of my application would enter an airline code (such as CO) and a flight number (such as 1444) before submitting a remote call to the FlightAware site.
. Monitor network connectivity to ensure that the FlightAware service was accessible.
. Retrieve archived flight data to provide a way for the end user to review previous flights’ data.
. Time automatic flight data retrieval to query the FlightAware service only as often as updated data was available (once every six minutes). So what else would you add to this application feature list? Immediately coming to mind are some convenience features—emailing or real-time messaging the flight data to friends and family, manually pushing the locally stored data from the SQLite database to a server-side database, and the capability to delete historical flight data. Polling data from the server-side database after connectivity was re-established is also worthwhile considering. If you have more ideas, please feel free to add your feedback in the “Exercises” section at the end of the hour in the “Workshop” section. In the next section, you will see how I decided to design the layout of my Go Fly AIR application.
Architecting Your Application Off the bat, I must admit I am not a designer, so if you’re expecting to read about all the Flash, Photoshop, Fireworks, or other graphics tools of your choice I used to create my AIR user interface (UI), I hope you will not be too disappointed. In Hours 1, “Taking in a Deep Breath of AIR,” and 7, “Writing an AIR Application with Flash CS3 or Dreamweaver CS3,” you might recall reading about choosing the IDE tool that best fits your developer hand. For me, that tool is Flex Builder 3. I also usually use ServiceCapture to monitor the data communication between my Flex or AIR
345
346
HOUR 21: Building an AIR Application
applications and the server-side infrastructure. For the Go Fly AIR application, the features I wanted to include dictated the requirement for an application server, a database server, and a web server. I have the most experience with ColdFusion, so I chose ColdFusion 8 for my application server. My database experience includes all the big players, but as cost was a major consideration, I opted for mySQL 5. I am a fan of the Apache projects, so the Apache HTTP server (version 2.2) served as my web server. For the AIR desktop application’s end-user side, I leveraged the File API, the network connectivity-related classes, the validation-related classes, the Timer class, and other Flash- or Flex-based and AIR-only classes. For the Remote Procedure Call (RPC) data service I practiced what I preach and selected the RemoteObject RPC data service. Figure 21.2 shows a diagram of the client-side and server-side infrastructure I used for this application.
FIGURE 21.2
Technology Platform for “Go Fly”
Client-side and server-side infrastructure diagram.
“Go Fly”
Rich Internet Applications Content and Applications Rich Content
Client Framework
Adobe Flex
MXML
Browser
Adobe Flash Player
Desktop
Adobe AIR
ActionScript
ActionScript
Run Times
Operating Systems
Client
JavaScript
ActionScript
PDF
HTML,CSS, etc.
Mac, Windows, Linux, etc.
AMF
Server HTTP, HTTPS, Raw Sockets, RTMP Server
Adobe ColdFusion
mySQL 5 Database
Coding Your Application
347
Coding Your Application To build my Go Fly AIR application, I chose the skill set that I have the most experience with—Flex and ActionScript 3 for the client-side code and ColdFusion Markup Language (CFML) for the server-side portion. The final application I coded includes five MXML files, the XML-based application descriptor file, one ActionScript 3 custom class file, one ColdFusion component (CFC), one PDF, and various image files used throughout the application. These files are shown in Table 21.1 and then discussed, individually, in the code listings that follow the table.
TABLE 21.1
AIRGoFly AIR Project Files
Filename
Purpose
gofly.mxml
Main application for Go Fly (shown in Listing 21.1).
FlightDetails.mxml
A Flex-based pop-up window that shows the flight information returned from the RemoteObject call (shown in Listing 21.2).
FlightDG.mxml
A Flex-based pop-up window that shows the archived flights returned from the server-side database (shown in Listing 21.3).
FlightPlayBack.mxml
A Flex-based pop-up window that replays the archived flight information returned from the server-side database (shown in Listing 21.4).
AIRinFlightContainer.mxml A Flex-based title window that displays a locally stored
PDF (shown in Listing 21.5). gofly-app.xml
The XML-based application descriptor (not shown because it is automatically generated by Flex Builder 3).
ConnectionStatus.as
A custom class that handles the connectivity monitoring (shown in Listing 21.6).
flight.cfc
A ColdFusion component (CFC) that handles the server-side features (shown in Listing 21.7).
For my Go Fly application I am using a local version of ColdFusion 8 Developer Edition, so you will see http://localhost/flex2gateway/ for the endpoint of my RemoteObject calls to the flight.cfc. If you do not have a ColdFusion application server installed on the PC that you use for trying the code from this hour, you may download a trial or developer edition from https://www.adobe.com/cfusion/tdrc/index.cfm?product=coldfusion.
By the Way
348
HOUR 21: Building an AIR Application
Figure 21.3 shows a screen capture of the opening screen of the Go Fly application. You see two Flex-based TextInput controls—one for the airline code and one for the flight number. Clicking on the Search button triggers a RemoteObject call to the server-side CFC on the ColdFusion application server.
FIGURE 21.3 Go Fly opening screen.
Listing 21.1 is a long piece of code, and for your convenience, is available online: http://www.airination.info/airtraining/tyairin24/LISTING%2021.html. Hopefully, if I have done my job well, much of it should look familiar. Here’s how all this code works.
Initializing the Application In line 2, the applicationComplete event calls an initApp() function. The initApp() function, in lines 75–83, adds an Event.NETWORK_CHANGE listener in line
77, calls a checkConnection() function in the ConnectionStatus class in line 79, and then adds two TimerEvent.TIMER listeners in lines 80 and 81. Finally in this initializing function, a custom function, startTimer2(), is called in line 82. The startTimer2() function is shown in lines 182–185. In line 184, the myTimer2 timer
is started. The onTimer2 handler function myTimer2 is shown in lines 186–189. In line 188, a custom function, monitorConnectionStatus(), is called and is shown in lines 190–211. This function uses a conditional to test the Internet connectivity,
Coding Your Application
connection.iStatus, in line 192. (Listing 21.6 shows the source of the iStatus
value—a one means the Internet connection is available; a zero means the Internet connection is not available).
Searching for a Flight In line 303, the Search Flex-based button is shown. The click event calls the validateForm function (passing a string ’live’ to the function); this function is
shown in lines 132–171 and includes validation-type coding leveraging the Flexbased ValidationResultEvent class. The validation code simply ensures that the airline code and the flight number are entered; if both or either one is missing, the end user receives a Flex-based alert visually notifying him which entry is missing. The end user cannot proceed without clearing the alert message and filling in both pieces of required flight information. After the airline code and the flight number are no longer missing, there are two conditional checks in lines 159–167. These conditionals have three possible outcomes:
. The first test confirms that the Internet connection is available; a non-zero (!=0) or one indicates that the Internet connection is available and the second conditional test is performed in line 169. This test determines if the Search button was clicked and a ’live’ string was passed or if the Archive button was clicked and an ’archive’ string was passed.
. When both conditionals are true, the RemoteObject call, roFlight. getFlightDetails, is called. The airline code and flight number are concate-
nated in line 157 into the flight variable, which is then passed to roFlight. getFlightDetails in line 161. If the first conditional is true (Internet avail-
able) but the second one is false (’archive’ is passed), the RemoteObject call, roFlight.getArchivedFlights, is called and the flight variable is passed in line 163.
. If the first conditional is false, there’s no need to test the second conditional, so the custom function getFlightFromFS() is called in line 166. This function is shown in lines 231–245. It attempts to read the flight information from the end user’s file system. If data is found, this data is pushed in line 240 into the HTML control, found in line 300.
Displaying the Flight Information Depending on which RemoteObject function is called or which offline file system data retrieval method is used, displaying the flight information utilizes different functions. There are three possible paths to displaying the flight information.
349
350
HOUR 21: Building an AIR Application
The first possibility involves the RemoteObject tag which is shown in lines 3–11. If both conditionals test true, the getFlightDetails method (shown in Listing 21.7) is called in line 8 with the result event handler, getFlightDetailsHandler. This handler function is shown in lines 84–95; in line 86, the flight details are stored on the end user’s PC by calling the setFlightToFS() function. This makes this data available later if the application loses the Internet connection. This function is shown in lines 212–230 and includes all the code to record the same flight details that will also be written to the server-side database. A visual UI element, lblProgress, is cleared and hidden in lines 87 and 88 (this tells the end user that the data retrieval is complete). In line 89, the first timer, myTimer, is started. This is the timer that performs a six-minute count so the FlightAware site can be pinged again for fresh flight information. The timer handler is shown in lines 123–131. In line 125, the airline code and the flight number are concatenated into the variable, flight. In line 127, the RemoteObject method, roFlight.getFlightDetails, is called again (this happens once each six minutes due to the myTimer timer interval). The visual UI element, lblProgress, is set to “Retrieving flight data...” and displayed in lines 128 and 129 (this tells the end user that the data retrieval is being requested). The stop method of the myTimer is called in line 130. Back in the getFlightDetailsHandler, line 90 tests a conditional, blnWindowOpen; if false, the HTML control’s htmlLoader property and loadString
method is passed the flight information. The HTML control now renders the flight data as shown in Figure 21.4. If the blnWindowOpen is true, the Flex-based pop-up, represented by the FlightDetails.mxml component, is opened in line 93. This component also displays the flight information inside an HTML control, as shown in Listing 21.2.
FIGURE 21.4 Flight information retrieved via the RemoteObject
RPC data service.
Coding Your Application
351
The second possibility also involves the RemoteObject tag, which is shown in lines 3–11. If the first conditional tests true (the Internet connection is available) and the second one tests false (the Archive button was clicked), the getArchivedFlights method (shown in Listing 21.7) is called in line 9 with the result event handler, getArchivedFlightsHandler. This handler is shown in lines 96–102, and the event.result is placed into a public Flex-base ArrayCollection in line 98. (A Flex-
based ArrayUtil class method, toArray, tweaks the format of the data, so it works better in the ArrayCollection source property.) In lines 99–101, a pop-up is used to open and position the FlightDG.mxml component. This component is a Flex-based data grid that displays all the possible flights and data points from the server-side archived flights database table. Figure 21.5 shows a screen capture of this data grid. Clicking on any of the rows triggers the itemClick event shown in Listing 21.3, line 60. The itemClick event calls the custom function getDetails() shown in Listing 21.3, lines 29–38. The getDetails() function calls a function in the parent main application, getArchFlightDetails, and passes in the flightnum and flightid data (this data comes from the mySQL database and is discussed in the “Retrieving the Server-Side Data” section). The getArchFlightDetails function is shown in Listing 21.1, lines 103–105. In line 104, the getArchivedFlightDetails RemoteObject method, defined in line 10, is called; this calls the same named function in the flight.cfc (shown in Listing 21.7). The result event handler for this RemoteObject
call is getArchivedFlightDetailsHandler and is shown in lines 106–111. In lines 108 and 109, the lblProgress UI text is cleared and hidden. Finally the HTML control is filled with the event.result data in line 110.
FIGURE 21.5 Selecting previous flight information from a data grid.
352
HOUR 21: Building an AIR Application
The final possibility involves leveraging the AIR File API. If the first conditional test result is false (Internet connection is not available), the custom function getFlightFromFS() is called (in line 166 of Listing 21.1). The getFlightFromFS()
function is shown in lines 231–245. In line 232 of Listing 21.1, a Flash-based Dictionary class is declared as the FlightDict variable.
By the Way
The Dictionary class enables you to create a dynamic collection of properties, which uses strict equality (===) for key comparison on nonprimitive object keys. When an object is used as a key, the object’s identity, not the value returned from calling toString() on it, is used to look up the object. Primitive (built-in) objects, like numbers, in a Dictionary collection behave in the same manner as they do when they are the property of a regular object.
In line 233, a test is run to determine whether the File object, fFlight, exists. If the conditional is true, a FileStream variable, fs, is declared in line 234. In line 235, the synchronous open command is passed the fFlight File object and the AIR-only FileMode class, FileMode.READ. Line 236 loads the Dictionary variable, FlightDict, with the data from the fs.readObject() method. The FileStream
variable, fs, is closed in line 237. In line 238, the [Bindable] public variable, txtFlightInfo, is filled with the FlightDict.flightdetails data. A quick test is
performed in line 239 to ensure that the txtFlightInfo is not empty. If the txtFlightInfo is not empty, the HTML control is filled with the data stored in the txtFlightInfo variable in line 240; otherwise an “Error deserializing data” alert is
displayed to the end user. Entering an airline carrier code and a flight number (refer to Figure 21.3) and clicking on the Search button results in the flight information being returned from the RemoteObject call (refer to Figure 21.4).
Listing 21.2 is the code for the FlightDetails.mxml component that is used to display flight data that has already been retrieved once, without having to call the RemoteObject method again. This is for efficiency’s sake—no need to call the server-
side remote function but once every six minutes. When this component is called (Listing 21.1 line 93), the creationComplete event is triggered (Listing 21.2 line 2) after the component loads completely, and then the fillFlightInfo() function is called. The fillFlightInfo() function is shown in lines 8–11. In line 10, an HTML control is loaded with the data passed from the main application via the sFlightInfo string variable (shown in Listing 21.1, line 93).
Coding Your Application
LISTING 21.2
Code for the Online Flight Information Component,
FlightDetails.mxml 1 2 3
4
14 15
16
17
18 19
Displaying the Archived Flight Information One of the features of this application is the capability to recall historical flight information, referred to as archived flights throughout this hour. I opted to display the archived flights flight number and the date of the flight in a Flex-based data grid. Refer to Figure 21.5 to see a screen capture of this presentation. Listing 21.3 is the code for FlightDG.mxml, which is used to display all of the archived flights so the end user can decide which one(s) to review. As you have seen in many of the code examples, the creationComplete event in line 2 calls a custom function, initComp(). The initComp() function is shown in lines 19–23. In line 22, the main application’s Array variable, aryFlightDetails, is set to some of the internal data of the main application’s ArrayCollection, as in the arcFlights.list.source[0].list.source data. This is used as the dataProvider
property of the DataGrid variable, dgFlights, in line 60. The itemClick event of dgFlights calls the custom function getDetails() shown in lines 29–38. The getDetails() function calls a function in the parent main application, getArchFlightDetails, and passes in the flightnum and flightid data (this data
comes from the mySQL database and is discussed in the “Retrieving the Server-Side Data” section).
If you attempt to use the arcFlights.list.source[0].list.source code in line 22 as the dataProvider of the DataGrid, you will see a warning in the Flex compiler about the array not being bindable as coded. The code will still work, but if warnings bug you as much as they do me, you should change the dataProvider of the DataGrid, as I have done in line 60, to arcFlights.getItemAt(0).list.source.
This component has two buttons, a Close button in line 55 and a Play All button in line 54. Clicking the Close button calls the closeWindow() function. In lines 24–28, the function simply closes the pop-up with this code: PopUpManager. removePopUp(this). The Play All button calls the replayAll() function shown in
lines 42–47. In line 43, another pop-up window, FlightPlayBack.mxml, is called and opened. In line 46, the closeWindow() function is called. Now only one pop-up window is open—FlightPlayBack.mxml (the code is shown in Listing 21.4).
Did you Know?
356
HOUR 21: Building an AIR Application
Replaying an Archived Flight If an end user clicks on the Play All button in the data grid listing of the archived flights, a timer-based play feature rotates through all of the archived flights that were listed in the data grid in chronological order. Figure 21.6 is a screen capture of the first archived flight information displayed.
FIGURE 21.6 Replaying flight information via the Timer class.
Take a look at Listing 21.4. Once again you see the creationComplete event in line 2, calling a custom function, fillFlightInfo(). The fillFlightInfo() function is shown in lines 17–23. In line 18, an array of the data for one or more flights from the main application is passed into a local array, aryFlightsToReplay. In lines 19 and 20, two timer event listeners, TimerEvent.TIMER, are added to two timers (one is a 500-millisecond timer, myTimer, and one is a 5-second timer, myTimer2). An interesting thing about the myTimer variable is that the number of times it is repeated is based on the size of the archived data points; it is set in line 16 to aryFlightDetails.length (the number of elements in the array equals the number
of flight data points). In line 21, the first timer is started with myTimer.start(). In line 22, the setFocus() method is called on the Close button, with id equal to btnClose. This sets the focus to the Close button. Remember that the first timer, myTimer, is started already and runs only once after 500 milliseconds (in line 14 you
see that it will only run one time); its handler function is onTimer and is shown in lines 24–28. In line 25, the HTML control is filled with the array’s data based on the
Coding Your Application
evaluation of aryFlightDetails[counter].flightdetails. The counter variable is declared in line 13. The counter is incremented in line 14 (counter++). myTimer2 (the 5-second timer) is started in line 15. The handler function for the TimerEvent.TIMER event is onTimer2 and is shown in lines 29–36. Line 30 tests a
conditional: Is the counter variable less than the aryFlightsToReplay.length? If true, the HTML control is filled with the array’s data based on the evaluation of aryFlightDetails[counter].flightdetails in line 31. Line 32 increments the counter variable. Five seconds later the HTML control will be refilled with the next
flight’s data.
LISTING 21.4
Code for Replaying Archived Flight Information,
FlightPlayBack.mxml 1 2 3
4
46 47 48 49
Displaying a PDF in an HTML Control Another feature I included in this Go Fly application is referred to as PDF integration. Imagine that you wanted to include some “help content” in an embedded PDF, and you see how this might be utilized for your AIR application. Figure 21.7 shows a locally stored PDF file loaded into an HTML control. (The PDF file would be compiled into the deployed .air file.)
FIGURE 21.7 PDF integration into the AIR application.
Coding Your Application
Listing 21.5 gets started in line 2 with the creationComplete event calling the custom init() function. The init() function, shown in lines 11–43, is actually a switch/case block of code that simply evaluates the HTMLLoader.pdfCapability
value (discussed in Hour 8, “Writing an AIR Application with PDF Integration”). If the end user has the correct version of Adobe Acrobat Reader or Adobe Acrobat (8.1 or later), the HTMLLoader.pdfCapability evaluates to a zero, and the HTMLLoader variable, pdfContainer, is declared in line 16. In lines 17 and 18, the height and width properties of the pdfContainer variable are set. In line 19, the load method
of pdfContainer is passed the URLRequest variable, ’assets/pdfs/AIRinFlightPreview.pdf’. Finally, the addChild method of the HTML control is passed to pdfContainer in line 20. The remaining code in the switch/case block will only be triggered if the end user does not have the appropri-
ate Acrobat software. The end user will see an alert message as to the issue he needs to resolve to view the PDF.
LISTING 21.5 Code for a Title Window that Displays a PDF, AIRinFlightContainer.mxml 1 2 3
4 0 14 trace(“HTMLPDFCapability.STATUS_OK --> “ + ➥HTMLLoader.pdfCapability); 15 //statusLb.text += “ OK”; 16 var pdfContainer:HTMLLoader = new HTMLLoader(); 17 pdfContainer.width = htmlContainer.width; 18 pdfContainer.height = htmlContainer.height; 19 pdfContainer.load(new ➥URLRequest(“assets/pdfs/AIRinFlightPreview.pdf”)); 20 htmlContainer.addChild(pdfContainer); 21 break; 22 case 3201: // HTMLPDFCapability.ERROR_INSTALLED_READER_NOT_FOUND ➥--> 3201 23 trace(“HTMLPDFCapability.ERROR_INSTALLED_READER_NOT_FOUND —> “ + ➥HTMLLoader.pdfCapability); 24 statusLb.text += “ Unable to load pdf files. No version of Adobe ➥Reader is detected.”;
359
360
HOUR 21: Building an AIR Application
25 26 27 28 29 30 31 32 33 34
35 36 37 38 39
40 41 42 43 44 45 46 47
return; break; case 3202: // HTMLPDFCapability.ERROR_INSTALLED_READER_TOO_OLD --> ➥3202 trace(“HTMLPDFCapability.ERROR_INSTALLED_READER_TOO_OLD --> “ + ➥HTMLLoader.pdfCapability); statusLb.text += “ Unable to load pdf files. Adobe Reader is ➥detected, but the version is too old.”; return; break; case 3203: // HTMLPDFCapability.ERROR_PREFERRED_READER_TOO_OLD --> ➥3203 trace(“HTMLPDFCapability.ERROR_PREFERRED_READER_TOO_OLD --> “ + ➥HTMLLoader.pdfCapability); statusLb.text += “ Unable to load pdf files. A sufficient version ➥(8.1 or later) of Adobe Reader or Acrobat is detected, but the ➥the version of Adobe Reader that is set up to handle PDF content ➥is older than Adobe Reader or Acrobat 8.1.”; return; break; case 3204: // HTMLPDFCapability.ERROR_CANNOT_LOAD_READER --> 3204 trace(“HTMLPDFCapability.ERROR_CANNOT_LOAD_READER --> “ + ➥HTMLLoader.pdfCapability); statusLb.text += “ Unable to load pdf files. An error was returned ➥by the OS when trying to load the Adobe Reader or Acrobat ➥application or one of its necessary libraries.”; return; break;
} } ]]>
48
49 50 51
Monitoring the Internet Connection You saw Listing 21.6 in Hour 16, “Connectivity with AIR Networking,” so a detailed analysis is not needed here. The bottom line in this AIR application is that this class monitors the connection to the Internet. The FlightAware data is from an Internet site, so without an Internet connection, no flight information is available. This class tests the connection and handles the UI changes that keep the end user advised as to the availability of features.
Coding Your Application
LISTING 21.6 Code for the Custom ConnectionStatus.as Class that Monitors Internet Connectivity 1 package info.airapps.actionscripts 2 { 3 // imports needed for this AS Class 4 import flash.events.NetStatusEvent; 5 import flash.system.System; 6 import flash.net.URLLoader; 7 import flash.net.URLRequest; 8 import mx.managers.CursorManager; 9 import flash.events.HTTPStatusEvent; 10 import flash.events.IOErrorEvent; 11 import mx.core.Application; 12 public class ConnectionStatus { 13 // embed images and declare persistent image classes 14 [Embed(source=”../../../assets/images/smile.png”)] 15 [Bindable] public var imgConnected:Class; 16 [Embed(source=”../../../assets/images/frown.png”)] 17 [Bindable] public var imgDisconnected:Class; 18 [Bindable] public var iStatus:int; 19 // checks the connectivity by accessing the URL, ➥http://labs.insideflex.com 20 public function checkConnection():void { 21 // triggers the display of a watch glass or busy cursor 22 CursorManager.setBusyCursor(); 23 // declare a URLRequest variable 24 var headRequest:URLRequest = new URLRequest(); 25 // set the URLRequest method to HEAD 26 headRequest.method = “HEAD”; 27 // set the URL 28 headRequest.url = “http://labs.insideflex.com”; 29 // declare a URLLoader variable and pass the URLRequest 30 var response:URLLoader = new URLLoader(headRequest); 31 /* add a HTTP_STATUS event listener: Listens for the HTTP_STATUS; 32 statusChanged() function is called when the listener event occurs */ 33 response.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusChanged); 34 /* add a IO_ERROR event listener: Listens for an I/O connectivity issue; 35 onError() function is called if the listener event occurs */ 36 response.addEventListener(IOErrorEvent.IO_ERROR, onError); 37 } 38 // handler function for HTTPStatusEvent events 39 public function statusChanged(status:HTTPStatusEvent):void { 40 // remove the watch glass or busy cursor 41 CursorManager.removeBusyCursor(); 42 // conditional to check the status 43 if (status.status == 0 || status.status == 404) { 44 iStatus = 0; 45 } else { 46 iStatus = 1; 47 } 48 //Alert.show(iStatus.toString()); 49 } 50 // handler function for IOErrorEvent events 51 public function onError(error:IOErrorEvent):void { 52 // remove the watch glass or busy cursor 53 CursorManager.removeBusyCursor();
361
362
HOUR 21: Building an AIR Application
54 55 56 57 58 59 60 61 } 62}
iStatus = 0; } // handler function for networkChangeEvent events public function onConnectionChange(networkChangeEvent:Event):void { // check the connection checkConnection(); }
Retrieving the Server-Side Data Listing 21.7 shows the ColdFusion component (CFC) or server-side powerhouse. A walk-through on the code is beyond the scope of this book. It is important to understand the mechanics of this CFC (albeit for a ColdFusion developer the parts of the machinery are also important).
SELECT flightid, flightnum, flightdetails, flightlookuptimestamp FROM ➥tblflightinfo WHERE userip = AND flightnum = ORDER BY flightlookuptimestamp ASC
var qSelect = ““; userip = getVisitorIP();
SELECT * FROM tblflightinfo WHERE userip = AND flightnum = AND flightid =
Coding Your Application
The first function inside the CFC is getFlightDetails, and this is the function that utilizes the CFHTTP tag, a syndication tag or screen scraper. It reaches out (a GET call) and communicates with an external URL (such as http://flightaware.com/live/flight/ #arguments.flightnumber#) to provide the data that fills the real-time HTML control. The #arguments.flightnumber# is the CFML syntax for passing in (or receiving) data into a CFC function. An interesting piece of code is shown in line 16, as it, in effect, creates a 2,000-millisecond delay. Lines 17–25 clears all the unwanted data from the screen scrape (no need for headers, sidebars, or footers). Line 26 calls the next function, writeFlightDetails, passing the flight HTML data and the flight number to the function. The writeFlightDetails function writes the flight data to the server-side mySQL 5 database table, tblflightinfo. In line 60, another function, getArchivedFlights, is the power behind filling the data grid with the archived flight data. Line 81 is the getArchivedFlightDetails function that retrieves the flight information when the end user clicks on one of the rows in the data grid of archived flights. So there you have it. I have built an AIR application that, if furthered refined, could prove useful to some end users. Of course, I would never release this application in the current state. As mentioned earlier in this hour, other features could improve this application, particularly adding a SQLite local database and a synchronization feature to the server-side database. You covered a great deal of material in this hour, and you should now understand one approach for building your AIR applications. Before starting the next hour, you should review what you have learned in the following Workshop.
Workshop The workshop contains an exercise to help reinforce what you’ve learned in this hour.
Exercises I am interested in hearing your feedback and your approach to building an AIR application. Email your feedback to [email protected].
365
This page intentionally left blank
Meet the Certificate Authorities
367
HOUR 22
Signing AIR Applications In this hour, you’ll learn . . . .
About certificate authorities Obtaining a certificate Leveraging a publisher identifier Using a timestamping server
Meet the Certificate Authorities Previous hours had at least a passing mention of digital certificates. At the risk of sounding like a broken record, I must say the importance of digitally signing your AIR applications can’t be minimized because AIR applications continue to spread onto end users’ desktops.
An .air file cannot be created without digitally signing the application, at a bare minimum, with a self-signed certificate.
During the initial dialog of an AIR application’s installation, if it does not have a valid digital certificate from a certificate authority (CA), the publisher shows as Unknown. Figure 22.1 shows a screen capture of this issue. Let’s clean this issue up by selecting a certificate authority. Two of the largest certificate authorities are well known in the information technology security arena: VeriSign (http://www.verisign.com/products-services/securityservices/code-signing/digital-ids-code-signing/) and Thawte (http://www.thawte.com/ code-signing/index.html). Doing a quick Google search you can find other CAs, such as GlobalSign (http://www.globalsign.com/developer/code-signing-certificate/ index.htm).
Watch Out!
368
HOUR 22: Signing AIR Applications
FIGURE 22.1 The dreaded Unknown Publisher dialog.
Selecting a certificate authority is a personal matter of course, but you might want to consult with others who have actually obtained a certificate from a CA. The “Exercises” section at the end of this hour contains a link to a blog where readers who have obtained a digital certificate from a CA can share their experiences.
Obtaining a Certificate Here is my personal experience with obtaining a digital certificate from Thawte. The steps I followed are as follows:
1. Using the Firefox browser (version 2+), browse to http://www.thawte.com/ code-signing/index.html?click=main-nav-products-codesigning. Click the Click Here to Buy button (see Figure 22.2).
2. Select the Adobe®AIR™ Developer Certificate radio button and click the Submit button.
3. Complete the three-step enrollment process:
. Configure your enrollment by answering questions about how long you want the certificate to last before expiration (one or two years) and your organization (or personal) information, including company name, type of organization, contact information, strength of encryption, and selected password. The site also offers several payment methods: credit card, check, or wire transfer.
Obtaining a Certificate
369
. Confirm your enrollment information and click the Accept button at the bottom of the page (see Figure 22.3). You are given the opportunity to read the Thawte Code Signing Certificate Subscriber Agreement or download it at https://www.thawte.com/repository/pdf/ thawte_codesigning_cert_agreement.pdf.
. Complete the enrollment form. FIGURE 22.2 Clicking the Click Here to Buy button kicks off the process.
FIGURE 22.3 Confirming your certificate enrollment.
370
By the Way
HOUR 22: Signing AIR Applications
After completing the enrollment, it might take some time (as in days) for Thawte to verify the information you submitted. The steps it takes to validate your information are extensive. You can read more about it at https://www.thawte.com/ ssl-digital-certificates/free-guides-whitepapers/pdf/enroll_codesign_eng.pdf.
4. After your information is verified, you should receive an email from Thawte with instructions on how to retrieve the certificate. It is important that you retrieve the certificate using Firefox because you will need the Firefox browser to export the certificate in a format that the Adobe code signing tools can use. Follow the emailed instructions carefully, and click on the link contained in it (again make sure it opens in the Firefox browser). Log in to the Thawte website using the password you created in Step 3.
5. After you are logged in, click the Fetch button to obtain the certificate. This automatically installs your certificate into your Firefox browser’s certificate manager.
6. Next, open the Firefox browser’s certificate manager by selecting Tools/Options from the menu, clicking the Advanced icon, selecting the Encryption tab, and clicking on the View Certificates button as shown in Figure 22.4.
FIGURE 22.4 Opening the Firefox browser’s Encryption tab.
Obtaining a Certificate
371
Figure 22.5 shows the view of the Thawte certificate.
FIGURE 22.5 View of the Thawte certificate for U Saw It Enterprises.
7. Next, you need to export your certificate. Select it and then click the Backup button. The Firefox browser saves your certificate and private key in the PKCS12 format (this is the new certificate that you will use for digitally signing
your AIR applications).
8. In the last step, you are presented with a dialog where you enter the location you want to store your certificate.
With this new certificate, you are no longer an unknown publisher, and end users will come to respect and trust you in time. Figure 22.6 shows the results.
FIGURE 22.6 U Saw It Enterprises, the AIR application publisher.
372
HOUR 22: Signing AIR Applications
So how does the AIR runtime and installer read the publisher information? The next section in this hour discusses this topic.
Leveraging a Publisher Identifier In Hour 18, “Encryption and Security in AIR,” you saw that as part of the process of building an .air file, the AIR Developer Tool (ADT) generates a publisher ID unique to the certificate used to build the .air file. If you reuse the same certificate for all of your AIR applications, they will all have the same publisher ID. This is how your repeat AIR application end users develop a trusting relationship with you, the publisher. They see the quality of your work and the lack of security-related issues, and your AIR applications are readily accepted. The publisher ID is also used to identify an AIR application in local connection communications. You can identify the publisher ID of an installed application by writing code like the following: NativeApplication.nativeApplication.publisherID;
Figure 22.7 shows the publisher ID for a self-signed digital certificate on a Windows OS.
FIGURE 22.7 The publisher ID for a self-signed digital certificate on a Windows OS.
It is important to remember that during the generation or regeneration of a digital certificate, the fields used to generate a certificate must be exactly the same if the publisher ID is to remain the same. In addition, the root certificate of a CA-issued certificate and the public key of the certificate must be the same. The possible fields used to generate the publisher ID are Name, CommonName, Surname, GivenName, Initials, GenerationQualifier, DNQualifier, CountryName, LocalityName, StateOrProvinceName, OrganizationName, OrganizationalUnitName, Title, Email, SerialNumber, DomainComponent, Pseudonym, BusinessCategory, StreetAddress, PostalCode, PostalAddress, DateOfBirth, PlaceOfBirth, Gender, CountryOfCitizenship, CountryOfResidence, and NameAtBirth.
Using a Timestamping Server
373
Using a Timestamping Server In Hour 18, you saw quite a bit of information about timestamping your AIR applications during the digital signing. You will recall that when you sign an AIR file with any of the integrated development environments (IDEs) or the ADT, the packaging tool queries a timestamp authority server to obtain a third-party, impartial, and verifiable date and time of signing—a timestamp. The timestamp obtained is embedded in the AIR file. By timestamping your .air file (as long as the signing certificate is valid at the time of signing), the AIR file can be installed, even after the certificate has expired. Otherwise, if no timestamp is obtained, the AIR file will cease to be installable when the certificate expires or is invalidated. By default, some of the AIR development IDEs packaging tools will obtain a timestamp. However, to allow applications to be packaged when the timestamp service is unavailable, you can turn timestamping off. The official position that Adobe recommends is that all publicly distributed AIR files should include a timestamp. The default timestamp authority used by the AIR packaging tools is Geotrust (this is adjustable when using the ADT from the command line: -tsa url). The timestamping server must be RFC3161-compliant (http:// www.ietf.org/rfc/rfc3161.txt). That was a quick review of what you have seen in earlier hours, so now let’s examine some alternative timestamping servers. A Google search for free timestamping servers found OpenTSA (http://www.opentsa.org/). One of the OpenTSA site’s resources links (http://security.polito.it/ts/) is a collection of timestamping-related links and implementations. This link leads you to http://security.polito.it/ts/#pubtsa, a list of publicly available timestamp authorities. If you are unable to connect to a timestamping server with the ADT (see Figure 22.8), you can use the -tsa none command to complete the generation of the .air file.
FIGURE 22.8 “Could not generate timestamp” message from the ADT.
Another busy hour and you covered a great deal of material. You should now understand how and why to sign your AIR applications with a digital certificate from a certificate authority. Before starting the next hour, you should review what you have learned in the following Workshop.
374
HOUR 22: Signing AIR Applications
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. The VeriSign and Thawte digital certificates are too expensive for my budget.
Are there any less expensive alternatives? A. Yes, perhaps. You should search for possible free offers, as they have existed in the past. For example, the Adobe AIR Marketplace offered a free Thawte code signing certificate during the writing of this Hour.
Q. Do I have to use the Firefox browser to obtain a digital certificate? A. Not at all. You may use other browsers by following the instructions supplied by Microsoft Authenticode, VeriSign, or Thawte.
Q. What does a CA digital certificate actually do? A. A CA digital certificate simply confirms that software (such as an AIR application) has indeed come from the publisher who has signed it.
Q. What does the unknown publisher in the AIR installer signal to a savvy end
user? A. The unknown publisher immediately implies that the AIR application includes a self-signed certificate and not one issued by a CA.
Quiz 1. Can you use a different timestamping authority server? 2. Can you package an AIR application without supplying a digital certificate? 3. What happens to a publisher ID if any of the fields used to generate the ID are changed?
4. How can you create your .air file without timestamping it?
Workshop
Answers 1. The default timestamp authority used by the AIR packaging tools is Geotrust, but that is adjustable when using the ADT by adding the following into the command line: -tsa url. The timestamping server must be RFC3161-compliant.
2. Adobe was so concerned with AIR applications’ safe deployment that you cannot build an AIR package for distribution without adding a digital certificate to the generated .air file. You can test the packaging process with a self-signed certificate created in Flex Builder 3, Dreamweaver CS3 with the Dreamweaver CS3 AIR extension, or Flash CS3 Professional with the Flash CS3 AIR upgrade, but Adobe does not recommend doing this for the final version you will distribute.
3. For the generation or regeneration of a self-signed certificate, the fields used to generate a certificate must be exactly the same if the publisher ID is to remain the same. In addition, the root certificate of a CA-issued certificate and the public key of a self-signed certificate must be the same. The possible fields used to generate the publisher ID are Name, CommonName, Surname, GivenName, Initials, GenerationQualifier, DNQualifier, CountryName, localityName, StateOrProvinceName, OrganizationName, OrganizationalUnitName, Title, Email, SerialNumber, DomainComponent, Pseudonym, BusinessCategory, StreetAddress, PostalCode, PostalAddress, DateOfBirth, PlaceOfBirth, Gender, CountryOfCitizenship, CountryOfResidence, and NameAtBirth.
4. If you choose to not timestamp your .air file, you can use the -tsa none command to complete the generation of the .air file without timestamping.
Exercises In an effort to hear from those who have experience in obtaining a digital certificate from a certificate authority, this blog post, http://www.flexination.info/archives/ entries/CD6B1BF6-FD32-F4F3-F3D6B70524260DF2.shtml, asks the following questions:
1. Who is the best CA for AIR applications? 2. In your opinion, what makes them the best CA?
Please feel free to post your comments on the blog, or you can email your comments to [email protected]. Your comments will be considered for inclusion in future revisions of this title.
375
This page intentionally left blank
Using the Updater Class
377
HOUR 23
Updating AIR Applications After Deployment In this hour, you’ll learn . Using the Updater class . Updating an AIR application . Remotely updating AIR applications
Using the Updater Class In this hour, you will see how to update a previously deployed AIR application. If for no other reason than to support a new version of the AIR runtime, being able to update your AIR applications is a must-have feature.
During the initial evolution of AIR, the XML-based application descriptor has changed and required regeneration of the .air file. In some cases, changes in the AIR APIs have required tweaks to the code.
Watch Out!
You might recognize some similarity between the issue of keeping deployed AIR applications updated to the latest and greatest versions and the “DLL hell” of clientserver desktop applications of the 1990s.
A number of problems were commonly encountered with DLL files, especially after numerous applications had been installed and uninstalled on a system. The problems include conflicts between DLL versions, missing required DLLs, and orphaned, unnecessary DLL copies. These problems are often referred to as DLL hell.
By the Way
378
HOUR 23: Updating AIR Applications After Deployment
Fortunately with AIR, you can avoid this issue, as this update capability is part of the AIR runtime. With just a minimal amount of developer effort, the AIR applications you write can seamlessly update the version and features by a detection-andnotification capability. As soon as new updates are available, previously deployed applications can be automatically updated (the end user can still opt out from any update). The capability for a deployed AIR application to periodically test for updates allows the update process to be driven by the deployed desktop application. This resembles the old school client/server paradigm, where the server maintains the latest and greatest version of the application and the client simply utilizes the latest deployed server application. This auto-update feature eliminates the painful distribution processes of the past where a system administrator had to go desktop to desktop to upgrade an application. Keep in mind that the manual methods of updating still work; end users can still update an AIR application by double-clicking on a new .air file on their computer or clicking on an Install Now badge from a browser, using the seamless install feature. The physical .air file can be supplied in an email, downloaded from a website, found on a mailed CD-ROM or DVD, or located in an AIR library, such as the ones found on the AIR Marketplace or a third-party site such as O2Apps.com. Regardless of the update source, the AIR installer application manages the update, alerting the user if an already existing application is being updated. The class that is used for updating AIR applications is the AIR-only Updater class. It comes in the flash.desktop package. Aside from the constructor, the Updater class includes a single public method, update(), which updates the running version of an AIR application to a version contained in the specified AIR file. You should use the update() method of the Updater class to kick off the installation dialog for an upgrade to your AIR application. As can be seen in the AIR Flex 3 API application, the update() method requires that a reference to the AIR file (File class) and the version (String class) be passed when calling it. After this method is called, the currently running AIR application closes and a new AIR installer dialog opens. The end user is then prompted to update the application, uninstall the currently installed application, run the currently installed version, or cancel the installation process. The code in Listing 23.1 demonstrates the type of code you will write to accomplish this. (You must instantiate an Updater object and call the update() method on it as this method is not static.)
LISTING 23.1
AIR Using the Updater Class
import flash.fileSystem.File; import flash.desktop.Updater; // instantiate the Updater object var myUpdater:Updater = new Updater(); // instantiate a file reference to the .air file
Using the Updater Class
379
var myAIRFile:File = File.applicationStore.resolvePath(“TYAIRin24_v2.air”); // initialize the version variable as a String var myVersion:String = “v2”; // call the update method passing in the air file and the version ➥variablemyUpdater.update(myAIRFile, myVersion);
If you try to run the update() method directly from the AIR Debug Launcher (ADL) as you do when testing your application in Adobe Flex Builder or from a command prompt, you will see this error: “Error: This method is not supported if application is launched from ADL.”
Did you Know?
The end user sees the dialog shown in Figure 23.1 during the upgrade process. Note that if the updated AIR application requires an updated AIR runtime, this step is also handled during the installation process and under the complete control of your end user. Because an end user can ignore the upgrade request of the AIR runtime or omit it due to inadequate administrative permissions, it is the developer’s responsibility to write code to handle the unexpected actions of the end users to prevent possible endless loops of the installation process.
FIGURE 23.1 AIR application Update dialog.
After the AIR application has been updated, rerunning the same .air file results in the dialog shown in Figure 23.2.
380
HOUR 23: Updating AIR Applications After Deployment
FIGURE 23.2 AIR application Version Already Exists dialog.
Updating an AIR application When updating your AIR applications, you should follow these general steps:
1. Determine the update version of your application. For example, in the sample code shown in Listing 23.2, the version you want to update to is TYAIRin24_v2.
2. Provide instructions on how to obtain the updated .air file or provide a delivery mechanism for delivering the new version of the AIR application to the end user. For example, a copy of the AIR file (in this example, TYAIRin24_v2.air) is downloaded to the desktop. Additional error-handling code leveraging the exists() method from the File class is shown in Listing 23.2, line 26. This
line of code handles .air file version mismatches.
LISTING 23.2
Updating an Application
1 2 3
4
40 41 42
3. Instantiate the Updater class. 4. Call the update() method of the Updater class, passing in a File object that corresponds to the new AIR file and the version number in a string.
5. Call the testVersion() function that you placed in your AIR application (in Listing 23.2, it is in line 7) to ensure that the AIR application detects that the version has been updated. This ensures that your user does not get caught in an endless loop installation scenario.
6. The AIR runtime shuts down your AIR application, installs the new version, and then restarts the application. Clicking on the Check Updates button calls the check4Updates() function in line 19. This function displays an alert, as shown in Figure 23.3.
FIGURE 23.3 Upgrade success.
382
HOUR 23: Updating AIR Applications After Deployment
Now that you have seen a manual type of AIR application update, let’s take a look at a server-side controlled update.
Updating AIR Applications Remotely Another method for updating an AIR application is through a remote server monitoring approach. An Internet-accessible, remote .air file is examined for changes in the XML-based descriptor file. As changes in the application descriptor file’s version are detected, your AIR application can monitor changes to the .air file on a remote server through a monitoring method that you program into your AIR application. The method is remotely alerted that an updated .air file is available on the server, and the user can receive an alert from the running AIR application that an upgrade is available. Listing 23.3 shows an example of this type of .air version monitoring. The applicationComplete event, in line 2, runs each time the application starts and triggers the checkForRemoteUpdates() function that contacts the remote server. (The actual call is done by the HTTPService send() method of myService (the id of the HTTPService), shown in line 11.) It checks the version information for the lat-
est and greatest .air file by some server-side technology. If a more proactive and frequent check is required, simply add a timer-based function that does the polling of the remote server more frequently.
LISTING 23.3
Check for Remote Updates
1 2 3
4
5
Figure 23.4 shows the result of running this example AIR application. You completed another hour, and you should now understand how to update your deployed AIR applications. Before starting the next hour, review what you have learned in the following Workshop.
FIGURE 23.4 AIR application remote upgrade available.
384
HOUR 23: Updating AIR Applications After Deployment
Workshop The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you’ve learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.
Q&A Q. Can the Updater class handle automatic AIR runtime upgrades as well as
AIR application updates? A. Yes, the Updater class can upgrade both the AIR runtime as well as the actual AIR application.
Q. Does a change in the XML of the application descriptor require updating the .air file?
A. Yes. When the content in the AIR descriptor file changes, the .air file must be re-created to update the AIR application.
Q. Can you force your end users to upgrade your AIR application as you
improve it? A. No, you cannot force an end user to upgrade your AIR application; you can certainly compel them to upgrade by explaining how the update will solve world hunger.
Q. Why would you want to create a server-side remote upgrade process? A. A server-side remote upgrade process can make the upgrade process much less of a hassle in the deployment of an upgraded AIR application. The server-side deployment keeps you from having to call, email, or otherwise contact the end users of your application about the availability of an upgrade; instead your application will troll for upgrades each time it is run.
Quiz 1. Describe the general steps you take to manually upgrade an AIR application. 2. Can you read properties in the application descriptor? 3. What is the exists() method from the File class used for?
Workshop
4. If you try to run the update() method directly from the AIR Debug Launcher (ADL), as you do when testing your application in Adobe Flex Builder, what happens?
Answers 1. When updating your AIR applications, you should follow these general steps: A. Determine the update version of your application. B. Provide instructions on how to obtain the updated .air file or provide a delivery mechanism for delivering the new version of the AIR application to the end user. C. Instantiate the Updater class. D. Call the update() method of the Updater class, passing in a File object that corresponds to the new AIR file and the version number in a string. E. Call the “installation successful” function that you placed in your AIR application to ensure that the AIR application detects that the version has been updated. This ensures that your user does not get caught in an endless loop installation scenario. F. The AIR runtime shuts down your AIR application, installs the new version, and then restarts the application.
2. Yes, you can read properties in the application descriptor with code similar to this: var appDescriptor:XML = ➥NativeApplication.nativeApplication.applicationDescriptor; var ns:Namespace = appDescriptor.namespace(); var appVersion:String = appDescriptor.ns::version;
3. The exists() method of the File class ensures that the updated .air file is available.
4. If you try to run the update() method directly from the AIR Debug Launcher (ADL), as you do when testing your application in Adobe Flex Builder or from a command prompt, you will see this error: “Error: This method is not supported if application is launched from ADL.”
Exercises Develop a server-side example of a remote upgrade technique, create an archive zip of the files, and email it to [email protected]. Your approach will be considered for inclusion in future revisions of this title.
385
This page intentionally left blank
Using the AIR Documentation
HOUR 24
Where Do I Go from Here? In this hour, you’ll learn . Using the AIR documentation . Accessing other resources, such as the Adobe Developer Connection
Using the AIR Documentation In this hour, you will see some suggestions on how to continue learning about and improving your understanding of AIR. Each day more and more AIR resources pop up on the Internet. As developers continue to flock to this new Adobe product, the amount of information is improving both in quantity and quality. A suggested first stop is reviewing the voluminous amount of documentation available from Adobe. The AIR Flex 3 API application that you used throughout the reading of this title was created from just a single set of informative HTML/JavaScript-based files supplied in the AIR SDK. The AIR SDK also contains no fewer than seven instructional PDF files. You can download the AIR SDK from http://airdownload.adobe.com/air/win/ download/latest/AdobeAIRSDK.zip. After you extract the archive, you see these PDFs:
. Developing Adobe AIR Applications with Adobe Flash CS3 Professional (dev_guide_flash.pdf)
. Developing Adobe AIR Applications with HTML and AJAX (dev_guide_html.pdf)
. Building and Deploying Adobe Flex 3 Applications (air_build_deploy_flex3.pdf)
387
388
HOUR 24: Where Do I Go from Here?
. Using Adobe Flex Builder 3 (air_using_fb_flex3.pdf) . Creating and Extending Adobe Flex 3 Components (datavis_flex3.pdf) . Developing Adobe AIR Applications with Adobe Flex 3 (dev_guide_flex_air1.pdf)
. Adobe Flex 3 Developer Guide (devguide_flex3.pdf) If you have an Internet connection, the documentation is available in LiveDocs. A list of these documents is available at http://www.adobe.com/support/ documentation/en/air/. Finally in this category of useful help-related information, you should take a peek at the AIR Forums (http://www.adobe.com/cfusion/webforums/forum/ index.cfm?forumid=75).
Meet the Adobe Developer Connection AIR developers, welcome to the Adobe AIR Developer Center (http://www.adobe.com/ devnet/air/). If you are not aware of this resource, which is pictured in Figure 24.1, it is important that you take a look at this valuable web application. It is packed full of articles written by the leading AIR developers and authors.
FIGURE 24.1 Home page of the Adobe AIR Developer Center.
Meet the Adobe Developer Connection
The Adobe AIR Developer Center includes Home, Getting Started, Samples, Downloads, Community, and Cookbook (Beta) tabs.
Home The Home tab contains information about the AIR runtime and links that are segregated by the type of developer:
. Develop with HTML/Ajax . Develop with Flash . Develop with Flex Additional sections of content include featured articles and tutorials, tools to build on Adobe AIR, popular Adobe AIR bloggers, and a list of weblogs, upcoming events, and recent articles.
Getting Started The Getting Started tab contains links to information about starting to build applications using HTML, JavaScript, Flash, or Flex. More detailed content about developing with HTML, Ajax, Flash, and Flex is available, too.
Samples The Samples tab contains sample applications for ideas and demonstrations of what you can build with AIR. Figure 24.2 shows a few of these sample AIR applications.
Downloads The Downloads tab contains sections of content including
. Software and tools to develop on Adobe AIR . Software related to Adobe AIR . Community tools and frameworks
Community The Community tab contains on-demand presentations, community resources, Adobe resources, Adobe user groups, and Adobe AIR events.
389
390
HOUR 24: Where Do I Go from Here?
FIGURE 24.2 Adobe AIR Developer Center sample applications.
Cookbook (Beta) The Cookbook (Beta) tab allows developers to share knowledge and find answers to common coding problems, as well as to post comments and rate posted contributions.
Meet the Adobe XML News Aggregator for AIR Another great repository for what’s going on in AIR development is the Adobe XML News Aggregator (http://feeds.adobe.com/index.cfm?query= bySmartCategory&smartCategoryId=28&smartCategoryName= AIR&smartCategoryKey=F2DFD9E0-FBB6-4C2D-2AFE6AFD941FDDB1). The Adobe XML News Aggregator allows you to create custom RSS feeds so you can read personalized Adobe news in your own RSS aggregator. Start by selecting the language you want to receive Adobe news in, and then further customize your RSS feed by selecting additional topic criteria. After you have generated your personalized RSS feed, copy the URL from your browser’s location bar and paste it into your RSS aggregator. Figure 24.3 shows the AIR-related blog posts for August 20, 2008. As you see in this figure, the topics are varied but you can still learn quite a bit from reading the posts.
Meet the Adobe AIR Marketplace
391
FIGURE 24.3 Adobe XML News Aggregator for AIR posts for August 20, 2008.
Meet the Adobe AIR Marketplace The Adobe AIR Marketplace is a place where AIR developers can publish their AIR applications for users to download. The Adobe AIR Marketplace is at http://www.adobe.com/cfusion/exchange/index.cfm?event=productHome&exc=24& loc=en_us. This is a great place to be inspired with the work that other developers are creating for the AIR runtime. There is a business model for you to publish your AIR applications, at some point in time, for profit; however, as of August 2008, all AIR Marketplace applications are either shareware, freeware, or demo. Figure 24.4 shows a screen capture of the home page for the Adobe AIR Marketplace. You made it. The last hour in this title is now complete. You should now understand how to find additional resources for developing AIR applications. I hope you enjoyed the reading and found the information presented helpful. You covered a great deal of material in this book. Before moving to the appendixes, you should give the exercise in the Workshop a try.
392
HOUR 24: Where Do I Go from Here?
FIGURE 24.4 Home page for the Adobe AIR Marketplace.
Workshop The following workshop contains an exercise to help reinforce what you’ve learned in this hour.
Exercises Perform a search for AIR development information, and if you find some especially helpful, email the links to [email protected]. Your links will be considered for inclusion in future revisions of this title.
PART IV
Appendixes APPENDIX A
AIR and Flex 3 API Reference
395
APPENDIX B
Additional Resources for AIR Developers
397
This page intentionally left blank
395
APPENDIX A
AIR and Flex 3 API Reference Throughout the early hours of this book, you were prompted to download and install the HTML/JavaScript-based AIR application that included the AIR 1.5/Flex 3 API documentation. If for some reason you missed those prompts, you may download the AIR 1.5 / Flex 3 API application from http://www.airination.info/airtraining/ airflex3api/AIRFlex3API_v1.air. Because the AIR/Flex 3 APIs are continuing to evolve, recompiling this AIR application is highly encouraged. If you would like to recompile this AIR application from scratch, you can follow these steps:
1. Download and extract the AIR SDK from http://airdownload.adobe.com/air/ win/download/latest/AdobeAIRSDK.zip.
2. After it is extracted, copy all the files and subfolders from {AIRSDKInstallFolder}\AIR1_flex_docs\langref to C:\AIRFlex3API.
3. Create and store an AIR application descriptor file (name it AIRFLEX3APIapp.xml) in the C:\AIRFlex3API folder, with this content:
If the AIR runtime xmlns changes, you might need to adjust it in the application descriptor.
4. Create the four icons (airicon16x16.png, airicon32x32.png, airicon48x48.png, and airicon128x128.png) that are referenced in the AIRFLEX3API-app.xml file. You can also download the icons used from
http://www.airination.info/airtraining/tyairin24/AIRFlex3API.zip. This zip archive also includes the application descriptor file and an ADTForAIRExample.bat file with the ADT commands needed to package the
AIR application.
5. Extract the AIRFlex3API.zip archive to a temporary folder and copy the four icons into the C:\AIRFlex3API\ AIR1_flex_docs\langref\images folder. Copy the AIRFLEX3API-app.xml file to one folder level higher: C:\AIRFlex3API\ AIR1_flex_docs\langref. The remaining ADTForAIRExample.bat file can be opened with your favorite text editor.
6. Run the commands found in the ADTForAIRExample.bat one by one in a command prompt window: cd\ cd AIRFLEX3API adt -certificate -cn “XYZ AIR Development Services, Inc.” 2048-RSA myCert.pfx tyairin24 adt -package -storetype pkcs12 -keystore myCert.pfx -tsa none “AIRFLEX3API.air” AIRFLEX3API-app.xml . tyairin24
These commands create the AIRFLEX3API.air file.
7. Double-click the AIRFLEX3API.air file to install your new AIR application.
You have successfully created the AIR Flex 3 API application. You can use this valuable resource any time you want to look up information for an AIR or Flex 3 API, a class, or a package. I think you will find this much speedier than wading through other types of help documentation or an online search engine.
397
APPENDIX B
Additional Resources for AIR Developers Adobe Resource
J–K–L JavaScript AIR API classes, accessing, 102-106 coding practices, 108, 110 HTML-based AIR applications, importing libraries to, 96-97 security, 108, 110 leveraging server-side features HTTP communication, 337-338 messaging, 339-340 remoting, 333-335 web services, 336-337 Linux AIR runtime installations, 19, 21 AIR SDK installations, 24 Loader class, 277, 279-280 local data storage, 287 local shared objects, 289-291 local SQL databases, 292-297 writing data to file systems, 288-289 local shared objects, 289-291 local SQL databases, 292-297 logins, encrypted data storage, 307
M Mac OS X AIR runtime installations, 19, 21 suggested minimum configurations, 18-19 testing, 19 AIR SDK installations, 22-23 Dock icon, bouncing, 325-327 maximizable node (XML), 67 maxSize node (XML), 68 menus application menus, 259, 261 context menus, 267 Dock icon menus, 264-265 pop-up menus, 268-269 System Tray icon menus, 266 window menus, 262-263 messagecolor parameter (flashvars), 39 messages could not generate timestamp messages, 373 toast messages, creating, 319-323 messaging, leveraging, 339-340 minimizable node (XML), 67 minSize node (XML), 68 missing directories, creating, 228 monitorConnectionStatus( ) function, 81-82 monitoring Internet connections (application build process), 360-362 mx.core.Window class, creating windows via, 187-189
N name node (XML), 65 nativeDragComplete event, 242 NativeDragManager class, 235-236, 238 NativeDragOptions class, 237 nativeDragStart event, 241
nativeDragUpdate event, 241-242 NativeMenu class, 257, 259 NativeMenuItem class, 257 NativeWindow class creating windows via, 183, 185-187 moving windows via, 188 NativeWindowInitOptions class, properties of, 184 NetStatusEvent class, 276-277 network connectivity, 273 HTTPStatusEvent class, 274-276 Loader class, 277, 279-280 NetStatusEvent class, 276-277 ServiceMonitor class, 280-281 URLMonitor class, 282-284 New Flex Project Wizard (Flex Builder 3), 57-58 New Project Wizard (Aptana Studio), 94 New Site option (Dreamweaver CS3, Site menu), 122 news aggregators, Adobe XML, 390 nonapplication sandbox, 16 notifications Dock icon (Mac OS), bouncing, 325-327 status bar notifications, creating, 315-317 system tray icons, creating, 323-325 toast messages, creating, 319-323 Windows Taskbar, highlighting, 318
T taskbar (Windows), highlighting, 318 testing AIR applications (Flex Builder 3), 48 HTML-based AIR applications, 99-100 TextPad, Dreamweaver CS3 versus, 114 Timer class, 217 timer functions (Flex-based AIR applications), 79-80 Timestamp check box (Flash CS3), 120 timestamping, 17 AIR codes, 308-309 GeoTrust, 18 timestamping servers, 373 title node (XML), 66 toast messages, creating, 319-323 ToolTips (Flex-based AIR applications), 86-87 transparent node (XML), 66 troubleshooting application descriptor files, 63
U Updated Adobe AIR dialog, 163 updates to AIR applications manual updates, 380-381 remote updates, 382-383 Updater class, 377-378, 381 application descriptor files, 68 URLMonitor class, 282-284 Use Custom UI for Updates check box (Flash CS3), 118 user interfaces application descriptor files, 68 Flex-based AIR applications, 86-87
How can we make this index more useful? Email us at [email protected]
408
user notifications
user notifications Dock icon (Mac OS), bouncing, 325-327 status bar notifications, creating, 315-317 system tray icons, creating, 323-325 toast messages, creating, 319-323 Windows Taskbar, highlighting, 318 username field (encrypted data storage), clearing, 307
W web pages, AIR application installations via, 166-170 web resources for developers, 397-398 Adobe AIR Developer Center, 388-390 Adobe AIR Marketplace, 391 Adobe XML News Aggregator, 390 Air forums, 388 web services, leveraging, 336-337 width node (XML), 67 window menus, 262-263
X–Z x node (XML), 67 XML application descriptor files. See application descriptor files applicationComplete tag, 74 content node, 66 copyright node, 65 creationComplete tag, 74 description node, 65 filename node, 64 height node, 67 maximizable node, 67 maxSize node, 68 minimizable node, 67 minSize node, 68 name node, 65 resizable node, 67 systemChrome node, 66 title node, 66 transparent node, 66 version node, 65 visible node, 67 width node, 67 x node, 67 y node, 67 y node (XML), 67
THIS PRODUCT informit.com/register Register the Addison-Wesley, Exam Cram, Prentice Hall, Que, and Sams products you own to unlock great benefits. To begin the registration process, simply go to informit.com/register to sign in or create an account. You will then be prompted to enter the 10- or 13-digit ISBN that appears on the back cover of your product.
About InformIT
Registering your products can unlock the following benefits: • Access to supplemental content, including bonus chapters, source code, or project files. • A coupon to be used on your next purchase. Registration benefits vary by product. Benefits will be listed on your Account page under Registered Products.
— THE TRUSTED TECHNOLOGY LEARNING SOURCE
INFORMIT IS HOME TO THE LEADING TECHNOLOGY PUBLISHING IMPRINTS Addison-Wesley Professional, Cisco Press, Exam Cram, IBM Press, Prentice Hall Professional, Que, and Sams. Here you will gain access to quality and trusted content and resources from the authors, creators, innovators, and leaders of technology. Whether you’re looking for a book on a new technology, a helpful article, timely newsletters, or access to the Safari Books Online digital library, InformIT has a solution for you.
informIT.com
THE TRUSTED TECHNOLOGY LEARNING SOURCE
Addison-Wesley | Cisco Press | Exam Cram IBM Press | Que | Prentice Hall | Sams SAFARI BOOKS ONLINE
Take
Adobe AIR ®
™
to the Next Step All the expert knowledge and proven code you need to build state-of-the-art rich desktop applications with the breakthrough AIR platform.
Adobe AIR development team member Stacy Tyler Young illustrates the power of this ®
technology through real-life application examples based on the official AIR release. You’ll discover how AIR helps you solve problems you just couldn’t solve before by extending the reach of your Web applications onto users’ Windows, Mac, or Linux desktops. Then, building on your existing HTML, JavaScript, Ajax, or Adobe Flex skills, you’ll master the powerful AIR API—moving quickly from task-oriented examples to larger-scale, real-world projects. Young doesn’t just cover coding: He helps you maximize your effectiveness throughout the entire development lifecycle, via AIR design patterns, frameworks, continuous integration, custom builds, and automated testing.
Learn more about this title and read sample material at informit.com/title/9780672329715 informit.com/sams
Also Available in Safari Books Online.
Sams Teach Yourself When you only have time for the answers™ Whatever your need and whatever your time frame, there’s a Sams TeachYourself book for you. With a Sams TeachYourself book as your guide, you can quickly get up to speed on just about any new product or technology—in the absolute shortest period of time possible. Guaranteed. Learning how to do new things with your computer shouldn’t be tedious or time-consuming. Sams TeachYourself makes learning anything quick, easy, and even a little bit fun.
Windows Server 2008 in 24 Hours Joe Habraken ISBN-13: 978-0-672-33012-4
ASP.NET 3.5 in 24 Hours
Visual Basic 2008 in 24 Hours
Scott Mitchell
James Foxall
ISBN-13: 978-0-672-32997-5
ISBN-13: 978-0-672-32984-5
SQL in 24 Hours, Fourth Edition Ryan Stephens Ron Plew Arie Jones
Microsoft SQL Server T-SQL in 10 Minutes Ben Forta ISBN-13: 978-0-672-32867-1
ISBN-13: 978-0-672-33018-6
Sams Teach Yourself books are available at most retail and online bookstores, in both print and e-book versions. For more information or to order direct visit our online bookstore at www.informit.com/sams Online editions of all Sams Teach Yourself titles are available by subscription from Safari Books Online at safari.samspublishing.com
Try Safari Books Online FREE Get online access to 5,000+ Books and Videos
FREE TRIAL—GET STARTED TODAY! www.informit.com/safaritrial Find trusted answers, fast Only Safari lets you search across thousands of best-selling books from the top technology publishers, including Addison-Wesley Professional, Cisco Press, O’Reilly, Prentice Hall, Que, and Sams.
Master the latest tools and techniques In addition to gaining access to an incredible inventory of technical books, Safari’s extensive collection of video tutorials lets you learn from the leading video training experts.
WAIT, THERE’S MORE! Keep your competitive edge With Rough Cuts, get access to the developing manuscript and be among the first to learn the newest technologies.
Stay current with emerging technologies Short Cuts and Quick Reference Sheets are short, concise, focused content created to get you up-to-speed quickly on new and cutting-edge technologies.
FREE Online Edition
Your purchase of Sams Teach Yourself Adobe AIR Programming in 24 Hours includes access to a free online edition for 45 days through the Safari Books Online subscription service. Nearly every Sams book is available online through Safari Books Online, along with more than 5,000 other technical books and videos from publishers such as Addison-Wesley Professional, Cisco Press, Exam Cram, IBM Press, O’Reilly, Prentice Hall, and Que.
SAFARI BOOKS ONLINE allows you to search for a specific answer, cut and paste code, download chapters, and stay current with emerging technologies.
Activate your FREE Online Edition at www.informit.com/safarifree STEP 1: Enter the coupon code: GHZSLZG. STEP 2: New Safari users, complete the brief registration form. Safari subscribers, just log in. If you have difficulty registering on Safari or accessing the online edition, please e-mail [email protected]