1. Trang chủ
  2. » Công Nghệ Thông Tin

O’Reilly Programming Flex 2 phần 10 docx

59 1,1K 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 59
Dung lượng 1,06 MB

Nội dung

Debugging with Flex Builder 2 | 417 While debugging, you also have the ability to review values of variables at runtime. The Variables panel (see Figure 17-5) will list all object instances as well as their child properties and values. To change a value, right-click on the variable and select Change Value. This will prompt you for the new value. When debugging an application, you also have the ability to set break- points in and step through Flex framework code. Stepping through framework code will happen automatically when needed. To set breakpoints within the framework, you will need to open the class file. An easy way to do this is to use the shortcut Ctrl-Shift-T within Flex Builder 2 and select the appropriate type. Once the class file is opened, you can set breakpoints as you would normally. You can have only a single active debug session running at once. To end a debug ses- sion you can either close Flash Player or your browser, or you can click on the red square within the Debug panel. Caution should be taken when closing an active debug session by closing the browser when it is executing within a browser, as ses- sions that are in a halted state can cause a web browser to close unexpectedly. This book does not fully cover all the functionality possible with the debugger within Flex Builder 2. For full coverage, you can review the documentation provided with Flex Builder 2. Figure 17-5. The Variables panel 418 | Chapter 17: Application Debugging Remote Debugging When attempting to isolate a bug in an application, it is possible that you will encounter a case where a bug is reproducible on only a specific machine. For such a case, you can use the Flash Debug Player’s remote debugging feature. This feature can also be useful if you would want to use the Flex Builder debugger on a Windows or Mac-based machine while the application is executed under Linux, which does not have a native version of Flex Builder available. As mentioned earlier, debugging occurs over a TCP connection on port 7935. Such a connection is typically established on the same machine transparently, but with remote debugging it is established from one machine to another. One machine will typically be running the debugger and can be referred to as the server, while the other will be running the application and can be referred to as the client machine. Once a connection is established between the client and the server, all of the features of using a debugger function in the same manner. It’s important to remember that in a typical workstation, the the client machine may not be configured properly for remote debugging. Remember that the Flash Debug Player is required for a debug session, so you will need to ensure that it is installed on the client machine. It is also important to keep in mind that the client machine will need to be executing a debug- enabled SWF in the same manner as we discussed earlier in the chapter. To initiate a debug session, follow these steps: 1. Initialize the debugger on the server machine. • With FDB: One benefit of using FDB when initializing a remote debugging session is that the steps for initializing FDB are exactly the same as initializ- ing a local session. You initialize FDB by launching FDB and executing the run command. • With Flex Builder’s Debugger: Initializing a remote debugging session with Flex Builder is more involved. Flex Builder’s debugger doesn’t formally sup- port remote debugging, although it is possible. We will cover remote debug- ging with Flex Builder in the next section. 2. Initialize the debug-enabled SWF on the client machine and ensure that the debug player is installed. 3. Once initialized, the player will prompt you for a debugger, because the debug- ger is not running on the client machine. Input the IP address of the server run- ning the debugger and select Connect. 4. If the server is running the debugger and listening for a connection, the client and server will connect. Note here that you will also need to ensure that the server is not blocking port 7935. Once a connection has been established, debugging can be performed in the same manner discussed earlier in this chapter. Logging Using trace( ) Within an Application | 419 Establishing a Remote Debugging Session with the Flex Builder Debugger As mentioned earlier, debugging sessions—both local and remote—are established over a TCP connection on port 7935. Flex Builder uses the same connection to estab- lish debug sessions. Although by default Flex Builder does not expose remote debug- ging capabilities, it still is possible to do so. To initiate a remote debug session with Flex Builder, follow these steps: 1. Compiled a debug-enabled .swf. 2. Copy the debug-enabled .swf to the remote client machine. 3. On the machine that will run the Flex Builder debugger (server), create an empty HTML file (typically within your project’s bin folder). 4. Ensure that no firewall is actively blocking port 7935. 5. Edit the debug configuration within Flex Builder (select Run ➝ Run). 6. Select the target debug configuration. 7. Uncheck the “Use defaults” checkbox. 8. Click on the Browse button for the debug file path. 9. Select the blank HTML page. 10. Click on Run (at this point, Flex Builder is waiting for a remote connection, in the same manner FDB does). 11. Open the debug-enabled .swf on the remote machine and, when prompted for a remote host address, input the host address of the machine with the Flex Builder debugger. Logging Using trace( ) Within an Application Although not an advanced debugging technique, at one time or another a developer will find a need to trace (also referred to as log) messages from within an applica- tion. For this purpose, Flash Player exposes a global trace( ) method. Messages can be logged from anywhere within an application simply by calling the trace( ) method and passing any parameter of type string: trace("application initialized"); Trace messages are typically displayed by attaching the debugger to an application. With an active FDB debug session, trace messages will be displayed in the console. With Flex Builder, launching a debug session will automatically do this and trace messages will be shown in the Console panel in the debugging perspective (see Figure 17-6). 420 | Chapter 17: Application Debugging One of the great benefits of using the trace statement in this manner is the ability to receive the messages in real time while an application is running. The trace( ) method also supports passing in arrays or multiple arguments (REST-style argu- ments). This can be very useful in dumping data for informational purposes—for example, if you wanted to be able to easily track what children are currently in the Display Child list. Example 17-1 contains two children. When you click the button, the clickHandler( ) function is called and an array of children is displayed in the output window. As with other debugging methods we have seen thus far, using the trace( ) function requires the Flash Debug Player. Although often you will just use the Flex Builder Debugger to output trace messages, with the debug version of the player you have the option of outputting the trace messages to a file. You may want to use this fea- ture if you are having a hard time isolating user-reported bugs by having the user configure his machine to log all trace calls to a file and allow you to review the log- files at a later time for clues on what sequence of events may have caused the bug. Figure 17-6. Flex Builder Debugger Console panel Example 17-1. Calling the clickHandler( ) function <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script> <![CDATA[ private function clickHandler( ):void { trace(this.getChildren( )); } ]]> </mx:Script> <mx:Button id="buttonOne" click="clickHandler( )" label="Dump Data"/> <mx:Label id="labelTwo"/> </mx:Application> The Logging Framework | 421 This also is useful for when a tester isolates a bug in an application and provides cor- responding log information. By default, installing the Debug Player does not enable trace logging. You will need to configure the player to enable logging. The configuration filename is mm.cfg. Under Windows XP, it is located at C:\Documents and Settings\user_name, and under Mac OS X, it is located in /Application Support/Macromedia/Flash Player/. For other operating systems, consult the Flash Player documentation. First review your operating system-specific path for an existing mm.cfg. If none already exists, you will need to create one. The configuration file is a plain text file that supports several options. Most important, you will be interested in the ErrorReportingEnable, MaxWarnings, TraceOutputFileEnable, and TraceOutputFileName configuration properties. A basic mm.cfg file that enables the trace output includes the following: TraceOutputFileEnable=1 Once the configuration file is updated and saved to the proper location with the file- name mm.cfg, the Flash Debug Player will log trace messages to the same location as the mm.cfg file with a log filename of flashlog.txt. You may also be interested in log- ging all errors; if so, you just need to enable ErrorReportingEnable: TraceOutputFileEnable=1 ErrorReportingEnable=1 If you prefer to create a logfile not in the default location, or if you want to use a dif- ferent filename, you may do so using the TraceOutputFileName property. Here we are creating a logfile in the root drive with the filename weirdBug.txt: TraceOutputFileEnable=1 ErrorReportingEnable=1 TraceOutputFileName=c:/weirdBug.txt The Logging Framework The trace( ) statement can be a powerful method of logging, but if you have any for- mal logging experience, you likely used some sort of logging framework or built your own. Flex includes a logging framework that offers several benefits over using the trace( ) statement alone. The logging framework consists of two main components: the logger and the target. The logger is used by an application to configure the logging framework and to send messages which are output via a target. A target is used to specify where log messages are output. They can be output to any mechanism that Flash Player supports. The logging framework includes a TraceTarget, which inherits from LineFormattedTarget and AbstractTarget and implements the ILoggingTarget interface. 422 | Chapter 17: Application Debugging TraceTarget internally sends messages via the global trace( ) function. This will often be the target you use. Here’s an example using the logging framework with TraceTarget: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="initializeHandler( )"> <mx:Script> <![CDATA[ import mx.logging.Log; import mx.logging.targets.TraceTarget; private var _target:TraceTarget; private function initializeHandler( ):void { _target = new TraceTarget( ); _target.includeTime = true; _target.includeLevel = true; _target.includeCategory = true; Log.addTarget(_target); } private function sendToLog( ):void { Log.getLogger("com.oreilly.programmingflex.MainClass").info("Log Message"); } ]]> </mx:Script> <mx:Button click="sendToLog( )" label="Log Message"/> </mx:Application> In this example, clicking on a button will send a message in the same manner as call- ing trace( ) would. The main distinction to just using trace( ) is the ability to config- ure the target to include extra information, supply a category for a message, and have different levels of errors. The Flex framework internally uses the logging framework within the mx.rpc.* package with the WebService, RemoteObject, and HTTPService components. This allows you to retrieve details of the communication between the Flex client and the server. We will cover debugging remote data communication later in this chapter. A target can support extra functionality. In the preceding example, the date, cate- gory, and level were enabled. This will instruct the target to include the time, cate- gory of message, and level with the messages. The built-in targets support other properties which you may want to explore. The Logging Framework | 423 Specifying the Logging Options A log message must define two values: the level of the message, which we discussed, and the category. The category is required to define the origins of a message and, in return, allow you to filter what is displayed by the logging framework. In the preced- ing example, the category was com.oreilly.programmingflex.MainClass. It is a good idea to specify a category based on the package and class, as this will allow you to easily filter and identify the origins of logged messages. The built-in targets support the ability to filter the messages so that only messages you are interested in are displayed. This is useful in cases where you are interested only in log messages within a certain package, and is achieved via the filters prop- erty of the target. The filters property accepts an array of categories. A category fil- ter can be any text value, but it is recommended that you follow package-naming conventions. You may also specify an * (wildcard) filter—for example, the following category filter of com.oreilly.* will instruct the target to output all messages in the com.oreilly package and within its subpackages: _target.filters = ["com.oreilly.*"]; You also can define multiple filters as well as redefine the filters at any time. Setting the level is achieved in a similar manner. The default logging level is ALL, but you can define another level by setting the level property: _target.level = LogEventLevel.FATAL; The logger supports sending several levels of messages with the debug(), error(), fatal( ), info( ), and warn( ) methods. Alternatively, you can call the log( ) method of the logger and pass in a log level. You can find the different levels with the con- stant values LogEventLevel.FATAL, LogEventLevel.ERROR, LogEventLevel.WARN, LogEventLevel.INFO, and LogEventLevel.DEBUG. This can be useful if you want to out- put all messages during development and debugging, but limit what is output in a production environment. When setting a log level, all messages in that level and above are logged. For example, setting the level to WARN will log all messages with that level as well as messages with a FATAL or ERROR level. Defining a Custom Target If the built-in targets are not sufficient, you can define your own. To define your own target you need to implement the ILoggingTarget interface. For convenience, the log- ging framework includes the AbstractTarget class, which already implements a default set of behaviors that you can easily subclass to define your own target. Example 17-2 is a custom target that will send a message to a remote server via the Socket class rather than via trace( ). 424 | Chapter 17: Application Debugging Example 17-3 is updated to use the new SocketTarget. Example 17-2. Custom target sending a message to a remote server via the Socket class package com.oreilly.programmingflex.logging.targets { import flash.net.Socket; import mx.logging.LogEvent; import mx.logging.AbstractTarget; public class SocketTarget extends AbstractTarget { private var _host:String; private var _port:int; private var _socket:Socket; public function SocketTarget(host:String = "localhost",port:int = 18080) { _host = host; _port = port; //This example ommits the error handling, for production you will //need to handle errors when creating the socket and when sending //messages _socket = new Socket(host,port); super( ); } override public function logEvent(event:LogEvent):void { _socket.writeUTF(event.message); _socket.flush( ); } } } Example 17-3. Example 17-2 updated to use the new SocketTarget <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="initializeHandler( )"> <mx:Script> <![CDATA[ import com.oreilly.programmingflex.logging.targets.SocketTarget; import mx.logging.Log; private var _target:SocketTarget; private function initializeHandler( ):void { _target = new SocketTarget( ); Log.addTarget(_target); } private function sendToLog( ):void Debugging Remote Data | 425 With Flex’s built-in logging framework, you will be able to log messages, easily change options so that you can more easily debug an application, and integrate the framework within your application. Debugging Remote Data Although you can use the debugger to inspect data after Flex has received it and before Flex sends it, you may want to find out more details regarding what data is being sent and received. You can achieve this by using the logging framework, or a data inspector. Debugging with the Flex Logging Framework The WebService, HTTPService, and RemoteObject components use the Flex logging framework, which can greatly assist debugging applications. Messages are automati- cally logged to the Flex logging framework, so you won’t need to enable the compo- nents to explicitly begin logging. Messages that are logged are within the mx. messaging.* filter. Example 17-4 is an HTTPService call with a TraceTarget that will only show log messages related to the server calls. { Log.getLogger("com.oreilly.programmingflex.MainClass").info("Log Message"); } ]]> </mx:Script> <mx:Button click="sendToLog( )" label="Log Message"/> </mx:Application> Example 17-4. HTTPService call with a TraceTarget that shows log messages related to server calls <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="initializeHandler( )"> <mx:Script> <![CDATA[ import mx.logging.Log; import mx.logging.targets.TraceTarget; private var _target:TraceTarget; private function initializeHandler( ):void { _target = new TraceTarget( ); _target.includeTime = true; _target.includeLevel = true; _target.includeCategory = true; _target.filters = ["mx.messaging.*"]; Log.addTarget(_target); } Example 17-3. Example 17-2 updated to use the new SocketTarget (continued) 426 | Chapter 17: Application Debugging This example will log messages from the HTTPService but not from the button click handler, which can be very useful when you are working with a larger application and you are only interested in viewing the log information from the mx.rpc compo- nents. The server component logs useful information on both the data that is being sent and received, as well as the information that can be used for profiling messaging performance. For the WebService component, this can be especially useful in gauging Flex’s performance in terms of serializing and deserializing SOAP messages. Debugging Using a Data Inspector When debugging network programming code, using a data inspector (packet sniff- ing tools or a proxy) is invaluable. With Flex, these tools can also be very useful. Adobe does not provide such a built-in tool, but many tools exist that work with Flex. If you are already comfortable with a tool, you can continue to use that tool. Some common network debugging tools include the following: ServiceCapture This cross-platform proxy tool for debugging RPC communication supports AMF3 (http://kevinlangdon.com/serviceCapture). Charles This cross-platform proxy tool for debugging RPC communication also sup- ports AMF3 (http://www.xk72.com/charles/download.php). Wireshark (similar to Ethereal) This is a feature-complete packet sniffer that is capable of inspecting all traffic for both real-time applications as well as RPC (http://www.wireshark.org). Fiddler This is a quick HTTP proxy debugger that is free. It supports RPC debugging, but does not support AMF3 (http://www.fiddlertool.com). Summary In many ways, a development platform is only as good as the debugging capabilities available to the developer. In this chapter, we covered many of the methods you can use to debug Flex applications. private function sendToLog( ):void { Log.getLogger("com.oreilly.programmingflex.Logging").info("Log Message"); } ]]> </mx:Script> <mx:Button click="sendToLog( )" label="Log Message"/> <mx:Button click="service.send( );" label="Send HTTPService"/> <mx:HTTPService id="service" url="http://www.w3c.org"/> </mx:Application> Example 17-4. HTTPService call with a TraceTarget that shows log messages related to server calls [...]... styleName="heading" x= "10" y= "10" /> [Event(name="editChange", type="com.oreilly.programmingflex.contactmanager events.EditChangeEvent")] Flex framework) This code should look familiar to you in that you can work with the component in the same way you are used to working with the Flex component In... Chapter 2 Now, to update the main application file, we need to update the namespace reference to reflect the new package (see Example 18-3) MXML Component Basics | 431 Example 18-3 Updating the namespace to reflect the new package ... code, we have set the property value from the parent container: Most of the time, you will want a property to accept any value of... Example 18-5 Updated Main.mxml file referencing the enumeration value So far in this section, we covered using properties to pass and retrieve values... encoding="utf-8"?> In Example... Example 18-8 ContactDetails with event metadata tag added [Event(name="editChange", type="com.oreilly.programmingflex.contactmanager.events EditChangeEvent")] In Example 18-8, we added... the com.oreilly.programmingflex contactmanager.events package It is good practice as usual to specify a package for a class and for events, and to place all events in an events package This is consistent with the Flex framework and allows users to import a single package that will contain all events Here is the definition of the EditChangeEvent class: package com.oreilly.programmingflex.contactmanager.events . encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com /20 06/mxml" xmlns:pf2="com.oreilly. programmingflex.contactmanager.views.*"> <pf2:ContactDetails/> </mx:Application> MXML. xmlns:mx="http://www.adobe.com /20 06/mxml" width=" ;100 %" height=" ;100 %"> <mx:Label id="heading" styleName="heading" x=" ;10& quot; y=" ;10& quot;/> <mx:Button. xmlns:mx="http://www.adobe.com /20 06/mxml" initialize="init( )" xmlns: pf2=" com.oreilly.programmingflex.contactmanager.views.*"> <pf2:ContactDetails mode="view"

Ngày đăng: 06/08/2014, 08:22

TỪ KHÓA LIÊN QUAN