How To create a SharePoint Web Part with BotDetect CAPTCHA

This article describes steps for creating a SharePoint Web Part using the Lanapsoft BotDetect CAPTCHA control. It is a very simple Web Part that allows you to validate user input, comparing it to the code shown in the CAPTCHA image.

Prerequisites

  • Microsoft Visual Studio 2005
  • Microsoft Windows SharePoint Services
  • BotDetect 2.0.10 for ASP.NET 2.0

In this article we assume that you are running Visual Studio 2005 on a server running Windows SharePoint Services or Microsoft Office SharePoint Server 2007.

Start by downloading the sample SharePoint Web Part project.

Step 1: Creating a new Web Part Library project

  1. Start Visual Studio 2005
  2. On the File menu, point to New, and then click Project
  3. In the New Project dialog box, click Visual C# Projects, and then select the Web Control Library template
  4. Type "LanapWebPart" as the name and specify the location for the project files, and then click OK

To create a Web Part, you need to add a reference to the Microsoft.SharePoint, System.XML and Lanap.BotDetect assemblies.

Step 2: Initial Project Settings

Before you start working with the code for a Web Part, you must make the following changes to your project settings:

  • Set the version number
  • Strong-name the assembly

To set the version number:

  1. In Solution Explorer, double-click AssemblyInfo.cs.
  2. Edit the line:
    [assembly: AssemblyVersion("1.0.*")]
    so that it reads:
    [assembly: AssemblyVersion ("1.0.0.0")]

To strong-name the assembly:

  1. Right click on your project name and select properties
  2. Choose Signing tab
  3. Check "Sign the assembly" option
  4. In "Choose a strong name key file" choose "<New...>"
  5. In new dialog type a file name and optionally a password
  6. Save project settings

Step 3: Adding namespace directives

  • Add the following using directives near the top of your code:
    using Microsoft.SharePoint.WebPartPages;
    using System.Xml.Serialization;
    using System.Web.UI.HtmlControls;
    using Lanap.BotDetect;

Step 4: Defining Toolbox data

  • Replace the following line:
    [ToolboxData("<{0}:WebCustomControl1 runat=server>")]
    with this line:
    [ToolboxData("<{0}:LanapSimpleWebPart runat=server>")]

Step 5: Inheriting from the WebPart base class

  • Replace this line of code:
    public class WebCustomControl1 : WebControl
    with
    public class LanapSimpleWebPart : WebPart

Step 6: Defining a XML namespace for the entire WebPart class

  • Add this line of code above the declaration for your WebPart class:
    [XmlRoot(Namespace="LanapWebPart")]

Step 7: Defining the Logic and Rendering of Your Web Part

  • After you complete the previous steps, you can define the logic and rendering for your Web Part. We are going to add a Lanap.BotDetect.Captcha object (displaying the CAPTCHA image), a TextBox (entering the CAPTCHA code), a Button (invoking CAPTCHA validation), and a Label (displaying the CAPTCHA validation result).
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    using Microsoft.SharePoint.WebPartPages;
    using System.Xml.Serialization;
    using System.Web.UI.HtmlControls;
    using Lanap.BotDetect;
    
    namespace LanapWebPart
    {
      [XmlRoot(Namespace = "LanapWebPart")]
      [ToolboxData("<{0}:LanapSimpleWebPart runat=server>")]
      public class LanapSimpleWebPart : WebPart
      {
        private TextBox _inputText;
        private Button _submitButton;
        private Label _messageLabel;
        private Lanap.BotDetect.Captcha _captchaControl;
    
        protected override void CreateChildControls()
        {
          base.CreateChildControls();
    
          _captchaControl = new Lanap.BotDetect.Captcha();
          _captchaControl.ID = "LanapCaptcha";
    
          _inputText = new TextBox();
          _inputText.ID = "InputText";
    
          _submitButton = new Button();
          _submitButton.ID = "SubmitButton";
          _submitButton.Text = "Validate";
    			
          _submitButton.Click +=
            new EventHandler(submitButton_Click);
    
          _messageLabel = new Label();
          _messageLabel.ID = "MessageLabel";
    
          this.Controls.Add(_captchaControl);
          this.Controls.Add(_inputText);
          this.Controls.Add(_submitButton);
          this.Controls.Add(_messageLabel);
        }
    
        void submitButton_Click(object sender, EventArgs e)
        {
          string captchaText = 
            ((TextBox)Controls[1]).Text.Trim().ToUpper();
    				
          ((TextBox)Controls[1]).Text = null;
    
          if (_captchaControl.Validate(captchaText))
          {
            ((Label)Controls[3]).Text = "Success!";
          }
          else
          {
            ((Label)Controls[3]).Text = "Error!";
          }
        }
      }
    }

Step 8: Register a Web Part assembly as a SafeControl

  1. Open the web.config file of your SharePoint site.
  2. Add the following lines in the <SafeControls> block:
    <SafeControl
      Assembly="LanapWebPart, Version=1.0.0.0, Culture=neutral,
        PublicKeyToken=82da7a1cd3cc100b"
      Namespace="LanapWebPart"
      TypeName="*"
      Safe="True"
    />
  3. Replace the PublicKeyToken value (82da7a1cd3cc100b) with the actual value for your Web Part's assembly. To determine the correct PublicKeyToken value for the Assembly attribute of the <SafeControl> tag of your Web Part, use the sn.exe command-line utility:
    sn.exe -T C:\inetpub\wwwroot\bin\SimpleWebPart.dll

Step 9: Registering Http Handlers

  • Add the following lines to the <system.web> section of the SharePoint "Web.config" file:
    <httpHandlers>
      <add verb="*" path="LanapCaptcha.ashx" 
        type="Lanap.BotDetect.CaptchaHandler, Lanap.BotDetect" />
    </httpHandlers>
  • Add the following lines to the <appSettings> section of the SharePoint "Web.config" file:
    <appSettings>
      <add key="LBD_RequestExtension" value=".ashx" />
    </appSettings>

Step 10: Deploying Your Web Part

  • To deploy your Web Part to a SharePoint site, copy your web part's assembly to the C:\inetpub\wwwroot\bin folder of your SharePoint server (or to the global assembly cache folder at C:\windows\assembly)

Step 11: Creating a Web Part Definition File (.dwp)

  • A Web Part Definition file (.dwp) file is a simple XML file that contains property settings for a single Web Part. To import your Web Part into a Web Part Page, simply upload the .dwp file. After uploading the Web Part, you can display the Web Part by dragging it into one of the zones of the Web Part Page.

    Two properties are required in the .dwp file: Assembly and TypeName. However, to display a default name and description for the Web Part after it is imported, you should also include the Title and Description properties. If you want to set other Web Part properties during import, you can also define them in a .dwp file. A .dwp file takes the following form:

    <?xml version="1.0"?>
    <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
       <Assembly>AssemblyName(with no .dll extension),
          Version=VersionNumber, Culture=Culture,
          PublicKeyToken=PublicKeyToken</Assembly>
       <TypeName>WebPartNamespace.WebPartClassName</TypeName>
       <Title>DefaultWebPartTitle</Title>
       <Description>WebPartDescription</Description>
    </WebPart>

    Your Web Part's .dwp part should look like this one:

    <?xml version="1.0"?>
    <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
      <Assembly>LanapWebPart, Version=1.0.0.0, Culture=Neutral,
        PublicKeyToken=def148956c61a16b</Assembly>
      <TypeName>LanapWebPart.LanapSimpleWebPart</TypeName>
      <Title>Lanap Simple Web Part</Title>
      <Description>This web part shows Lanapsoft BotDetect
        Captcha image and validates user input</Description>
    </WebPart>

Step 12: Importing Your Web Part into a Web Part Page

To use and test your Web Part, import it into a Web Part Page on a server running Windows SharePoint Services or Microsoft Office SharePoint Server 2007.

  1. Open a Web Part Page on your server.
  2. Select Edit Page from the Site Actions menu in the upper right corner of the page, and click Add a Web Part in one of the zones.
  3. In the Add Web Parts dialog box, click Advanced Web Part gallery and options in the lower right corner.
  4. In the Add Web Parts pane, click Import.
  5. Browse to the location of the SimpleWebPart.dwp file, and then click the Upload button. After uploading, the page will refresh, and "My Simple Web Part" should be displayed under Imported Web Part.
  6. Drag the icon next to "My Simple Web Part" to a zone on the Web Part Page.
  7. Type some text in the text box, and then click Set Web Part Title to test the part.

How To create a SharePoint Web Part with BotDetect CAPTCHA screenshot

Notes and Troubleshooting

  • To use the Web Part built in the described way in an anonymous SharePoint site, the IIS anonymous access user account (IUSR_<SERVER_NAME>) should be granted Read permissions to Lanap.BotDetect.dll. Alternatively, you could use the Lanap.BotDetect.dll assembly from the GAC.
  • Make sure Session State is allowed in the <httpModules> section of the SharePoint web.config file:
    <add name="Session" 
      type="System.Web.SessionState.SessionStateModule" />
letter
about