Thursday, September 24, 2015

A Simple CAPTCHA Image Verification in C# and ASP.Net

Captcha.ashx
<%@ WebHandler Language="C#" Class="Captcha" %>
using System;
using System.Web;
using System.Drawing;
using System.IO;
using System.Web.SessionState;

public class Captcha : IHttpHandler, IReadOnlySessionState
{
   
    public void ProcessRequest (HttpContext context) {
        Bitmap bmpOut = new Bitmap(200, 50);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.FillRectangle(Brushes.Black, 0, 0, 200, 50);
        g.DrawString(context.Session["Captcha"].ToString(), new Font("Verdana", 18), new SolidBrush(Color.White), 0, 0);
        MemoryStream ms = new MemoryStream();
        bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        byte[] bmpBytes = ms.GetBuffer();
        bmpOut.Dispose();
        ms.Close();
        context.Response.BinaryWrite(bmpBytes);
        context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}
Read my previous code snippet that explains how to generate image from a string using C# and ASP.NET. The above HttpHandler uses the same code discussed in the code snippet. Rendering the contents as an image will prevent the automatic software programs from reading its contents.

How to use it in our ASPX page?

It is very simple. Include an ASPX page (Default.aspx in our example). Drag an Image control and textbox control to enter the displayed code. With the help of custom validator control, we can validate the user input with Session variable content. Refer the below code that has the ASPX markup.

Default.aspx
<div>
      <asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txtVerify"
            ErrorMessage="You have Entered a Wrong Verification Code!Please Re-enter!!!" OnServerValidate="CAPTCHAValidate"></asp:CustomValidator>      
     <asp:Image ID="imCaptcha" ImageUrl="~/CAPTCHA/Captcha.ashx" runat="server" />
        <asp:TextBox ID="txtVerify" runat="server"></asp:TextBox>
        <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" /></div>

Default.aspx.cs
public partial class CAPTCHA_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //ImageVerification
        if (!IsPostBack)
        {
            SetVerificationText();          
        }
    }
    public void SetVerificationText()
    {
        Random ran = new Random();
        int no = ran.Next();
        Session["Captcha"] = no.ToString();
    }
    protected void CAPTCHAValidate(object source, ServerValidateEventArgs args)
    {
        if (Session["Captcha"] != null)
        {
            if (txtVerify.Text != Session["Captcha"].ToString())
            {               
                SetVerificationText();
                args.IsValid = false;
                return;
            }
        }
        else
        {          
            SetVerificationText();
            args.IsValid = false;
            return;
        }
     
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }
            //Save the content
        Response.Write("You are not a SPAMMER!!!");
        SetVerificationText();
    }
}

The above code initializes the Session variable (Session["Captcha"]) with a random number which is then rendered as a image by the HttpHandler on execution of the page.

Block or Disable Cut, Copy and Paste operation in ASP.Net TextBox Using jQuery

<script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>    
    <script type="text/javascript">
        $(function() {
        $("#<% =txtEmail.ClientID %>,#<% =txtConfirmEmail.ClientID%>").bind("cut copy paste", function(event) {
                event.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>    
        <b>Email </b><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
        <b>Confirm Email </b><asp:TextBox ID="txtConfirmEmail" runat="server"></asp:TextBox>

Read a Text File in C# and ASP.Net

string root = Server.MapPath("~");
string Template = root +"\\filetext.txt";
StringBuilder line = new StringBuilder();
using (StreamReader rwOpenTemplate = new StreamReader(Template))
{
while (!rwOpenTemplate.EndOfStream)
{
line.Append(rwOpenTemplate.ReadToEnd());
}
}

SQL Server Joins With Examples

Types of Joins
  1. Inner Join
  2. Outer Join
    • Left outer Join
    • Right outer Join
    • Full outer Join
  3. Cross Join
  4. Equi Join
  5. Self Join

CREATE TABLE EmployeeDetails (
  EmpId int PRIMARY KEY,
  EmpFirstName varchar(50),
  EmpLastName varchar(50),
  Department varchar(50),
  DepartID int
)

CREATE TABLE EmpSalary (
  EmpID int,
  EmpFullName varchar(80),
  EmpSalary int,
  EmpWorkingYears int
)

SELECT
  *
FROM EmpSalary

INSERT INTO EmpSalary (EmpId, EmpFullName)
  VALUES (1007, 'Naresh Choulla')

INSERT INTO EmpSalary (EmpId, EmpFullName)
  VALUES (1008, 'Choulla Naresh')


INSERT INTO EmployeeDetails
  VALUES (1001, 'Naresh', 'Choulla', 'IT', 2)
INSERT INTO EmployeeDetails
  VALUES (1002, 'Sachin', 'Tendulkar ', 'IT', 2)
INSERT INTO EmployeeDetails
  VALUES (1003, 'Prince', 'Mahesh', 'Accounts', 3)
INSERT INTO EmployeeDetails
  VALUES (1004, 'Shruti', 'hassan', 'HR', 1)
INSERT INTO EmployeeDetails
  VALUES (1005, 'anushka', 'sharma', 'IT', 2)
INSERT INTO EmployeeDetails
  VALUES (1006, 'Hyd', 'Hitech', 'Accounts', 3)
-----------------------------------
SELECT
  *
FROM EmpSalary

INSERT INTO EmpSalary
  VALUES (1001, 'naresh choulla', 35000, 3)
INSERT INTO EmpSalary
  VALUES (1002, 'Varun Sharma', 25000, 2)
INSERT INTO EmpSalary
  VALUES (1003, 'Jaspreet Sharma', 20000, 2)
INSERT INTO EmpSalary
  VALUES (1004, 'Shruti Sharma', 18000, 1)
INSERT INTO EmpSalary
  VALUES (1005, 'Shaili Sharma', 25000, 2)
INSERT INTO EmpSalary (EmpFullName, EmpSalary, EmpWorkingYears)
  VALUES ('Shaili Sharma', 6000, 1)


SELECT
  *
FROM EmpSalary
SELECT  * FROM EmployeeDetails
-- \inner join
SELECT
  EmployeeDetails.EmpId,
  EmployeeDetails.EmpFirstName,
  EmpSalary.EmpSalary
FROM EmployeeDetails
JOIN EmpSalary
  ON EmployeeDetails.EmpId = EmpSalary.EmpID

--  Left outer join

SELECT
  e.EmpId,
  e.EmpFirstName,
  e.DepartID,
  s.EmpSalary
FROM EmployeeDetails e
LEFT OUTER JOIN EmpSalary s
  ON e.EmpId = s.EmpID

SELECT
  e.EmpId,
  e.EmpFirstName,
  e.DepartID,
  s.EmpSalary
FROM EmployeeDetails e
RIGHT OUTER JOIN EmpSalary s
  ON e.EmpId = s.EmpID

SELECT
  e.EmpId,
  e.EmpFirstName,
  e.DepartID,
  s.EmpSalary
FROM EmployeeDetails e
FULL OUTER JOIN EmpSalary s
  ON e.EmpId = s.EmpID

-- Cross join
SELECT
  EmployeeDetails.EmpId,
  EmployeeDetails.EmpFirstName,
  EmpSalary.EmpSalary
FROM EmployeeDetails
CROSS JOIN EmpSalary
--on EmployeeDetails.EmpId = EmpSalary.EmpID

-- Equi Join

SELECT
  *
FROM EmployeeDetails
JOIN EmpSalary
  ON EmployeeDetails.EmpId = EmpSalary.EmpID

-- Self Join
SELECT
  *
FROM EmployeeDetails
ALTER TABLE EmployeeDetails
ADD ManagerID int

UPDATE EmployeeDetails
SET ManagerID = 1002
WHERE empid = 1001
UPDATE EmployeeDetails
SET ManagerID = 1002
WHERE empid = 1005
UPDATE EmployeeDetails
SET ManagerID = 1006
WHERE empid = 1003
UPDATE EmployeeDetails
SET ManagerID = 1004
WHERE empid = 1007
UPDATE EmployeeDetails
SET ManagerID = 1004
WHERE empid = 1008

SELECT
  *
FROM EmployeeDetails

SELECT
  a.EmpId,
  a.EmpFirstName AS ManagerName,
  b.EmpId AS ManagerID,
  b.EmpFirstName AS EmployeeName
FROM EmployeeDetails a,
     EmployeeDetails b
WHERE a.EmpId = b.ManagerID

CREATE TABLE computer (
  CompID int,
  computerDes varchar(100),
  Price int
)

DELETE FROM computer
WHERE CompID = 2
INSERT INTO computer
  VALUES (1, 'Pentium 4,1GB RAM', 25000)
INSERT INTO computer
  VALUES (2, 'Dual Core,2GB RAM', 35000)
CREATE TABLE Addon (
  id int,
  description varchar(100),
  price int
)
INSERT INTO Addon
  VALUES (1, 'Speakers', 5000)
INSERT INTO Addon
  VALUES (2, 'printer', 15000)

SELECT
  *
FROM computer
SELECT
  *
FROM Addon


SELECT
  computer.computerDes,
  Addon.description,
  computer.Price + Addon.price AS totalprice
FROM computer
CROSS JOIN Addon
--on EmployeeDetails.EmpId = EmpSalary.EmpID