Thursday, 15 May 2014

How to Create Captcha with Refresh Button in C# ASP.NET

In this article, i am going to give completely idea about how to create captcha image with refresh button.Firstly, we have to create two pages one for creating captcha image and another one for creating randomly generated text inside captcha image.
CreateCaptcha.aspx
<!DOCTYPE html>

<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>
CreateCaptcha.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Web.UI.WebControls;

public partial class CreateCaptcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DrawCaptcha();
    }

    void DrawCaptcha()
    {
        // Set the page's content type to JPEG files and clears all content output from the buffer stream
        Response.Clear();
        Response.ContentType = "image/jpeg";

        // Create integer variables
        int height = 40;
        int width = 100;

        // Create a bitmap and use it to create a Graphics object
        Bitmap bmp = new Bitmap(width, height);
        Graphics g = Graphics.FromImage(bmp);

        // Set text positon inside rectangle
        Rectangle rect = new Rectangle(6, 8, 0, 0);
        g.Clear(Color.White);

        // Set graphic properties to produce high quality output
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

        g.DrawString(Session["captcha"].ToString(), new Font("Thaoma", 15, FontStyle.Bold), Brushes.Green, rect);
        g.DrawRectangle(new Pen(Color.Purple), 2, 2, width - 5, height - 5);
        g.Flush();

        // Save the bitmap to the response stream and convert it to JPEG format
        bmp.Save(Response.OutputStream, ImageFormat.Jpeg);

        // Release memory used by the Graphics object and the bitmap
        g.Dispose();
        bmp.Dispose();
    }
}
Now Create Signup Page in which captcha would be shown

Signup.aspx
<form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
            <table style="border: solid 1px black; padding: 20px; position: relative; top: 50px;"
                align="center">
                <tr>
                    <td>Name :
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Email ID :
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmailID" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Password :
                    </td>
                    <td>
                        <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Confirm Password :
                    </td>
                    <td>
                        <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Enter Below Code :
                    </td>
                    <td>
                        <asp:TextBox ID="txtCaptcha" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td valign="middle">
                        <asp:UpdatePanel ID="UP1" runat="server">
                            <ContentTemplate>
                                <table>
                                    <tr>
                                        <td style="height: 50px; width: 100px;">
                                            <asp:Image ID="imgCaptcha" runat="server" />
                                        </td>
                                        <td valign="middle">
                                            <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
                                        </td>
                                    </tr>
                                </table>
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Button ID="btnRegiser" runat="server" Text="Register" OnClick="btnRegister_Click" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
Signup.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

public partial class Signup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CreateCapctha();
        }
    }

    // fucntion to create new captcha of 6 digits
    void CreateCapctha()
    {
        try
        {
            Random random = new Random();
            string letterCombination = "01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // combination of letters from which captcha will be made
            StringBuilder captcha = new StringBuilder();
            for (int i = 0; i < 6; i++)
            {
                captcha.Append(letterCombination[random.Next(letterCombination.Length)]);
            }

            Session["captcha"] = captcha.ToString();
            imgCaptcha.ImageUrl = "CreateCaptcha.aspx";
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

    // create new captcha by just calling the specified funtion
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        CreateCapctha();
    }

    // validate captcha against user entered text, if not match it creates another one
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        if (Session["captcha"].ToString() != txtCaptcha.Text)
        {
            Response.Write("Captcha Code is Invalid");
            CreateCapctha();
        }

        else
        {
            // Do Some Stuff Here...
        }
    }
}

That’s it!!…..Happy Programming...

No comments:

Post a Comment