How to create a captcha code in asp.net? - CodingPot | Programming Blog - C#, VB.Net, ASP.Net, MVC, Angularjs Tutorials

Thursday, 19 July 2018

How to create a captcha code in asp.net?

In this Tutorial, we will see “How to create a captcha code in asp.net”. You must have seen that most of all sites have the captcha code in a registration form or another form. Before proceeding this example we should know that “What is Captcha Code?” And “Why we should use Captcha Code?” A Captcha Code Protect your site from Bots. Captcha is abbreviated as “Completely Automated Public Turing test to tell computers and Human Apart”.
How to create a captcha code in asp.net

What Is Captcha Code?

A CAPTCHA is a type of response test used in computing to determine whether or not the user is human.

Why We Should Use Captcha Code?

CAPTCHA is mainly used as a security check to ensure only human users can pass through. Computers or bots are not capable of solving a CAPTCHA.

Let’s go with the example of CAPTCHA Code, in this example, we will set the captcha code on the Registration page. So we should create a Database and registration table in SQL Server. After created Database and table we will create the project so Open visual studio and create a new empty project with an appropriate name. In this example, we will use the entity framework for creating an example. So, first of all, create 2 new folders (captcha, model). In the model folder we will create Entity Data Model and in the captcha folder, we will create web pages for the web application. Right click on model folder and Add New Item and select Data option from left panel and then in the center panel select ADO.NET Entity Data Model and then click on “Add” button then select Model contents of “EF Designer from database” then select the Data Connection and click on Next button then select the Tables, Views, Stored Procedure which you have created in the SQL Database and then click on Finish button.
An Entity Data Model is created, let’s create Registration Web page, Right click on captcha folder and select Add New Item. In the Add New Item Popup Model select the web option from the left panel and then in center panel select the Web Form and give the appropriate name of the page and click on Add button. In the Registration page add the below code for Registration and CAPTCHA code. In this page, we have used Bootstrap CSS file for better User Interface and bootstrap Js file and JQuery file links.

Registration.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Registration.aspx.cs" Inherits="Captcha.captcha.Registration" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <style type="text/css"> body { color: #fff; background: #63738a; font-family: 'Roboto', sans-serif; } .form-control { height: 40px; box-shadow: none; color: #969fa4; } .form-control:focus { border-color: #5cb85c; } .form-control, .btn { border-radius: 3px; } .signup { width: 400px; margin: 0 auto; padding: 30px 0; } .signup h2 { color: #636363; margin: 0 0 15px; position: relative; text-align: center; } .signup h2:before, .signup h2:after { content: ""; height: 2px; width: 30%; background: #d4d4d4; position: absolute; top: 50%; z-index: 2; } .signup h2:before { left: 0; } .signup h2:after { right: 0; } .signup form { color: #999; border-radius: 3px; margin-bottom: 15px; background: #f2f3f7; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); padding: 30px; } .signup .form-group { margin-bottom: 20px; } .signup .btn { font-size: 16px; font-weight: bold; min-width: 140px; outline: none !important; } .signup .row div:first-child { padding-right: 10px; } .signup .row div:last-child { padding-left: 10px; } </style> <title>Captcha Code Example</title> </head> <body> <form id="form1" runat="server"> <div class="signup"> <h2>Register</h2> <div class="form-group"> <asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control" placeholder="First Name"></asp:TextBox> </div> <div class="form-group"> <asp:TextBox ID="txtLastName" runat="server" CssClass="form-control" placeholder="Last Name"></asp:TextBox> </div> <div class="form-group"> <asp:TextBox ID="txtEmail" runat="server" TextMode="Email" CssClass="form-control" placeholder="Email"></asp:TextBox> </div> <div class="form-group"> <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" CssClass="form-control" placeholder="Password"></asp:TextBox> </div> <div class="form-group"> <asp:Image ID="imgCaptcha" runat="server" ImageUrl="CreateCaptcha.aspx?New=1" Height="100" Width="400" /> </div> <div class="form-group"> <asp:TextBox ID="txtCaptcha" runat="server" CssClass="form-control" placeholder="Enter Captcha Code"></asp:TextBox> <asp:Label ID="lblMessage" runat="server"></asp:Label> </div> <div class="form-group"> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" CssClass="btn btn-success btn-lg btn-block" Text="Register Now" /> </div> <div class="form-group"> <asp:Label ID="lblSucess" runat="server"></asp:Label> </div> </div> </form> </body> </html>

You can see in the above code we have used Image control for the generate CAPTCHA code and In the ImageUrl property, we have set “CreateCaptcha.aspx?New=1” because CAPTCHA code Image creates in “CreateCaptcha.aspx” page. So we should to create CreateCaptcha Webpage but in this page, we don’t add any code in the (.aspx) page. In the (.aspx.cs) page we will write the code for generating CAPTCHA code.

CreateCaptcha.aspx.cs


using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Captcha.captcha { public partial class CreateCaptcha : System.Web.UI.Page { string code = string.Empty; protected void Page_Load(object sender, EventArgs e) { CreateCaptchaImage(); } public void CreateCaptchaImage() { Bitmap objBitmap = new Bitmap(130, 80); Graphics objGraphics = Graphics.FromImage(objBitmap); objGraphics.Clear(Color.White); Random objRandom = new Random(); objGraphics.DrawLine(Pens.Black, objRandom.Next(0, 50), objRandom.Next(10, 30), objRandom.Next(0, 200), objRandom.Next(0, 50)); objGraphics.DrawRectangle(Pens.Blue, objRandom.Next(0, 20), objRandom.Next(0, 20), objRandom.Next(50, 80), objRandom.Next(0, 20)); objGraphics.DrawLine(Pens.Blue, objRandom.Next(0, 20), objRandom.Next(10, 50), objRandom.Next(100, 200), objRandom.Next(0, 80)); Brush objBrush = default(Brush); //create background style HatchStyle[] aHatchStyles = new HatchStyle[] { HatchStyle.BackwardDiagonal, HatchStyle.Cross, HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal, HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical, HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross, HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid, HatchStyle.ForwardDiagonal, HatchStyle.Horizontal, HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard, HatchStyle.LargeConfetti, HatchStyle.LargeGrid, HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal }; //create rectangular area RectangleF oRectangleF = new RectangleF(0, 0, 300, 300); objBrush = new HatchBrush(aHatchStyles[objRandom.Next(aHatchStyles.Length - 3)], Color.FromArgb((objRandom.Next(100, 255)), (objRandom.Next(100, 255)), (objRandom.Next(100, 255))), Color.White); objGraphics.FillRectangle(objBrush, oRectangleF); //Generate the image for captcha string captchaText = string.Format("{0:X}", objRandom.Next(1000000, 9999999)); //add the captcha value in session Session["CaptchaCode"] = captchaText; Font objFont = new Font("Courier New", 15, FontStyle.Bold); //Draw the image for captcha objGraphics.DrawString(captchaText, objFont, Brushes.Black, 20, 20); objBitmap.Save(Response.OutputStream, ImageFormat.Gif); } } }
You can see in above code we have created Image CAPTCHA code and then set the Captcha code in the Session. This Session value we will use for a check that user entered code is same as Captcha code or not. Let’s write the registration code in the code behind of Registration Web page.

Registration.aspx.cs


using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Captcha.model; namespace Captcha.captcha { public partial class Registration : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { try { ExampleEntities2 entity = new ExampleEntities2(); if (txtCaptcha.Text == Session["CaptchaCode"].ToString()) { tbl_registration registration = new tbl_registration(); registration.FirstName = txtFirstName.Text; registration.LastName = txtLastName.Text; registration.Email = txtEmail.Text; registration.Password = txtPassword.Text; entity.tbl_registration.Add(registration); entity.SaveChanges(); lblSucess.Text = "Successfully Registered"; } else { lblMessage.Text = "Please enter correct captcha !"; lblMessage.ForeColor = System.Drawing.Color.Red; } } catch (Exception ex) { } } } }
In the code-behind, we have created submit button click event and check user entered code is a match to Session Captcha code. If the Captcha code is matched then go for Registration otherwise showing the error message on the page.


3 comments:

  1. Rana From Haryana10 August 2018 at 06:18

    Bahut Khoob

    ReplyDelete
  2. Nice way but this has possibility to get same number in subsequent requests in Captcha.

    ReplyDelete