I was trying to find a solution to block spammers adding data to the database, using C#. This is the quick solution I found.
First create an image tag in the webform that has the submit form.
<IMGheight="30"alt=""src="Turing.aspx"width="80">
As you see, the source for the picture will be a file called “Turing.aspx”.
Later, create the webform “Turing.aspx” with the code below:
publicclass Turing1 : System.Web.UI.Page
{
privatevoid Page_Load(object sender, System.EventArgs e)
{
Bitmap objBMP =new System.Drawing.Bitmap(60,20);
Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Green);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
//' Configure font to use for text
Font objFont = new Font("Arial", 8, FontStyle.Bold);
string randomStr="";
int[] myIntArray = newint[5] ;
int x;
//That is to create the random # and add it to our string
Random autoRand = new Random();
for (x=0;x<5;x++)
{
myIntArray[x] = System.Convert.ToInt32 (autoRand.Next(0,9));
randomStr+= (myIntArray[x].ToString ());
}
//This is to add the string to session cookie, to be compared later
Session.Add("randomStr",randomStr);
//' Write out the text
objGraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3);
//' Set the content type and return the image
Response.ContentType = "image/GIF";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
}
And this is the code for the Submit button on the main form:
privatevoid btnSubmit_ServerClick(object sender, System.EventArgs e)
{
if (Page.IsValid && (txtTuring.Value.ToString () ==
Session["randomStr"].ToString ()))
{
// The Code to insert data
}
else
{
Label1.Text ="Please enter info correctly";
}
}
All you do is to write some random chars out at the same formating and font. This will prevent maybe some beginners to get the code, but with just some simple coding algorithms its possible to get the wanted letters back from the image!
All spamm blocking image creators use differnt high, angels and fonts for sometimes each letter.