Skip to main content

Creating the CAPTCHA Functionality

Introduction:

According to wikipedia, CAPTCHA ("Completely Automated Public Turing test to tell Computers and Humans Apart") is a challenge response test which is used to check that if the user is human or not. CAPTCHA is used exclusively in applications where the user input is required. These applications include Blogs, Forums and Portals. In this article I will demonstrate how to create a simple webpage that uses CAPTCHA functionality.

The CreateImage Method:

The first task is to create an image and put it on the screen. For that I have created an ASP.NET page named CaptchaControl.aspx. The CaptchaControl.aspx page will be responsible for displaying the image to the user. Let’s take a look at the following code which generates the image.

private void CreateImage()

{

string code = GetRandomText();

Bitmap bitmap = new Bitmap(200,150,System.Drawing.Imaging.PixelFormat.Format32bppArgb);

Graphics g = Graphics.FromImage(bitmap);

Pen pen = new Pen(Color.Yellow);

Rectangle rect = new Rectangle(0,0,200,150);

SolidBrush b = new SolidBrush(Color.DarkKhaki);

SolidBrush blue = new SolidBrush(Color.Blue);

int counter = 0;

g.DrawRectangle(pen, rect);

g.FillRectangle(b, rect);

for (int i = 0; i <>

{

g.DrawString(code[i].ToString(), new Font("Verdena", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));

counter += 20;

}

DrawRandomLines(g);

Response.ContentType = "image/gif";

bitmap.Save(Response.OutputStream,ImageFormat.Gif);

g.Dispose();

bitmap.Dispose();

}

There is a bunch of stuff going on inside the CreateImage method. The GetRandomText method generates the random text and returns to the caller. If you are unfamiliar with creating random strings then I would suggest that you check out my article Creating Random Password. After I created the Rectangle where the text would appear I resized the text to give it a strange look. Finally, I called the DrawRandomLines method which protects the image from OCR softwares.

The GetRandomText Method:

The purpose of the GetRandomText method is to generate a random text every time a user gets the old text wrong. Take a look at the simple method which returns the random text.

private string GetRandomText()

{

StringBuilder randomText = new StringBuilder();

if (Session["Code"] == null)

{

string alphabets = "abcdefghijklmnopqrstuvwxyz";

Random r = new Random();

for (int j = 0; j <= 5; j++)

{

randomText.Append(alphabets[r.Next(alphabets.Length)]);

}

Session["Code"] = randomText.ToString();

}

return Session["Code"] as String;

}

The DrawRandomLines Method:

The DrawRandomLines method puts the lines on the text which, are displayed on an image. The purpose of these lines is to make it difficult for the bots to read the text. This way the text can only be read by humans.

private void DrawRandomLines(Graphics g)

{

SolidBrush green = new SolidBrush(Color.Green);

for (int i = 0; i <>

{

g.DrawLines(new Pen(green, 2), GetRandomPoints());

}

}

private Point[] GetRandomPoints()

{

Point[] points = { new Point(rand.Next(10, 150), rand.Next(10, 150)), new Point(rand.Next(10, 100), rand.Next(10, 100)) };

return points;

}

Using the CAPTCHA Page:

We have created the CAPTCHA feature but the question is how do we use it. In order to use the CAPTCHA feature you will need to create a page which consumes the CaptchaControl.aspx page. I have created the Default.aspx page which uses the CaptchaControl.aspx as the ImageUrl to the ASP.NET image control. Check out the complete HTML code of the Default.aspx page.

<form id="form1" runat="server">

<div>

<asp:Image ID="myImage" runat="server" ImageUrl="~/CaptchaControl.aspx" />

<br />

<br />

Enter code: <asp:TextBox ID="TextBox1" runat="server">asp:TextBox>

<asp:Button ID="Button1" runat="server" Text="Validate" OnClick="Button1_Click" />

<br />

<br />

<asp:Label ID="lblError" runat="server" Font-Bold="True" Font-Size="X-Large" ForeColor="Red">asp:Label>div>

form>

The important thing to note is the ASP.NET image control which, requests the CaptchaControl.aspx

page and generates the image. The code for the validation of the user text against the CAPTCHA text is pretty simple and you can view it in the downloaded files.


Comments

Popular posts from this blog

World Environment Day

This entry is in response to the Conserve, Recycle and Discover contest organised by blogadda.com in association with Pringoo ! World Environment Day, commemorated on 5 June since 1972, is one of the ways focuses world attention on the environment and encourages political action. People from countries all over the world have mobilized for individual and organized environmental action. Activities involve all sectors of society, governments, non- and inter-governmental organizations, businesses, industries, civil society, media and schools. Please take the following Pledge to save our environment. 1, I pledge to Recycle more, use less water and electricity. 2, I pledge to smoke less in 2010. 3, I pledge to send more electronic documents instead of using paper. 4, I pledge to continue using my bicycle to go to work (instead of my motorbike). 5, wash with full loads it is more energy efficient than doing several smaller ones. 6, Incite of dryer I will use hang dry for energy sav...

GridView Alphabet Paging

Introduction: GridView paging feature allow us to display fixed number of records on the page and browse to the next page of records. Although paging is a great feature but sometimes we need to view all the items alphabetically. The idea behind this article is to provide a user with a list of all the alphabets and when the user clicks on a certain alphabet then all the records starting with that alphabet will be populated in the GridView control. Populating the GridView Control: The first task is to populate the GridView control. I will be using the Northwind database in my article which, is installed by default for SQL SERVER 2000 and SQL SERVER 7 databases. The code below is used to populate the GridView control. private void BindData() { string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true"; SqlConnection myConnection = new SqlConnection(connectionString); SqlDataAdapter ad = new SqlDataAdapter("SELECT P...

TED

TED is a nonprofit devoted to Ideas Worth Spreading. It began in 1984 as an annual conference devoted to Technology, Entertainment and Design -- hence TED -- but TED's reach, and its scope, have become ever broader since then. TEDTalks cover science, arts, politics, global issues, architecture, music and more. Speakers come from a wide variety of communities and disciplines -- people like Bill Clinton, Nobel laureate Murray Gell-Mann, Wikipedia co-founder Jimmy Wales, and Google co-founders Sergey Brin and Larry Page. The TED Conference itself takes place in Long Beach each spring, with a simulcast event in Palm Springs. In 2009, we'll also host a summer conference in Oxford, UK, called TEDGlobal, as well as a conference in fall 2009 called TEDIndia, in Mysore, India. Anyone can apply to attend a TED Conference! If you want to come, apply for an invitation. More info here: http://www.ted.com/conferences