nedjelja, 31. svibnja 2009.

AJAX: captcha - Create It

What is captcha: secure picture with randomly generated letters in registration process on asp.net page.

In this demonstration we are going to create captcha, secure picture with letters in registration process. Captcha will be created in asp.net, AJAX and C# technology.

The major thing on captcha will be done in C# code behind.

How to create captcha :

1. Create New aspx page in your Project (name it: Captcha.aspx)
3. Before namespace include this directives:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;

2. On PageLoad() of Captcha.aspx paste this code (change MapPath and name of picture):

//Folder for pictures under your project
string mpath = Server.MapPath("../../Images/");

string imgFunnyCat = mpath + "funny-cat.jpg";


Bitmap objBMP = new System.Drawing.Bitmap(imgFunnyCat);
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", 11, FontStyle.Bold);
string randomStr = "";
int[] myIntArray = new int[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.Black, 20, 8);

string slika = mpath + "aa.jpeg";

//' Set the content type and return the image
Response.ContentType = "image/Jpeg";
//objBMP.Save(slika, ImageFormat.Jpeg);
objBMP.Save(Response.OutputStream, ImageFormat.Jpeg);

objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();

4. On other page; Register page (in Design mode), inside of ajax update panel, include Image control and Button control.
Image control should have ImageUrl property to show on Captcha.aspx page

asp:Image ID="Image1" runat="server" ImageUrl="~/UI/Controls/Captcha.aspx" /

and Button property Click shoul have Button1_Click value

asp:Button ID="Button2" runat="server" Text="Button" onclick="Button1_Click" /

5. In code behind of Register page, in button click event you should put code with ImageUrl to show on Captcha.asp page and with generated id. (because, ajax update will happened only if something is changed. And this URL will be generated randomly.

protected void Button1_Click(object sender, EventArgs e)
{
Image1.ImageUrl = "~/UI/Controls/Captcha.aspx?id=" + Guid.NewGuid() + "";
}