Showing posts with label how to use captcha control in asp.net c#. Show all posts
Showing posts with label how to use captcha control in asp.net c#. Show all posts

Friday, December 25, 2015

Create CAPTCHA in ASP.NET C#

In this article going to explain how to create CAPTCHA in asp.net c#.

Before creating the captcha first we want to know why we using captcha?

Captcha code ids kind of image is used to validate client browser window really has a human typing into it or not Or simply say captcha is only be read by human not by robots.( Robots ia a kind of program that automativally submit the data to the website) and when we want to prevent it we use the captcha.

Now Lets move with creating captcha in asp.net c#

Firstly Create a "GenerateCaptcha.aspx" page

code of GenerateCaptcha.aspx"


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GenerateCaptcha.aspx.cs" Inherits="GenerateCaptcha" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>

code of GenerateCaptcha.aspx.cs"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public partial class GenerateCaptcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        int height = 30;
        int width = 100;
        Bitmap bmp = new Bitmap(width, height);
        RectangleF rectf = new RectangleF(10, 5, 0, 0);
        Graphics g = Graphics.FromImage(bmp);
        g.Clear(Color.White);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawString(Session["captcha"].ToString(), new Font("Segoe UI", 15, FontStyle.Strikeout), Brushes.Red, rectf);
        g.DrawRectangle(new Pen(Color.Bisque), 1, 1, width - 2, height - 2);
        g.Flush();
        Response.ContentType = "image/jpeg";
        bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
        g.Dispose();
        bmp.Dispose();
    }
}

Now Create another Default.aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
       <form id="form1" runat="server">
    <div>
       <asp:Panel ID="pnlCheckCaptcha" runat="server" GroupingText="<b>Check Captcha"></b>&nbsp;<table>
       <tr>
       <td>Write Catcha Here</td>
       <td><asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox></td>
       </tr>
       <tr>
       <td><asp:Image ID="imgCaptcha" runat="server" /></td>
       <td>
        <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
       </td>
       </tr>
       <tr>
       <td colspan="2" align="center"><asp:Button ID="btnchekcatcha" runat="server"
               Text="Check" onclick="btnchekcatcha_Click"/>
               <asp:Label ID="lblmsg" runat="server" ForeColor="Red"></asp:Label>
               </td>
       </tr>
       </table>
       </asp:Panel>
    </div>
    </form>
</body>
</html>

Default.aspx.cs page code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                GetCapctha();
            }
        }
        catch (Exception ex)
        {
            lblmsg.Text = ex.Message.ToString();
        }
    }
    void GetCapctha()
    {
        try
        {
            Random random = new Random();
            string combination = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            StringBuilder captcha = new StringBuilder();
            for (int i = 0; i < 6; i++)
                captcha.Append(combination[random.Next(combination.Length)]);
            Session["captcha"] = captcha.ToString();
            imgCaptcha.ImageUrl = "GenerateCaptcha.aspx?" + DateTime.Now.Ticks.ToString();
        }
        catch
        {
            throw;
        }
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        try
        {
            GetCapctha();
        }
        catch (Exception ex)
        {
            lblmsg.Text = ex.Message.ToString();
        }
    }
   
    protected void btnchekcatcha_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["captcha"].ToString() != txtCaptcha.Text)
                lblmsg.Text = "Invalid Captcha Code";
            else
                lblmsg.Text = "Valid Captcha Code";
            GetCapctha();
        }
        catch (Exception ex)
        {
            lblmsg.Text = ex.Message.ToString();
        }
    }
}

Output