Resumé

Captcha Custom WebControl for ASP.Net

Cristian Merighi () 0.00

In this fully accessible and downloadable piece of code, I use GDI+ and C# to develop a simple Captcha WebControl. I think this could be a good start point for creating more enhanced versions.
This article is obsolete. Some functionalities might not work anymore. Comments are disabled.

A Captcha image (captcha stands for Completely Automated Public Turing test to tell Computers and Humans Apart) is a security trick which prevents bots to spam your blog/forum/whatever.

Here's my implementation of a custom "Captcha" WebControl, written in C#: you can add it to your website project and handle it with a CompareValidator as ControlToCompare (remember to set EnableClientScript to false), just to be sure that you're facing a human being when you get valid posted stuff!

The class can be inherited so that the key behaviors and appearances can be overridden.

Captcha class C# code...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Pacem.Web.UI.WebControls
{
    [DefaultProperty("Code"), ValidationProperty("Code")]
    [ToolboxData("<{0}:Captcha runat=\"server\" />")]
    public class Captcha : System.Web.UI.WebControls.Image
    {
        [Bindable(true)]
        [Category("Data")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Code
        {
            get
            {
                string s = (string)ViewState["Code"];
                return ((s == null) ? string.Empty : s);
            }
            set
            {
                ViewState["Code"] = value;
            }
        }

        [Bindable(true)]
        [Category("Behavior")]
        [DefaultValue(true)]
        public bool AutoGenerateCode
        {
            get
            {
                if (ViewState["AutoGenerateCode"] == null) return true;
                return bool.Parse(ViewState["AutoGenerateCode"].ToString());
            }
            set { ViewState["AutoGenerateCode"] = value; }
        }

        protected override void CreateChildControls()
        {
            if (string.IsNullOrEmpty(Code) && !AutoGenerateCode) throw new Exception("Pacem: Code property must be provided for Captcha webcontrol.");
            if(string.IsNullOrEmpty(Code)) GenerateCode();

            Guid guid = Guid.NewGuid();
            System.IO.MemoryStream bmp = GenerateBitmapStream();
            System.Web.HttpContext.Current.Application.Add(string.Concat(XCWebResource.ChartNamePrefixInApplication,guid.ToString()), bmp);
            base.ImageUrl = string.Format("{1}?id={0}", guid, XCWebResource.HandlerFileName);

            base.CreateChildControls();
        }

        protected virtual void GenerateCode()
        {
            Code = CaptchaHelper.GenerateRandomCode(5);
        }

        protected virtual System.IO.MemoryStream GenerateBitmapStream()
        {
            return CaptchaHelper.CreateCaptchaStream(Code);
        }

        public void RefreshCode()
        {
            Code = string.Empty;
            ChildControlsCreated = false;
        }
    }
}

...and Captcha WebControl as it appears in its simple markup form:

<pacem:Captcha runat="server" ID="Captcha1" />

In order to have it fully functioning, custom HttpModule reference must be added to Web.config:

<httpModules>
    <add name="XCWebResource" 
    type="Pacem.Web.UI.WebControls.XCWebResource, Pacem.Web.UI.WebControls"/>
</httpModules>
zip file « download code

Take care. Bye.

feedback
 

Syndicate

Author

Cristian Merighi facebook twitter google+ youtube

Latest articles

Top rated

Archive

Where am I?

Author

Cristian Merighi facebook twitter google+ youtube

I'm now reading

Feeds