Image Verification technique inside a Form |
Visite: 27386 |
martedì 13 giugno 2006 |
Framework 2.0
This article shows how to use Image Verification in your ASP.NET Forms.
This technique is used to prevent spammers messages in your applications like blogs, forums or guestbooks.
My example uses the
ImageVerification
class that provides istance methods for showing password image to the user
and to verify the password written in the TextBox control.
Everytime one istance of
ImageVerification
is created, one new password is stored in the DataSet controlled
by the class.
Is possible to use the SessionID or IpAddress of the client as primary key of the DataTable.
DataSet is created every N minutes to prevent unattended growing up of the Application object.
You can modify these settings in the web.config file.
Creating the image
The
CreateImageOnTheFly method of the
ImageVerification class saves an image
on-the-fly in the Http output of the current client Request.
public void CreateImageOnTheFly(int width, int height)
{
string p = this.Password;
if (p != null)
{
Random r = new Random();
Bitmap b = new Bitmap(width, height, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(b);
// set antialias for the text
g.TextRenderingHint = TextRenderingHint.AntiAlias;
// set the background color
g.Clear(_BackColor);
Matrix m = new Matrix();
for (int i = 0; i < p.Length; i++)
{
// reset matrix
m.Reset();
// rotate the matrix
m.RotateAt(r.Next(-30, 30), new PointF(Convert.ToInt64(width * (0.10 * i)), Convert.ToInt64(height * 0.5)));
// apply the transform
g.Transform = m;
// draw the text to the image
g.DrawString(p[i].ToString(), _TextFont, SystemBrushes.ActiveCaptionText, Convert.ToInt64(width * (0.10 * i)), Convert.ToInt64(height * 0.2));
// reset the matrix for the graphics object
g.ResetTransform();
}
// save the created image to the output stream of httpcontext
b.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Gif);
g.Dispose();
b.Dispose();
}
}
This method needs one password stored in the Application DataSet, else no image will be showed to the client.
With the
Save method
of
Bitmap class is possible to save one image directly to the Http output of the client Request,
without create new files.
Set the password
The password must be set using one of two
ImageVerification methods:
- SetRandomPassword(int size, bool
lowerCase)
To create and automatically store in the DataSet a
size long password. The
lowerCase parameter indicates if the password has to have lower chars or not.
- SetPassword(string
password)
Store the password passed as parameter in the DataSet.
Only after the use of one of these two methods, is possible to use the
CreateImageOnTheFly method.
Storing password
As I told, all the clients' passwords are stored in the Application DataSet. This DataSet has only one DataTable with
two columns inside: SessionID and Code.
In the first column there
will be stored the SessionID or the IpAddress of the client (depends by the settings used in the web.config file)
while in the second column the password's value.
public void SetRandomPassword(int size, bool lowerCase)
{
StringBuilder s = new StringBuilder();
Random r = new Random();
for (int i = 0; i < size; i++)
{
char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * r.NextDouble() + 65)));
s.Append(ch);
}
// storing the password in the DataSet
InsertCode((lowerCase ? s.ToString().ToLower() : s.ToString()));
}
public void SetPassword(string password)
{
InsertCode(password);
}
private void InsertCode(string password)
{
if (HttpContext.Current.Application["ivDataSet"] == null) CreateCodesDataSet(); // creates the DataSet if null
DataSet ds = (DataSet)HttpContext.Current.Application["ivDataSet"];
DataTable dt = ds.Tables[0];
DataRow[] drw = dt.Select("SessionID='" + GetPrimaryKey + "'"); // searching for the SessionID/IpAddress
if (drw.Length == 0)
{
// code not found
DataRow dr = dt.NewRow();
dr["SessionID"] = GetPrimaryKey;
dr["Code"] = password;
dt.Rows.Add(dr);
}
else
{
// sessionID found
drw[0]["Code"] = password;
}
// saving the DataSet in the Application
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["ivDataSet"] = ds;
HttpContext.Current.Application.UnLock();
}
Using the ImageVerification class
This class needs one ASP.NET page (Image.aspx for example) to show the Http output.
There isn't HTML code in this page, only C# code:
protected void Page_Load(object sender, EventArgs e)
{
ImageVerification v = new ImageVerification();
v.BackColor = Color.Yellow;
v.TextFont = new Font("Lucida Console", 14, FontStyle.Bold);
v.CreateImageOnTheFly(150, 30);
}
The ASP.NET page contains the Form is like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Form Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="imgCode" runat="server" ImageUrl="Image.aspx" />
<br />
<asp:TextBox ID="txtCode" runat="server" Columns="10" MaxLength="7"></asp:TextBox>
<asp:Button ID="btnCheck" runat="server" OnClick="btnCheck_Click" Text="Check" />
<br />
<asp:Label ID="labResult" runat="server"></asp:Label></div>
</form>
</body>
</html>
The C# code for this page is:
private ImageVerification v = new ImageVerification();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
v.SetRandomPassword(7, false); // set the random password
//v.SetPassword("custompassword");
}
}
protected void btnCheck_Click(object sender, EventArgs e)
{
// check the password inserted by the user
if (v.IsValidPassword(txtCode.Text))
{
labResult.Text = "Correct code!";
labResult.ForeColor = Color.Green;
}
else
{
labResult.Text = "Incorrect code!";
labResult.ForeColor = Color.Red;
}
}
That's all!
This simple example demonstrates you how to use Image Verification technique in your ASP.NET pages.
Click here to download the example project
|
thanks very good code :)
|
| Scritto da AYTAC - mercoledì 19 luglio 2006 alle ore 21.34 |
|
thanks very good code :)
|
| Scritto da AYTAC - mercoledì 19 luglio 2006 alle ore 23.00 |
|
Thanks for the code. But your link to your code at http://blog.devexperience.net/en/11/download/ImageVerification.zip results in a 404 Page Not found error.
|
| Scritto da multiplex - sabato 2 settembre 2006 alle ore 8.45 |
|
I managed to download it from the Italian site.
Is there any way to make the image more distorted? Thanks.
|
| Scritto da multiplex - sabato 2 settembre 2006 alle ore 9.23 |
|
Very nice code, thank you very much!
Though, it seems like the image sometimes doesnt display in Internet Explorer on some computers.
Have anyone experienced this and know what the problem is?
All the best!
|
| Scritto da Merhaba - domenica 3 settembre 2006 alle ore 18.14 |
|
I managed to download it from the Italian site. Is there any way to make the image more distorted? Thanks
|
| Scritto da Merhaba - martedì 17 ottobre 2006 alle ore 13.01 |
|
messahhio
|
| Scritto da AGO - lunedì 20 novembre 2006 alle ore 17.35 |
|
Just what I needed
Thanks very much
|
| Scritto da 1Liter - sabato 20 gennaio 2007 alle ore 14.50 |
|
Thanks for the code.
But, I wonder why this one is not working when I tested on Windows2003 server. It works fine with my XP professional. Do you any idea regarding with this.
Thanks,
Myo
|
| Scritto da MyoZaw - giovedì 1 febbraio 2007 alle ore 6.28 |
|
Excellent code!
I customised my preference and it works very well.
Many thanks
|
| Scritto da N707 - sabato 24 febbraio 2007 alle ore 19.36 |
|
great article
|
| Scritto da Ahmet BUTUN - giovedì 1 marzo 2007 alle ore 23.19 |
|
Hi!
Thanks very much for the code. I'm a total newbee and I would like to know how to use this code with, for example, the create user wizard in Visual Web Developer? How and where should I put this code making it work so that the user only can register when the verification is correct? I would be very grateful if You could give me an example on how to do this.
Thanks!
|
| Scritto da Patrik - domenica 29 aprile 2007 alle ore 22.04 |
|
When I publish on windows 2003 server (allowing ,with vs2005,the precompiled site to be updatable) in place of the image code appear a blank box. Anyway if I upload entirely the site, with sources files, without compiling it, when I refresh the form page with "refresh" button of explorer I get the previuos problem.
|
| Scritto da roberto - mercoledì 13 giugno 2007 alle ore 18.00 |
|
Hi all. We have developed a free ASP.NET contol that is not dissimilar to the Google verification image. You can try it and download a copy from here http://www.roundedpanel.baysoft-net.co.uk/
Give it a try!
Cheers
|
| Scritto da Dan - lunedì 22 ottobre 2007 alle ore 18.24 |
|
Where is your ImageVerification Clas . You can just use everywhere this class but not define any namespace or dll file which can I use.
For practically, always mention these things when apply.
How can I use this code without this class.
|
| Scritto da Sushil Kumar gupta - mercoledì 12 marzo 2008 alle ore 10.53 |
|
By far, this is one of the best image verification codes. I customized it to generate random color and font each time a call is made.
|
| Scritto da Shams - mercoledì 19 marzo 2008 alle ore 16.00 |
|
This image randomly doesn't work with windows vista.
|
| Scritto da Matt - mercoledì 9 aprile 2008 alle ore 13.27 |
This image randomly doesn't work with windows vista.
What do you mean? What means Vista, sorry? With Internet Explorer 7 doesn't work? Coz i can use it with FF and IE6-7 without any problems. I didn't try with others browsers but i think it's all ok too.
I'm confused...
|
| Scritto da ZofM - mercoledì 9 aprile 2008 alle ore 13.38 |
|
Image varification Code in ASP.NET
|
| Scritto da Shambhu - lunedì 14 aprile 2008 alle ore 15.33 |
|
Hi this example is nice BUT it doesn't work with Mozilla Firefox Browser!! What should be done to make it work with Firefox??
|
| Scritto da Zobi - venerdì 18 aprile 2008 alle ore 10.58 |
|
Thanx :)
|
| Scritto da Anders - venerdì 23 maggio 2008 alle ore 11.04 |
|
Hi, this exam working good. I'm using Vista, IE7, Firefox
|
| Scritto da Thanh Tan - giovedì 28 agosto 2008 alle ore 3.41 |
|
Hi, thanks very much for the code.
I have a problem, the code works fine and displays image properly if I publish my website to Windows 2003 running IIS6 but, however, if I publish my site to Windows 2000 running IIS 5, the image does not display.
has anybody come across this problem before?
if yes then please I will be greatful of any solution provided.
Thanks!
|
| Scritto da shigarr - lunedì 10 novembre 2008 alle ore 18.44 |
|
Do anybody know how to extract images from webbrowser control without refreshing, and save to local drive?
|
| Scritto da WebFromSubmitter - martedì 24 febbraio 2009 alle ore 15.10 |
|
thanks for this article
|
| Scritto da unknown - lunedì 2 marzo 2009 alle ore 10.50 |
|
This blog Is very informative , I am really pleased to post my comment on this blog . It helped me with ocean of knowledge so I really believe you will do much better in the future . Good job web master .
|
| Scritto da top seo tech - venerdì 3 luglio 2009 alle ore 11.15 |
Scrivi nuovo commento