### Complete Full-Screen Video Player Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/rich-media-content/working-with-video/playing-video-in-full-screen-mode.md A comprehensive example demonstrating video playback setup, including NetConnection and NetStream, and initiating full-screen mode via a button click. Requires the fl.controls.Button component. ```actionscript package { import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import flash.display.StageDisplayState; import fl.controls.Button; import flash.display.Sprite; import flash.events.MouseEvent; import flash.events.FullScreenEvent; import flash.geom.Rectangle; public class FullScreenVideoExample extends Sprite { var fullScreenButton:Button = new Button(); var video:Video = new Video(); public function FullScreenVideoExample() { var videoConnection:NetConnection = new NetConnection(); videoConnection.connect(null); var videoStream:NetStream = new NetStream(videoConnection); videoStream.client = this; addChild(video); video.attachNetStream(videoStream); videoStream.play("http://www.helpexamples.com/flash/video/water.flv"); fullScreenButton.x = 100; fullScreenButton.y = 270; fullScreenButton.label = "Full Screen"; addChild(fullScreenButton); fullScreenButton.addEventListener(MouseEvent.CLICK, fullScreenButtonHandler); } private function fullScreenButtonHandler(event:MouseEvent) { var screenRectangle:Rectangle = new Rectangle(video.x, video.y, video.width, video.height); stage.fullScreenSourceRect = screenRectangle; stage.displayState = StageDisplayState.FULL_SCREEN; } public function onMetaData(infoObject:Object):void { // stub for callback function } } } ``` -------------------------------- ### App URL Scheme Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/html-content-in-adobe-air/programming-html-and-javascript-in-air/about-urls-in-air.md Example of an app URL pointing to a directory within the installed application's root. ```html app:/images ``` -------------------------------- ### Download a file using a server-side script with GET parameters Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/files-and-data/working-with-the-file-system/using-the-filereference-class.md This example shows how to download a file by passing parameters to a server-side script (e.g., ColdFusion) using the GET method. It includes necessary imports and error handling for the download process. ```actionscript package { import flash.display.Sprite; import flash.net.FileReference; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; public class DownloadFileExample extends Sprite { private var fileToDownload:FileReference; public function DownloadFileExample() { var request:URLRequest = new URLRequest(); request.url = "http://www.[yourdomain].com/downloadfile.cfm"; request.method = URLRequestMethod.GET; request.data = new URLVariables("id=2"); fileToDownload = new FileReference(); try { fileToDownload.download(request, "file2.txt"); } catch (error:Error) { trace("Unable to download file."); } } } } ``` -------------------------------- ### Basic Dynamic NetStream Setup Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/rich-media-content/working-with-video/writing-callback-methods-for-metadata-and-cue-points.md Instantiates a dynamic NetStream subclass and attaches it to a Video object for playback. This demonstrates the basic setup for a dynamic NetStream. ```actionscript var ns:DynamicCustomNetStream = new DynamicCustomNetStream(); ns.play("video.flv"); var vid:Video = new Video(); vid.attachNetStream(ns); addChild(vid); ``` -------------------------------- ### Set AIR Application to Start at Login Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/client-system-interaction/air-application-invokation-and-termination.md This snippet demonstrates how to set the `startAtLogin` property to `true` for an AIR application. It includes error handling for cases where the property cannot be set, such as when the application is not installed. The application must be installed for this to work correctly. ```actionscript package { import flash.desktop.InvokeEventReason; import flash.desktop.NativeApplication; import flash.display.Sprite; import flash.events.InvokeEvent; public class StartAtLogin extends Sprite { public function StartAtLogin() { try { NativeApplication.nativeApplication.startAtLogin = true; } catch ( e:Error ) { trace( "Cannot set startAtLogin:" + e.message ); } NativeApplication.nativeApplication.addEventListener( InvokeEvent.INVOKE, onInvoke ); } private function onInvoke( event:InvokeEvent ):void { if( event.reason == InvokeEventReason.LOGIN ) { //do background processing... trace( "Running in background..." ); } else { this.stage.nativeWindow.activate(); } } } } ``` -------------------------------- ### Initialize StageVideo and Video Event Listeners Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/rich-media-content/working-with-video/using-the-stagevideo-apis.md Set up StageVideoAvailabilityEvent and VideoEvent listeners in the ADDED_TO_STAGE event handler to ensure your application is visible and StageVideo is available. This example demonstrates the initial setup for net connections, video object, and event listeners. ```actionscript public class SimpleStageVideo extends Sprite private var nc:NetConnection; private var ns:NetStream; public function SimpleStageVideo() // Constructor for SimpleStageVideo class // Make sure the app is visible and stage available addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); } private function onAddedToStage(event:Event):void //... // Connections nc = new NetConnection(); nc.connect(null); ns = new NetStream(nc); ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); ns.client = this; // Screen video = new Video(); video.smoothing = true; // Video Events // the StageVideoEvent.STAGE_VIDEO_STATE informs you whether // StageVideo is available stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, onStageVideoState); // in case of fallback to Video, listen to the VideoEvent.RENDER_STATE // event to handle resize properly and know about the acceleration mode running video.addEventListener(VideoEvent.RENDER_STATE, videoStateChange); //... ``` -------------------------------- ### Display Page Setup Dialog Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/client-system-interaction/printing/advanced-printing-techniques.md Shows the operating system's Page Setup dialog. Always check PrintJob.supportsPageSetupDialog before calling. ```actionscript import flash.printing.PrintJob; var myPrintJob:PrintJob = new PrintJob(); //check for static property supportsPageSetupDialog of PrintJob class if (PrintJob.supportsPageSetupDialog) { myPrintJob.showPageSetupDialog(); } ``` -------------------------------- ### Initiate Window Resizing and Moving Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/client-system-interaction/working-with-air-native-windows/managing-windows.md This example demonstrates how to start resizing and moving operations on a native window. It requires the flash.display.Sprite and flash.events.MouseEvent classes. The resize and move operations are initiated by mouse down events on specific handle areas. ```ActionScript 3.0 package { import flash.display.Sprite; import flash.events.MouseEvent; import flash.display.NativeWindowResize; public class NativeWindowResizeExample extends Sprite { public function NativeWindowResizeExample():void { // Fills a background area. this.graphics.beginFill(0xFFFFFF); this.graphics.drawRect(0, 0, 400, 300); this.graphics.endFill(); // Creates a square area where a mouse down will start the resize. var resizeHandle:Sprite = createSprite(0xCCCCCC, 20, this.width - 20, this.height - 20); resizeHandle.addEventListener(MouseEvent.MOUSE_DOWN, onStartResize); // Creates a square area where a mouse down will start the move. var moveHandle:Sprite = createSprite(0xCCCCCC, 20, this.width - 20, 0); moveHandle.addEventListener(MouseEvent.MOUSE_DOWN, onStartMove); } public function createSprite(color:int, size:int, x:int, y:int):Sprite { var s:Sprite = new Sprite(); s.graphics.beginFill(color); s.graphics.drawRect(0, 0, size, size); s.graphics.endFill(); s.x = x; s.y = y; this.addChild(s); return s; } public function onStartResize(event:MouseEvent):void { this.stage.nativeWindow.startResize(NativeWindowResize.BOTTOM_RIGHT); } public function onStartMove(event:MouseEvent):void { this.stage.nativeWindow.startMove(); } } } ``` -------------------------------- ### File URL Scheme Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/html-content-in-adobe-air/programming-html-and-javascript-in-air/about-urls-in-air.md Example of a file URL pointing to a text file on the local file system. ```html file:///c:/AIR Test/test.txt ``` -------------------------------- ### App-Storage URL Scheme Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/html-content-in-adobe-air/programming-html-and-javascript-in-air/about-urls-in-air.md Example of an app-storage URL pointing to a settings file within the application's dedicated storage directory. ```html app-storage:/settings/prefs.xml ``` -------------------------------- ### ActionScript 3.0: Multiple-Page Printing Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/client-system-interaction/printing/printing-example-multiple-page-printing.md Demonstrates how to print multiple pages by adding individual sprites to a PrintJob. Ensure the PrintJob is started and pages are added within try-catch blocks. ```actionscript package { import flash.display.MovieClip; import flash.printing.PrintJob; import flash.printing.PrintJobOrientation; import flash.display.Stage; import flash.display.Sprite; import flash.text.TextField; import flash.geom.Rectangle; public class PrintMultiplePages extends MovieClip { private var sheet1:Sprite; private var sheet2:Sprite; public function PrintMultiplePages():void { init(); printPages(); } private function init():void { sheet1 = new Sprite(); createSheet(sheet1, "Once upon a time...", {x:10, y:50, width:80, height:130}); sheet2 = new Sprite(); createSheet(sheet2, "There was a great story to tell, and it ended quickly.\n\nThe end.", null); } private function createSheet(sheet:Sprite, str:String, imgValue:Object):void { sheet.graphics.beginFill(0xEEEEEE); sheet.graphics.lineStyle(1, 0x000000); sheet.graphics.drawRect(0, 0, 100, 200); sheet.graphics.endFill(); var txt:TextField = new TextField(); txt.height = 200; txt.width = 100; txt.wordWrap = true; txt.text = str; if (imgValue != null) { var img:Sprite = new Sprite(); img.graphics.beginFill(0xFFFFFF); img.graphics.drawRect(imgValue.x, imgValue.y, imgValue.width, imgValue.height); img.graphics.endFill(); sheet.addChild(img); } sheet.addChild(txt); } private function printPages():void { var pj:PrintJob = new PrintJob(); var pagesToPrint:uint = 0; if (pj.start()) { if (pj.orientation == PrintJobOrientation.LANDSCAPE) { throw new Error("Page is not set to an orientation of portrait."); } sheet1.height = pj.pageHeight; sheet1.width = pj.pageWidth; sheet2.height = pj.pageHeight; sheet2.width = pj.pageWidth; try { pj.addPage(sheet1); pagesToPrint++; } catch (error:Error) { // Respond to error. } try { pj.addPage(sheet2); pagesToPrint++; } catch (error:Error) { // Respond to error. } if (pagesToPrint > 0) { pj.send(); } } } } } ``` -------------------------------- ### Demonstrating TabStop Alignment Options Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/text/using-the-flash-text-engine/controlling-text.md Illustrates the effect of different TabStop alignment types (START, CENTER, DECIMAL, END) on text layout within a TextBlock. This example requires importing flash.text.engine.* and flash.display.Sprite. ```actionscript package { import flash.text.engine.*; import flash.display.Sprite; public class TabStopExample extends Sprite { public function TabStopExample() { var format:ElementFormat = new ElementFormat(); format.fontDescription = new FontDescription("Arial"); format.fontSize = 16; var tabStops:Vector. = new Vector.(); tabStops.push( new TabStop(TabAlignment.START, 20), new TabStop(TabAlignment.CENTER, 140), new TabStop(TabAlignment.DECIMAL, 260, "."), new TabStop(TabAlignment.END, 380)); var textBlock:TextBlock = new TextBlock(); textBlock.content = new TextElement( "\tt1\tt2\tt3\tt4\n" + "\tThis line aligns on 1st tab\n" + "\t\t\t\tThis is the end\n" + "\tThe following fragment centers on the 2nd tab:\t\t\n" + "\t\tit's on me\t\t\n" + "\tThe following amounts align on the decimal point:\n" + "\t\t\t45.00\t\n" + "\t\t\t75,320.00\t\n" + "\t\t\t6,950.00\t\n" + "\t\t\t7.01\t\n", format); textBlock.tabStops = tabStops; var yPosition:Number = 60; var previousTextLine:TextLine = null; var textLine:TextLine; var i:int; for (i = 0; i < 10; i++) { textLine = textBlock.createTextLine(previousTextLine, 1000, 0); textLine.x = 20; textLine.y = yPosition; addChild(textLine); yPosition += 25; previousTextLine = textLine; } } } } ``` -------------------------------- ### Example Socket Policy File Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/security/loading-data.md This is an example of a socket policy file that grants access from various domains to specific ports. It uses the `` tag with `domain` and `to-ports` attributes. ```xml ``` -------------------------------- ### XML Opening Tag Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/core-actionscript-classes/working-with-xml/basics-of-xml.md Illustrates the syntax for an opening XML tag, marking the beginning of an element. ```xml ``` -------------------------------- ### WikiParser Constructor and Initialization Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/core-actionscript-classes/using-regular-expressions/regular-expressions-example-a-wiki-parser.md Initializes the WikiParser with sample Wiki data. This method is part of the class setup. ```actionscript public function WikiParser() { wikiData = setWikiData(); } ``` -------------------------------- ### Basic Print Job Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/client-system-interaction/printing/printing-a-page.md This example demonstrates the essential sequence of statements to initiate a print job, add a page, and send it to the printer using ActionScript 3.0. It includes necessary package, import, and class definitions for compilation. ```actionscript package { import flash.printing.PrintJob; import flash.display.Sprite; public class BasicPrintExample extends Sprite { var myPrintJob:PrintJob = new PrintJob(); var mySprite:Sprite = new Sprite(); public function BasicPrintExample() { myPrintJob.start(); myPrintJob.addPage(mySprite); myPrintJob.send(); } } } ``` -------------------------------- ### Start Asynchronous Shader Execution Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/display/working-with-pixel-bender-shaders/using-a-shader-in-stand-alone-mode.md Call the start() method without arguments to execute the shader asynchronously. Program execution continues immediately, and completion is signaled via events. ```actionscript job.start(); ``` -------------------------------- ### Simple XML Data Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/core-actionscript-classes/working-with-xml/basics-of-xml.md Demonstrates a basic XML structure representing song information. ```xml <song> <title>What you know? Steve and the flubberblubs 1989 2006-10-17-08:31 ``` -------------------------------- ### Displaying "Hello World!" with Flash Text Engine Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/text/using-the-flash-text-engine/creating-and-displaying-text.md This example demonstrates the basic usage of Flash Text Engine classes to create and display a simple string with default formatting. It shows how to instantiate TextElement, ElementFormat, and TextBlock, and then render a single line of text. ```actionscript package { import flash.text.engine.*; import flash.display.Sprite; public class HelloWorldExample extends Sprite { public function HelloWorldExample() { var str = "Hello World! This is Flash Text Engine!"; var format:ElementFormat = new ElementFormat(); var textElement:TextElement = new TextElement(str, format); var textBlock:TextBlock = new TextBlock(); textBlock.content = textElement; var textLine1:TextLine = textBlock.createTextLine(null, 300); addChild(textLine1); textLine1.x = 30; textLine1.y = 30; } } } ``` -------------------------------- ### Initialize File and FileStream Objects Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/files-and-data/working-with-bytearrays/bytearray-example-reading-a-zip-file.md Sets up File and FileStream objects to access the 'HelloAIR.zip' file located in the desktop directory. ```ActionScript // File variables for accessing .zip file var zfile:File = File.desktopDirectory.resolvePath("HelloAIR.zip"); var zStream:FileStream = new FileStream(); ``` -------------------------------- ### Basic Regular Expression Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/core-actionscript-classes/using-regular-expressions/index.md This regular expression matches a string that starts with the character 'A' followed by one or more sequential digits. It demonstrates a simple pattern matching scenario. ```ActionScript /A\d+/ ``` -------------------------------- ### Sound Visualizer using SoundMixer.computeSpectrum() Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/rich-media-content/working-with-sound/accessing-raw-sound-data.md This example demonstrates how to create a real-time sound visualizer by capturing and plotting the sound spectrum data. It loads an MP3 file and uses the ENTER_FRAME event to continuously update the waveform visualization. ```actionscript import flash.display.Graphics; import flash.events.Event; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundMixer; import flash.net.URLRequest; const PLOT_HEIGHT:int = 200; const CHANNEL_LENGTH:int = 256; var snd:Sound = new Sound(); var req:URLRequest = new URLRequest("bigSound.mp3"); snd.load(req); var channel:SoundChannel; channel = snd.play(); addEventListener(Event.ENTER_FRAME, onEnterFrame); snd.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete); var bytes:ByteArray = new ByteArray(); function onEnterFrame(event:Event):void { SoundMixer.computeSpectrum(bytes, false, 0); var g:Graphics = this.graphics; g.clear(); g.lineStyle(0, 0x6600CC); g.beginFill(0x6600CC); g.moveTo(0, PLOT_HEIGHT); var n:Number = 0; // left channel for (var i:int = 0; i < CHANNEL_LENGTH; i++) { n = (bytes.readFloat() * PLOT_HEIGHT); g.lineTo(i * 2, PLOT_HEIGHT - n); } g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT); g.endFill(); // right channel g.lineStyle(0, 0xCC0066); g.beginFill(0xCC0066, 0.5); g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT); for (i = CHANNEL_LENGTH; i > 0; i--) { n = (bytes.readFloat() * PLOT_HEIGHT); g.lineTo(i * 2, PLOT_HEIGHT - n); } g.lineTo(0, PLOT_HEIGHT); g.endFill(); } function onPlaybackComplete(event:Event) { removeEventListener(Event.ENTER_FRAME, onEnterFrame); } ``` -------------------------------- ### Connect to a LocalConnection Server Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/networking-and-communication/communicating-with-other-flash-player-and-air-instances.md Demonstrates how to establish a connection to a LocalConnection server using a unique connection name. Includes error handling for cases where the server is already running. ```actionscript try { connection.connect("conn1"); } catch (error:ArgumentError) { trace("Error! Server already exists\n"); } ``` -------------------------------- ### List Directory Contents Synchronously Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/files-and-data/working-with-the-file-system/working-with-directories.md Use `getDirectoryListing()` to get an array of File objects for files and subfolders in a directory. This example lists the contents of the user's documents directory. ```actionscript var directory:File = File.documentsDirectory; var contents:Array = directory.getDirectoryListing(); for (var i:uint = 0; i < contents.length; i++) { trace(contents[i].name, contents[i].size); } ``` -------------------------------- ### Basic Video Playback Control Setup Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/rich-media-content/working-with-video/controlling-video-playback.md Initializes NetConnection and NetStream, attaches a Video object, and sets up event listeners for playback control buttons. This code is required before using playback control methods. ```actionscript var nc:NetConnection = new NetConnection(); nc.connect(null); var ns:NetStream = new NetStream(nc); ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); ns.play("video.flv"); function asyncErrorHandler(event:AsyncErrorEvent):void { // ignore error } var vid:Video = new Video(); vid.attachNetStream(ns); addChild(vid); ``` -------------------------------- ### Using the app: URI Scheme Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/networking-and-communication/http-communications/loading-external-data.md The app: URI scheme specifies a path relative to the root directory of the installed AIR application. This example shows how to resolve a path to an assets subdirectory. ```actionscript var dir:File = File.applicationDirectory; dir = dir.resolvePath("assets"); trace(dir.url); // app:/assets ``` -------------------------------- ### Full ActionScript 3.0 Class for 3D Transformations Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/display/working-in-three-dimensions-3d/performing-complex-3d-transformations.md A complete ActionScript 3.0 class demonstrating the setup and application of multiple 3D transformations using both DisplayObject properties and Matrix3D objects. ```actionscript package { import flash.display.Sprite; import flash.display.Shape; import flash.display.Graphics; import flash.geom.*; public class Matrix3DTransformsExample extends Sprite { private var rect1:Shape; private var rect2:Shape; public function Matrix3DTransformsExample():void { var pp:PerspectiveProjection = this.transform.perspectiveProjection; pp.projectionCenter = new Point(275,200); this.transform.perspectiveProjection = pp; rect1 = new Shape(); rect1.x = -70; rect1.y = -40; rect1.z = 0; rect1.graphics.beginFill(0xFF8800); rect1.graphics.drawRect(0,0,50,80); rect1.graphics.endFill(); addChild(rect1); rect2 = new Shape(); rect2.x = 20; rect2.y = -40; rect2.z = 0; rect2.graphics.beginFill(0xFF0088); rect2.graphics.drawRect(0,0,50,80); rect2.graphics.endFill(); addChild(rect2); doTransforms(); } private function doTransforms():void { rect1.rotationX = 15; rect1.scaleX = 1.2; rect1.x += 100; rect1.y += 50; rect1.rotationZ = 10; var matrix:Matrix3D = rect2.transform.matrix3D; matrix.appendRotation(15, Vector3D.X_AXIS); matrix.appendScale(1.2, 1, 1); matrix.appendTranslation(100, 50, 0); matrix.appendRotation(10, Vector3D.Z_AXIS); rect2.transform.matrix3D = matrix; } } } ``` -------------------------------- ### Play Movie Clip Animation on Button Click Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/display/working-with-movie-clips/controlling-movie-clip-playback.md This example demonstrates how to start a MovieClip's animation when a button is clicked. It involves registering a click event listener to call the play() method. ```actionscript // This function will be called when the button is clicked. It causes the // bicycle animation to play. function playAnimation(event:MouseEvent):void { bicycle.play(); } // Register the function as a listener with the button. startButton.addEventListener(MouseEvent.CLICK, playAnimation); ``` -------------------------------- ### Create a Native Window Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/client-system-interaction/working-with-air-native-windows/creating-windows.md This snippet demonstrates the process of creating a new native window, setting its initialization options, and configuring its basic properties and display settings. ```actionscript public function createNativeWindow():void { //create the init options var options:NativeWindowInitOptions = new NativeWindowInitOptions(); options.transparent = false; options.systemChrome = NativeWindowSystemChrome.STANDARD; options.type = NativeWindowType.NORMAL; //create the window var newWindow:NativeWindow = new NativeWindow(options); newWindow.title = "A title"; newWindow.width = 600; newWindow.height = 400; newWindow.stage.align = StageAlign.TOP_LEFT; newWindow.stage.scaleMode = StageScaleMode.NO_SCALE; //activate and show the new window newWindow.activate(); } ``` -------------------------------- ### Get WebKit Version using HTMLLoader Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/html-content-in-adobe-air/about-the-html-environment/index.md Determine the installed WebKit version by examining the default user agent string returned by an HTMLLoader object. This is useful for understanding compatibility and potential rendering differences. ```ActionScript var htmlLoader:HTMLLoader = new HTMLLoader(); trace( htmlLoader.userAgent ); ``` -------------------------------- ### Launch Native Process and Listen for Output Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/networking-and-communication/communicating-with-native-processes-in-air.md Launches a native executable (test.exe) with a command-line argument and sets up an event listener to capture data from its standard output stream. Ensure the native process is accessible from the application directory. ```ActionScript var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo(); var file:File = File.applicationDirectory.resolvePath("test.exe"); nativeProcessStartupInfo.executable = file; var processArgs:Vector. = new Vector.(); processArgs.push("hello"); nativeProcessStartupInfo.arguments = processArgs; process = new NativeProcess(); process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData); process.start(nativeProcessStartupInfo); public function onOutputData(event:ProgressEvent):void { var stdOut:ByteArray = process.standardOutput; var data:String = stdOut.readUTFBytes(process.standardOutput.bytesAvailable); trace("Got: ", data); } ``` -------------------------------- ### Initializing Application and Getting Capabilities Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/client-system-interaction/client-system-environment/capabilities-example-detecting-system-capabilities.md This method is invoked when the main application file's creationComplete event is dispatched. It retrieves system capabilities and sets them as the data provider for a DataGrid component. ```ActionScript private function initApp():void { var dp:Array = CapabilitiesGrabber.getCapabilities(); capabilitiesGrid.dataProvider = dp; } ``` -------------------------------- ### Synchronous Database Operations with Error Handling Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/files-and-data/working-with-local-sql-databases-in-air/using-synchronous-database-operations.md This example demonstrates using try-catch-finally blocks for error handling during synchronous database operations. It includes opening a connection, starting a transaction, inserting data, and handling potential SQLErrors by rolling back the transaction. ```actionscript var conn:SQLConnection = new SQLConnection(); // The database file is in the application storage directory var folder:File = File.applicationStorageDirectory; var dbFile:File = folder.resolvePath("DBSample.db"); // open the database conn.open(dbFile, SQLMode.UPDATE); // start a transaction conn.begin(); try { // add the customer record to the database var insertCustomer:SQLStatement = new SQLStatement(); insertCustomer.sqlConnection = conn; insertCustomer.text = "INSERT INTO customers (firstName, lastName)" + "VALUES ('Bob', 'Jones')"; insertCustomer.execute(); var customerId:Number = insertCustomer.getResult().lastInsertRowID; // add a related phone number record for the customer var insertPhoneNumber:SQLStatement = new SQLStatement(); insertPhoneNumber.sqlConnection = conn; insertPhoneNumber.text = "INSERT INTO customerPhoneNumbers (customerId, number)" + "VALUES (:customerId, '800-555-1234')"; insertPhoneNumber.parameters[":customerId"] = customerId; insertPhoneNumber.execute(); // if we've gotten to this point without errors, commit the transaction conn.commit(); } catch (error:SQLError) { // rollback the transaction conn.rollback(); } ``` -------------------------------- ### HTML Structure and JavaScript for Drag-and-Drop Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/user-interaction/drag-and-drop-in-air/example-overriding-the-default-html-drag-in-behavior.md This snippet includes the HTML structure for a drag-and-drop example and the associated JavaScript functions to handle drag start, drag end, drag enter/over, and drop events. It demonstrates overriding default behaviors and processing different data types. ```html Drag-and-drop

Source

Items to drag:

  • Plain text.
  • HTML formatted text.
  • A URL.
  • An image
  • Uses "-webkit-user-drag:none" style.
  • Uses "-webkit-user-select:none" style.

Target

Drag items from the source list (or elsewhere).

Plain textHtml textURLFile listBitmap Data
     
``` -------------------------------- ### HTTP URL Scheme Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/html-content-in-adobe-air/programming-html-and-javascript-in-air/about-urls-in-air.md Example of a standard HTTP URL for accessing a web resource. ```html http://www.adobe.com ``` -------------------------------- ### Load and Add Image Content to a Container Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/display/display-programming/loading-display-content-dynamically.md This example shows how to load an image, listen for its completion, and then add the actual loaded content (the image) to a specific container. It requires importing necessary classes and setting up an event listener. ```actionscript import flash.display.*; import flash.net.URLRequest; import flash.events.Event; var container:Sprite = new Sprite(); addChild(container); var pictLdr:Loader = new Loader(); var pictURL:String = "banana.jpg" var pictURLReq:URLRequest = new URLRequest(pictURL); pictLdr.load(pictURLReq); pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded); function imgLoaded(event:Event):void { container.addChild(pictLdr.content); } ``` -------------------------------- ### HTTPS URL Scheme Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/html-content-in-adobe-air/programming-html-and-javascript-in-air/about-urls-in-air.md Example of a standard HTTPS URL for accessing a secure web resource. ```html https://secure.example.com ``` -------------------------------- ### Load data from a local file using FileReference Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/files-and-data/working-with-the-file-system/using-the-filereference-class.md This example demonstrates how to prompt the user to select a file and then load its data into memory. It includes event listeners for file selection, progress, completion, and errors. Ensure FileReference.browse() is called before load(). ```actionscript package { import flash.display.Sprite; import flash.events.*; import flash.net.FileFilter; import flash.net.FileReference; import flash.net.URLRequest; import flash.utils.ByteArray; public class FileReferenceExample1 extends Sprite { private var fileRef:FileReference; public function FileReferenceExample1() { fileRef = new FileReference(); fileRef.addEventListener(Event.SELECT, onFileSelected); fileRef.addEventListener(Event.CANCEL, onCancel); fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError); fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, * The `FileReference.load()` method returns immediately after being called, but the data being loaded isn't available immediately. The `FileReference` object dispatches events to invoke listener methods at each step of the loading process. The `FileReference` object dispatches the following events during the loading process: `open` event (`Event.OPEN`): Dispatched when the load operation starts. `progress` event (`ProgressEvent.PROGRESS`): Dispatched periodically as bytes of data are read from the file. `complete` event (`Event.COMPLETE`): Dispatched when the load operation completes successfully. `ioError` event (`IOErrorEvent.IO_ERROR`): Dispatched if the load process fails because an input/output error occurs while opening or reading data from the file. Once the `FileReference` object dispatches the complete event, the loaded data can be accessed as a `ByteArray` in the `FileReference` object's `data` property. The following example shows how to prompt the user to select a file and then load the data from that file into memory: The example code first creates the `FileReference` object named `fileRef` and then calls its `browse()` method. The `browse()` method opens a dialog box that prompts the user to select a file. When a file is selected, the code invokes the `onFileSelected()` method. This method adds listeners for the `progress` and `complete` events and then calls the `FileReference` object's `load()` method. The other handler methods in the example simply output messages to report on the progress of the load operation. When the loading completes, the application displays the contents of the loaded file using the `trace()` method. In Adobe AIR, the `FileStream` class provides additional functionality for reading data from a local file. See [Reading and writing files](./reading-and-writing-files.md). ``` -------------------------------- ### Create and Open a Local SQL Database File Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/files-and-data/working-with-local-sql-databases-in-air/creating-and-modifying-a-database.md This snippet demonstrates how to create a new SQL database file or open an existing one in the application's storage directory. It includes basic error handling for the connection process. ```actionscript var conn:SQLConnection = new SQLConnection(); // The database file is in the application storage directory var folder:File = File.applicationStorageDirectory; var dbFile:File = folder.resolvePath("DBSample.db"); try { conn.open(dbFile); trace("the database was created successfully"); } catch (error:SQLError) { trace("Error message:", error.message); trace("Details:", error.details); } ``` ```actionscript import flash.data.SQLConnection; import flash.errors.SQLError; import flash.filesystem.File; private function init():void { var conn:SQLConnection = new SQLConnection(); // The database file is in the application storage directory var folder:File = File.applicationStorageDirectory; var dbFile:File = folder.resolvePath("DBSample.db"); try { conn.open(dbFile); trace("the database was created successfully"); } catch (error:SQLError) { trace("Error message:", error.message); trace("Details:", error.details); } } ``` -------------------------------- ### XML Data Structure Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/core-actionscript-classes/working-with-xml/traversing-xml-structures.md Defines an XML structure for employee data, used in subsequent filtering examples. ```actionscript var x:XML = Zmed Sue Data analyst McGee Chuck Jr. data analyst ``` -------------------------------- ### DRM Preloader Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/rich-media-content/using-digital-rights-management/understanding-the-protected-content-workflow.md This class demonstrates how to preload DRM-protected content metadata and handle authentication and voucher loading. It sets up event listeners for DRM events and initiates the preloading process. ```actionscript package { import flash.display.Sprite; import flash.events.DRMAuthenticationCompleteEvent; import flash.events.DRMAuthenticationErrorEvent; import flash.events.DRMErrorEvent; import flash.events.DRMStatusEvent; import flash.events.NetStatusEvent; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.NetStreamPlayOptions; import flash.net.drm.AuthenticationMethod; import flash.net.drm.DRMContentData; import flash.net.drm.DRMManager; import flash.net.drm.LoadVoucherSetting; public class DRMPreloader extends Sprite { private var videoURL:String = "app-storage:/video.flv"; private var userName:String = "user"; private var password:String = "password"; private var preloadConnection:NetConnection; private var preloadStream:NetStream; private var drmManager:DRMManager = DRMManager.getDRMManager(); private var drmContentData:DRMContentData; public function DRMPreloader():void { drmManager.addEventListener( DRMAuthenticationCompleteEvent.AUTHENTICATION_COMPLETE, onAuthenticationComplete); drmManager.addEventListener(DRMAuthenticationErrorEvent.AUTHENTICATION_ERROR, onAuthenticationError); drmManager.addEventListener(DRMStatusEvent.DRM_STATUS, onDRMStatus); drmManager.addEventListener(DRMErrorEvent.DRM_ERROR, onDRMError); preloadConnection = new NetConnection(); preloadConnection.addEventListener(NetStatusEvent.NET_STATUS, onConnect); preloadConnection.connect(null); } private function onConnect( event:NetStatusEvent ):void { preloadMetadata(); } private function preloadMetadata():void { preloadStream = new NetStream( preloadConnection ); preloadStream.client = this; var options:NetStreamPlayOptions = new NetStreamPlayOptions(); options.streamName = videoURL; preloadStream.preloadEmbeddedData( options ); } public function onDRMContentData( drmMetadata:DRMContentData ):void { drmContentData = drmMetadata; if ( drmMetadata.authenticationMethod == AuthenticationMethod.USERNAME_AND_PASSWORD ) { authenticateUser(); } else { getVoucher(); } } private function getVoucher():void { drmManager.loadVoucher( drmContentData, LoadVoucherSetting.ALLOW_SERVER ); } private function authenticateUser():void { drmManager.authenticate( drmContentData.serverURL, drmContentData.domain, userName, password ); } private function onAuthenticationError( event:DRMAuthenticationErrorEvent ):void { trace( "Authentication error: " + event.errorID + ", " + event.subErrorID ); } private function onAuthenticationComplete( event:DRMAuthenticationCompleteEvent ):void { trace( "Authenticated to: " + event.serverURL + ", domain: " + event.domain ); getVoucher(); } private function onDRMStatus( event:DRMStatusEvent ):void { trace( "DRM Status: " + event.detail); trace("--Voucher allows offline playback = " + event.isAvailableOffline ); trace("--Voucher already cached = " + event.isLocal ); trace("--Voucher required authentication = " + !event.isAnonymous ); } private function onDRMError( event:DRMErrorEvent ):void { trace( "DRM error event: " + event.errorID + ", " + event.subErrorID + ", " + event.text ); } public function onPlayStatus( info:Object ):void { preloadStream.close(); } } } ``` -------------------------------- ### XML Element with Content and Attributes Example Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/core-actionscript-classes/working-with-xml/basics-of-xml.md An example of an XML element that contains child elements and also defines attributes in its opening tag. ```xml What do you know? Steve and the flubberblubs Happy 2006-10-17-08:31 ``` -------------------------------- ### Examples of String Literals Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/core-actionscript-classes/working-with-strings/basics-of-strings.md Illustrates various examples of string literals, including text, numbers, and URLs, enclosed in double quotation marks. ```actionscript "Hello" ``` ```actionscript "555-7649" ``` ```actionscript "https://www.adobe.com/" ``` -------------------------------- ### Example Usage of JSONDictionaryExtnExample and JSON.stringify Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/core-actionscript-classes/using-native-json-functionality.md Demonstrates creating instances of `JSONGenericDictExample` and `JSONDictionaryExtnExample`, populating the dictionary, and then serializing it to a JSON string using `JSON.stringify`. The output shows how custom objects are represented in JSON. ```actionscript import flash.display.MovieClip; import flash.text.TextField; var a_bob1:JSONGenericDictExample = new JSONGenericDictExample("Bob", new Date(Date.parse("01/02/1934"))); var a_bob2:JSONGenericDictExample = new JSONGenericDictExample("Bob", new Date(Date.parse("05/06/1978"))); var a_jen:JSONGenericDictExample = new JSONGenericDictExample("Jen", new Date(Date.parse("09/09/1999"))); var e = new JSONDictionaryExtnExample(); e[a_bob1] = {earnings: 40, violations: 2}; e[a_bob2] = {earnings: 10, violations: 1}; e[a_jen] = {earnings: 25, violations: 3}; trace("JSON.stringify(e): " + JSON.stringify(e)); // {"class JSONDictionaryExtnExample": //{"id_class_JSONGenericDictExample_10001": //{"earnings":10,"violations":1}, //"id_class_JSONGenericDictExample_10002": //{"earnings":25,"violations":3}, //"id_class_JSONGenericDictExample_10000": // {"earnings":40,"violations":2}}} var e_result = JSON.stringify(e); ``` -------------------------------- ### Play a Sound with Start Time and Loops Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/rich-media-content/working-with-sound/playing-sounds.md Plays a sound from a specified start time and repeats it a fixed number of times. The startTime is in milliseconds. ```actionscript var snd:Sound = new Sound(new URLRequest("repeatingSound.mp3")); snd.play(1000, 3); ``` -------------------------------- ### Start Synchronous Shader Execution Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/display/working-with-pixel-bender-shaders/using-a-shader-in-stand-alone-mode.md Pass 'true' to the start() method to execute the shader synchronously. The program will pause until the shader completes its operation. ```actionscript job.start(true); ``` -------------------------------- ### NetStream with Metadata and Cue Point Handlers Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/rich-media-content/working-with-video/writing-callback-methods-for-metadata-and-cue-points.md Extends the dynamic NetStream setup by defining and assigning specific handlers for metadata and cue points. This allows for custom actions when metadata or cue points are encountered during video playback. ```actionscript var ns:DynamicCustomNetStream = new DynamicCustomNetStream(); ns.onMetaData = metaDataHandler; ns.onCuePoint = cuePointHandler; ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv"); var vid:Video = new Video(); vid.attachNetStream(ns); addChild(vid); function metaDataHandler(infoObject:Object):void { trace("metadata"); } function cuePointHandler(infoObject:Object):void { trace("cue point"); } ``` -------------------------------- ### Create a Basic NativeWindow Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/client-system-interaction/working-with-air-native-windows/creating-windows.md Instantiate a NativeWindow with standard system chrome and opaque background. The window is initially hidden and requires explicit activation or setting the visible property to true. ```actionscript var options:NativeWindowInitOptions = new NativeWindowInitOptions(); options.systemChrome = NativeWindowSystemChrome.STANDARD; options.transparent = false; var newWindow:NativeWindow = new NativeWindow(options); ``` -------------------------------- ### Check if IME is Installed and Enabled Source: https://github.com/joshtynjala/actionscript-3.0-developers-guide/blob/main/user-interaction/keyboard-input/using-the-ime-class.md Verify if an IME is installed and active before using IME functionalities. This prevents errors by ensuring the IME is available and enabled. ```actionscript if (Capabilities.hasIME) { if (IME.enabled) { trace("IME is installed and enabled."); } else { trace("IME is installed but not enabled. Please enable your IME and try again."); } } else { trace("IME is not installed. Please install an IME and try again."); } ```