Skip to main content

How to create simple mathmatical captcha in ASP.Net C#.Net and VB.Net

In this tutorial i am going to explain about how to create simple mathmatical captcha in asp.net c#.net and vb.net. The basic idea is generating two numbers using random function and storing the addition of that two numbers in the session and also converting the numbers into image using the available libraries. On the target page where the captcha is implemented we will have the textbox to get the input from the user and check the textbox value is equal to the session value. It it is equal then we consider the user is a human else it is a robot.

In my previous article i have explained about Visual Studio Keyboard Shortcuts , How To get data from WEB API , How To Create Your First WEB API Project, Check Container Exists In Azure Blob , Convert Datatable To Json Data Array , How To Show Tooltip On Mouse Hover In Gridview and many articles in C#.Net,VB.Net,Grid View,Javascript,jQuery,SQL Server and many other topics.


Here to explain the process i have created an empty website. Then do the right click on the website and click Add then Add New Item as shown in the figure.

Then select WebForm Template and then name the form as Captcha.aspx as shown in the figure.

Leave the aspx file. We no need to do anything in that file.In the code behind file include the necessary namespaces. The entire code is given below.

C#.Net:

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

public partial class Capcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Defining brush color
        Color brushColor = System.Drawing.Color.Green;

        // Creating object for bitmap
        Bitmap objBitmap = new System.Drawing.Bitmap(100, 30);

        // Creating object for Graphics class
        Graphics objGraphics = System.Drawing.Graphics.FromImage(objBitmap);
        objGraphics.Clear(Color.Transparent);

        // Creating object for Font class
        Font objFont = new Font("Times New Roman", 14, FontStyle.Regular);

        string inputNumberString = "";

        Random r = new Random();

        int a = r.Next(99, 999);
        int b = r.Next(99, 999);

        int c = a + b;

        inputNumberString = a.ToString() + " + " + b.ToString() + " = ";

        //Storing the captcha value in the session
        Session["CaptchaValue"] = c.ToString();

        SolidBrush myBrush = new SolidBrush(brushColor);

        objGraphics.DrawString(inputNumberString, objFont, myBrush, 3, 3);

        //Adding the content type
        Response.ContentType = "image/png";

        System.IO.MemoryStream mem = new MemoryStream();

        //Saving the bitmap image
        objBitmap.Save(mem, ImageFormat.Png);

        //Writing the image to output screen
        mem.WriteTo(Response.OutputStream);

        // Disposing Font Object
        objFont.Dispose();

        // Disposing Graphics Object
        objGraphics.Dispose();

        // Disposing Bitmap Object
        objBitmap.Dispose();
    }
}

VB.Net:

Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Text
Imports System.IO

Partial Public Class Capcha
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        'Defining brush color
        Dim brushColor As Color = System.Drawing.Color.Green

        ' Creating object for bitmap
        Dim objBitmap As Bitmap = New System.Drawing.Bitmap(100, 30)

        ' Creating object for Graphics class
        Dim objGraphics As Graphics = System.Drawing.Graphics.FromImage(objBitmap)
        objGraphics.Clear(Color.Transparent)

        ' Creating object for Font class
        Dim objFont As New Font("Times New Roman", 14, FontStyle.Regular)

        Dim inputNumberString As String = ""

        Dim r As New Random()

        Dim a As Integer = r.[Next](99, 999)
        Dim b As Integer = r.[Next](99, 999)

        Dim c As Integer = a + b

        inputNumberString = a.ToString() + " + " + b.ToString() + " = "

        'Storing the captcha value in the session
        Session("CaptchaValue") = c.ToString()

        Dim myBrush As New SolidBrush(brushColor)

        objGraphics.DrawString(inputNumberString, objFont, myBrush, 3, 3)

        'Adding the content type
        Response.ContentType = "image/png"

        Dim mem As System.IO.MemoryStream = New MemoryStream()

        'Saving the bitmap image
        objBitmap.Save(mem, ImageFormat.Png)

        'Writing the image to output screen
        mem.WriteTo(Response.OutputStream)

        ' Disposing Font Object
        objFont.Dispose()

        ' Disposing Graphics Object
        objGraphics.Dispose()

        ' Disposing Bitmap Object
        objBitmap.Dispose()
    End Sub
End Class

Now to test the captcha works correct or not i have added one more aspx file called demo.aspx in the project. In the aspx page i have a image control whose href attribute call the captcha.aspx. And i have a textbox control to get the user input and a button to validate user input with the session value. And i have a Label to display the status message. While clicking on the submit button the code will check whether the entered value and the session value are equal. If yes then it will return the status as human else as Robot. Below is the aspx code

HTML Markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Demo.aspx.cs" Inherits="Demo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

    <form id="form2" runat="server">
        <table>
            <tr>
                <td colspan="2">What is the result of below calculation?</td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ForeColor="Red" runat="server" ID="lblStatus"></asp:Label></td>
            </tr>
            <tr>
                <td>
                    <img src="Captcha.aspx" /></td>
                <td>
                    <asp:TextBox runat="server" ID="txtCaptcha"></asp:TextBox></td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" /></td>
            </tr>
        </table>
    </form>

</body>
</html>


Below is the code behind file code.

C#.Net

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

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

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string result = txtCaptcha.Text;
        if (result == Session["CaptchaValue"].ToString())
        {
            lblStatus.Text = "Correct.. You are a human..!";
        }
        else
        {
            lblStatus.Text = "InCorrect.. You are not a human..!";
        }
        txtCaptcha.Text = "";
    }
}

VB.Net

Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class Demo
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)

    End Sub
    Protected Sub btnSubmit_Click(sender As Object, e As EventArgs)
        Dim result As String = txtCaptcha.Text
        If result = Session("CaptchaValue").ToString() Then
            lblStatus.Text = "Correct.. You are a human..!"
        Else
            lblStatus.Text = "InCorrect.. You are not a human..!"
        End If
        txtCaptcha.Text = ""
    End Sub
End Class

The output will look like below..
Output of How to create simple mathmatical captcha in ASP.Net C#.Net and VB.Net
Download Sourcecode:
Sourcecode of  How to create simple mathmatical captcha in ASP.Net C#.Net and VB.Net
If you like this article then share with your friends and comment your valuable feedback.. Happy coding..

Comments

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     {         sb.Append( "Minus " );         inputNo = -inputNo;     }     string [] words0 = { "" , "One " ,

C# code to send mail using smtp from gmail,yahoo mail and live mail

Introduction: In my previous article I have explained about   How to bind/Unbind events in jQuery . In this article I am going to explain about how to send mail from ASP.Net using gmail,yahoomail and live mail credentials. Explanation: First Include the below namespaces in your code behind file. using System; using System.Net; using System.Net.Mail;

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw