![]() |
Web Development »
ASP.NET »
General
Intermediate
Image Verifier - Custom Control in ASP.NETBy Nataraj KAn article on how to create a custom control to render dynamic images with random text content which can be used for code verification. |
C# 2.0, Windows, .NET 2.0, ASP.NET, WebForms, VS2005, Architect, Dev
|
||||||||||
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
This article describes how to create a custom control in ASP.NET for implementing image verification functionality. What is this Image Verification? You might have seen this implemented in many websites like microsoft.com, google.com, yahoo.com etc during the signup process. It's simply used for verifying the user's input, by validating the code which user enters against a random code displayed as image in the form. This helps the application to identify automated submission of forms and reject such requests which could even crash any web site by inputting bulk data to site.
I saw this functionality implemented in various sites and thought of implementing the same while creating a personal website. When I started implementing the functionality in my site I faced few issues. Some of them are generating random text, persisting the text so that it can be verified against the user input code during post backs, avoid storing the generated code in viewstate or urls etc. Gradually I found solutions to these issues. I will be explaining those solutions in the below sections.
Explaining every piece of code used in the sample application is difficult through this article. Hence I will explain the following key steps involved in the development of this custom control.
1. Create a custom control capable of rendering <img> tags.
2. Generate a random text, persist it and render it as image.
3. Verify the user input against the persisted random text.
First of all we need to create a custom control which can render the standard HTML <img> tags. It should also generate a dynamic url and attach it to the src attribute of the <img> tag generated.
This is done in the example by derving a class named ImageVerifier from WebControl, as shown below.
namespace NatsNet.Web.UI.Controls
{
[DefaultProperty("Text")] [ToolboxData("<{0}:ImageVerifier runat="server">")]
public class ImageVerifier : WebControl, IHttpHandler
{
private string m_UniqueID = string.Empty;
public ImageVerifier(): base(HtmlTextWriterTag.Img) { }
private string MyUniqueID { ... }
public string Text { ... }
private string GetRandomText() { ... }
protected override void OnInit(EventArgs e) { ... }
protected override void LoadControlState(object savedState) { ... }
protected override object SaveControlState() { ... }
protected override void Render(HtmlTextWriter output) { ... }
public void ProcessRequest(HtmlTextContext context) { ... }
public bool IsReusable { ... }
}
}
In addition to deriving the control from WebControl, I have implemented the IHttpHandler too in that class. This is for making the control render the image itself in addition to the normal <img> tag rendering.
The rendering of the control happens inside the Render method.
protected override void Render(HtmlTextWriter output)
{
output.AddAttribute(HtmlTextWriterAttribute.Src, "ImageVerifier.axd?uid=" + this.MyUniqueID);
base.Render(output);
output.Write("<script language="'javascript'">");
output.Write("function RefreshImageVerifier(id,srcname)");
output.Write("{ var elm = document.getElementById(id);");
output.Write(" var dt = new Date();");
output.Write(" elm.src=srcname + '&ts=' + dt;");
output.Write(" return false;");
output.Write("}</script>");
output.Write(" <a href='#' onclick=\"return RefreshImageVerifier('"
+ this.ClientID + "','ImageVerifier.axd?&uid="
+ this.MyUniqueID + "');\">Refresh</a>");
}
The first line in the Render method assigns the src attribute for the rendered <img> tag. It generates the url in the format "ImageVerifier.axd?uid=" + this.MyUniqueID. The control has given a property named MyUniqueID which will be a unique GUID generated for each control instance. The last line of the Render method outputs a hyperlink to refresh the image with out postback.
For rendering a dynamic text as the image of this control we will be using the same class ImageVerifier through the implementation of IHttpHandler method public void ProcessRequest(HttpContext context). This method will be called when the browser request the url specified in the src attribute of the <img> tag rendered. In order to make this happen we need to configure our ImageVerifier class as an HttpHandler for the URLs like ImageVerifier.axd in the web.config file of the consuming application.
<httpHandlers>
<add
verb="GET"
path="ImageVerifier.axd"
type="NatsNet.Web.UI.Controls.ImageVerifier, NatsNet.Web.UI.Controls"
/>
</httpHandlers>
Below is the implementation of the ProcessRequest() method.
public void ProcessRequest(HttpContext context)
{
Bitmap bmp = new Bitmap(180, 40);
Graphics g = Graphics.FromImage(bmp);
string randString = GetRandomText();
string myUID = context.Request["uid"].ToString();
if (context.Cache[myUID] == null)
context.Cache.Add( myUID,
randString,
null,
Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(5),
System.Web.Caching.CacheItemPriority.Normal,
null
);
else
context.Cache[myUID] = randString;
g.FillRectangle(Brushes.WhiteSmoke,0, 0, 180, 40);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
Random rand = new Random();
for (int i = 0; i < randString.Length; i++)
{
Font drawFont = new Font("Arial", 18,
FontStyle.Italic | (rand.Next() % 2 == 0 ? FontStyle.Bold : FontStyle.Regular));
g.DrawString(randString.Substring(i,1), drawFont, Brushes.Black, i * 35 + 10, rand.Next()% 12);
Point[] pt = new Point[15];
for (inti = 0; i < 15; i++)
{
pt[i] = newPoint(rand.Next() % 180, rand.Next() % 35);
g.DrawEllipse(Pens.LightSteelBlue,pt[i].X, pt[i].Y, rand.Next() % 30 + 1, rand.Next() % 30 + 1);
}
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ContentType = "image/jpeg";
bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.End();
}
}
In the ProcessRequest() method a random text is generated using the private method GetRandomText() and is persisted using the Cache object as shown above. The value of query string uid will be used as the key for persisting the random text in the Cache object.
For generating random text of a specific length we can write any custom logic. Here in the sample I have used Random class to generate random numbers and convert them to corresponding characters. The same can be implemented in different ways as you wish.
private string GetRandomText()
{
string uniqueID = Guid.NewGuid().ToString();
string randString = "";
for (int i = 0, j = 0; i < uniqueID.Length && j < 5; i++)
{
char l_ch = uniqueID.ToCharArray()[i];
if ((l_ch >= 'A' && l_ch <= 'Z') || (l_ch >= 'a' && l_ch <= 'z') || (l_ch >= '0' && l_ch <= '9'))
{
randString += l_ch;
j++;
}
}
return randString;
}
Finally what we need is to validate the user input against the random text which is displayed as the image. For this I have added a Text property for our user control. This property retrieves the random text stored in the Cache and returns it. We can use this value to verify the user input.
public string Text
{
get
{
return string.Format("{0}",
HttpContext.Current.Cache[this.MyUniqueID]);
}
}
Below code shows an example of the code to be implemented in the consuming application for verifying the user input.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtImgVerifyText.Text == ImageVerifier1.Text)
{
// User has input the correct text so can continue
// processing the request.
}
else
{
// Either user has input an incorrect value or the request
// is not generated by the manual input. So do not continue
// processing the request.
}
}
In this article I have explained how to use the concept of Image Verification to help applications in identifying automated submission of forms. The implementation of this Image Verification has used few coding concepts such as HttpHandlers, Random class, Cache object etc.
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 5 Nov 2007 Editor: |
Copyright 2007 by Nataraj K Everything else Copyright © CodeProject, 1999-2009 Web17 | Advertise on the Code Project |