top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to generate CAPTCHA in C#?

0 votes
293 views
How to generate CAPTCHA in C#?
posted Feb 29, 2016 by Jayshree

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

In most of the websites when you register yourself, you need to enter a code to verify that you are a human not a bot. CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is the best approach to restrict an automatic submission of a form. Normally, we create an image dynamically with different random combinations of letters and numbers. User needs to enter this random generated code in a text box and we then check whether user has entered the right code or not by comparing both.

There are dozens of code samples available to generate CAPTCHA in C# but I will provide you the simple logic to generate CAPTCHA code for human confirmation. This simple technique will help developers to generate a CAPTCHA code in a better way. With this code sample you can create your own CAPTCHA image. It contains an ASP.NET page “GenerateCaptcha.aspx” which contains the code of CAPTCHA image. Another page “Default.aspx” has all other code to for user interaction. You can also download the entire sample code from above link.

1.Create a new website in Visual Studio and add two files in it.

Defaul.aspx
GenerateCaptcha.aspx

2.Add following namespaces and write code below in Page Load event of GenerateCaptcha.aspx.cs file.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

Response.Clear();
int height = 35;
int width = 80;
Bitmap objBmp = new Bitmap(width, height);
RectangleF rectf = new RectangleF(10, 5, 0, 0);
Graphics objGraphics = Graphics.FromImage(objBmp);
objGraphics.Clear(Color.White);
objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
objGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
objGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
objGraphics.DrawString(Session["CaptchaCode"].ToString(), new Font("Chiller", 18, FontStyle.Italic), Brushes.Blue, rectf);
objGraphics.DrawRectangle(new Pen(Color.Green), 1, 1, width - 2, height - 2);
objGraphics.Flush();
Response.ContentType = "image/jpeg";
objBmp.Save(Response.OutputStream, ImageFormat.Jpeg);
objGraphics.Dispose();
objBmp.Dispose();

3.Now add code below in Default.aspx page

<asp:ScriptManager ID="ScriptManager1" runat="server">asp:ScriptManager>
<table>
    <tr>
        <td valign="middle">
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <table>
                        <tr>
                            <td style="height: 50px; width:100px;">
                                 <asp:Image ID="imgCaptchaCode" runat="server" />
                            </td>
                            <td valign="middle">
                                <asp:Button ID="btnRefreshCode" runat="server" Text="Refresh Code" onclick="btnRefreshCode_Click" />
                            </td>
                        </tr>
                    </table>
                </ContentTemplate>
            </asp:UpdatePanel>
        </td>
    </tr>
    <tr>
        <td>Enter above code:
            <asp:TextBox ID="txtCaptchaCode" runat="server" Width="100px"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnOk" runat="server" Text="OK" onclick="btnOk_Click" Width="98px" />
        </td>
    </tr>
</table>

4.Write following code in Default.aspx.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

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

    void FillCapcthaCode()
    {
        try
        {
            Random objRandom = new Random();
            string combination = "**********abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            StringBuilder captchaCode = new StringBuilder();

            for (int i = 0; i < 5; i++)
            {
                captchaCode.Append(combination[objRandom.Next(combination.Length)]);
            }

            Session["CaptchaCode"] = captchaCode.ToString();
            imgCaptchaCode.ImageUrl = "GenerateCaptcha.aspx?" + DateTime.Now.Ticks.ToString();

        }
        catch(Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

    protected void btnRefreshCode_Click(object sender, EventArgs e)
    {
        FillCapcthaCode();
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        if (Session["CaptchaCode"].ToString() != txtCaptchaCode.Text)
        {
            Response.Write("Please write valid Code");
        }
        else
        {
            Response.Write("You have entered valid code");
        }
        txtCaptchaCode.Text = string.Empty;
        FillCapcthaCode();
    }
 }

5.Press F5 and see the result

answer Feb 29, 2016 by Shivaranjini
...