Saturday 18 April 2015

Captcha Using ASP.Net

There is much technical logic to make captcha I am not expert and deep technical but I have tricks that make me able to make captcha. My logic is simple; Make some static image with alphanumeric character. You can change the text shape using photoshop. After creating image add image text into database with an id, generate random number and match it with database id field then fetch image text value and matched its value form user value provide by text box. Following images and code are example of my logic. Enjoy it !

    








  • Make three static image content number as in figure
  • Make entry in database to each figure number as in database snap shot
  • Add global asax file following is code of asax file which you have to change. This has many built in function for various action Session_Start function is one of them which is used to maintain session.

void Session_Start(object sender, EventArgs e) 
    {
        Session["Captcha_id"] = 0;

    }
Page code
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page 
{
   
    Random rnd = new Random(); 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["id"] = rnd.Next(1, 4);
            switch (int.Parse(Session["id"].ToString()))
            {
                case 1:
                    Image1.ImageUrl = "~/captcha/c1.jpg";
                    break;
                case 2:
                    Image1.ImageUrl = "~/captcha/c2.jpg";
                    break;
                case 3:
                    Image1.ImageUrl = "~/captcha/c3.jpg";
                    break;

            }
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if(TextBox1.Text==string.Empty)
        {
            Label1.Text="Please provide captcha code";
        }
        else
        {
        SqlConnection con=new SqlConnection(@"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=work;Integrated Security=True");
        SqlCommand com = new SqlCommand();
            try
            {
                com.Connection = con;
                con.Open();
                com.CommandText = "select value from captcha where id=" + Session["id"];
                if (com.ExecuteScalar().ToString() == TextBox1.Text)
                {
                    Response.Redirect("Default2.aspx");
                }
                else
                {
                    Label1.Text = "Invalid Captcha Code";
                }
            }
            catch(Exception ex)
            {
                Label1.Text=ex.Message;
            }
        }
    }
}


No comments:

Post a Comment