Monday, 20 July 2020

Captcha Generator in Asp.net WebForms


Step1: Open the project in Asp.Net Web Application & named it      CaptchaGenerator

Step2: Select “Empty” with “WebForm” keep other options unchecked

Step3: Right Click on “CaptchaGenerator” & select  ‘Add’ to add webforms, name it as “Login.aspx” , “Home.aspx” and “Captchaimage.aspx”



Step4: Add “Images” folder & store refresh.jpg image in it

Step5: Add following code inside <div> in   Login.aspx


<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <table style="border:3px solid blue;margin-left:auto;margin-right:auto;">
                <caption>Login Form</caption>
                <tr>
<td>User Name :</td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Width="150"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Password&nbsp;&nbsp; :</td>
                    <td>
                        <asp:TextBox ID="txtPwd" runat="server" TextMode="Password" Width="150"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Captcha&nbsp;&nbsp;&nbsp; :</td>
                    <td>
                        <asp:UpdatePanel ID="updatePanel1" runat="server">
                            <ContentTemplate>
                                <asp:Image ID="imgCaptcha" runat="server" BorderStyle="Solid" Width="100" Height="30" />
                        <asp:ImageButton ID="btnRefresh" runat="server" ImageUrl="~/Images/refresh.jpg" Height="30px" Width="30px" OnClick="btnRefresh_Click" />
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </td>
                </tr>
                <tr>
                    <td>Enter Captcha :</td>
                    <td>
                        <asp:TextBox ID="txtCaptcha" runat="server" Width="150" AutoCompleteType="Disabled"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="align-content:center">
                        <asp:Button ID="btnCaptchaLogin" runat="server" Text="Login with Captcha" Width="123px" OnClick="btnCaptchaLogin_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="align-content:center">
                        <asp:Label ID="lblStatus" runat="server" ForeColor="Red" Text="Messages"></asp:Label>
                    </td>
                </tr>
            </table>


Step6: Right click on Login.aspx & goto ViewCode and write following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CaptchaGenrator
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                GenerateCaptcha();
        }
        private void GenerateCaptcha()
        {
            string values = "0123456789abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            StringBuilder strCaptcha = new StringBuilder();
            Random random = new Random();
            for(int i=0;i<=6;i++)
            {
                int randomValue = random.Next(values.Length);
                strCaptcha.Append(values[randomValue]);
            }
            Session["Captcha"] = strCaptcha.ToString();
            imgCaptcha.ImageUrl = "~/Captchaimage.aspx?" + DateTime.Now.Ticks;
        }

        protected void btnRefresh_Click(object sender, ImageClickEventArgs e)
        {
            GenerateCaptcha();
        }

        protected void btnCaptchaLogin_Click(object sender, EventArgs e)
        {
            if(Session["Captcha"].ToString() != txtCaptcha.Text)
            {
                lblStatus.Text = "Wrong Captcha, Please try again";
                txtCaptcha.Text = "";
                GenerateCaptcha();
            }
            else
            {
                if(txtName.Text == "Pankaj" && txtPwd.Text == "12345")
                {
                    Response.Redirect("Home.aspx");
                }
                else
                    lblStatus.Text = "Invalid Username $ Password,Please try again";
                GenerateCaptcha();
            }
        }
    }
}

Step7: Right click on Captchaimage.aspx & goto ViewCode and write following code
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CaptchaGenrator
{
    public partial class Captchaimage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
            int Width =100 , Height = 30;
            Bitmap bmp = new Bitmap(Width, Height);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            Rectangle rect = new Rectangle(1, 1, Width - 2, Height - 2);
            g.DrawRectangle(new Pen(Color.Red), rect);
            g.FillRectangle(new SolidBrush(Color.Bisque), rect);
            g.DrawString(Session["Captcha"].ToString(), new Font("ArialBlack",12, FontStyle.Italic), Brushes.Black, 10, 5);
            g.DrawBezier(new Pen(Color.Yellow), new Point(0, 5), new Point(10, 10), new Point(10, 20), new Point(100, 5));
            Response.ContentType = "image/jpeg";
            bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
        }
    }
}
Step8: Goto Home.aspx & write following code in <div>

<h1 style="text-align:center; background-color:burlywood;color:white;border:double">Welcome To Home Page</h1>

Step9: Run Login.aspx enter the proper Username , Password & Captcha
Click on ‘Login With Captcha’ button ,login page will redirect to Home page. 

PostedBy: pankaj_bhakre