C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !






Captcha Images


Posted Date: 06 Aug 2008    Resource Type: Code Snippets    Category: ASP.NET WebForms
Author: fayazMember Level: Gold    
Rating: Points: 10



With this code sample you can create your own captcha image or captcha control. This resource contains the entire code to help you do so. It contains a normal ASP.NET page "default.aspx" followed by the ASP.NET page that contains the Captcha image. Also, the web.config file for the entire project is given in the examples.

1. default.aspx file follows


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<style type="text/css">
.correct
{fontfamiy:verdana,arial;fontweight:bold;color:red}
.error
{fontfamiy:verdana,arial;fontweight:bold;color:red}


</style>
</head>
<body onload="Button1_Click">
<form id="form1" runat="server">
<div>

<asp:Image ID="myImage" runat="server" ImageUrl="~/CaptchaControl.aspx" />
<br />
<br />

Enter code: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>


<asp:Button ID="Button1" runat="server" Text="Validate" OnClick="Button1_Click" />
<asp:Label ID="MessageLabel" runat="server" Height="50px" Text="" Width="150px"></asp:Label><br /><br />


</div>
</form>
</body>
</html>


2.default.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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

}
}
protected void Button1_Click(object sender, EventArgs e)
{
// validate the code

string userEnteredCode = TextBox1.Text;

ValidateUserCode(userEnteredCode);
}

private void ValidateUserCode(string userEnteredCode)
{
if (Session["Code"].ToString().Equals(userEnteredCode))
{
this.MessageLabel.Text = "Nice to know that you are not a bot.";
this.MessageLabel.CssClass = "correct";
//Response.Write("Nice to know that you are not a bot.");
}
else
{
// clear the session and generate a new code
Session["Code"] = null;
this.TextBox1.Text = "";
this.MessageLabel.CssClass = "error";
this.MessageLabel.Text = "the text u typed is incorrect please try again....";
//Response.Write("the text u typed is incorrect please try again");
}
}
}



3.CaptchaControl.aspx


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>


4.CaptchaControl.aspx.cs is the code-behind file for CaptchaControl.aspx


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

public partial class CaptchaControl : System.Web.UI.Page
{
private Random rand = new Random();

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateImage();
}
}

private void CreateImage()
{
string code = GetRandomText();

Bitmap bitmap = new Bitmap(200, 50, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

Graphics g = Graphics.FromImage(bitmap);
Pen pen = new Pen(Color.Yellow);
Rectangle rect = new Rectangle(0, 0, 200, 50);

SolidBrush b = new SolidBrush(Color.Black);
SolidBrush blue = new SolidBrush(Color.Blue);

int counter = 0;

g.DrawRectangle(pen, rect);
g.FillRectangle(b, rect);

for (int i = 0; i < code.Length; i++)
{
g.DrawString(code[i].ToString(), new Font("Verdena", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
counter += 20;
}

DrawRandomLines(g);

bitmap.Save(Response.OutputStream, ImageFormat.Gif);

g.Dispose();
bitmap.Dispose();

}

private void DrawRandomLines(Graphics g)
{
SolidBrush green = new SolidBrush(Color.Green);
//for (int i = 0; i < 20; i++)
//{
// g.DrawLines(new Pen(green, 2), GetRandomPoints());
//}

}

private Point[] GetRandomPoints()
{
Point[] points = { new Point(rand.Next(10, 150), rand.Next(10, 150)), new Point(rand.Next(10, 100), rand.Next(10, 100)) };
return points;
}

private string GetRandomText()
{
StringBuilder randomText = new StringBuilder();

if (Session["Code"] == null)
{
string alphabets = "abcdefghijklmnopqrstuvwxyz1234567890";

Random r = new Random();
for (int j = 0; j <= 5; j++)
{

randomText.Append(alphabets[r.Next(alphabets.Length)]);
}

Session["Code"] = randomText.ToString();
}

return Session["Code"] as String;
}

}


5. web.config is give below. It is well commented to help you understand.


<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true"/>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>


Fayaz

Attachments

  • captcha code (20088-6359-Captcha.zip)



  • Responses


    No responses found. Be the first to respond and make money from revenue sharing program.

    Feedbacks      
    Popular Tags   What are tags ?   Search Tags  
    Using Captcha Control in ASP.NET  .  Create your own captcha  .  Create Captcha Control in ASP.NET  .  Create Captcha Control  .  Adding Captcha controls to ASP.NET pages  .  

    Post Feedback


    This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
    You must Sign In to post a response.
    Next Resource: Creating Captcha Page in ASP.Net
    Previous Resource: Access database thorough class files
    Return to Discussion Resource Index
    Post New Resource
    Category: ASP.NET WebForms


    Post resources and earn money!
     
    Related Resources



    dotNet Slackers   BizTalk Adaptors    Web Design


    Contact Us    Privacy Policy    Terms Of Use