Wednesday, May 21, 2008

How we can use captcha image in our registration page

1) Class for capthca image.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
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.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

/// [summary]
/// Summary description for randomImage
/// [/summary]
/// //This class is used to generate CaptchaImage on SignUp1 page.Image will generate randomly When different user
/// //user comes to SignUp1 page
public class randomImage
{
#region Private Properties

// Internal properties.
private string text;
private int width;
private int height;
private string familyName;
private Bitmap image;
#endregion

#region Public Properties
// Public properties (all read-only).
public string Text
{
get { return this.text; }
}
public Bitmap Image
{
get { return this.image; }
}
public int Width
{
get { return this.width; }
}
public int Height
{
get { return this.height; }
}

#endregion

#region Public Methods
// For generating random numbers.
private Random random = new Random();
// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width and height.
// ====================================================================
// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width and height.
// ====================================================================
public randomImage(string s, int width, int height)
{
this.text = s;
this.SetDimensions(width, height);
this.GenerateImage();
}

// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width, height and font family.
// ====================================================================
public randomImage(string s, int width, int height, string familyName)
{
this.text = s;
this.SetDimensions(width, height);
this.SetFamilyName(familyName);
this.GenerateImage();
}
// ====================================================================
// This member overrides Object.Finalize.
// ====================================================================
~randomImage()
{
Dispose(false);
}

// ====================================================================
// Releases all resources used by this object.
// ====================================================================
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}

// ====================================================================
// Custom Dispose method to clean up unmanaged resources.
// ====================================================================
protected virtual void Dispose(bool disposing)
{
if (disposing)
// Dispose of the bitmap.
this.image.Dispose();
}
// ====================================================================
// Sets the image width and height.
// ====================================================================
private void SetDimensions(int width, int height)
{
// Check the width and height.
if (width [= 0)
throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
if (height [= 0)
throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}

// ====================================================================
// Sets the font used for the image text.
// ====================================================================
private void SetFamilyName(string familyName)
{
// If the named font is not installed, default to a system font.
try
{
Font font = new Font(this.familyName, 12F);
this.familyName = familyName;
font.Dispose();

}
catch (Exception ex)
{
string msg = ex.Message;
this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
}
}
// ====================================================================
// Creates the bitmap image.
// ====================================================================
private void GenerateImage()
{
// Create a new 32-bit bitmap image.
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);

// Create a graphics object for drawing.
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);

// Fill in the background.
HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.White , Color.White);
g.FillRectangle(hatchBrush, rect);

// Set up the text font.
SizeF size;
float fontSize = rect.Height + 1;
Font font;
// Adjust the font size until the text fits within the image.
do
{
fontSize--;
font = new Font(this.familyName, fontSize, FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width ] rect.Width);

// Set up the text format.
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

// Create a path using the text and warp it randomly.
GraphicsPath path = new GraphicsPath();
path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format);
float v = 30F;
PointF[] points =
{
new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

// Draw the text.
hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.SkyBlue , Color.SkyBlue );
g.FillPath(hatchBrush, path);

// Add some random noise.
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i [ (int)(rect.Width * rect.Height / 30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m / 50);
int h = this.random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}

// Clean up.
font.Dispose();
hatchBrush.Dispose();
g.Dispose();

// Set the image.
this.image = bitmap;
}
/// [summary]
/// This function helps to create a new random code which will be displayed in the
/// ImageRegistrationStr1 and will be used as digital signature.
/// [/summary]
/// [param name="codeCount"] The codeCount to be followed inside the function[/param]
/// [returns] String kind of variable which will be loaded with random code we needed.[/returns]
public string CreateRandomCode(int codeCount)
{
//try
//{
// String variable which contains all the possible characters.
string allChar = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
// String type array which will be filled by dividing the above string variable.
string[] allCharArray = allChar.Split(',');
// variable for temporary use.
string randomCode = "";
int temp = -1;
//Create an Object of Random Class
Random rand = new Random();

for (int Counter = 0; Counter [ codeCount; Counter++)
{
if (temp != -1)
{
//Create an Object of Random Class using specified seed value
rand = new Random(Counter * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(17);
if (temp != -1 && temp == t)
{
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
//checkCode = randomCode;
////Session["CheckCode"] = checkCode;
}
return randomCode;
//}

//catch (Exception ex)
//{
// Session["Error"] = ex.Message;
// Response.Redirect("PageForErrors.aspx");
//}

}

#endregion

#region Constructor of the class
public randomImage()
{
//
// TODO: Add constructor logic here
//
}
#endregion
}



2) Code of JPEGImage.aspx.cs page which convert in image and call in image source as


#region [------------------------------ Directories----------------------------------------]
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawingy;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
#endregion
//This page is used to generate CaptchaImage which is randomly changed when user at SignUp1 page
public partial class Users_JPEGImage : System.Web.UI.Page
{
#region [--------------------------Page Load ----------------------------------]
protected void Page_Load(object sender, EventArgs e)
{
// Create a CAPTCHA image using the text stored in the Session object.
randomImage ci = new randomImage(this.Session["CaptchaImageText"].ToString(), 200, 50, "Century Schoolbook");


// Change the response headers to output a JPEG image.
this.Response.Clear();
this.Response.ContentType = "image/jpeg";

// Write the image to the response stream in JPEG format.
ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);

// Dispose of the CAPTCHA image object.
ci.Dispose();

}
#endregion
}

2a) nothing much in its aspx page

[script src="http://www.google-analytics.com/urchin . js" type="text/javascript"]
[/script]
[script type="text/javascript"]
_uacct = "UA-4349440-1";
urchinTracker();
[/script]
[/head]
[body]
[form id="JpegImage" method="post" runat="server"]

[/form]
[/body]
[/html]

3) on signup page

a)

on page load initial the session value with image text

this.Session["CaptchaImageText"] = objrandom.CreateRandomCode(7);

b)

display captcha image in signup page.

[asp:Image ID="Image2" ImageUrl="JPEGImage.aspx" runat="server" Width="167" Height="64"
EnableViewState="false" /]


c) on submit button campare text and captcha image value before save user information.


this.Session["CaptchaImageText"] = objrandom.CreateRandomCode(7);

No comments: