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

Beginning Ajax with ASP.NET- P26 pptx

15 109 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Tiêu đề Beginning Ajax With Asp.Net
Trường học University of Example
Chuyên ngành Computer Science
Thể loại Bài viết
Năm xuất bản 2025
Thành phố Example City
Định dạng
Số trang 15
Dung lượng 582,75 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Figure 13-22Clearly, 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 c

Trang 1

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 develdevel-opers 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

Trang 2

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

Trang 3

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 POSToperation in the following line:

xmlHttpObj.open(“POST”,”http://” + location.host + “/Chap14/DataFile.xml”, true);

AGEToperation 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 POSTverb 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

Trang 4

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.aspxpage) 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>

Trang 5

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

Trang 6

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 previprevi-ously 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:1511entry, 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

Trang 7

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= Pageand CALLBACKPARAM=nullarguments, respectively)

Trang 8

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 (.aspxfile) and the code-beside file (.csfile), 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;

Trang 9

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

Trang 10

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!

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