BotDetect ASP.NET 1.1 CAPTCHA Validation VB.NET Code Sample
The BotDetect ASP.NET CAPTCHA validation sample contains the basic code required to add a CAPTCHA control to an ASP.NET page and validate the user input. It can be used as a starting point when you are first learning how to use BotDetect CAPTCHA, and is equivalent to the result you will get if you are following the How To use BotDetect ASP.NET CAPTCHA in Visual Studio 2003 instructions.
Sample Project Location
By default, this sample project is installed at
C:\Program Files\Lanapsoft\BotDetect\ASP.NET 1.1\v2.0\Samples\VBNetBotDetect2Demo\.
You can also run it from the Start Menu:
Programs > Lanapsoft > BotDetect > ASP.NET 1.1 > v2.0 > Samples > VB.NET BotDetect CAPTCHA Validation Sample.
Default.aspx
Full Source Code Listing
<%@ Page Language="vb" AutoEventWireup="false"
Codebehind="Default.aspx.vb" Inherits="VBNetBotDetectDemo._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>
</form>
</body>
</html>
Explanation
Lines required to add the BotDetect CAPTCHA control to the ASP.NET form are bold. To use the <BotDetect:Captcha> control, we must first register the Lanap.BotDetect.dll assembly using the <%@Register %> directive.
The form also contains an <asp:TextBox> for the user input, an <asp:Button> to submit the page, and a pair of <asp:Label> controls which are used to show the CAPTCHA validation result.
The rest of the file is either generated by Visual Studio 2003 by default, or just defines the layout and visual presentation of the page.
Default.aspx.vb
Full Source Code Listing
Public Class _Default
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub _
InitializeComponent()
End Sub
Protected WithEvents MessageCorrectLabel As _
System.Web.UI.WebControls.Label
Protected WithEvents MessageIncorrectLabel As _
System.Web.UI.WebControls.Label
Protected WithEvents SampleCaptcha As _
Lanap.BotDetect.Captcha
Protected WithEvents CodeTextBox As _
System.Web.UI.WebControls.TextBox
Protected WithEvents ValidateButton As _
System.Web.UI.WebControls.Button
'NOTE: The following placeholder declaration is required by
'the Web Form Designer. Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form
'Designer. Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
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
End If
' clear user input on Reload button clicks
Dim scriptTemplate As String
scriptTemplate = "<script type='text/javascript'>" & _
"function LBD_ClearUserInput() {{" & _
" var LBD_textBox = document.getElementById('{0}');" & _
" if(LBD_textBox) {{" & _
" LBD_textBox.value = '';" & _
" }}" & _
"}}" & _
"LBD_RegisterHandler('PreReloadCaptchaImage', _
LBD_ClearUserInput);</script>"
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
'clear previous user code input
CodeTextBox.Text = ""
End If
End Sub
End Class
Explanation
Form processing is done in the Page_PreRender event handler, so all individual control events are executed before the CAPTCHA validation. If you want to validate the CAPTCHA before individual control events, you can move the code to the Page_Load event handler.
Also, the processing is not done in the ValidateButton_Click handler on purpose, in case there are multiple controls which can submit the page – we want to validate the CAPTCHA regardless of what caused the page to submit. Not to mention that most bots will not submit the page by clicking the button, but by simply constructing the POST request data, which might or might not include the "control which caused the postback" part, responsible for triggering the button click event. Checking the CAPTCHA on each page load ensures proper CAPTCHA security in all cases.
On the first page load (if (!IsPostBack)), the button and label controls are initialized, and the CAPTCHA validation is skipped, because the user didn't have a chance to solve it yet.
On each page load, we add a small JavaScript fragment to the textbox onkeyup client-side event handler, so the user input is immediately lowercased during typing. This serves to communicate the fact that the CAPTCHA code is not case-sensitive to the user.
Also, we register a custom PreReloadCaptchaImage client-side event handler which automatically clears the user CAPTCHA input on each reload. Since clicking the Reload button changes the CAPTCHA code randomly, this saves the user from having to delete any characters they might have typed before changing the code.
When the page is submitted (if (IsPostBack)), we forward the user input to the Captcha.Validate() method. In this simplified sample, we use the validation result just to display a message, and always show a new CAPTCHA. In most use cases, you will show a new CAPTCHA only if the user didn't solve the previous one correctly, and execute the protected code fragment (user registration, comment recording, etc.) if the CAPTCHA was solved correctly.
If you redirect the user to a different page upon successful CAPTCHA completion, and you want to protect such pages as well, it might be a good idea to set a Session variable (for example, Session["IsHuman"] = true), and check it on subsequent pages. Otherwise, some bots could be written to skip the CAPTCHA-protected page and go to those later pages directly, bypassing some of the protection.
Finally, since a new CAPTCHA image is shown on each page load and each CAPTCHA code can only be validated once (regardless of the validation result), the user input should always be cleared after the CAPTCHA validation.
Web.config
Full Source Code Listing
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="LanapCaptcha.aspx"
type="Lanap.BotDetect.CaptchaHandler, Lanap.BotDetect"/>
</httpHandlers>
<!-- 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="vb"
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>
Explanation
Lines necessary for BotDetect CAPTCHA to function properly have been bold, other lines are all standard values generated by Visual Studio 2003 by default. The <httpHandlers> element registers the path used for CAPTCHA image and sound requests for processing by Lanap.BotDetect.dll code, while the <sessionState> element declares the persistence mechanism used by BotDetect to keep the CAPTCHA codes and settings for each user.
You can use different Session State settings and modes depending on your application's needs, but you will have to ensure Session State persistence is available for BotDetect to work. Special care should be taken if you are running multiple load-balanced servers, as explained in this FAQ item.
Current BotDetect Versions
- BotDetect ASP.NET CAPTCHA v2.0.152009–11–23
- BotDetect ASP CAPTCHA v2.0.92009–02–12





