How to create an Ajax Captcha Control with less than 50 lines of code

Modified: 2008/10/06 17:32 by stians - Uncategorized
According to WikiPedia the meaning of the word Captcha is Completely Automated Public Turing test to tell Computers and Humans Apart! And it's basic purpose is as its name suggests to be able to check automatically if your users are Humans or Computers!

They're often used in association with comments on blogs, user signup forms or forum submit new post systems etc. Basically any place you'd like to avoid automated systems get to play with your own system. In most cases they're basically used as spam protection

In this example I've basically just added a DynamicImage which in the RetrieveImage Event returns an image containing some random letters which are set in the Page_Load by using our Session Object. Then when the user is supposed to submit the data where we should check if he's human or not we can compare the Session random text value against the Text property of some TextBox object contained on the same page.

For clarity I've removed everything that doesn't have anything to do directly with creating the Captcha.

Note also that like most things you can do in Gaia there's not one single line of "custom" JavaScript here! Everything is done in C# or declaratively in the .ASPX file!

Edit

ASPX Markup



Edit

C# Codebehind

protected void dynImg_RetrieveImage(object sender, RetrieveImageEventArgs e) { e.Image = new Bitmap(350, 50); Graphics g = Graphics.FromImage(e.Image);

// Background color g.FillRectangle( new SolidBrush(Color.Salmon), 0, 0, e.Image.Width, e.Image.Height);

// Text string imgText = Session"imgText" as string; g.DrawString( imgText, new Font(FontFamily.GenericSansSerif, 12F, FontStyle.Bold), new SolidBrush(Color.Black), 10, 12); }



And Voila! A finisihed captcha control ready for use in your applications.

ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.