Ejemplo de Código de Solución de Problemas C# BotDetect ASP.NET 1.1 CAPTCHA
Este ejemplo de BotDetect ASP.NET CAPTCHA muestra como usar el registro de errores que viene con BotDetect para soluciona problemas CAPTCHA. 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
- Default.aspx
- Default.aspx.cs
- Global.asax.cs
- Web.config
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 1.1\v2.0\Samples\CSharpBotDetect2Solución de problemasDemo\.
También lo puede arrancar desde el Menú de Inicio:
Programas > Lanapsoft > BotDetect > ASP.NET 1.1 > v2.0 > Samples > C# BotDetect Solución de problemas Demo Preview.
Default.aspx
Listado del Código Fuente Completo
<%@ Page language="c#" Codebehind="Default.aspx.cs"
AutoEventWireup="false" Inherits="CSharpBotDetectDemo._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 Preview</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>
</fieldset>
<div id="Note">
<span>NOTE: the Trial version will use "LANAP" instead of a
random code in 50% of renderings.</span>
</div>
<fieldset id="Solución de problemas">
<legend><span id="Solución de problemasLegend">CAPTCHA
Solución de problemas</span></legend>
<div class="Solución de problemas">
<p>Clicking 'Simulate Error' will throw a fake BotDetect
exception and log it to the 'log.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>
</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.cs
Listado del Código Fuente Completo
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CSharpBotDetectDemo
{
/// <summary>
/// Summary description for _Default.
/// </summary>
public class _Default : System.Web.UI.Page
{
protected Lanap.BotDetect.Captcha
SampleCaptcha;
protected System.Web.UI.WebControls.Button
ValidateButton;
protected System.Web.UI.WebControls.TextBox
CodeTextBox;
protected System.Web.UI.WebControls.Label
MessageIncorrectLabel;
protected System.Web.UI.WebControls.Label
MessageCorrectLabel;
protected System.Web.UI.WebControls.Button
CauseErrorButton;
protected System.Web.UI.WebControls.Label
ErrorLabel;
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET
// Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.PreRender +=
new System.EventHandler(this.Page_PreRender);
}
#endregion
protected void Page_PreRender(object sender, EventArgs e)
{
/// initial page setup
if (!IsPostBack)
{
/// 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.log' file.";
}
if (null != Session["error"])
{
ErrorLabel.Visible = true;
MessageCorrectLabel.Visible = false;
MessageIncorrectLabel.Visible = false;
Session["error"] = null;
}
else
{
ErrorLabel.Visible = false;
}
CodeTextBox.Attributes.Add("onkeyup",
"this.value = this.value.toLowerCase();");
if (IsPostBack)
{
/// validate the input code, and show the
/// appropriate message
string code = CodeTextBox.Text.Trim().ToUpper();
if (SampleCaptcha.Validate(code))
{
MessageCorrectLabel.Visible = true;
MessageIncorrectLabel.Visible = false;
}
else
{
MessageCorrectLabel.Visible = false;
MessageIncorrectLabel.Visible = true;
}
/// clear previous user code input
CodeTextBox.Text = null;
}
}
protected void CauseErrorButton_Click(object sender,
EventArgs e)
{
Session["error"] = true;
throw new Lanap.BotDetect.Exceptions.CaptchaWebException(
"Simulated exception");
}
}
}
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.cs
Listado del Código Fuente Completo
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
namespace CSharpBotDetectSolución de problemasDemo
{
/// <summary>
/// Summary description for Global.
/// </summary>
public class Global : System.Web.HttpApplication
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
public Global()
{
InitializeComponent();
}
protected void Application_Start(Object sender, EventArgs e)
{
}
protected void Session_Start(Object sender, EventArgs e)
{
}
protected void Application_BeginRequest(Object sender,
EventArgs e)
{
}
protected void Application_EndRequest(Object sender,
EventArgs e)
{
}
protected void Application_AuthenticateRequest(Object sender,
EventArgs e)
{
}
protected void Application_Error(Object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void Session_End(Object sender, EventArgs e)
{
}
protected void Application_End(Object sender, EventArgs e)
{
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
}
#endregion
}
}
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" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/>
</configSections>
<!-- This section contains the log4net configuration settings -->
<log4net debug="false">
<!-- Define some output appenders -->
<appender name="FileAppender"
type="log4net.Appender.FileAppender">
<file value="log.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>
<!-- Setup the root category, add the appenders and set
the default priority -->
<logger name="ErrorLogger">
<level value="ERROR" />
<appender-ref ref="FileAppender" />
</logger>
</log4net>
<system.web>
<httpHandlers>
<add verb="*" path="LanapCaptcha.aspx"
type="Lanap.BotDetect.CaptchaHandler, Lanap.BotDetect"/>
</httpHandlers>
<httpModules>
<add type="Lanap.BotDetect.Solución de problemas.ErrorTrackingModule,
Lanap.BotDetect.Solución de problemas" name="ErrorTrackingModule"/>
</httpModules>
<!-- DYNAMIC DEBUG COMPILATION
Set compilation debug="true" to enable ASPX debugging. Otherwise,
setting this value to false will improve runtime performance of
this application. Set compilation debug="true" to insert debugging
symbols (.pdb information) into the compiled page. Because this
creates a larger file that executes more slowly, you should set
this value to true only when debugging and to false at all other
times. For more information, refer to the documentation about
debugging ASP.NET files.
-->
<compilation
defaultLanguage="c#"
debug="false"
/>
<!-- CUSTOM ERROR MESSAGES
Set customErrors mode="On" or "RemoteOnly" to enable custom error
messages, "Off" to disable.
Add <error> tags for each of the errors you want to handle.
"On" Always display custom (friendly) messages.
"Off" Always display detailed ASP.NET error information.
"RemoteOnly" Display custom (friendly) messages only to users not
running on the local Web server. This setting is recommended for
security purposes, so that you do not display application detail
information to remote clients.
-->
<customErrors
mode="RemoteOnly"
/>
<!-- AUTHENTICATION
This section sets the authentication policies of the application.
Possible modes are "Windows", "Forms", "Passport" and "None".
"None" No authentication is performed.
"Windows" IIS performs authentication (Basic, Digest, or
Integrated Windows) according to its settings for the
application. Anonymous access must be disabled in IIS.
"Forms" You provide a custom form (Web page) for users to
enter their credentials, and then you authenticate them
in your application. A user credential token is stored
in a cookie.
"Passport" Authentication is performed via a centralized
authentication service provided by Microsoft that offers
a single logon and core profile services for member sites.
-->
<authentication mode="Windows" />
<!-- AUTHORIZATION
This section sets the authorization policies of the
application. You can allow or deny access to application
resources by user or role. Wildcards: "*" mean everyone,
"?" means anonymous (unauthenticated) users.
-->
<authorization>
<allow users="*" /> <!-- Allow all users -->
<!--
<allow users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
<deny users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
-->
</authorization>
<!-- APPLICATION-LEVEL TRACE LOGGING
Application-level tracing enables trace log output for
every page within an application.
Set trace enabled="true" to enable application trace
logging. If pageOutput="true", the trace information
will be displayed at the bottom of each page. Otherwise,
you can view the application trace log by browsing the
"trace.axd" page from your web application root.
-->
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>
<!-- SESSION STATE SETTINGS
By default ASP.NET uses cookies to identify which requests
belong to a particular session. If cookies are not available,
a session can be tracked by adding a session identifier to the
URL. To disable cookies, set sessionState cookieless="true".
-->
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>
<!-- GLOBALIZATION
This section sets the globalization settings of the application.
-->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>
</system.web>
</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 web.config. El framework de log4net ofrece muchas otras opciones de inicio de sesión, desde destinos de salida del reistro a diferentes niveles de registro de mensajes (búsqueda, depuración, y otros mensajes), los que pueden ser manejados en distintas maneras. Para simplificar, este ejemplo de proyecto usa un registro de archivos simple – si está interesado en otras opciones, por favor consulte la log4net documentación.
Versiones Actuales de BotDetect
- BotDetect ASP.NET CAPTCHA v2.0.152009–11–23
- BotDetect ASP CAPTCHA v2.0.92009–02–12
Advertencia
Esta página es una traducción no oficial de la página original: BotDetect CAPTCHA Troubleshooting C# Code Sample y puede estar incompleta, incorrecta o poco actualizada.
Última traducción del 2009-12-18. Esto se aplica para los productos BotDetect ASP.NET CAPTCHA v2.0.15 y BotDetect ASP CAPTCHA v2.0.9.





