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

By
Advertisement
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..

0 comments:

Post a Comment

Online Casino