BotDetect ASP.NET 2.0 CAPTCHA Solución de problemas VB.NET - Ejemplo de Código

Este ejemplo muestra como usar el registro de errores que viene con BotDetect ASP.NET CAPTCHA para solucionar problemas. Es equivalente al resultado que obtendría si siguiera la guía Cómo registrar errores de BotDetect a un archivo de texto. Simula una excepción en el código de BotDetect y demuestra como puede ser registrado y manejado.

ATENCIÓN

Este ejemplo registra errores e intentos de validación en un archivo de texto dentro del sistema de archivos del servidor, así sólo funcionará en entornos correctamente preparados.

Ubicación de los archivos del proyecto de ejemplo

Por defecto, este ejemplo de proyecto es instalado en
C:\Archivos de Programa\Lanapsoft\BotDetect\ASP.NET 2.0\v2.0\Samples\VBNetBotDetect2TroubleshootingDemo\.

También lo puede arrancar desde el Menú de Inicio:
Programas > Lanapsoft > BotDetect > ASP.NET 2.0 > v2.0 > Samples > VB.NET BotDetect Troubleshooting Demo Preview.

Default.aspx

Listado del Código Fuente Completo

<%@ Page Language="VB" AutoEventWireup="false 
  CodeFile="Default.aspx.vb" Inherits="_Default" %>

<%@ Register Assembly="Lanap.BotDetect" Namespace="Lanap.BotDetect" 
  TagPrefix="BotDetect" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>BotDetect Demo</title>
    <link type='text/css' rel='Stylesheet' href="StyleSheet.css" />
</head>
<body>
    <form id="form1" runat="server">
    <fieldset id="Preview">
        <legend>
            <span id="PreviewLegend">CAPTCHA Validación Logging</span>
        </legend>
        <div id="PromptDiv">
            <span id="Prompt">Type the characters you see in 
              the picture</span>
        </div>
        <div id="CaptchaDiv">
            <BotDetect:Captcha ID="SampleCaptcha" runat="server" />
        </div>
        <div id="ValidationDiv">
            <asp:TextBox ID="CodeTextBox" runat="server">
            </asp:TextBox>
            <asp:Button ID="ValidateButton" runat="server" />
            <asp:Label ID="MessageCorrectLabel" runat="server">
            </asp:Label>
            <asp:Label ID="MessageIncorrectLabel" runat="server">
            </asp:Label>
        </div>
        <div class="ValidationSolución de problemas">
            <p>All Captcha validation attempts will be logged to the 
              'debug.txt' file in the sample folder.</p>
        </div>
        <div class="Solución de problemas">
            <p>
                <asp:Label ID="DebugLabel" runat="server"></asp:Label>
            </p>
        </div>
    </fieldset>
    <fieldset id="Solución de problemasError">
        <legend><span id="Solución de problemasErrorLegend">CAPTCHA Error 
            Logging</span></legend>
        <div class="Solución de problemas">
            <p>Clicking 'Simulate Error' will throw a fake BotDetect 
              exception and log it to the 'error.txt' file in the 
              sample folder.</p>
        </div>
        <asp:Button ID="CauseErrorButton" runat="server" 
            OnClick="CauseErrorButton_Click" />
        <div class="Solución de problemas">
            <p>
                <asp:Label ID="ErrorLabel" runat="server"></asp:Label>
            </p>
        </div>
    </fieldset>

    <div id="Note">
        <span>NOTE: the Trial version will use "LANAP" instead of a 
          random code in 50% of renderings.</span>
    </div>
    </form>
</body>
</html>

Explicación

Aparte de los elementos usuales requeridos para agregar BotDetect CAPTCHA a un formulario ASP.NET, este archivo también contiene un botón extra usado para simular una excepción interna BotDetect y varios elementos relacionados de presentación.

Default.aspx.vb

Listado del Código Fuente Completo

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_PreRender(ByVal sender As System.Object, _ 
        ByVal e As System.EventArgs) Handles MyBase.PreRender

        ' initial page setup
        If (Not IsPostBack) Then

            'set control text
            ValidateButton.Text = "Validate"
            MessageCorrectLabel.Text = "Correct!"
            MessageIncorrectLabel.Text = "Incorrect!"

            'these messages are shown only after validation
            MessageCorrectLabel.Visible = False
            MessageIncorrectLabel.Visible = False

            CauseErrorButton.Text = "Simulate error"
            ErrorLabel.Text = "An error has been generated. _
                Please check the 'error.txt' file."
								
            DebugLabel.Visible = False								
            DebugLabel.Text = "A validation attempt has been logged." _
              "Please check the 'debug.txt' file."
        End If

        If (Session("error") <> Nothing) Then
            ErrorLabel.Visible = True
            MessageCorrectLabel.Visible = False
            MessageIncorrectLabel.Visible = False
            Session("error") = Nothing
            DebugLabel.Visible = False
        Else
            ErrorLabel.Visible = False
        End If
				
        ' clear user input on Reload button clicks
        Dim scriptTemplate As String
        scriptTemplate = "function LBD_ClearUserInput() {{" & _
          "  var LBD_textBox = document.getElementById('{0}');" & _
          "  if(LBD_textBox) {{" & _
          "    LBD_textBox.value = '';" & _
          "  }}" & _
          "}}" & _
          "LBD_RegisterHandler('PreReloadCaptchaImage', _
            LBD_ClearUserInput);"

        Dim script As String
        script = String.Format(scriptTemplate, CodeTextBox.ClientID)
        If (Not Page.ClientScript.IsStartupScriptRegistered( _
            "CaptchaReloadClearInput")) Then
          Page.ClientScript.RegisterStartupScript(Me.GetType(), _ 
            "CaptchaReloadClearInput", script, True)
        End If
				
        ' automatically lowercase user input
        CodeTextBox.Attributes.Add("onkeyup", _ 
            "this.value = this.value.toLowerCase();")

        If (IsPostBack) Then
            'validate the input code, and show the 
            'appropriate message 
            Dim code As String = CodeTextBox.Text.Trim().ToUpper()

            If (SampleCaptcha.Validate(code)) Then
                MessageCorrectLabel.Visible = True
                MessageIncorrectLabel.Visible = False
            Else
                MessageCorrectLabel.Visible = False
                MessageIncorrectLabel.Visible = True
            End If
            
            DebugLabel.Visible = True

            'clear previous user code input
            CodeTextBox.Text = ""
        End If
    End Sub

    Protected Sub CauseErrorButton_Click(ByVal sender As _
        System.Object, ByVal e As System.EventArgs) Handles _ 
        CauseErrorButton.Click
				
        Session("error") = True
        Throw New Lanap.BotDetect.Exceptions.CaptchaWebException( _
            "Simulated exception")
    End Sub

End Class

Explicación

Aparte de la inicialización y validación de código usual CAPTCHA, el manejador de eventos CauseErrorButton_Click es usado para arrojar una excepción interna simulada BotDetect. Como esto es un proyecto de ejemplo simplificado que contiene solo una pagina la que es usada antes y después de que la excepción es arrojada y manejada, también usamos una bandera de Sesión para manejar la presentación de información de errores.

No hay código de manejo de errores en el código detrás del formulario, ya que un HttpModule especial es registrado en el archivo Web.config, que atrapa los errores internos BotDetect (pero no las excepciones generales) y escribe la información del error a un archivo de texto.

Global.asax

Listado del Código Fuente Completo

<%@ Application Language="VB" %>

<script runat="server">

    Sub Application_Start(ByVal sender As Object, _
        ByVal e As EventArgs)
        ' Code that runs on application startup
    End Sub
    
    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application shutdown
    End Sub
        
    Sub Application_Error(ByVal sender As Object, _
        ByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs
         Response.Redirect("Default.aspx")
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a new session is started
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a session ends. 
        ' Note: The Session_End event is raised only when the 
        ' sessionstate mode is set to InProc in the Web.config file. 
        ' If session mode is set to StateServer or SQLServer, 
        ' the event is not raised.
    End Sub
       
</script>

Explicación

Cómo el registro de errores interno BotDetect re-arroja cualquier excepción luego de registrar sus detalles, usted puede manejar todas las excepciones en sus aplicaciones de una manera consistente. En este ejemplo, vamos a ignorar el error y reescribiremos la única página en la aplicación.

Web.config

Listado del Código Fuente Completo

<?xml version="1.0"?>
<!-- 
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option en Visual.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
  <configSections>
    <section name="log4net" 
      type="log4net.Config.Log4NetConfigurationSectionHandler, 
      log4net"/>
  </configSections>
  <log4net configSource="log4net.config"/>
  <connectionStrings/>
  <system.web>
    <httpHandlers>
      <add verb="*" path="LanapCaptcha.aspx" 
        type="Lanap.BotDetect.CaptchaHandler, Lanap.BotDetect"/>
    </httpHandlers>
    <httpModules>
      <add type="Lanap.BotDetect.Solución de problemas.LoggingModule, 
        Lanap.BotDetect.Solución de problemas" name="LoggingModule"/>
    </httpModules>
    <sessionState mode="InProc" cookieless="AutoDetect" timeout="20" 
      sessionIDManagerType="Lanap.BotDetect.Persistence.
      CustomSessionIDManager, Lanap.BotDetect" />
    <!-- 
      Set compilation debug="true" to insert debugging 
      symbols into the compiled page. Because this 
      affects performance, set this value to true only 
      during development.
    -->
    <compilation debug="false" strict="false" explicit="true">
      <assemblies>
        <add assembly="System.Design, Version=2.0.0.0, 
          Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <!--
      The <authentication> section enables configuration 
      of the security authentication mode used by 
      ASP.NET to identify an incoming user. 
    -->
    <authentication mode="None"/>
    <!--
      The <customErrors> section enables configuration 
      of what to do if/when an unhandled error occurs 
      during the execution of a request. Specifically, 
      it enables developers to configure html error pages 
      to be displayed in place of a error stack trace.

      <customErrors mode="RemoteOnly" 
        defaultRedirect="GenericErrorPage.htm">
        <error statusCode="403" redirect="NoAccess.htm" />
        <error statusCode="404" redirect="FileNotFound.htm" />
      </customErrors>
    -->
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="LanapCaptchaHandler" />
      <add name="LanapCaptchaHandler" preCondition="integratedMode" 
        verb="*" path="LanapCaptcha.aspx" 
        type="Lanap.BotDetect.CaptchaHandler, Lanap.BotDetect" />
    </handlers>
    <modules>
      <remove name="LoggingModule" />
      <add name="LoggingModule" 
        preCondition="integratedMode" 
        type="Lanap.BotDetect.Solución de problemas.LoggingModule, 
        Lanap.BotDetect.Solución de problemas" />
    </modules>
  </system.webServer>
</configuration>

Explicación

Aparte del HttpHandler usual y declaraciones de Session State requeridas para todas las aplicaciones BotDetect CAPTCHA, dos elementos más son encesarios para habilitar el registro de errores que viene con BotDetect. El primero es la registración de HttpModule en la sección <httpModules>, que activa un especial ErrorTrackingModule de BotDetect. Para soportar máquinas ISS 7.0 configuradas para correr el tiempo de ejecución ASP.NET en el Modo Integrado, este mismo registro es repetido en la sección <handlers>.

El segundo elemento necesario es la declaración <configSection>, en la que registramos una sección de configuración especial para la configuración de log4net (el framework de registro .NET de código abierto usado para el registro de errores actual). Para simplificar los problemas, esta sección de configuración es ajustada para ser cargada desde un archivo externo .config.

Log4net.config

Listado del Código Fuente Completo

<?xml version="1.0"?>

<!-- This section contains the log4net configuration settings -->
<log4net debug="false">

  <!-- Errors are logged to a 'error.txt' file  -->
  <appender name="ErrorFileAppender" 
      type="log4net.Appender.FileAppender">
    <file value="error.txt" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout,log4net">
      <conversionPattern 
        value="%date [%thread] %type - %n%n%message%n%n" />
    </layout>
  </appender>

  <!-- Error logging is enabled, comment-out to disable -->
  <logger name="ErrorLogger">
    <level value="ERROR" />
    <appender-ref ref="ErrorFileAppender" />
  </logger>
	
  <!-- Debug info is logged to a 'debug.txt' file  -->
  <appender name="DebugFileAppender" 
      type="log4net.Appender.FileAppender">
    <file value="debug.txt" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout,log4net">
      <conversionPattern 
        value="%date [%thread] %type - %n%n%message%n%n" />
    </layout>
  </appender>

  <!-- Debug logging is enabled, comment-out to disable -->
  <logger name="DebugLogger">
    <level value="DEBUG" />
    <appender-ref ref="DebugFileAppender" />
  </logger>

</log4net>

Explicación

Usando la sintaxis de configuración log4net, este archivo instala un registrador de errores escribiendo detalles de excepciones a un archivo de texto llamado error.txt y localizado en la misma carpeta que el archivo log4net.config. Las validaciones de ingresos de Captcha son escritos en un archivo llamado debug.txt.

 

El Framework log4net ofrece varias opciones de registro, desde diferentes salidas de regsitro hasta diferentes niveles de mensajes de registro (búsqueda, depuración, y otros mensajes), que pueden ser manejados en distintas maneras. Para simplificar, este ejemplo de proyecto usa un registrador de archivo simple – si está interesado en otras opciones, por favor consulte la documentación log4net.

language: English Español Tiếng Việt