Friday, May 21, 2010

Captcha with asp.net using LINQ and Jquery

Hi, we all need to display captcha when ever we fill form.
So you can get thousands of captcha example when you search.
But the one i am providing you is interested and easy to implement.

First of all we need to create Http Handler(generic handler) below :

using System;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Web.SessionState;

namespace YourNamespace
{
public class Captcha : IHttpHandler,IRequiresSessionState
{
#region "ProcessRequest"

public void ProcessRequest(HttpContext context)
{
HttpContext.Current.Response.ContentType = "image/png";
var no = RandomText.GenerateRandomText(3);
//if (context.Session["Captcha"] == null) return;
HttpContext.Current.Session["Captcha"] = no;
//var bmpOut = new Bitmap(200, 50);
var bmpOut = new Bitmap(60, 25);
var g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, 60, 23);
g.DrawString(HttpContext.Current.Session["Captcha"].ToString(), new Font("Verdana", 18), new SolidBrush(Color.Gray), 0, 0);
var ms = new MemoryStream();
bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
var bmpBytes = ms.GetBuffer();
bmpOut.Dispose();
ms.Close();
context.Response.BinaryWrite(bmpBytes);
context.Response.End();
}
#endregion

#region "Properties"
public bool IsReusable
{
get
{
return true;
}
}
#endregion
}

public static class RandomText
{
#region "GenerateRandomText"

public static string GenerateRandomText(int textLength)
{

const string chars = "ABCDEFGHIJKLMNPQRSTUVWXYZ23456789";
var random = new Random();
var result = new string(
Enumerable.Repeat(chars, textLength)
.Select(s => s[random.Next(s.Length)])
.ToArray());
return result;
}
#endregion
}
}

Alert creating http handler now we need to create the .aspx part
where we will generate this image :

<!-- This part will placed in .aspx -->
<div class="float_left">
<img src="/Captcha.ashx?" id="img1" alt="" />
</div>
<div class="float_left paddingtop3">
 <a href="javascript:void(0);" class="message" id="newchapta">(Can’t see the image?)</a> 
</div>
Now in the same page, to change change content or re-generate image again on hyper link click,add the following code :

<script type="text/javascript">
// with this method this captcha gets chaned on client side ! have fun
$(function(e) {
$("#newchapta").click(function(e) {
var imgNew = $("#imgCode");
d = new Date();
imgNew.attr("src", 'Captcha.ashx?' + d.getTime());
});
});
</script>

Now on the server side we can match input entered by user like following code snippet :
<!-- For code behind here you can check text value entered by user where captcha.Text is the text box value -->
if (HttpContext.Session["Captcha"] != null)
{
if (HttpContext.Session["Captcha"].ToString().ToLower() != captcha.Text.ToLower())
{
error = "The digits you entered do not match the digits in the image.";
}
}

<!-- Till here -->

No comments:

Post a Comment