Monday, November 26, 2012

Creating Captcha Code in ASP.Net

Before entering in to the topic first we must know “What is the Captcha code?” and “Why we used it?” Most of the web sites having the Captcha validation to their sites.

What is the Captcha code?
Captcha code is simply a combination of some characters and numbers like ‘Alk13’ or ‘aTu2eP’ etc.

Why we used it?
We used it for validating this code was really typed by the human.


Ok, let’s come to the topic i.e. creating your own Captcha code in ASP.Net.

Step1: Go to the visual studio and create a new project (web site or web application) say “CaptchCode”.

Step2: Now add a new page into your application say “ShowCaptcha.aspx” and add this code into design source of the page.

<div>
<table>
  <tr>
    <td>
      <asp:Image ID="imgCaptcha" runat="server" ImageUrl="~/CreateCaptcha.aspx?New=1"/>
     </td>
   </tr>
   <tr>
    <td>
      <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>
     </td>
    </tr>
    <tr>
     <td>
       <asp:Label ID="lblMessage" runat="server"></asp:Label>
      </td>
     </tr>
     <tr>
      <td>
 <asp:Button ID="btnCaptcha" runat="server" Text="Validate Cpatcha Code" onclick="btnCaptcha_Click" />
       </td>
       </tr>
     </table>
    </div>

Note:- Here I am given the ImageUrl="~/CreateCaptcha.aspx?New=1” of image control. In CreateCaptcha.aspx we will write code for creating Captcha code.

Step3: Now add a new page into your application "CreateCaptcha.aspx" and create the following methods in its .cs file.


/// <summary>
/// method for create captcha image
/// </summary>
 private void CreateCaptchaImage()
{ 
 code = GetRandomText();
 Bitmap bitmap = new Bitmap(200, 60, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
 Graphics g = Graphics.FromImage(bitmap);
 Pen pen = new Pen(Color.Yellow);
 Rectangle rect = new Rectangle(0, 0, 200, 60);
 SolidBrush blue = new SolidBrush(Color.CornflowerBlue);
 SolidBrush black = new SolidBrush(Color.Black);
 int counter = 0;
 g.DrawRectangle(pen, rect);
 g.FillRectangle(blue, rect);

 for (int i = 0; i < code.Length; i++)
 {
    g.DrawString(code[i].ToString(), new Font("Tahoma", 10 + rand.Next(15, 20), FontStyle.Italic), black, new PointF(10 + counter, 10));
   counter += 28;
 }
 DrawRandomLines(g);          
 bitmap.Save(Response.OutputStream, ImageFormat.Gif);
 g.Dispose();
 bitmap.Dispose();

}
/// <summary>
/// Method for drawing lines
/// </summary>
/// <param name="g"></param>
private void DrawRandomLines(Graphics g)
{
   SolidBrush yellow = new SolidBrush(Color.Yellow);
   for (int i = 0; i < 20; i++)
   {g.DrawLines(new Pen(yellow, 1), GetRandomPoints());}

}
/// <summary>
/// method for gettting random point position
/// </summary>
/// <returns></returns>
private Point[] GetRandomPoints()
{
  Point[] points = { new Point(rand.Next(0, 150), rand.Next(1, 150)), new    Point(rand.Next(0, 200), rand.Next(1, 190)) };
  return points;
}
/// <summary>
/// Method for generating random text of 5 cahrecters as captcha code
/// </summary>
/// <returns></returns>
private string GetRandomText()
{
  StringBuilder randomText = new StringBuilder();          
  string alphabets = "012345679ACEFGHKLMNPRSWXZabcdefghijkhlmnopqrstuvwxyz";
  Random r = new Random();
  for (int j = 0; j <= 5; j++)
  {randomText.Append(alphabets[r.Next(alphabets.Length)]);}
    Session["CaptchaCode"] = randomText.ToString();
     return Session["CaptchaCode"] as String;
  }


Step4: Validating Captcha code in “ShowCaptcha.aspx.cs” page.

protected void btnCaptcha_Click(object sender, EventArgs e)
{
   //imgCaptcha.ImageUrl = "~/CreateCaptcha.aspx?New=0";
  if (Session["CaptchaCode"] != null && txtCaptcha.Text == Session["CaptchaCode"].ToString())
  {
     lblMessage.ForeColor = Color.Green;
     lblMessage.Text = "Captcha code validated successfully!!";
  }
  else
  {
   lblMessage.ForeColor = Color.Red;
   lblMessage.Text = "Captcha code is wrong!!";
  }
}



You can download the source code from here DownLoad. 
I hope this article will be helpful for you.
Happy Coding!!

No comments:

Post a Comment

^ Scroll to Top