ASP.NET Code
  Home arrow ASP.NET Code arrow Complete example using custom errors and w...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET CODE

Complete example using custom errors and write errors to the Event log
By: aspfree
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 26
    2003-06-01

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Writing to the Windows 2000 Event Log is a powerful feature of the ASP.NET and .NET framework. For those individuals who work in a large company and want to make track application errors, writing to the event log is a must!Writing to the Windows 2000 Event Log is a powerful feature of the ASP.NET and .NET framework. For those individuals who work in a large company and want to make track application errors, writing to the event log is a must!There wasn't any complete demos actually showing from A - Z how this was setup for the novice/common developer like me. Most novice developers need to be spoon fed how things are done the first time, once they see a simple example, they'll understand how the process works! This example is my reference how to make a complete application from A - Z setup and fail to understand how it works.[bold]Step 1[/bold]First of all the steps I followed was to create a simple web called eventlog. I also created the application root so the global.asax file would fire.Here is how to setup an application root:[bold]1.[/bold] Open Internet Service Manager MMC[italic](Start button, Control Panel, Administrative Tools, Internet Service Manager)[/italic][bold]2.[/bold] Located on the left side of the MMC, locate the Default Web and click the + buttonto expand the list of webs. [bold]3.[/bold] Right-click on the web your going to make an application root and choose properties.[bold]4.[/bold] Click the Create button.[bold]5.[/bold] After your done, the folder picture will appear like a box that is open. The application root is now created.[bold]Step 2[/bold]I opened the global web.config file and turned on custom errors. Path to this is c:\winnt\microsoft.net\framework\.. There are 3 choices available currently On, Off and RemoteOnly. From attending the conference, the recommended was RemoteOnly. This means anyone not on the console of the machine will see a friendly error and not the real thing. For this example I chose On. You also could leave the global web.config file custom errors turned off and configure at application level's web.config Either way works just fine.[bold]web.config -- this file is placed in the root of the \eventlog application root.[/bold]


    <configuration
            <
    system.web>
                    <
    customErrors mode="On" defaultRedirect="/eventlog/customerrorpage.aspx">
                            <
    error statusCode="404" redirect="/eventlog/404Page.aspx"/>
                            <
    error statusCode="403" redirect="/eventlog/403page.aspx"/>
                    </
    customErrors
            </
    system.web>
    </
    configuration

    [bold]Step 3[/bold]The next few items are just to create sample pages to make the application complete. I created a web.config, global.asax, Default.aspx page, and three sample error pages. 404page.aspx, 403page.aspx and customerrorpage.aspx page.Here are those pages code for all pages.[bold]Global.asax Page - This uses the Application_OnError event to capture stuff if an error happens[/bold]


    <%@ Import Namespace="System" %>
    <%@ 
    Import Namespace="System.Diagnostics" %>
    <
    script language="VB" runat=server>

    Public 
    Sub Application_OnError(Sender as Objectas EventArgs)
    'Captures the error and converts to a string
            dim LastError as Exception = Server.GetLastError()
            Dim ErrMessage as String = LastError.toString()

            Dim LogName As String = "MyLog"
            Dim Message As String = "Url " & Request.Path & " Error: " & ErrMessage

    Create Event Log if It Doesn't Exist
             If (Not EventLog.SourceExists(LogName)) Then
                  EventLog.CreateEventSource(LogName, LogName)
             End if

            Dim Log as New EventLog
            Log.Source = LogName

    '
    These are the five options that will display a different icon.
    'The numbers are just to show the order.  These aren't required
             Log
    .WriteEntry(MessageEventLogEntryType.Information1)
            
    ' Log.WriteEntry(Message, EventLogEntryType.Error, 2)
            ' 
    Log.WriteEntry(MessageEventLogEntryType.Warning3)
            
    ' Log.WriteEntry(Message, EventLogEntryType.SuccessAudit, 4)
            ' 
    Log.WriteEntry(MessageEventLogEntryType.FailureAudit5)
    End Sub
    </script>

    [bold]Default.aspx page[/bold]


    <% @Language="VB" %>
    <
    script language="VB" runat=server>
    Sub Page_Load(Sender As ObjectAs EventArgs)
    If 
    IsPostBack Then 
    'Declare all variables
             dim x as integer
             dim y as integer
             dim z as integer

    '
    set x and y to values to be divided by zero
             x 
    1
             y 
    0

    'perform the division by zero to raise the error
            z = x/y 
    End Sub
    </script>

    <html>
    <head>
    </head>
    <body>
    <form method="post" action="eventlog.aspx" name="form1" id="number">

    <asp:Button id="abutton" type="submit" text="Click Me to generate an error" runat="server" />
    </form>
    </body>
    </html>

    [bold]Customerrorpage.aspx[/bold]


    <html>
        <
    head></head>
                <
    body>
                        <
    h1>custom error page</h1>
                </
    body>
    </
    html>

    [bold]404page.aspx --Capture all 404(Not Found pages)[/bold]


    <html>
        <
    head></head>
                    <
    body>
                        <
    h1>404 error page</h1>
                    </
    body>
    </
    html>

    [bold]403page.aspx --Capture all 403(Restricted pages)[/bold]


    <html>
       <
    head></head>
            <
    body>
                    <
    h1>403 error page</h1>
            </
    body>
    </
    html

    [bold]Step 4[/bold]After all webs are created, web.config files in place. It was time to test out the application to see if it works. Type in http://localhost/eventlog/default.aspx file, this will display a button. Click it and see if this actually creates the log and writes the information to the event log. Actually only the custom error page will be displayed, the eventlog.aspx page will error and be transfered to the customerrorpage.aspx. The URL will be something like this. http://localhost/eventlog/customerrorpage.aspx?aspxerrorpath=/eventlog/eventlog.aspx [bold]Step 5[/bold]Verify the log was created and entry was placed in that log.Below is five possible types of Event log messages:[bold]Error[/bold]An error event. This indicates a significant problem the user should know about; usually a loss of functionality or data.[bold]FailureAudit[/bold]A failure audit event. This indicates a security event that occurs when an audited access attempt fails; for example, a failed attempt to open a file.[bold]Information[/bold]An information event. This indicates a significant, successful operation.[bold]SuccessAudit[/bold]A success audit event. This indicates a security event that occurs when an audited access attempt is successful; for example, logging on successfully.[bold]Warning[/bold]A warning event. This indicates a problem that is not immediately significant, but that may signify conditions that could cause future problems.Thats it! This was a high-level example with examples but hopefully helps in understanding how a sample application and using the new Error-handling features of ASP.NET... Enjoy!!
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP.NET Code Articles
    More By aspfree

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Cook up Web sites fast with CakePHP, Part 4: Use CakePHP&apos;s Session and Request Handler components

    CakePHP is a stable production-ready, rapid-development aid for building Web sites in PHP. This "Cook up Web sites fast with CakePHP" series shows you how to build an online product catalog using CakePHP.
    FREE! Go There Now!


    NEW! Develop Systems Software Assets with IBM Rational Asset Manager

    Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager.
    FREE! Go There Now!


    NEW! Hello World: Learn how to install and use the Rational Asset Manager Eclipse client

    In this tutorial, you can learn how to install and configure the IBM Rational Asset Manager Eclipse client, explore the different views in the Asset Management perspective, learn various search techniques, work with existing assets, and submit a new asset.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! IBM Rational AppScan Standard Edition V7.7

    Secure your Web applications with IBM Rational AppScan Standard Edition V7.7, previously known as Watchfire AppScan. This Web application security testing tool automates vulnerability assessments and scans and tests for common Web application vulnerabilities. Visit IBM developerWorks to download a free trial of IBM Rational AppScan Standard Edition V7.7.
    FREE! Go There Now!


    NEW! Rational Testing eKits

    Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing.
    FREE! Go There Now!


    NEW! The dirty dozen: preventing common application-level hack attacks

    As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Performance Tester V7.0.1

    Get a free trial download of the latest version of IBM Rational Performance Tester V7.0.1, a load and performance testing solution for teams concerned about the scalability of their Web-based applications. Combining multiple ease-of-use features with granular detail, Rational Performance Tester simplifies the test-creation, load-generation and data-collection processes that help teams ensure the ability of their applications to accommodate required user loads.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Tester for SOA Quality V7.0.1

    Get a free trial download of the latest version of IBM Rational Tester for SOA Quality V7.0.1, a functional and regression testing tool that enables the creation, comprehension, modification and execution of testing GUI-less Web services.
    FREE! Go There Now!


    Refresh! IBM Rational Systems Development Solution eKit

    With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET CODE ARTICLES

    - How to Use the ListBox Control in ASP.NET 2.0
    - How to Load XML Documents in ASP.NET 2.0
    - DataGrid Code
    - ASP.NET Guestbook
    - User Controls and Client Side Scripting
    - ASP.NET Programming with Microsoft's AS...
    - ASP.NET Basics (part 3): Hard Choices
    - ASP.NET Basics (part 2): Not My Type
    - ASP.NET Basics (part 1): Nothing But .Net
    - Directory Tree Browser
    - How to get the confirmation of Yes/No from a...
    - Complete example using custom errors and wri...
    - Paging Certain # records per page .NET style
    - General Methods of formatting and Subtractin...
    - .NET LinkButton web control





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek