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

mcts 70-562 Microsoft .NET Framework 3.5, ASP.NET Application Development phần 8 potx

108 359 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 108
Dung lượng 1,25 MB

Nội dung

Lesson 1: Using Web Site Programmability CHAPTER 11 727 //C# public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; context.Response.TransmitFile(@"C:\Users\Public\Pictures\Sample Pictures\" + "dock.jpg"); } NOTE DEFINING THE MIME TYPE Note that this code sample sets the context.Response.ContentType property to “image/ jpeg.” You should use this property to defi ne the correct Multipurpose Internet Mail Extensions (MIME) type so that the browser knows how to handle the fi le you send it. Otherwise, the browser might try to display it as text. 7. Open the Web.confi g fi le. Navigate to the <httpHandlers> node. Add a handler that maps the .jpg fi le extension to your ImageHandler class. The following markup demon- strates this: <configuration> <system.web> <httpHandlers> <add verb="*" path="*.jpg" type="ImageHandler"/> </httpHandlers> </system.web> </configuration> 8. Open Default.aspx in the designer. Drag an Image control to the page. Change the ImageUrl property to Test.jpg. This fi le does not exist, so a placeholder is displayed in the designer. However, this is a request for a .jpg fi le. Your HttpHandler will intercept this request and display the image as defi ned in the ProcessRequest code (it will display Dock.jpg). 9. Run your application using the local Web application server (and not IIS). The local Web server will simulate the custom handler. You can verify the results in a browser window. Lesson Summary n You can catch unhandled exceptions at the page level by responding to Page_Error, or at the application level by responding to Application_Error. In either event handler, you read the last error by calling Server.GetLastError. Then, you must remove it from the queue by calling Server.ClearError. //C# public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; context.Response.TransmitFile(@"C:\Users\Public\Pictures\Sample Pictures\" + "dock.jpg"); } NOTE DEFINING THE MIME TYPE Note that this code sample sets the context.Response.ContentType property to “ image/ jpeg. ” You should use this property to defi ne the correct Multipurpose Internet Mail Extensions (MIME) type so that the browser knows how to handle the fi le you send it. Otherwise, the browser might try to display it as text. <configuration> <system.web> <httpHandlers> <add verb="*" path="*.jpg" type="ImageHandler"/> </httpHandlers> </system.web> </configuration> 7 2 8 CHAPTER 11 Programming the Web Application n You can call WebConfi gurationManager.GetSection to return a confi guration section from the Web.confi g fi le. You cast the returned object to the section-specifi c type. If you make an update to the confi guration settings, write the changes by calling Con guration.Save or Con guration.SaveAs. n Asynchronous Web pages can improve performance in scenarios where the thread pool might be limiting performance. To enable asynchronous pages, fi rst add the Async=”true” attribute to the @ Page directive. Then, create events to start and end your asynchronous code. n By default, ASP.NET handles a limited number of fi le types, including .aspx, .ascx, and .axd. You can confi gure ASP.NET to handle any fi le type, which is useful if you need to dynamically generate normally static fi les, such as images. To confi gure ASP.NET to receive requests for other types, you create a custom HttpHandler class and add the type to the Web.confi g fi le in the httpHandlers section. Lesson Review You can use the following questions to test your knowledge of the information in Lesson 1, “Using Web Site Programmability.” The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE ANSWERS Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. 1. You catch an unhandled exception in a Page_Error handler. How can you access the last error? A. Server.GetLastError B. Server.ClearError C. Request.GetLastError D. Application.GetLastError 2. Which of the following can you use to catch unhandled exceptions in an application? (Choose all that apply.) A. Response_Error B. Page_Error C. Application_Error D. Server_Error 3. Which of the following code samples correctly retrieves the current cookie confi gura- tion settings? NOTE ANSWERS Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. Lesson 1: Using Web Site Programmability CHAPTER 11 729 A. 'VB Dim section As String = WebConfigurationManager.GetSection _ ("system.web/httpCookies") //C# string section = WebConfigurationManager.GetSection("system.web/httpCookies"); B. 'VB Dim section As HttpCookiesSection = _ WebConfigurationManager.GetSection("httpCookies") //C# HttpCookiesSection section = (HttpCookiesSection) WebConfigurationManager.GetSection("httpCookies"); C. 'VB Dim section As String = WebConfigurationManager.GetSection("httpCookies") //C# string section = WebConfigurationManager.GetSection("httpCookies"); D. 'VB Dim section As HttpCookiesSection = _ WebConfigurationManager.GetSection("system.web/httpCookies") //C# HttpCookiesSection section = (HttpCookiesSection) WebConfigurationManager.GetSection("system.web/httpCookies"); 4. You need to have ASP.NET dynamically generate Word documents when a Web browser requests a file ending in a .doc extension. How can you do this? A. Implement the IPartitionResolver interface. B. Implement the IHttpModule interface. C. Implement the IHttpHandler interface. D. Implement the IHttpHandlerFactory interface. 7 3 0 CHAPTER 11 Programming the Web Application Lesson 2: Using the ASP.NET Intrinsic Objects You can use the objects inside of ASP.NET to gain access to a lot of useful information about your application, the server hosting the application, and the client requesting resources on the server. These objects are referred to as the ASP.NET intrinsic objects. They are exposed through objects like Page, Browser, Server, and Context. Together, these objects provide you a great deal of useful information like the user’s Internet Protocol (IP) address, the type of browser making the request, errors generated during a response, the title of a given page, and much more. This lesson describes how you can use objects like Page, Browser, Response, Request, Server, and Context to program specifi c scenarios on your Web site. After this lesson, you will be able to: n Use the Browser object to identify client capabilities. n Use Page and Application context to examine and update information, such as the details of the client request and the communications being sent back to the client. n Access Web page headers to dynamically defi ne the page title or the style sheet. Estimated lesson time: 30 minutes Page and Application Context Overview You can access the many ASP.NET objects to examine almost any detail of the current request and response. These objects are exposed as properties of the Page object. You can refer- ence them through the Page object (Page.Response, for example) or you can reference them directly, without the qualifying namespace. Many of these objects have been with ASP since the fi rst version. Referencing them without the object qualifi er provides the same experience that ASP developers are used to. Table 11-2 lists the objects (exposed as properties of the Page object) that you can use to examine information relating to page and application context. TABLE 11-2 ASP.NET Intrinsic Objects OBJECT DESCRIPTION Response An instance of the System.Web.HttpResponse class. Provides access to the HTTP response sent from the server to the client after receiving an incom- ing Web request. You can use this class to inject text into the page, to write cookies, redirect the user, add cache dependencies, and other tasks related to the HTTP response. You can edit most aspects of the Response. After this lesson, you will be able to: n Use the Browser object to identify client capabilities. Browser object to identify client capabilities.Browser n Use Page and Application context to examine and update information, such as the details of the client request and the communications being sent back to the client. n Access Web page headers to dynamically defi ne the page title or the style sheet. Estimated lesson time: 30 minutes Estimated lesson time: 30 minutes Lesson 2: Using the ASP.NET Intrinsic Objects CHAPTER 11 731 Request An instance of the System.Web.HttpRequest class. Provides access to information that is part of the current page request as sent from the Web browser, including the request headers, cookies, client certificate, and query string. You can use this class to read what the browser sent to the Web server. These properties cannot be updated. Server An instance of the System.Web.HttpServerUtility class. Exposes utility meth- ods that you can use to transfer control between pages, get information about the most recent error, and encode and decode HTML text. Most of the useful Server methods are static. Context An instance of the System.Web.HttpContext class. Provides access to the entire current context (including the Request object). Most of the meth- ods and properties provided by Context are also provided by other more frequently used objects, such as Request and Server. Session An instance of the System.Web.HttpSessionState class. Provides informa- tion to the current user session. Also provides access to a session-wide cache you can use to store information, along with the means to control how the session is managed. For detailed information about the Session object, read Chapter 4, “ASP.NET State Management.” Application An instance of the System.Web.HttpApplicationState class. Provides access to application-wide methods and events for all sessions. Also provides access to an application-wide cache you can use to store information. For detailed information about the Application object, read Chapter 4. Trace An instance of the System.Web.TraceContext class. Provides a way to display both system and custom trace diagnostic messages in the HTTP page output. For more information about the Trace object, read Chapter 12, “Monitoring, Troubleshooting, and Debugging.” The Response Object The Page.Response property is an HttpResponse object that allows you to add data to the HTTP response being sent back to the client who requested a Web page. The Response object includes the following useful methods: n BinaryWrite Writes binary characters to the HTTP response. To write a text string instead, call Write. n AppendHeader Adds an HTTP header to the response stream. You only need to use this if you need to provide a special directive to the Web browser that IIS does not add. n Clear Removes everything from the HTTP response stream. n ClearContent Removes the content from the response stream, not including the HTTP headers. n ClearHeaders Removes the headers from the response stream, not including the content. 7 3 2 CHAPTER 11 Programming the Web Application n End Completes the response and returns the page to the user. n Flush Sends the current output to the client without ending the request. This is use- ful if you want to return a partial page to the user; for example, if you had to perform a time-consuming database query or submit information to a credit card processing service, you could display, “Processing your transaction” using Response.Write, call Response.Flush to send this message immediately to the user, process the transaction, and then display the transaction information when it is ready. n Redirect Instructs the Web browser to open a different page by returning an HTTP/302 code with the new Uniform Resource Locator (URL). This is an alternative to the Server.Transfer method, which causes ASP.NET to process a different page without the Web browser submitting a new request. n TransmitFile Writes a file to the HTTP response without buffering it. n Write Writes information to the HTTP response with buffering. n WriteFile Writes a file to the HTTP response with buffering. n WriteSubstitution Replaces strings in the response. This is useful if you are returning cached output, but you want to dynamically update that cached output. To initiate the replacement, call the WriteSubstitution method, passing it the callback method. On the first request to the page, WriteSubstitution calls the HttpResponseSubstitutionCallback delegate to produce the output. Then, it adds a substitution buffer to the response, which retains the delegate to call on future requests. Finally, it degrades client-side cachability from public to server-only, ensuring future requests to the page reinvoke the delegate by not caching on the client. As an alternative to using WriteSubstitution, you can use the Substitution control. The Response object also includes the following useful properties: n Cookies Enables you to add cookies that are sent back to the Web browser. If the Web browser supports cookies, it returns the exact same cookie to you using the Request object. For more information about cookies, read Chapter 7, “Using ADO.NET, XML, and LINQ with ASP.NET.” n Buffer If True, the response is buffered before sending it back to the user. If False, the response is sent back to the user in chunks. Typically, you should buffer the response, unless you are sending back a very large response, or the response will take a long time to generate. n Cache Gets the caching policy of the Web page, such as the expiration time and privacy policy. n Expires The number of minutes after which the browser should stop caching the page. Set this to the time period for which the page will be valid. If the page is con- stantly updated, set it to a very short period of time. If the page is static and rarely changes, you can increase this time to reduce the number of unnecessary page re- quests and improve the performance of your server. Lesson 2: Using the ASP.NET Intrinsic Objects CHAPTER 11 733 n ExpiresAbsolute Similar to the Expires property, ExpiresAbsolute sets an absolute date and time after which the page cache is no longer valid. n Status and StatusCode Gets or sets the HTTP status code that indicates whether the response was successful. For example, the status code 200 indicates a successful response, 404 indicates a file not found, and 500 indicates a server error. The Request Object The Page.Request property is an HttpRequest object that allows you to add data to the HTTP response being sent back to the client who requested a Web page. The Request object in- cludes the following useful methods: n MapPath Maps the virtual path to a physical path, allowing you to determine where on the file system a virtual path is. For example, this allows you to convert /about.htm to C:\Inetpub\Wwwroot\About.htm. n SaveAs Saves the request to a file. n ValidateInput Throws an exception if the user input contains potentially dangerous input, such as HTML input, or input that might be part of a database attack. ASP.NET does this automatically by default, so you only need to manually call this method if you have disabled ASP.NET security features. The Request object also includes several useful properties: n ApplicationPath Gets the ASP.NET application’s virtual application root path on the server. n AppRelativeCurrentExecutionFilePath Gets the virtual path of the application root and makes it relative by using the tilde (~) notation for the application root (as in ~/page.aspx). n Browser Allows you to examine details of the browser’s capabilities (see “Determining the Browser Type” later in this lesson). n ClientCertificate Gets the client’s security certificate, if the client provided one. n Cookies Enables you to read cookies sent from the Web browser that you have previously provided in a Response object. For more information about cookies, read Chapter 4. n FilePath Gets the virtual path of the current request. n Files If the client has uploaded files, this gets the collection of files uploaded by the client. n Headers Gets the collection of HTTP headers. n HttpMethod Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client. n IsAuthenticated A Boolean value that is True if the client is authenticated. n IsLocal A Boolean value that is True if the client is from the local computer. 7 3 4 CHAPTER 11 Programming the Web Application n IsSecureConnection A Boolean value that is True if the connection uses secure HTTP (HTTPS). n LogonUserIdentity Gets the WindowsIdentity object that represents the current user. n Params A combined collection that includes the QueryString, Form, ServerVari- ables, and Cookies items. For more information about query strings and cookies, read Chapter 4. n Path The virtual path of the current request. n PhysicalApplicationPath The physical path of the application root directory. n PhysicalPath The physical path of the current request. n QueryString A collection of query string variables. For more information about query strings, read Chapter 4. n RawUrl and Url The URL of the current request. n TotalBytes The length of the request. n UrlReferrer Gets information about the URL of the client’s previous request that linked to the current URL. You can use this to determine which page within your site or which external Web site brought the user to the current page. n UserAgent Gets the user agent string, which describes the browser the user has. Some non-Microsoft browsers indicate that they are Internet Explorer for compatibility. n UserHostAddress The client’s IP address. n UserHostName The Domain Name System (DNS) name of the remote client. n UserLanguages A sorted string array of languages the client browser has been con- figured to prefer. ASP.NET can automatically display the correct language for a user. For more information, read Chapter 13, “Globalization and Accessibility.” The Server Object The Page.Server property is an HttpServerUtil object that provides static methods useful for processing URLs, paths, and HTML. The most useful methods are the following: n ClearError Clears the last error. n GetLastError Returns the previous exception, as described in Lesson 1 of this chapter. n HtmlDecode Removes HTML markup from a string. You should call HtmlDecode on user input before displaying it again to remove potentially malicious code. n HtmlEncode Converts a string to be displayed in a browser. For example, if the string contains a “<” character, Server.HtmlEncode converts it to the “&lt” phrase, which the browser displays as a less-than sign rather than treating it as HTML markup. n MapPath Returns the physical file path that corresponds to the specified virtual path on the Web server. n Transfer Stops processing the current page and starts processing the specified page. The URL is not changed in the user’s browser. Lesson 2: Using the ASP.NET Intrinsic Objects CHAPTER 11 735 n UrlDecode Decodes a string encoded for HTTP transmission and sent to the server in a URL. n UrlEncode Encodes a string for reliable HTTP transmission from the Web server to a client through the URL. n UrlPathEncode URL encodes the path portion of a URL string and returns the en- coded string. n UrlTokenDecode Decodes a URL string token to its equivalent byte array using base 64 digits. n UrlTokenEncode Encodes a byte array into its equivalent string representation using base 64 digits suitable for transmission on the URL. The Context Object The Page.Context property is an HttpContext object that provides access to a variety of ob- jects related to the HTTP request and response. Many of these objects are redundant, provid- ing access to Page members including Cache, Request, Response, Server, and Session. However, the Context object includes several unique methods: n AddError Adds an exception to the page, which can later be retrieved by calling Server.GetLastError or cleared by calling Server.ClearError or Context.ClearError. n ClearError Clears the last error, exactly the same way as Server.ClearError. n RewritePath Assigns an internal rewrite path and allows for the URL that is requested to differ from the internal path to the resource. RewritePath is used in cookieless session state to remove the session state value from the path Uniform Resource Identifier (URI). The Context object also includes several unique properties: n AllErrors A collection of unhandled exceptions that have occurred on the page. n IsCustomErrorEnabled A Boolean value that is true if custom errors are enabled. n IsDebuggingEnabled A Boolean value that is true if debugging is enabled. n Timestamp The timestamp of the HTTP request. Determining the Browser Type HTML has a defined, controlled standard. However, not all Web browsers implement that standard in the same way. There are many differences among the many browser versions and brands. In addition, browsers often have different capabilities. Sometimes, this is because two competing browsers interpret standards differently. Other times, the browser might have restrictions imposed for security reasons or to better suit a mobile device. To make sure your Web pages are displayed properly, it’s important to test Web pages in every type of browser that your users might have. If you primarily rely on ASP.NET controls, your chances of running into a compatibility issue are greatly reduced. ASP.NET controls automatically adapt to different browser types and capabilities. However, if you use a lot of 7 3 6 CHAPTER 11 Programming the Web Application Dynamic Hypertext Markup Language (DHTML), JavaScript, and Cascading Style Sheets (CSS), you are bound to come across more than one browser compatibility issue. When you do run into an issue, you will want to adjust your Web page so that a single version of the page renders correctly for your supported browser types. To display different versions of Web pages for different browsers, you will need to write code that examines the HttpBrowserCapabilities object. This object is exposed through Request.Browser. Request .Browser has many members that you can use to examine individual browser capabilities. There are two primary methods exposed by HttpBrowserCapabilities. Table 11-3 lists these methods. TABLE 11-3 Request. B rowser Methods METHOD DESCRIPTION GetClrVersions Returns all versions of the .NET Framework common language runtime that are installed on the client. IsBrowser Gets a value indicating whether the client browser is the same as the specified browser. The HttpBrowserCapabilities object also exposes a number of properties. These proper- ties provide information about the browser making the request such as the browser type, if it supports cookies, if it is a mobile device, if it supports ActiveX, if it allows frames, and other browser-related options. Table 11-4 lists many of the more important Request.Browser properties. TABLE 11-4 Request.Browser Properties PROPERTY DESCRIPTION ActiveXControls Gets a value indicating whether the browser supports Ac- tiveX controls. AOL Gets a value indicating whether the client is an America On- line (AOL) browser. BackgroundSounds Gets a value indicating whether the browser supports playing background sounds using the <bgsounds> HTML element. Browser Gets the browser string (if any) that was sent by the browser in the User-Agent request header. Note that some non-Mi- crosoft browsers incorrectly identify themselves as Internet Explorer to improve compatibility. Therefore, this string is not always accurate. ClrVersion Gets the version of the .NET Framework that is installed on the client. Cookies Gets a value indicating whether the browser supports cook- ies. [...]... exceptions when using ASP.NET AJAX n Implement tracing of a Web application n Debug deployment issues n Monitor Web applications Lessons in this chapter: n Debugging an ASP.NET Application 749 n Troubleshooting a Running ASP.NET Application 762 CHAPTER 12 747 Before You Begin To complete the lessons in this chapter, you should be familiar with developing applications with Visual Studio using Microsoft Visual... to attach to the ASP.NET process on the server you wish to debug D In Visual Studio, use the Attach To Process dialog box to attach to the browser’s process that is running the application you wish to debug Lesson 1: Debugging an ASP.NET Application CHAPTER 12 761 Lesson 2: troubleshooting a running asp.net application Not all issues can be found using Visual Studio Therefore, ASP.NET provides the... Visual Studio 20 08 IDE n Using Hypertext Markup Language (HTML) and client-side scripting n Creating ASP.NET Web sites and forms 7 48 CHAPTER 12 Monitoring, Troubleshooting, and Debugging Lesson 1: debugging an asp.net application Debugging an ASP.NET Web site can be complicated, as the client and server are typically distributed across different machines In addition, the state that the application uses... shown in Figure 12-1 Lesson 1: Debugging an ASP.NET Application CHAPTER 12 749 3 Select Start Options from the left side of the dialog box 4 In the Debuggers section, at the bottom of the dialog box, select (or clear) the ASP.NET check box to enable (or disable) the ASP.NET debugger for Visual Studio FIGURE 12-1  The project Property Pages dialog box for an ASP.NET Web site Configure Debugging The second... debug an ASP.NET application using the standard features of the Visual Studio debugger like breakpoints, watch windows, code step-through, error information, and the like To do so, you must first configure ASP.NET for debugging There are two areas where you set this information: the project’s property page and the Web.config file Activate the ASP.NET Debugger The first step is to enable the ASP.NET debugger... Request.Browser object still indicates that the browser supports cookies For this reason, ASP.NET session state can be configured to test the client browser for cookie support Lesson 2: Using the ASP.NET Intrinsic Objects CHAPTER 11 737 MORE INFO asp.net sessiOn suppOrt fOr cOOkies For more information about ASP.NET sessions, refer to Chapter 4 Quick check 1 Which of the following browser capabilities... on Thankfully, Visual Studio and ASP.NET have a number of tools that allow you to get debugging information from your site during development This lesson covers setup and configuration of the ASP.NET debugging features This includes remote debugging and client-side script debugging NOTE chapter cOntents This lesson covers the configuration and setup of debugging with ASP.NET and Visual Studio It does... Lesson 1: Debugging an ASP.NET Application CHAPTER 12 755 figure 12-5 Using the Internet Options dialog box to enable script debugging for Internet Explorer NOTE debugging ajaX For more information on debugging client script that uses the Microsoft AJAX Library, see “Tracing AJAX Applications” in Lesson 2 of this chapter Quick check 1 In which dialog box do you enable the ASP.NET debugger for your... 11 Programming the Web Application CHAPTER 1 2 Monitoring, Troubleshooting, and Debugging A large part of the development process involves removing bugs and other issues from your application Microsoft Visual Studio and ASP.NET provide a number of tools to support this task This includes the ability to set breakpoints in code, to step through your code inside the Integrated Development Environment... test Chapter Summary n ASP.NET provides features for programming against your Web site For one, you can catch unhandled exceptions at both the page and application level You can do so by responding to the Page_Error or the Application_ Error methods You can also use the WebConfigurationManager.GetSection to work with configuration information in your Web.config file In addition, ASP.NET supports asynchronous . cookies. For this reason, ASP .NET session state can be configured to test the client browser for cookie support. 7 3 8 CHAPTER 11 Programming the Web Application MORE INFO ASP .NET SESSION SUPPORT. properties: n ApplicationPath Gets the ASP .NET application s virtual application root path on the server. n AppRelativeCurrentExecutionFilePath Gets the virtual path of the application root. IHttpHandlerFactory interface. 7 3 0 CHAPTER 11 Programming the Web Application Lesson 2: Using the ASP .NET Intrinsic Objects You can use the objects inside of ASP .NET to gain access to a lot of

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

TỪ KHÓA LIÊN QUAN