ASP.NET CAPTCHA Client-Side Workflow Settings C# Code Example

The ASP.NET Captcha client-side workflow settings example project shows how to use custom BotDetect CAPTCHA client-side events to execute user-defined JavaScript code at various stages of the Captcha challenge workflow.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

Client-side Captcha object initialization, Captcha image reloading, Captcha sound playback, built-in Captcha Ajax validation, and Captcha help link clicks all have a number of related client-side "events" and hooks where user-defined client-side callbacks can be injected.

User code can be associated with Captcha workflow events using the BotDetect.RegisterCustomHandler() function, as shown in the example JavaScript code.

Loading the form will initialize the client-side Captcha object (created by the BotDetect.Init() JavaScript call included in Captcha markup), and result in the PostInit event.

Clicking the Captcha sound icon will result in the PrePlaySound event before the audio elements are added to the page DOM. There is no PostPlaySound event since not all browsers allow user callbacks when browser sound playing finishes.

Clicking the Captcha reload icon will result in PreReloadImage and PostReloadImage events, executed before and after the Http request loading the new Captcha image from the server.

Clicking the Captcha image (i.e. the included Captcha help link) will result in the OnHelpLinkClick event.

Typing in a Captcha code and clicking the Validate button will first result in the PreAjaxValidate event, and later in either AjaxValidationFailed or AjaxValidationPassed depending on whether the server responds that the typed-in Captcha code was correct or not. In case of Ajax asynchronous request errors, AjaxValidationError will be called.

Download the BotDetect ASP.NET CAPTCHA Component and run this example

Visual Studio 2015 / Visual Studio 2013 / Visual Studio 2012 / .NET 4.6 / .NET 4.5

By default, the .NET 4.5 C# version of the ASP.NET Captcha client-side workflow settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET4.5\WebApp\CaptchaClientSideWorkflowSettingsExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > DotNET 4.5 Web Applications > Run

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>BotDetect ASP.NET CAPTCHA Options: Client-Side Workflow Settings Code 
  Example</title>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
</head>
<body>
  <form runat="server" class="column" id="form1">
    <h1>BotDetect ASP.NET CAPTCHA Options:
      <br />
      Client-Side Workflow Settings Code Example</h1>
    <fieldset>
      <legend>ASP.NET WebForm CAPTCHA Validation</legend>
      <p class="prompt">
        <label for="CaptchaCodeTextBox">Retype the characters from the picture:</label></p>
      <BotDetect:WebFormsCaptcha runat="server" ID="ExampleCaptcha" 
      UserInputControlID="CaptchaCodeTextBox" />
      <div class="validationDiv">
        <asp:TextBox ID="CaptchaCodeTextBox" runat="server"></asp:TextBox>
        <asp:Button ID="ValidateCaptchaButton" runat="server" 
        OnClientClick="startAsyncCaptchaValidation(); return false;" />
        <asp:Label ID="CaptchaCorrectLabel" runat="server" CssClass="correct"></asp:Label>
        <asp:Label ID="CaptchaIncorrectLabel" runat="server" 
        CssClass="incorrect"></asp:Label>
      </div>
    </fieldset>
    <h4>Custom BotDetect Client-Side Events Debug Log</h4>
    <div id="output"></div>
  </form>

  <script type="text/javascript">
    function log(text) {
      var output = document.getElementById('output');
      var line = document.createElement('pre');
      line.innerHTML = timestamp() + ' ' + text;
      output.insertBefore(line, output.firstChild);
    }

    function timestamp() {
      return new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
    }

    function format(url) {
      return url.replace(/^.*?\?/g, '').replace(/&/g, '\n  &');
    }

    BotDetect.RegisterCustomHandler('PostInit', function () {
      log('PostInit \n  CaptchaId ' + this.Id + '\n  InstanceId ' + this.
      InstanceId);
    });

    // custom javascript handler executed before Captcha sounds are played
    BotDetect.RegisterCustomHandler('PrePlaySound', function () {
      log('PrePlaySound');
    });

    // custom javascript handler executed before Captcha images are reloaded
    BotDetect.RegisterCustomHandler('PreReloadImage', function () {
      log('PreReloadImage\n  ' + format(this.Image.src) + '\n  AutoReload: ' + 
      this.AutoReloading);
    });

    // custom javascript handler executed after Captcha images are reloaded
    BotDetect.RegisterCustomHandler('PostReloadImage', function () {
      log('PostReloadImage\n  ' + format(this.Image.src));
    });

    // register handlers for the four steps of the BotDetect Ajax validation 
    // workflow
    BotDetect.RegisterCustomHandler('PreAjaxValidate', function () {
      log('PreAjaxValidate\n  ' + format(this.ValidationUrl + '&i=' + this.
      GetInputElement().value));
    });

    BotDetect.RegisterCustomHandler('AjaxValidationFailed', function () {
      log('AjaxValidationFailed');
    });

    BotDetect.RegisterCustomHandler('AjaxValidationPassed', function () {
      log('AjaxValidationPassed');
    });

    BotDetect.RegisterCustomHandler('AjaxValidationError', function () {
      log('AjaxValidationError');
    });

    BotDetect.RegisterCustomHandler('OnHelpLinkClick', function () {
      log('OnHelpLinkClick');
      this.FollowHelpLink = false; // abort help page opening
    });

    function startAsyncCaptchaValidation() {
      var input = document.getElementById('CaptchaCodeTextBox');
      if (input && 'text' == input.type) {
        // call the BotDetect built-in client-side validation function
        // this function must be called after the Captcha is displayed on the 
        // page, otherwise the
        // client-side object won't be initialized
        input.Captcha.StartAjaxValidation();
      }
    }
  </script>
</body>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
  protected void Page_PreRender(object sender, EventArgs e)
  {
    // initial page setup
    if (!IsPostBack)
    {
      // set control text
      ValidateCaptchaButton.Text = "Validate";
      CaptchaCorrectLabel.Text = "Correct!";
      CaptchaIncorrectLabel.Text = "Incorrect!";

      // these messages are shown only after validation
      CaptchaCorrectLabel.Visible = false;
      CaptchaIncorrectLabel.Visible = false;
    }

    if (IsPostBack)
    {
      // validate the Captcha to check we're not dealing with a bot
      bool isHuman = ExampleCaptcha.Validate();
      if (isHuman)
      {
        CaptchaCorrectLabel.Visible = true;
        CaptchaIncorrectLabel.Visible = false;
      }
      else
      {
        CaptchaCorrectLabel.Visible = false;
        CaptchaIncorrectLabel.Visible = true;
      }
    }
  }
}

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>

Visual Studio 2010 / .NET 4.0

By default, the .NET 4.0 C# version of the ASP.NET Captcha Client-Side Workflow Settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET4.0\WebApp\CaptchaClientSideWorkflowSettingsExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > DotNET 4.0 Web Applications > Run

The Visual Studio 2010 / .NET 4.0 source has no essential differences from the Visual Studio 2013 / Visual Studio 2012 / .NET 4.5 source.

Visual Studio 2008 / .NET 3.5

By default, the .NET 3.5 C# version of the ASP.NET Captcha Client-Side Workflow Settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET3.5\WebApp\CaptchaClientSideWorkflowSettingsExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > DotNET 3.5 Web Applications > Run

The Visual Studio 2008 / .NET 3.5 source has no essential differences from the Visual Studio 2013 / Visual Studio 2012 / .NET 4.5 source.

Visual Studio 2005 / .NET 2.0

By default, the .NET 2.0 C# version of the ASP.NET Captcha Client-Side Workflow Settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET2.0\WebApp\CaptchaClientSideWorkflowSettingsExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > DotNET 2.0 Web Applications > Run

The Visual Studio 2005 / .NET 2.0 source has no essential differences from the Visual Studio 2013 / Visual Studio 2012 / .NET 4.5 source.