Tài liệu Flash Builder 4 and Flex 4 Bible- P5 ppt

50 523 0
Tài liệu Flash Builder 4 and Flex 4 Bible- P5 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 6: Debugging Flex Applications 171 FIGURE 6.4 The Console view Preferences dialog box Terminating a debugging session You should always explicitly terminate a debugging session before trying to run or debug an appli- cation again. You can terminate a debugging session in many ways: l Choose Run ➪ Terminate from the Flash Builder menu. l As shown in Figure 6.5, click the square red Terminate button in the Console view. l Click the square red Terminate button in the Debug view (visible in the Flex Debugging perspective). l Close the browser in which the application is running (for a Web application). l Close the application (for a desktop application). Tip When you terminate a Web application’s debugging session from within Flash Builder, the browser sometimes closes automatically, depending on which Web browser and operating system you’re using and whether any other tabs or browser windows are open. For example, provided that no other sites are open, Internet Explorer and Firefox on Windows always close automatically. Firefox on the Mac doesn’t always close automatically. The fact that this behavior differs from one operating system to another is not a cause for concern. n 11_488959-ch06.indd 17111_488959-ch06.indd 171 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 172 FIGURE 6.5 The Console view’s Terminate button The Terminate button Using trace() and the Logging API With Flex, you can generate and send logging messages to Flash Builder and other logging targets at runtime. Tracing is typically useful when you’re trying to get runtime information about the following: l Variable values l The order of application execution l Whether various bits of code are being executed as expected In its simplest use, logging is accomplished through use of the trace() method. More advanced logging techniques are also available through an interface known as the Logging API. Using the trace() function The trace() function is global to Flash Player; that is, it’s always available without your having to reference or import an ActionScript class. The purpose of the trace() function is to send a text message to a logging target. In its simplest form, trace is called with a String value: trace(‘A tracing message’); You also can pass in variables and concatenated expressions that can result in a String: trace(“The value of myVariable is “ + myVariable); In fact, any object that can serialize to a String can be passed to trace(). In this example, an Array of String values is passed to trace(): trace([‘hello’, ‘world’]); Because the Array class is automatically serialized as a comma-delimited string, the resulting out- put message looks like this: hello,world 11_488959-ch06.indd 17211_488959-ch06.indd 172 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 6: Debugging Flex Applications 173 Trace messages in Flash Builder’s Console view When you debug a Flex application with Flash Builder, the value you pass into trace() is displayed in Flash Builder’s Console view. Tip Calls to trace() are ignored when you run, rather than debug, an application even though the same debug version of your application is being executed. These calls are also stripped from an application’s release version, so you can leave any calls to trace() in an application without affecting runtime performance or file size. n Try these steps to see the trace() function at work: 1. Create a new Flex application with the following code: <?xml version=”1.0” encoding=”utf-8”?> <s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009” xmlns:s=”library://ns.adobe.com/flex/spark” xmlns:mx=”library://ns.adobe.com/flex/mx”> <s:layout> <s:VerticalLayout horizontalAlign=”center” paddingTop=”20”/> </s:layout> <s:Button label=”Call Trace” click=”trace(‘Button Clicked’)”/> </s:Application> 2. Click Debug, or press F11 (Windows) or Ô+F11 (Mac), to debug the application. 3. Click Call Trace in the application to call trace(). 4. Switch back to Flash Builder, and look at the Console view. As shown in Figure 6.6, you should see the tracing message displayed in the Console view. FIGURE 6.6 A tracing message in the Console view Tracing message in the Console view Sending tracing messages to flashlog.txt Messages also can be saved to a text file named flashlog.txt. The flashlog.txt file is cre- ated by the debugger version of Flash Player in a particular folder on your system. 11_488959-ch06.indd 17311_488959-ch06.indd 173 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 174 Configuring Flash Player with mm.cfg You configure the use of flashlog.txt with another text file named mm.cfg. This file contains parameters that control what messages are sent to, and saved in, the file. The location of mm.cfg differs by operating system. Table 6.1 shows the location for each operating system that’s supported by Flash Player. TABLE 6.1 Location of mm.cfg Operating System Location Macintosh OS X /Library/Application Support/Macromedia Windows 95/98/ME %HOMEDRIVE%\%HOMEPATH% Windows 2000 & XP C:\Documents and Settings\username Windows Vista & 7 C:\Users\username Linux /home/username To save both error reporting and tracing messages to the flashlog.txt file, add these parameters on their own separate lines in mm.cfg: ErrorReportingEnable=1 TraceOutputFileEnable=1 After these settings have been created, the next time you debug a Flex application or Flash docu- ment, the flashlog.txt is created automatically. Each time you call trace(), the message is saved to the file, in addition to being sent to Flash Builder’s Console view. Location of flashlog.txt The flashlog.txt file is placed in a particular location that differs by operating system. Table 6.2 shows the location of flashlog.txt for each operating system on which Flash Player is supported. TABLE 6.2 Location of fl ashlog.txt Operating System Location Macintosh OS X /Users/username/Library/Preferences/Macromedia/ Flash Player/Logs Windows 95/98/ME/2000/XP C:\Documents and Settings\username\ Application Data\Macromedia\Flash Player\Logs Windows Vista & 7 C:\Users\username\AppData\ Roaming\Macromedia\Flash Player\Logs Linux /home/username/.macromedia/Flash_Player/Logs 11_488959-ch06.indd 17411_488959-ch06.indd 174 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 6: Debugging Flex Applications 175 Tip Both mm.cfg and flashlog.txt are simple text files and can be viewed and edited with any text editor. n Using the Logging API The Logging API is an advanced architecture that enables you to filter logging messages that are generated by the Flex Framework, and send messages to a logging target of your choice. The Logging API consists of an ActionScript interface named ILogger, a class that implements ILogger named LogLogger, a singleton class named Log, and a predefined tracing target class named TraceTarget. You can extend the API (application programming interface) by creating your own versions of ILogger implementations and tracing targets, but you also can make very good use of the API with just these pre-built components. Tip ActionScript 3 enables developers to use interfaces to define the required elements of a class definition. An interface isn’t the same thing as a class. For example, it doesn’t implement any code in its method definitions, and you can’t create an instance of an interface directly. Its purpose is to establish a contract that must be fulfilled by any classes that claim to implement its members. In the Flex framework, interfaces are always named within an initial uppercase I, followed by a descriptive name. For example, the interface named ILogger can be described simply as “the Logger interface.” n Using the Log class You get started with the Logging API by creating a Logger object using the Log class’s static getLogger() method. You can create custom logger objects that are sensitive to particular cate- gories of events, and you can automatically include that category information in logging messages. The syntax for getLogger() is: private var myLogger:ILogger = Log.getLogger(“myCategory”); The category you pass into getLogger() must be a nonblank string. If the category you provide is registered by an existing class that implements ILogger, you get an instance of that class. Otherwise, you get an instance of a class named mx.logging.LogLogger that implements basic logging functions. The Logging API supports these levels, in ascending order of panic: l ALL l DEBUG l INFO l WARN l ERROR l FATAL 11_488959-ch06.indd 17511_488959-ch06.indd 175 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 176 The Log class implements these methods that enable you to determine whether a logging target has been defined for various logging levels: l isDebug():Boolean l isInfo():Boolean l isWarn():Boolean l isError():Boolean l isFatal():Boolean Using Logger objects A logger class implements the ILogger interface. The interface includes these methods to send messages to a logging target: l debug(message:String, rest):void l error(message:String, rest):void l fatal(message:String, rest):void l info(message:String, rest):void l warn(message:String, rest):void l log(level:int, message:String, rest):void After you’ve created a logger object, you send a logging message with one of the previous methods. Most methods create a message with a specific logging level. For example, to send a message with a level of DEBUG, you call the logger object’s debug() method: myLogger.debug(“My debug message”); The debugging levels are defined as constants in a class named mx.logging.LogEventLevel. You also can send logging messages with the logger object’s log() method and explicitly pass in the appropriate level: myLogger.log(LogEventLevel.DEBUG, “My debug message”); Tip The use of the LogEventLevel class’s constants to select a logging level is considered a best practice. As with event names, any typos in the names of the constants result in compiler errors, as opposed to runtime errors or silent failures that you may encounter when using simple strings. n Logging levels are used to filter which messages are handled by various logging targets. Self-logging components The Logging API can be used to create a self-logging component. For example, the application in Listing 6.1 is a Button component that logs each click event to a logging target. 11_488959-ch06.indd 17611_488959-ch06.indd 176 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 6: Debugging Flex Applications 177 LISTING 6.1 A self-logging button component <?xml version=”1.0” encoding=”utf-8”?> <s:Button xmlns:fx=”http://ns.adobe.com/mxml/2009” xmlns:s=”library://ns.adobe.com/flex/spark” xmlns:mx=”library://ns.adobe.com/flex/mx” click=”logEvent(event)”> <fx:Script> <![CDATA[ import mx.logging.Log; import mx.logging.ILogger; private var myLogger:ILogger = Log.getLogger(“buttonEvents”); private function logEvent(event:MouseEvent):void { myLogger.debug(“LoggingButton “ + event.target.id + “ was clicked”); } ]]> </fx:Script> </s:Button> On the Web The code in Listing 6.1 is available in the Web site files in the chapter06 project’s debug package as LoggingButton.mxml. n Cross-Reference The code sample in Listing 6.1 uses the Flex event model to handle component events. The event model is described in Chapter 7. n Using tracing targets A tracing target is a class that can receive and process tracing messages. The TraceTarget class is included in the Flex Framework and is ideally suited to use in Flex applications. When you use the TraceTarget class, the output of the Logging API behaves just like output you create with the trace() method. The messages appear in Flash Builder’s Console view and, if you’ve configured Flash Player as described previously, are saved in flashlog.txt. The TraceTarget class supports these properties: l fieldSeparator:String. A string value to separate other values included in a logging message; defaults to a single space character. l includeCategory:Boolean. Indicates whether to include the logging message’s category in the logging message. 11_488959-ch06.indd 17711_488959-ch06.indd 177 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 178 l includeDate:Boolean. Indicates whether to include the current date in the logging message. l includeLevel:Boolean. Indicates whether to include the logging level in the logging message. l includeTime:Boolean. Indicates whether to include the current time in the logging message. l level:int. A logging level that this target will handle; defaults to LogEventLevel.ALL. You can instantiate TraceTarget with either MXML or ActionScript. Use this syntax to instanti- ate the class in its simplest form: <s:TraceTarget/> New Feature In Flex 4, the <sTraceTarget/> element must be placed inside the <fx:Declarations> element, along with other nonvisual object declarations: <fx:Declarations> <s:TraceTarget/> </fx:Declarations> n Caution The Declarations tag uses the fx prefix, because it’s a core part of MXML. The TraceTarget tag can use either the mx or the s prefix, because although it’s part of the Flex 3 class library, it’s registered in the mani- fests for both the older MX and the new Spark component sets. n Tip The <s:TraceTarget/> MXML declaration does not require an id property. Unless you need to call its methods or properties directly, the object can be declared anonymously. n In its default form, TraceTarget becomes a tracing target that handles all logging levels. However, the tracing messages you see include only the messages themselves and none of the other available logging data such as date, time, level, and category. Use this syntax to include all that information and separate the data elements from each other with a | (pipe) character: <s:TraceTarget id=”myTarget” includeCategory=”true” includeLevel=”true” includeDate=”true” includeTime=”true” fieldSeparator=”|”/> Finally, to make a tracing target display messages only for a particular logging level, use this syntax: <s:TraceTarget id=”myTarget” includeCategory=”true” includeLevel=”true” includeDate=”true” includeTime=”true” fieldSeparator=”|” level=”{LogEventLevel.DEBUG}”/> 11_488959-ch06.indd 17811_488959-ch06.indd 178 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 6: Debugging Flex Applications 179 Caution In the last example, the LogEventLevel class would have to be imported before being referenced in the TraceTarget.level binding expression: import mx.logging.LogEventLevel; n The resulting trace output generated by the self-logging button component in Listing 6.1 would look like this: 5/17/2009|21:43:44.051|[DEBUG]|buttonEvents|LoggingButton myLoggingButton was clicked The application in Listing 6.2 uses the self-logging button and a TraceTarget object. The TraceTarget object is configured only to handle messages with a logging level of DEBUG and to include all available information in each message. LISTING 6.2 An application with a self-logging component <?xml version=”1.0” encoding=”utf-8”?> <?xml version=”1.0” encoding=”utf-8”?> <s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009” xmlns:s=”library://ns.adobe.com/flex/spark” xmlns:mx=”library://ns.adobe.com/flex/mx” xmlns:debug=”debug.*”> <fx:Declarations> <s:TraceTarget id=”myTarget” includeCategory=”true” includeLevel=”true” includeDate=”true” includeTime=”true” level=”{LogEventLevel.DEBUG}” fieldSeparator=”|”/> </fx:Declarations> <fx:Script> <![CDATA[ import mx.logging.LogEventLevel; ]]> </fx:Script> <debug:LoggingButton id=”myLoggingButton” label=”Log Click Event” horizontalCenter=”0” top=”20”/> </s:Application> On the Web The code in Listing 6.2 is available in the Web site files in the chapter06 project folder as UseLogging Button.mxml . n 11_488959-ch06.indd 17911_488959-ch06.indd 179 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 180 The Logging API can enable you to build applications that keep you informed about their actions during a debugging session without having to make constant calls to the trace() method. With some advanced ActionScript programming, you also can create your own custom logger and trac- ing target classes. Using Breakpoints A breakpoint enables you to suspend application execution at runtime and inspect the applica- tion’s current state. Once you’re in a breakpoint, you can look at variable values, evaluate arbitrary ActionScript expressions, and take other actions that help you figure out what’s happening. Setting and clearing breakpoints Breakpoints can be set on any line that includes at least one ActionScript statement. For example, this code declares a button component but has no ActionScript code: <s:Button label=”Debug”/> If you set a breakpoint on the line containing that MXML declaration and then run the application in debug mode, the breakpoint icon changes to display a little red X to indicate that it will be ignored by the debugger. If you then hover the mouse cursor over the breakpoint while the application is sus- pended, Flash Builder displays a tooltip saying that you can’t put a breakpoint in that location. If, however, the same MXML declaration includes an event handler that executes some ActionScript code, it becomes a valid target for a breakpoint: <s:Button label=”Debug” click=”clickHandler()”/> Because this version of the declaration executes an ActionScript statement, placing a breakpoint on that line successfully suspends the application when the user clicks the button. Setting and removing breakpoints in an MXML or ActionScript editor You can set or remove a breakpoint in an MXML or ActionScript editor. To do so, perform one of these actions: l Place the cursor on the line where you want the breakpoint, and press Ctrl+Shift+B (Windows) or Ô+Shift+B (Mac). l Double-click the line number in the editor. l As shown in Figure 6.7, right-click the line number in the editor, and select Toggle Breakpoint. As shown in Figure 6.8, the breakpoint appears as a small dot to the left of the line number. 11_488959-ch06.indd 18011_488959-ch06.indd 180 3/5/10 2:23 PM3/5/10 2:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... the application’s remote request fails, return to Flash Builder and select Project ➪ Clean from the menu Then click OK in the Clean dialog box Flash Builder rebuilds the project from scratch and copies the data and CFC files to the server Then run and test the application again n 4 Close the browser and return to Flash Builder 5 Open WebServiceDemo.mxml and look at the code This application retrieves... resumes and then is suspended again at the line you selected n FIGURE 6.20 Flash Builder s Run menu during a debugging session Profiling Flex Applications Flash Builder includes tools for profiling Flex applications at runtime, providing valuable information about the frequency and duration of method calls, the size and number of object instances in memory, and overall memory usage Note The Flex profiling... Monitor Each uses one of the Flex SDK’s RPC components to communicate with the server and retrieve data Configuring a Flex project to use ColdFusion First I describe how to configure a Flex project for use with ColdFusion Flash Builder 4 enables you to configure an existing Flex project for use with an application server; this is a new feature that wasn’t available with Flex Builder 3 1 In the Package... the Flex and ColdFusion code both assume this relative location for the Web service and Flash Remoting applications n 197 Part I: Flex Fundamentals FIGURE 6. 24 Configuring the Flex project for use with ColdFusion 7 Click Validate Configuration to confirm that Flash Builder is able to connect to ColdFusion You should see a message at the top of the dialog box indicating that the Web root folder and. .. overall memory usage Note The Flex profiling tools were added in Flex Builder 3 They are included only with a Flash Builder Premium license n The profiling tools are packaged in a Flash Builder perspective named the Flash Profile perspective (formerly named the Flex Profiling perspective) You can profile an application from the Flash Builder toolbar or menu Follow these steps to run an application... data Next you’ll run the WebServiceDemo application and inspect the request and response Follow these steps: 1 Open and run WebServiceDemo.mxml 2 When the application appears in the browser, click Get Data 203 Part I: Flex Fundamentals 3 After the data has been retrieved and displayed in the application, close the browser and return to Flash Builder 4 Look at the Network Monitor view 5 Click the WebService... this option, Flash Builder always switches to this perspective automatically in future uses of breakpoints You can turn this on and off by selecting an option in the Run/Debug section of Flash Builder s Preferences dialog box n After a breakpoint has been activated, Flash Builder shows you the current code execution position with the Debug Current Instruction Pointer, shown in Figure 6. 14 If you move... you to trace and inspect network traffic at runtime The new Network Monitor brings back these capabilities and improves on them It’s tightly integrated into Flash Builder, so you no longer need to start up an extra application to get the debugging information you need You can use the Network Monitor to inspect the size and contents of requests and responses sent between the Flex client and the application... operator n Using the Breakpoints view Flash Builder s Breakpoints view shows you the application’s current breakpoints and enables you to add, remove, enable, or disable breakpoints as needed The Breakpoints view is displayed in the Flex Debugging perspective To use the Breakpoints view, follow these steps: 1 Choose Window ➪ Perspective ➪ Flex Debugging from the Flash Builder menu 2 Click the Breakpoints... window displaying information about the current line 186 Chapter 6: Debugging Flex Applications FIGURE 6. 14 The Debug Current Instruction Pointer and current line information Inspecting variables and expressions When a breakpoint is active during a debugging session, Flash Builder enables you to inspect values of variables and objects that are in the application’s scope You can use two views for this . watermark. Chapter 6: Debugging Flex Applications 173 Trace messages in Flash Builder s Console view When you debug a Flex application with Flash Builder, the value. RoamingMacromedia Flash PlayerLogs Linux /home/username/.macromedia /Flash_ Player/Logs 11 _48 8959-ch06.indd 1 741 1 _48 8959-ch06.indd 1 74 3/5/10 2:23 PM3/5/10

Ngày đăng: 22/01/2014, 01:20

Từ khóa liên quan

Mục lục

  • Adobe Flash® Builder™ 4 and Flex® 4 Bible

    • About the Author

    • Credits

    • Contents at a Glance

    • Contents

    • Preface

      • Getting the Most Out of This Book

      • Using the Book’s Icons

      • Acknowledgments

      • Part I: Flex Fundamentals

        • Chapter 1: About Flex 4

          • Learning the Fundamentals of Flex

          • Understanding Adobe Flash Player

          • Flex 4 Development Tools

          • Getting Help

          • Summary

          • Chapter 2: Using Flash Builder 4

            • Getting Flash Builder

            • Installing Flash Builder 4

            • Getting to Know Eclipse Features

            • Using Flash Builder

            • Getting Help

            • Searching for Code

            • Generating Code

            • Integrating Flash Builder with Flash Professional CS5

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan