ASP.NET CAPTCHA Form Object Settings VB.NET Code Example

The ASP.NET Captcha form object settings example project shows how to configure BotDetect CAPTCHA challenges by setting Captcha control properties in ASP.NET form source.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

Multiple ASP.NET forms within the same ASP.NET website can be protected by BotDetect Captcha challenges: e.g. you could add Captcha controls in both your Contact form and Registration form source.

To function properly, separate Captcha challenges placed on each form should have different names (CaptchaId values, Captcha1 and Captcha2 in this example), and can use completely different Captcha settings.

Even multiple Captcha instances placed on the same form won't interfere with each other's validation and functionality. And if a user opens the same page in multiple browser tabs, each tab will independently validate the shown Captcha code.

Shared Captcha settings should always be placed in the web.config application configuration file, and only diverging settings set through Captcha object instance properties in form code, to avoid code duplication.

Settings that affect only Captcha container markup generation take effect immediately (changing Captcha.Html output), but settings that affect Captcha challenge (image or sound) generation in separate Http requests need to be saved in ASP.NET Session state when set through Captcha object instance properties in form source, consuming server resources and reverting to defaults when the ASP.NET Session expires.

Please note that if configured values are dynamic (e.g. CaptchaRandomization helper or other function calls in form code), they will be re-calculated only when the form is reloaded (form code is executed). For example, Captcha ImageStyle randomized in ASP.NET form source will not change on each Captcha Reload button click, but only on each form load.

Download the BotDetect ASP.NET CAPTCHA Component and run this example
  • C#
  • VB.NET

Visual Studio 2005-2017 / .NET 2.0 and onwards

By default, the VB.NET version of the ASP.NET Captcha form object settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect CAPTCHA\aspnetlegacy+netlegacy\Examples\TraditionalAPI\CaptchaFormObjectSettingsExample\VBNet

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect CAPTCHA > ASPNETLEGACY + NETLEGACY Examples > Legacy ASP.NET + Legacy .NET Run code examples

Default.aspx

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

<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
  <title>BotDetect ASP.NET CAPTCHA Options: Form Object Settings Code Example</title> 
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" /> 
  <script type="text/javascript" src="<%= BotDetect.Web.CaptchaUrls.Absolute.ScriptIncludeUrl %>"></script> 
</head> 
<body> 
  <form runat="server" class="column" id="form1"> 
    <h1>BotDetect ASP.NET CAPTCHA Options: 
      <br /> 
      Form Object Settings Code Example</h1> 
    <fieldset> 
      <legend>ASP.NET WebForm CAPTCHA Validation</legend> 
      <p class="prompt"> 
        <label for="Captcha1CodeTextBox">Retype the characters from the picture:</label></p> 
      <BotDetect:WebFormsCaptcha runat="server" ID="Captcha1" 
      UserInputControlID="Captcha1CodeTextBox" 
        CodeLength="6" 
        CodeStyle="Numeric" 
        DisallowedCodeSubstringsCsv="1,2,3,4,5,00,777,9999" 
        CodeTimeout="300" 
        ImageStyle="SunAndWarmAir" 
        ImageSize="250,60" 
        ImageFormat="Png" 
        CustomDarkColor="Black" 
        CustomLightColor="White" 
        SoundEnabled="true" 
        SoundStyle="Synth" 
        SoundFormat="WavPcm8bit8kHzMono" 
        SoundRegenerationMode="Limited" 
        Locale="es-MX" 
        ImageTooltip="Custom Mexican Spanish Captcha image tooltip" 
        SoundTooltip="Custom Mexican Spanish Captcha sound icon tooltip" 
        ReloadTooltip="Custom Mexican Spanish Captcha reload icon tooltip" 
        HelpLinkText="Custom Mexican Spanish Captcha help link text" 
        HelpLinkUrl="custom-mexican-spanish-captcha-help-page.html" 
        ReloadEnabled="true" 
        UseSmallIcons="false" 
        UseHorizontalIcons="false" 
        SoundIconUrl="" 
        ReloadIconUrl="" 
        IconsDivWidth="27" 
        HelpLinkEnabled="true" 
        HelpLinkMode="Text" 
        TabIndex="-1" 
        AdditionalCssClasses="class1 class2 class3" 
        AdditionalInlineCss="border: 4px solid #fff; background-color: #f8f8f8;" 
        AddScriptInclude="true" 
        AddInitScript="true" 
        AutoUppercaseInput="true" 
        AutoFocusInput="true" 
        AutoClearInput="true" 
        AutoReloadExpiredCaptchas="true" 
        AutoReloadTimeout="7200" 
        SoundStartDelay="100" 
        RemoteScriptEnabled="true" /> 
      <div class="validationDiv"> 
        <asp:TextBox ID="Captcha1CodeTextBox" runat="server"></asp:TextBox> 
        <asp:Label ID="Captcha1CorrectLabel" runat="server" CssClass="correct" 
        Text="Correct!" Visible="false"></asp:Label> 
        <asp:Label ID="Captcha1IncorrectLabel" runat="server" 
        CssClass="incorrect" Text="Incorrect!" Visible="false"></asp:Label> 
      </div> 
    </fieldset> 

    <fieldset> 
      <legend>ASP.NET WebForm CAPTCHA Validation</legend> 
      <p class="prompt"> 
        <label for="Captcha2CodeTextBox">Retype the characters from the picture:</label></p> 
      <BotDetect:WebFormsCaptcha runat="server" ID="Captcha2" 
      UserInputControlID="Captcha2CodeTextBox" /> 
      <div class="validationDiv"> 
        <asp:TextBox ID="Captcha2CodeTextBox" runat="server"></asp:TextBox> 
        <asp:Label ID="Captcha2CorrectLabel" runat="server" CssClass="correct" 
        Text="Correct!" Visible="false"></asp:Label> 
        <asp:Label ID="Captcha2IncorrectLabel" runat="server" 
        CssClass="incorrect" Text="Incorrect!" Visible="false"></asp:Label> 
      </div> 
    </fieldset> 

    <asp:Button ID="SubmitFormButton" runat="server" Text="Submit Form" /> 
  </form> 
</body> 
</html> 

Default.aspx.vb

Imports BotDetect 

Partial Class _Default 
  Inherits System.Web.UI.Page 
  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As  _ 
  System.EventArgs) Handles Me.PreRender 
    'Captcha2 code-behind setup 

    Captcha2.CodeLength = 4 
    Captcha2.CodeStyle = CodeStyle.Alpha 
    Captcha2.DisallowedCodeSubstringsList = New List(Of String)(New String() { 
    "AAA", "BBB", "CCC"}) 
    Captcha2.CodeTimeout = 900 ' 15 minutes 

    ' only re-calcualated on form load 
    Dim imageStyles As ImageStyle() = 
    { 
      ImageStyle.BlackOverlap, 
      ImageStyle.Graffiti, 
      ImageStyle.Overlap 
    } 
    Captcha2.ImageStyle = CaptchaRandomization.GetRandomImageStyle(imageStyles) 
    Captcha2.ImageSize = New System.Drawing.Size(120, 35) 
    Captcha2.ImageFormat = ImageFormat.Png 
    Captcha2.CustomDarkColor = System.Drawing.Color.DarkGreen 
    Captcha2.CustomLightColor = System.Drawing.ColorTranslator.FromHtml("#eeeeff") 

    Captcha2.SoundEnabled = True 
    Captcha2.SoundStyle = SoundStyle.Dispatch 
    Captcha2.SoundFormat = SoundFormat.WavPcm8bit8kHzMono 
    Captcha2.SoundRegenerationMode = SoundRegenerationMode.None 

    Captcha2.Locale = "fr-CA" 
    Captcha2.ImageTooltip = "Custom Canadian French Captcha image tooltip" 
    Captcha2.SoundTooltip = "Custom Canadian French Captcha sound icon tooltip" 
    Captcha2.ReloadTooltip = "Custom Canadian French Captcha reload icon tooltip" 
    Captcha2.HelpLinkUrl = "custom-canadian-french-captcha-help-page.html" 
    Captcha2.HelpLinkText = "Custom Canadian French Captcha help link text" 

    Captcha2.ReloadEnabled = True 
    Captcha2.UseSmallIcons = True 
    Captcha2.UseHorizontalIcons = True 
    Captcha2.SoundIconUrl = "" 
    Captcha2.ReloadIconUrl = "" 
    Captcha2.IconsDivWidth = 50 
    Captcha2.HelpLinkEnabled = True 
    Captcha2.HelpLinkMode = HelpLinkMode.Image 
    Captcha2.TabIndex = 15 
    Captcha2.AdditionalCssClasses = "" 
    Captcha2.AdditionalInlineCss = "" 

    Captcha2.AddScriptInclude = True 
    Captcha2.AddInitScript = True 
    Captcha2.AutoUppercaseInput = True 
    Captcha2.AutoFocusInput = True 
    Captcha2.AutoClearInput = True 
    Captcha2.AutoReloadExpiredCaptchas = True 
    Captcha2.AutoReloadTimeout = 3600 ' 1 hour 
    Captcha2.SoundStartDelay = 1000 ' 1 second 
    Captcha2.RemoteScriptEnabled = True 


    ' Form validation 
    If (IsPostBack) Then 

      Dim isHuman1 As Boolean = Captcha1.Validate() 
      If (isHuman1) Then 

        Captcha1CorrectLabel.Visible = True 
        Captcha1IncorrectLabel.Visible = False 

      Else 

        Captcha1CorrectLabel.Visible = False 
        Captcha1IncorrectLabel.Visible = True 
      End If 

      Dim isHuman2 As Boolean = Captcha2.Validate() 
      If (isHuman2) Then 

        Captcha2CorrectLabel.Visible = True 
        Captcha2IncorrectLabel.Visible = False 

      Else 

        Captcha2CorrectLabel.Visible = False 
        Captcha2IncorrectLabel.Visible = True 

      End If 
    End If 
  End Sub 
End Class 

Web.config

<?xml version="1.0"?> 
<!-- 
  For more information on how to configure your ASP.NET application, please  
  visit 
  http://go.microsoft.com/fwlink/?LinkId=169433 
  --> 
<configuration> 
  <configSections> 
    <section name="botDetect" requirePermission="false" 
    type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect"/> 
  </configSections> 
  <appSettings> 
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/> 
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/> 
  </appSettings> 
  <system.web> 
    <httpHandlers> 
      <!-- Register the HttpHandler used for BotDetect Captcha requests --> 
      <add verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.CaptchaHandler, BotDetect"/> 
    </httpHandlers> 
    <!-- Register a custom SessionIDManager for BotDetect Captcha requests --> 
    <sessionState mode="InProc" cookieless="AutoDetect" timeout="20" 
    sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/> 
    <!-- Session state is required for BotDetect storage; you can also turn if off  
    globally and only enable for BotDetect-protected pages if you prefer --> 
    <pages controlRenderingCompatibilityVersion="4.5" enableSessionState="true"> 
      <controls> 
      <!-- Register the BotDetect tag prefix for easier use in all pages --> 
      <add assembly="BotDetect" namespace="BotDetect.Web.UI" 
      tagPrefix="BotDetect"/> 
      </controls> 
    </pages> 
    <compilation debug="false" targetFramework="4.5"/> 
    <httpRuntime requestValidationMode="4.5" targetFramework="4.5" 
    encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> 
    <machineKey compatibilityMode="Framework45"/> 
  </system.web> 
  <system.webServer> 
    <validation validateIntegratedModeConfiguration="false"/> 
    <handlers> 
      <!-- Register the HttpHandler used for BotDetect Captcha requests (IIS 7.0+) --> 
      <remove name="BotDetectCaptchaHandler"/> 
      <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" 
      path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect"/> 
    </handlers> 
  </system.webServer> 
  <botDetect helpLinkEnabled="true" helpLinkMode="image" /> 
</configuration>