Monday, July 19, 2010

CAPTCHA generation in asp.net c#

CAPTCHA stands for "completely automated public Turing test to tell computers and humans apart." What it means is, a program that can tell humans from machines using some type of generated test. A test most people can easily pass but a computer program cannot. Mainly intended to reduce spam on our websites.





Captcha generation here descibed below contain the following sections


1) A handler file (ashx) to produce captcha

2)Validation of captcha.



Handler file Look like this.


captcha.ashx..................................................................


<%@ WebHandler Language="C#" Class="captcha" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;


public class captcha : IHttpHandler {
 
    public void ProcessRequest (HttpContext context) {

        string text = context.Request["captcha"].ToString();
        Bitmap bmpimg = new Bitmap(100, 50);
        Graphics g = Graphics.FromImage(bmpimg);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.FillRectangle(Brushes.Black, 0, 0, 100, 10);
        g.DrawString(text, new Font("Verdana", 18), new SolidBrush(Color.White), 0, 0);
        MemoryStream ms = new MemoryStream();
        bmpimg.Save(ms, ImageFormat.Jpeg);
        byte[] data = ms.GetBuffer();
        bmpimg.Dispose();
        ms.Close();
        context.Response.BinaryWrite(data);
        context.Response.Flush();
        context.Response.End();
    
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}



Next the aspx page ...

     
       













and Finally the CS page


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.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
   static string rndstrig;
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            generate();
        }
    }

    private void generate()
    {
        Random rnd = new Random();
        rndstrig = rnd.Next(1000, 9999).ToString();
        imgcapthca.ImageUrl = "~/captcha.ashx?captcha=" + rndstrig;
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
    
    }
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (txtcaptchacheck.Text == rndstrig)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
        generate();
    }
}

the O/p will be like this

No comments:

Post a Comment