Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 64 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
64
Dung lượng
529,99 KB
Nội dung
</td> <td nowrap align=”right”> <%# DataBinder.Eval(Container.DataItem, “TimeGenerated”, _ “{0:MM-dd-yyyy HH:mm:ss}”) %> </td> </tr> <tr> <td colspan=”3”> <%# GetHtmlMessage(Container.DataItem) %> </td> </tr> </table> </itemtemplate> <separatortemplate> <hr width=”100%” noshade size=”1”> </separatortemplate> </asp:datalist> </td> </tr> </table> </form> </body> </html> Listing 5.2 HTML for ErrorManager/Default.aspx (continued) This page sets up an ASP:DataList Web server control to display the entries con- tained in the event log, if the event log is installed. Next, switch to the code-behind file, and type the complete listing shown in Listing 5.3 (do not modify the Web Forms Designer generated code section, however). Option Strict On Option Explicit On Imports System.Diagnostics Namespace ErrorManager Public Class DefaultPage Inherits System.Web.UI.Page Protected WithEvents EMDataList As System.Web.UI.WebControls.DataList Protected WithEvents EMClear As System.Web.UI.WebControls.Button Protected WithEvents EMEvents As _ System.Web.UI.HtmlControls.HtmlTableRow Protected WithEvents EMStatus As System.Web.UI.WebControls.Label Private blnInstalled As Boolean = HasErrorManager() Private Sub Page_Load(ByVal sender As System.Object, _ Listing 5.3 Code for ErrorManager/Default.aspx.vb Building the ASP.NET Error Manager 303 ByVal e As System.EventArgs) Handles MyBase.Load Dim evtEM As EventLog ‘ ‘ If the custom event log is not installed, do ‘ not show the data list or the “Clear” button. ‘ If blnInstalled = False Then EMStatus.Text = “The ASP.NET Error Manager is currently “ & _ “NOT installed.” EMEvents.Visible = False EMClear.Visible = False Return End If ‘ ‘ Otherwise, show both and bind the data list ‘ to the event log entries collection. ‘ EMStatus.Text = “The ASP.NET Error Manager is currently installed.” EMEvents.Visible = True EMClear.Visible = True evtEM = New EventLog(“ASP.NET Error Manager”) EMDataList.DataSource = evtEM.Entries EMDataList.DataBind() evtEM.Dispose() End Sub ‘ ‘ This method is used as a check to ‘ see if the custom event log exists. ‘ Friend Function HasErrorManager() As Boolean Return EventLog.Exists(“ASP.Net Error Manager”) End Function ‘ ‘ This method converts NewLines in the event log ‘ entry message into <br> tags so they will look ‘ at least somewhat formatted. ‘ Protected Function GetHtmlMessage(ByVal item As Object) As String Dim entry As EventLogEntry If TypeOf item Is EventLogEntry Then entry = CType(item, EventLogEntry) Listing 5.3 Code for ErrorManager/Default.aspx.vb (continued) 304 Project 5 Return entry.Message.Replace(Environment.NewLine, “<br>”) End If End Function ‘ ‘ This method is used to clear ‘ the event log of all entries. ‘ Private Sub EMClear_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles EMClear.Click Dim evtEM As EventLog evtEM = New EventLog(“ASP.NET Error Manager”) evtEM.Clear() EMDataList.DataSource = evtEM.Entries EMDataList.DataBind() evtEM.Dispose() End Sub End Class End Namespace Listing 5.3 Code for ErrorManager/Default.aspx.vb (continued) That’s all there is to it. You now have all the necessary code to view and clear your custom event log. When the page loads, the first thing it does is check to see if the event log exists. If not, it will make both the button used to clear the log and the data list that is used to display it invisible (thus removing it from the HTML output). After that initial check, it binds the data list to the EventLog Entries property, which contains the collection of individual entries, and then releases any unmanaged resources that may be held by the evtEM event log component. Of course, you could make this as fancy as you want by adding the Error, Warning, and Information graphics, and sorting, filtering, and paging to the data list, but I’ll leave that to your capable hands. The next step is to add a plain text file to this directory that can hold our email tem- plate. Right-click the ErrorManager directory, and select Add —> Add New Item. Then select the text file template, name it ErrorEMail.txt, and click OK. Type the following text in the file, and save it. This will be the default email that is sent to an administrator when a site failure occurs. <html> <head> <title>An Error Occurred On Your Site</title> Building the ASP.NET Error Manager 305 <style> body { font-family: Verdana; font-size: 10pt; } table { font-family: Verdana; font-size: 10pt; } </style> </head> <body> <p>A visitor encountered an error while browsing your site. The visitor was successfully redirected to a custom error page and did not see the details of the error.</p> <p>The error details are as follows:</p> <blockquote>%CUSTOM_INSERT%</blockquote> <p>Please correct the cause of this error as soon as possible.</p> <p><font size=”2”>THIS MESSAGE WAS SENT BY AN AUTOMATED SYSTEM. DO NOT REPLY.</font></p> </body> </html> Next, we’ll tackle the custom error pages in HTTP status code order . . . Building the Error/Denied Page This is the page that visitors will see when they attempt to access a protected resource with incorrect authorization. Select the Error folder in Solution Explorer, right-click it, and select Add —> New Web Form. Name the page Denied.aspx, and then click Open. Switch to HTML view for the Denied.aspx page, and type the code as it is shown in Listing 5.4. <%@ Page Language=”vb” AutoEventWireup=”false” Codebehind=”Denied.aspx.vb” Inherits=”Project05.Error.Denied” %> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”> <html> <head> <title>Access to the requested page was denied </title> <meta name=”GENERATOR” content=”Microsoft Visual Studio.NET 7.0”> <meta name=”CODE_LANGUAGE” content=”Visual Basic 7.0”> <meta name=”vs_defaultClientScript” content=”JavaScript”> <meta name=”vs_targetSchema” Listing 5.4 HTML for Error/Denied.aspx 306 Project 5 content=”http://schemas.microsoft.com/intellisense/ie5”> <link rel=”stylesheet” href=” /Styles.css”> </head> <body ms_positioning=”FlowLayout”> <form id=”Denied” method=”post” runat=”server”> <table cellpadding=”0” cellspacing=”0” border=”0” width=”100%” height=”100%”> <tr> <td valign=”top” align=”middle” height=”42”> <h1> Access to the requested page was denied </h1> </td> </tr> <tr> <td valign=”top”> <p> Some parts of this site are secured and are therefore not available to the general public. If you have received this message in error, our site administrators have already been notified and will correct the problem as soon as possible. </p> <p> <asp:label id=”ContactUs” runat=”server” font-size=”1.3em”>Please feel free to contact our customer service department regarding this issue at <nobr>1-800-555-5555</nobr>, or use the form below to send us an <nobr>e-mail</nobr> message.</asp:label> </p> </td> </tr> <tr> <td valign=”top” align=”middle”> <table cellpadding=”0” cellspacing=”5” border=”0” id=”EMailForm” runat=”server”> <tr> <td colspan=”3”> <asp:validationsummary id=”Summary” runat=”server” displaymode=”BulletList” headertext=”Please correct the following and try again:” showsummary=”True”></asp:validationsummary> </td> </tr> <tr> <td> E-Mail Address: </td> <td> <asp:textbox id=”EMailFrom” runat=”server” maxlength=”255” width=”3in”></asp:textbox> Listing 5.4 HTML for Error/Denied.aspx (continued) Building the ASP.NET Error Manager 307 </td> <td> <asp:requiredfieldvalidator id=”EMailFromRequired” runat=”server” controltovalidate=”EMailFrom” errormessage=”Your e-mail address is required for reply” display=”Static”>*</asp:requiredfieldvalidator> </td> </tr> <tr> <td> Subject: </td> <td> <asp:textbox readonly=”True” id=”EMailSubject” runat=”server” maxlength=”255” width=”3in”></asp:textbox> </td> <td rowspan=”3”> </td> </tr> <tr> <td valign=”top”> Message: </td> <td valign=”top”> <asp:textbox id=”EMailMessage” runat=”server” rows=”10” textmode=”MultiLine” width=”3in”></asp:textbox> </td> </tr> <tr> <td colspan=”2” align=”right”> <asp:button id=”SendButton” runat=”server” text=”Send Now”></asp:button> </td> </tr> </table> <table cellpadding=”0” cellspacing=”0” border=”0” align=”center” id=”SuccessNotice” runat=”server”> <tr> <td> Your message was sent successfully. In 10 seconds, you will be redirected to the public home page. If the redirect does not work, please use the link at the bottom of this page. </td> </tr> </table> </td> Listing 5.4 HTML for Error/Denied.aspx (continued) 308 Project 5 </tr> <tr> <td valign=”bottom” align=”middle”> <a href=”/default.aspx”>Return to the public home page</a> </td> </tr> </table> </form> </body> </html> Listing 5.4 HTML for Error/Denied.aspx (continued) This page explains to users that parts of the site are secure and that an administrator has been notified of the access attempt, and gives the visitor an opportunity to contact customer service regarding this event. The code-behind for this page is shown in Listing 5.5. Option Strict On Option Explicit On Imports System.Web.Mail Namespace [Error] Public Class Denied Inherits System.Web.UI.Page Protected WithEvents Summary As _ System.Web.UI.WebControls.ValidationSummary Protected WithEvents EMailFrom As System.Web.UI.WebControls.TextBox Protected WithEvents EMailFromRequired As _ System.Web.UI.WebControls.RequiredFieldValidator Protected WithEvents EMailSubject As System.Web.UI.WebControls.TextBox Protected WithEvents EMailMessage As System.Web.UI.WebControls.TextBox Protected WithEvents ContactUs As System.Web.UI.WebControls.Label Protected WithEvents EMailForm As System.Web.UI.HtmlControls.HtmlTable Protected WithEvents SuccessNotice As _ System.Web.UI.HtmlControls.HtmlTable Protected WithEvents SendButton As System.Web.UI.WebControls.Button Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim strTo As String SuccessNotice.Visible = False ‘ Listing 5.5 Code for Error/Denied.aspx.vb Building the ASP.NET Error Manager 309 ‘ If we’re not set up to send e-mail, don’t offer it. ‘ strTo = CStr(Application(“CustomerServiceEMail”)) If strTo = Nothing Then ContactUs.Text = “Please feel free to contact our “ & _ “customer service department regarding this issue at “ & _ “<nobr>1-800-555-5555</nobr>.” EMailForm.Visible = False Return End If EMailSubject.Text = “Access Denied to Page “”” & _ Request.QueryString(“aspxerrorpath”) & “””” If Not Page.IsPostBack Then ‘ ‘ Pre-validate so the asterisk shows up. ‘ EMailFromRequired.Validate() Summary.Visible = False Else If Not Page.IsValid Then Summary.Visible = True Return End If End If End Sub ‘ ‘ This sends the e-mail and then notifies the visitor and redirects ‘ them to the default page. ‘ Private Sub SendButton_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles SendButton.Click Dim strTo As String Dim emlMsg As MailMessage Dim emlSender As SmtpMail strTo = CStr(Application(“CustomerServiceEMail”)) If Not strTo = Nothing Then emlMsg = New MailMessage() emlMsg.To = CStr(Application(“CustomerServiceEMail”)) emlMsg.From = EMailFrom.Text.Trim() emlMsg.Subject = EMailSubject.Text emlMsg.BodyFormat = MailFormat.Text emlMsg.Body = EMailMessage.Text Listing 5.5 Code for Error/Denied.aspx.vb (continued) 310 Project 5 Try emlSender = New SmtpMail() Try emlSender.Send(emlMsg) ‘ ‘ If the mail was sent successfully, redirect ‘ back to the home page after 10 seconds. ‘ Response.AppendHeader(“Refresh”, _ “10;URL=/Project05/Default.aspx”) EMailForm.Visible = False SuccessNotice.Visible = True Catch End Try Finally emlSender = Nothing End Try End If End Sub End Class End Namespace Listing 5.5 Code for Error/Denied.aspx.vb (continued) This code sets up the visual details of the page based upon the server configura- tion’s current capabilities and then responds when the Send Now button is clicked. The square brackets around the namespace name Error are required because Error is a reserved keyword. You can use keywords as parameters, properties, method names, and so on as long as they are qualified in this way. Building the Error/NotFound Page This page is almost identical to the Denied page, with some minor changes in the wording in the page. Within the Error directory, add another Web Forms page named NotFound.aspx, and in HTML view, type the code shown in Listing 5.6. <%@ Page Language=”vb” AutoEventWireup=”false” Codebehind=”NotFound.aspx.vb” Inherits=”Project05.Error.NotFound” %> Listing 5.6 HTML for Error/NotFound.aspx Building the ASP.NET Error Manager 311 <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”> <html> <head> <title>The page you were looking for was not found </title> <meta name=”GENERATOR” content=”Microsoft Visual Studio.NET 7.0”> <meta name=”CODE_LANGUAGE” content=”Visual Basic 7.0”> <meta name=”vs_defaultClientScript” content=”JavaScript”> <meta name=”vs_targetSchema” content=”http://schemas.microsoft.com/intellisense/ie5”> <link rel=”stylesheet” href=” /Styles.css”> </head> <body ms_positioning=”FlowLayout”> <form id=”NotFound” method=”post” runat=”server”> <table cellpadding=”0” cellspacing=”0” border=”0” width=”100%” height=”100%”> <tr> <td valign=”top” align=”middle” height=”42”> <h1> The page you were looking for was not found </h1> </td> </tr> <tr> <td valign=”top”> <p> Like any popular Internet property, this site is always under construction. Sometimes when we make these changes our customers temporarily find some broken links in our site. Our site administrators are now aware that the page you were looking for is not available and may implement an automatic redirect to the correct page. </p> <p> <asp:label id=”ContactUs” runat=”server” font-size=”1.3em”>Let us help you find what you were looking for by using the form below to send us an e-mail. Alternatively, you may contact our customer service department at <nobr>1-800-555-5555</nobr>.</asp:label> </p> </td> </tr> <tr> <td valign=”top” align=”middle”> <table cellpadding=”0” cellspacing=”5” border=”0” id=”EMailForm” runat=”server”> <tr> <td colspan=”3”> <asp:validationsummary id=”Summary” runat=”server” displaymode=”BulletList” headertext=”Please correct the following and try again:” Listing 5.6 HTML for Error/NotFound.aspx (continued) 312 Project 5 TEAMFLY Team-Fly ® [...]... how you will attack the creation of the online store: 1 Modify the sample database to include new tables specific to the store 2 Create Insert, Select and Update stored procedures for common tasks 3 Create Views in SQL Server to access the data 4 Create the classes in your project that can be considered the data access layer and the business logic layer 5 Create ASP.NET user controls that make up the... Listing 5 .10 Code for Global.asax.vb (continued) Here, you are loading a template email file upon application startup and setting the source value that will be used with this particular application (other ASP.NET applications may specify that sources be placed in the ASP.NET Error Manager event log) On each request, you are loading the application-specific configuration settings This is a quick operation,... selected 6 Click the OK button Figure 6. 2 is an example of what your New Project dialog box should look like Setting Up the Database This project will use the Northwind Traders database in SQL Server as a starting point for formatting tables and data Since the Northwind Traders application that ships with Microsoft Access is actually a desktop version of an e-commerce application, the structure of the database... the tables that we borrow will need to be slightly modified Figure 6. 3 is a diagram of the database you will be using Figure 6. 3 Online store database diagram Building the Online Store Application Table 6. 1 The ShoppingCart Table FIELD NAME DATA TYPE LENGTH NULLS DESCRIPTION PKID Int 4 No Primary Key, Identity column CartID VarChar 50 No Shopping cart ID, based on GUID created in the application ProductID... done in previous projects, you do not need to worry about using any of those files Follow these steps to create your project file and Web site in IIS 1 Start Visual Studio NET 2 From the Start page, click the New Project button 3 Select ASP.NET from the list of templates 4 Type project 06 in the Name box 335 3 36 Project 6 Figure 6. 2 New Project dialog box 5 Set the Location field to the location of your... the application whenever a configuration ‘ change takes place ‘ Sub Application_BeginRequest(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.BeginRequest ‘ Fires at the beginning of each request Dim cfg As ConfigurationSettings ‘ ‘ These are the custom settings recognized by our application ‘ cfg = New ConfigurationSettings() Application.Lock() Application(“AdministratorEMail”)... SmtpMail ‘ ‘ Get the error that occurred ‘ exc = Server.GetLastError If Not exc Is Nothing Then sbError = New StringBuilder(40 96) ‘ ‘ Build a string containing the list of exceptions ‘ that occurred and information about each We’re ‘ using a StringBuilder because it performs better ‘ at concatenation than String, since concatenation ‘ on normal strings always involve a copy operation ‘ Do Until exc Is Nothing... From an administrative standpoint, some useful features could include: s s View product sales history s s View customer order history s s View demographic sales data Figure 6. 1 is an example of the complete user interface for the online store created in the project Figure 6. 1 Online store user interface Building the Online Store Application The project is broken down into several steps that will allow... application ‘ Here is where we want to initialize the Application variables that ‘ we want to remain in memory throughout the life of the application ‘ Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) Dim strPath As String Dim strErrorEMail As String Dim frdReader As StreamReader ‘ ‘ Here, we read in our text file and use it as a template for the ‘ error e-mails that we will generate... By inserting this location tag, you can override the default configuration for specific subdirectories It is available for use in the ASP.NET configuration files as well as in the rest of the NET runtime, including Windows Forms applications and the like By making this change, we are overriding the default authorization configuration to specify that members of the BUILTIN\Administrators groups are permitted . %> </td> </tr> </table> </itemtemplate> <separatortemplate> <hr width= 100 %” noshade size=”1”> </separatortemplate> < /asp: datalist> </td> </tr> </table> </form> </body> </html> Listing. width=”3in”>< /asp: textbox> Listing 5.4 HTML for Error/Denied.aspx (continued) Building the ASP. NET Error Manager 307 </td> <td> < ;asp: requiredfieldvalidator id=”EMailFromRequired” runat=”server”. EventLog( ASP. NET Error Manager”) evtEM.Clear() EMDataList.DataSource = evtEM.Entries EMDataList.DataBind() evtEM.Dispose() End Sub End Class End Namespace Listing 5.3 Code for ErrorManager/Default.aspx.vb