Beginning Ajax with ASP.NET- P26 pptx

15 108 0
Beginning Ajax with ASP.NET- P26 pptx

Đ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

install the Venkman tool within Firefox. Once installed, the tool can be accessed from the Tools➪JavaScript Debugger menu option. Note that the direct link to the download/install location is https://addons.mozilla.org/ extensions/moreinfo.php?id=216 . This section does not attempt to provide a detailed examination of the features and functionality of the Venkman debugger, because this is beyond the scope of this chapter. Instead, this is a brief overview provided to give you an idea of what is possible with Venkman. Detailed information and tutorials are available from the link shown in the preceding Note. Venkman allows a complete JavaScript debugging experience within the Firefox browser. The interface of Venkman is not as intuitive as the server-side debugging experience within Visual Studio .NET; however, it does provide a very usable and powerful way of debugging JavaScript code by supporting standard and advanced debugging features such as: ❑ Setting of breakpoints within JavaScript code ❑ Triggering of breakpoints based on conditions within your code such as a value of a variable or when an exception is thrown ❑ Adding watch conditions to monitor the value of variables within currently executing script code ❑ Supporting of multiple views within the Venkman interface, providing a fully customizable interface ❑ Profiling of JavaScript code to measure the execution speed of your JavaScript application These features provide a similar client-side debugging experience to that provided by Visual Studio .NET on the server side; however, even advanced features such as profiling are not natively supported by Visual Studio .NET, especially on the client side. Venkman is a free download that not only provides exceptional value, but also provides a powerful array of features that are a valuable asset to any devel- oper doing JavaScript development, most notably developers writing Ajax applications. The Man in the Middle The IE Developer Toolbar for Internet Explorer, the DOM Inspector within Firefox, and the Venkman debugger are valuable tools to assist a web developer in debugging, and identifying any issues within a web page or application. These combined with both server- and client-side debugging features previ- ously discussed, provide an excellent set of tools and techniques to identify, debug, and resolve issues within web applications, particularly those that contains a large degree of JavaScript. However, at this point, one area remains largely unaddressed — that of the actual HTTP traffic that is generated by the web application itself. This is particularly important for Ajax-style applications that can initiate many asynchronous postback operations that are not immediately apparent by just examining the user interface and any associated interaction. Without being able to examine the actual data that form the HTTP communication, a developer can identify issues based only on the effects of the data that is sent and received, and, therefore, make assumptions given those effects. To make this point clear, Figure 13-22 illustrates what aspect of the web application is being referred to. 351 Debugging 16_78544X ch13.qxp 7/18/06 3:18 PM Page 351 Figure 13-22 Clearly, the actual traffic being sent and received by a web application is crucial to its correct operation, and you would assume that if the code were correct at both the client and server levels, then examining the actual content of the HTTP traffic would not be necessary. In some cases, this may be correct; however, it is not always apparent when some code is incorrect. Furthermore, assumptions can be made regarding the operation of the application and associated code that result in unexpected HTTP contents that can adversely affect the operation of the application and yield incorrect and/or unexpected results. This becomes very apparent when dealing with HTTP headers. The HTTP headers that are sent with a request need to be very specific to the operation being performed. For most operations, these headers are implicitly sent along with any requests you make from code, or in some cases, easily mistaken. Examine the following example code: <script type=”text/javascript”> function MakeXMLHTTPCall(){ var xmlHttpObj; xmlHttpObj = CreateXmlHttpRequestObject(); if (xmlHttpObj) { The HTTP requests and responses generated by an application flow between the client (browser) and the web server. How do we know what gets sent and received? Workstation Web Browser Web Server HTTP Traffic/Data Request Response Request Response 352 Chapter 13 16_78544X ch13.qxp 7/18/06 3:18 PM Page 352 xmlHttpObj.open(“POST”,”http://” + location.host + “/Chap14/DataFile.xml”, true); xmlHttpObj.onreadystatechange = function() { if ( xmlHttpObj.readyState == READYSTATE_COMPLETE ) { alert(“Request/Response Complete”); } } xmlHttpObj.send(null); } } </script> When this code is executed, an alert box is presented stating that the request/response is complete, and the code seems to have been successful. If you were to examine the traffic generated by this request, you would see that this request actually generated a 405 error code and was unsuccessful. The problem is that the code specifies a POST operation in the following line: xmlHttpObj.open(“POST”,”http://” + location.host + “/Chap14/DataFile.xml”, true); A GET operation should be used here instead, as shown in the following line: xmlHttpObj.open(“GET”,”http://” + location.host + “/Chap14/DataFile.xml”, true); Without your being able to examine the network traffic and associated error codes, it would not be easily apparent what error was occurring and the fact that the POST verb was the cause of the problem. What is required is a tool that enables a developer to examine and monitor the traffic negotiated between the client and the server — the data that goes over the wire. A tool for just this purpose is the subject of the next section. In some cases, it may also be necessary to specifically construct the data that is sent to a server, and ulti- mately, the only way to truly verify that the server is receiving what you think it’s being sent is to actually examine what is being sent. There are many tools and network monitors available that will allow you to examine network traffic in various forms. However, the actual function of sending data over the network (whether that network be the Internet or a local intranet) relies on many layers of networking components and protocols acting together. Web developers are typically interested only in the traffic pertinent to their web application. One such tool that effectively provides this functionality is Fiddler. Fiddler Fiddler is a freely available tool that installs as a component that can be activated from within Microsoft Internet Explorer and allows the HTTP traffic between a browser and a server to be easily viewed, exam- ined, and manipulated, or fiddled with (hence, the name of Fiddler). The Fiddler home page, where a copy can be downloaded, is located at www.fiddlertool.com/fiddler. 353 Debugging 16_78544X ch13.qxp 7/18/06 3:18 PM Page 353 A full set of documentation, instructions, and tutorials exists on Fiddler site, and this is not intended to be a detailed instructional text on how to use Fiddler. However, it is worth discussing how this tool can be used to assist the debugging process within a web application, specifically using Ajax techniques. Once Fiddler has been downloaded and installed, it can be accessed by selecting the Tools➪Fiddler menu option. In addition, it appears as a new icon within the Internet Explorer toolbar (see Figure 13-23). Figure 13-23 Try It Out Using Fiddler To see Fiddler in action, create a new web site project within Visual Studio .NET. Add a new page (or modify the existing default.aspx page) so that the web page and associated code-beside file contain the following code. TestFiddler.aspx —Web Form <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”TestFiddler.aspx.cs” Inherits=”FiddlerExamples_TestFiddler” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Test Fiddler</title> <script type=”text/javascript”> function OnCallComplete(arg,ctx) { var dataReturned = arg.split(“;”); var cnt = 0; for (var cnt=0; cnt < dataReturned.length;cnt++) { alert(“Data #” + cnt + “ returned was: “ + dataReturned[cnt]); } } </script> </head> <body> <form id=”form1” runat=”server”> <div> <button onclick=”DoCallback(null,null);”>Do Async Callback</button> </div> </form> </body> </html> 354 Chapter 13 16_78544X ch13.qxp 7/18/06 3:18 PM Page 354 TestFiddler.aspx.cs —Code-Beside file using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class FiddlerExamples_TestFiddler : System.Web.UI.Page, ICallbackEventHandler { protected void Page_Load(object sender, EventArgs e) { string js = Page.ClientScript.GetCallbackEventReference(this, “arg”, “OnCallComplete”, “ctx”, true); string jsFunction = “function DoCallback(arg,ctx) { “ + js + “ } “; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “Callback”, jsFunction,true); } #region ICallbackEventHandler Members public string GetCallbackResult() { System.Threading.Thread.Sleep(2000); string[] dataToReturn = new string[] { “Data1”, “DataPart2”, “SomeData3” }; // return a hardcoded string array as a single string return string.Join(“;”, dataToReturn); } public void RaiseCallbackEvent(string eventArgument) { // Do nothing here } #endregion } Ensure that the application runs by right-clicking on the modified page with the mouse and selecting View in Browser. A simple web page should be displayed with a single button labeled Do Async Callback. Clicking the button with the mouse should result in a 2-second delay and then three alert boxes displaying the returned data values of Data1, DataPart2, and SomeData3. This page is obviously not very complex, but it does utilize an asynchronous postback to execute a server-side method and retrieve some data for display. Now click on the Fiddler icon shown previously or access the Fiddler tool by selecting the Tools➪Fiddler menu option. 355 Debugging 16_78544X ch13.qxp 7/18/06 3:18 PM Page 355 This will display a new dialog window. Ignore that window for now, but do not close it. Select the previ- ous browser window (that is running the web page previously listed), and click the button labeled Do Async Callback. The same result should be seen within the browser, that is, the display of the three result values. Bring the Fiddler window to the foreground by clicking in the window or selecting it in the windows taskbar. You will notice that all requests made by the browser are now logged in the Fiddler window. These will include the original request for the page as specified in the address bar, but also any additional requests for images, script libraries, and other resources that the page loads as part of its functionality and display. The Fiddler screen should now look similar Figure 13-24. Figure 13-24 You will notice that the asynchronous request issued by the browser has been logged in the Fiddler win- dow in the left-hand pane (indicated in the figure by the localhost:1511 entry, although the port number may be different on different systems). Select this entry by clicking on it with the mouse. The right-hand section of the display should now show some details about the request. This initial display shows some simple performance timings as well as the total bytes for the request and response itself. Click on the Session Inspector tab in the right-hand pane. This will initially display the HTTP headers that were sent as part of the HTTP request in the top right-hand pane. The bottom right-hand pane will auto- matically have the Transformer section selected. Select the Headers tab in the bottom right-hand pane. This will then display the HTTP headers that were sent from the web server as part of the response. The Fiddler display window should now look like Figure 13-25. 356 Chapter 13 16_78544X ch13.qxp 7/18/06 3:18 PM Page 356 Figure 13-25 This is useful for examining the HTTP headers of the request/response sequence to ensure that the correct headers are being set in an easy-to-view tree-type display. This is especially important when for- mulating your own Simple Object Access Protocol (SOAP) requests (as demonstrated in Chapter 4 of this book). However, one of the most useful aspects of Fiddler is the ability to examine the raw contents of the request/response sequence. With the Fiddler display still showing the headers, click on the Raw tab in both the top and bottom right-hand panes. This display shows the entire request and response data, including header information, as it would be sent by the client and received from the server. In the top-right pane, showing the request, you can see the HTTP headers and also the associated data payload of the HTTP request. This should be something similar to the following text: __EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUJNzgzNDMwNTMzZGRyE%2BruV%2Bh77 fo76pKQAZFknAX7Ag%3D%3D&__CALLBACKID=__Page&__CALLBACKPARAM=null From this, you can get an idea of how asynchronous client script callbacks notify the server of what control generated the callback and what the argument of the call is (via the _CALLBACKID=__Page and __CALLBACKPARAM=null arguments, respectively). 357 Debugging 16_78544X ch13.qxp 7/18/06 3:18 PM Page 357 Looking at the request data in the bottom-right pane, again you can see the HTTP headers that form the response and also response data that has been sent back as a result of the asynchronous request. The response data should look similar to the following: 0|Data1;DataPart2;SomeData3 This enables you to verify that what is being displayed within the browser through the application code is in fact what has been returned by the server. Try It Out Using Fiddler Breakpoints to Manipulate Request/Response Data Directly One of the most powerful features of Fiddler is its ability to allow request and response data to be altered by setting breakpoints at the request and response points. This is completely external to the breakpoints associated with any client- or server-side code. Once a Fiddler breakpoint is hit, request or response data can be examined and/or manipulated and then allowed to continue to its destination with the modified data. This provides an excellent way of debugging and testing your applications. An example best illustrates this. Create a new web page within Visual Studio .NET and copy the follow- ing code into the web page ( .aspx file) and the code-beside file (.cs file), respectively. Web Form —TestFiddlerBreakpoint.aspx <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”TestFiddlerBreakpoint.aspx.cs” Inherits=”FiddlerExamples_TestFiddler” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Test Fiddler Breakpoint</title> <script type=”text/javascript”> function OnCallComplete(arg,ctx) { alert(“The argument returned from the server was: “ + arg); } </script> </head> <body> <form id=”form1” runat=”server”> <div> <button onclick=”DoCallback(‘button clicked!’,null);”>Do Async Callback</button> </div> </form> </body> </html> Code-Beside File — TestFiddlerBreakpoint.cs using System; using System.Data; using System.Configuration; 358 Chapter 13 16_78544X ch13.qxp 7/18/06 3:18 PM Page 358 using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class FiddlerExamples_TestFiddler : System.Web.UI.Page, ICallbackEventHandler { private string _argReceived = null; protected void Page_Load(object sender, EventArgs e) { string js = Page.ClientScript.GetCallbackEventReference(this, “arg”, “OnCallComplete”, “ctx”, true); string jsFunction = “function DoCallback(arg,ctx) { “ + js + “ } “; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “Callback”, jsFunction,true); } #region ICallbackEventHandler Members public string GetCallbackResult() { System.Threading.Thread.Sleep(2000); return string.Format(“The argument received by the server was ‘{0}’ at {1}”, _argReceived, DateTime.Now.ToShortTimeString()); } public void RaiseCallbackEvent(string eventArgument) { _argReceived = eventArgument; } #endregion } As performed in the previous section, using the mouse, right-click on this page in Visual Studio .NET and select View in Browser. Verify that the application works as expected by clicking the button on the web page. An alert box should be displayed with the text similar to that shown in Figure 13-26. Figure 13-26 359 Debugging 16_78544X ch13.qxp 7/18/06 3:18 PM Page 359 The server-side method simply accepts the argument that was sent by the client and returns a string displaying that argument, in addition to the time on the server. In the previous example, the client (browser) sent the string button clicked! as an argument. Click on the Fiddler icon or select the Tools➪Fiddler menu option to load the Fiddler display. Select the Rules➪Automatic Breakpoints➪Before Requests menu option, or simply press the F11 key. Now click on the button on the web form to initiate the asynchronous call. On the taskbar, the Fiddler task icon should highlight to indicate it requires some acknowledgment. Switch to the Fiddler application and select the request that was initiated (in the left-hand Fiddler pane) with the mouse. Click on the Session Inspector tab in the top right-hand pane of the Fiddler display. The display should look similar to Figure 13-27. Figure 13-27 Fiddler has intercepted this request, and because you have enabled breakpoints on requests, Fiddler has stopped the request from proceeding until you allow it to proceed. Select the TextView tab in the top right-hand pane of the Fiddler display. The text content of the HTTP Request data should be displayed and look similar to the following text: __EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUJNzgzNDMwNTMzZGT4go7HPnnHZvVOI xsR9u48Hce4EA%3D%3D&__CALLBACKID=__Page&__CALLBACKPARAM=button%20clicked! 360 Chapter 13 16_78544X ch13.qxp 7/18/06 3:18 PM Page 360 [...]... copy of the current node with namespace nodes but without child nodes and attributes copy-of This element creates a copy of the current node as well as namespace nodes, child nodes, and attributes of the current node decimal-format This element provides the characters and symbols used when converting numbers in strings This element is used along with the format-number()... This element is used to specify an action for the element When the element returns a true, an action is performed with- param This defines the value of a parameter that is passed to a template For the to work, the name in the with- param element must match the name in the element XSLT Functions XSLT contains a set of built-in methods Other methods used... utilized within a client script scenario This type of code has traditionally been very difficult to debug, and Visual Studio NET makes this task much simpler, enabling the use of familiar debugging methods and techniques ❑ In addition, techniques to investigate and manipulate the DOM tree were provided to allow a detailed view of how the web page is represented The DOM is used internally within browsers... characters are output as their encoded versions transform This element is synonymous with the stylesheet element variable This element is used to declare a local or global variable If no value is specified for the select attribute, a value may be defined within the element when This element is used to specify an action... desired behavior within web applications ❑ Finally, a method of investigating, testing, and modifying the data that actually travels between the client and server was examined The freely available Fiddler tool was used to provide a powerful and easy to use way of viewing, manipulating, and intercepting this data in both a structured display and also in its raw form 361 Chapter 13 At the beginning of this... value of yes will terminate processing after the message is sent to the output stream The value of no will allow processing to continue namespace-alias This element replaces a namespace in the style sheet with a different namespace in the output stream number otherwise This element specifies a default action for...Debugging Replace the text button%20clicked! with the text I_am_a_hacker (note: do not use spaces) The request data should now look like the following: EVENTTARGET=& EVENTARGUMENT=& VIEWSTATE=%2FwEPDwUJNzgzNDMwNTMzZGT4go7HPnnHZvVOI xsR9u48Hce4EA%3D%3D&... another include This element includes the contents of one style sheet in another key This element declares a named key that may be used in a style sheet with a key() function message This element writes a message to the output This is typically used to report errors back to the output stream . dealing with HTTP headers. The HTTP headers that are sent with a request need to be very specific to the operation being performed. For most operations, these headers are implicitly sent along with. default.aspx page) so that the web page and associated code-beside file contain the following code. TestFiddler.aspx —Web Form <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”TestFiddler.aspx.cs” Inherits=”FiddlerExamples_TestFiddler”. on the modified page with the mouse and selecting View in Browser. A simple web page should be displayed with a single button labeled Do Async Callback. Clicking the button with the mouse should

Ngày đăng: 03/07/2014, 06:20

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

Tài liệu liên quan