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 < 20; 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.
Below is an image of how the application looks like:
