WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 123 users


WorldofASP.NET >> ASP.NET >> Unedited ASP.NET

Implement captcha control library for ASP.NET

a captcha control, image, image handler, and supression class for form validation
Published Date : 02 Jul 2008
Author : Hans Candra
Language : C#
Platform : .NET
Technology : ASP.NET,Web Forms
Views : 2851
Rating : (0 votes so far)



Introduction

CAPTCHA stands for "completely automated public Turing test to tell computers and humans apart." What it means is, a program that can tell humans from machines using some type of generated test. A test most people can easily pass but a computer program cannot.

A CAPTCHA is a type of challenge-response test used in computing to ensure that the response is not generated by a computer. The process involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade. Because other computers are unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human. A common type of CAPTCHA requires that the user type the letters or digits of a distorted image that appears on the screen.

You've probably encountered such tests when signing up for an online email or forum account. The form might include an image of distorted text. CAPTCHAs are used to prevent automated software from performing actions which degrade the quality of service of a given system, whether due to abuse or resource expenditure. Although CAPTCHAs are most often deployed as a response to encroachment by commercial interests, the notion that they exist to stop only spammers is mistaken.

This article demonstrates how to create such an library for CAPTCHA and employ it within an ASP.NET web form.

Main

Files:

CaptchaImage.cs - defines the CapchaImage object which actually creates the image.

Default.aspx, Default.aspx.cs - a sample web form.

CaptchaImageHandler.cs - to communicate between the class library and implemented web form.

Let's look at each component and it's purpose. The first thing you had to deal with was the image generated by the CAPTCHA class. This was originally done with a dedicated .aspx form-- something that won't exist for a server control. How could someone generate an image on the fly? To do that, first you need to modified Web.config in HttpHandler section:

<httphandlers>
    <add verb="GET" path="CaptchaImage.aspx" type="WebControlCaptcha.CaptchaImageHandler, WebControlCaptcha">
</add>
</httphandlers>


Next you also need to add a page control to web.config:


<pages>
<controls>
<add tagprefix="captcha" namespace="WebControlCaptcha" 

assembly="WebControlCaptcha">
</add>
</controls>
</pages>

httpHandlers in Web.Config defines a special page named CaptchaImage.aspx. Now, this page doesn't actually exist. When a request for CaptchaImage.aspx occurs, it will be intercepted and handled by a class that implements the IHttpHandler interface: CaptchaImageHandler. Here's the relevant code section:

namespace WebControlCaptcha
{
    public class CaptchaImageHandler : IHttpHandler, IRequiresSessionState
    {
        #region IHttpHandler Members

        public void ProcessRequest(HttpContext context)
        {
            CaptchaImage ci;
            HttpApplication app = context.ApplicationInstance;

            if (app.Request.QueryString["guid"] == null)
            {
                app.Response.StatusCode = 404;
                app.CompleteRequest();
            }
            string guid = app.Request.QueryString["guid"];

            string s = String.Empty;
            if (app.Request.QueryString["s"] != null)
            {
                s = app.Request.QueryString["s"];
            }


            if (String.IsNullOrEmpty(s))
            {
                ci = (CaptchaImage) context.Cache[guid];
            }
            else
            {
                ci = (CaptchaImage) context.Session[guid];
            }


            if (ci == null)
            {
                app.Response.StatusCode = 404;
                app.CompleteRequest();
            }
            else
            {
                Bitmap b = ci.RenderImage();
                b.Save(app.Context.Response.OutputStream, ImageFormat.Jpeg);
                b.Dispose();
                app.Response.ContentType = "image/jpg";
                app.Response.StatusCode = 200;
                app.CompleteRequest();
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }

        #endregion
    }
}


A new CAPTCHA image will be generated, and the image streamed directly to the browser from memory.

The default.aspx example:


	


	<form id="form1" runat="server">
	<div>
	 <captcha:captchacontrol id="CaptchaControl1" runat="server"
 captchabackgroundnoise="Extreme" captchafontwarping="Medium">
</captcha:captchacontrol>
			 
			<asp:validationsummary id="ValidationSummary1" 
runat="server" validationgroup="captcha"></asp:validationsummary>
			<p></p>
			<br>
			<asp:button id="Button1" runat="server" 
validationgroup="captcha" text="Submit">
</asp:button>
	
	</div>
	</form>



Noted above important syntax is captcha:captchaControl and validation group. You need specify the group of your validation control and button to submit it. If you have other validation in the same form, you can specify it with same validation group for example email validation, password validation, etc. See below:


         <table width="550" cellpadding="3" width="100%" border="0">
                <tr align="center">
                    <td class="style1">
                        Your Name :
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" 

runat="server" ControlToValidate="txtName"
                            Display="Dynamic" ValidationGroup="Details" 

ErrorMessage="Please Enter Your Name"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr align="center">
                    <td class="style1">
                        User Name :
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" 

runat="server" ControlToValidate="txtUserName"
                            Display="Dynamic" ValidationGroup="Details" 

ErrorMessage="Please Enter UserName"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr align="center">
                    <td class="style1">
                        Email Address :
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                        <asp:RegularExpressionValidator 

ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail"
                            Display="Dynamic" ValidationGroup="Details" 

ErrorMessage="Please Enter Valid Email"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+

([-.]\w+)*"></asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ValidationGroup="Details" 

ID="RequiredFieldValidator2"
                            runat="server" ControlToValidate="txtEmail" 

Display="Dynamic" ErrorMessage="Please Enter Email"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr align="center">
                    <td class="style1">
                        Password :
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtPassword" runat="server" 

TextMode="Password"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 

ValidationGroup="Details"
                            runat="server" ControlToValidate="txtPassword" 

Display="Dynamic" ErrorMessage="Please Enter Password"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr align="center">
                    <td class="style1">
                        Confirm Password :
                    </td>
                    <td align="left">
                        <asp:TextBox ID="txtConfirmPassword" TextMode="Password" 

runat="server"></asp:TextBox>
                        <asp:CompareValidator ID="CompareValidator1" 

ValidationGroup="Details" runat="server"
                            ControlToCompare="txtPassword" 

ControlToValidate="txtConfirmPassword" ErrorMessage="Password not 
match"></asp:CompareValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div>
                            <captcha:CaptchaControl ID="CaptchaControl1" 

runat="server" CaptchaBackgroundNoise="Extreme"
                                CaptchaFontWarping="Medium"></captcha:CaptchaControl>
                             
                            <asp:ValidationSummary Visible="false" 

ID="ValidationSummary1" ValidationGroup="Details"
                                runat="server" />
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        <asp:Button ID="btnRegister" runat="server" 

ValidationGroup="Details" Text="Register"
                            CssClass="button" OnClick="btnRegister_Click" />
                    </td>
                </tr>
            </table>

Conclusion

Now that it is wrapped up into an ASP.NET server control, it should be easier than ever to simply drop on a web form, set a few properties, and validating a submitted web form. Please don't hesitate to provide any feedback. Hope you can find it useful.

References

Include all the useful links or references that can help users learn about this tutorial

  1. Code Project Captcha Image
  2. Brief explanation about Captcha

    Download Source Code



    Tag Cloud
      asp.net url parameters   frames image gallery thumbnails asp.net   asp.net listbox control   cannot start service from the command line or a debugger   asp.net activate user   asp.net cookies encryption   asp.net delegate   create httpwebrequest   asp.net httpwebrequest   asp.net encryption   asp httpwebrequest   httpwebrequest .net   checkboxlist datasource   tooltip asp.net   asp.net upload ajax progress   "javascript in asp.net"   datalist control   httpmodule httphandler   form view in asp.net   asp.net random number   generate random number asp.net   httpwebrequest vb.net   formview asp.net   contact us asp.net   formview displaying inserted data   ajax updatepanel button   cannot start service from the command line or a debugger. a windows service must   edit update insert in a gridview c#   asp.net pass data from one page to another   httpwebresponse   asp.net file upload progress   smart device application   httpwebrequest in asp.net 2.0   feedback form in asp.net   httpwebrequest asp.net c#   asp.net cookie shopping cart   httpwebrequest create   asp.net tooltip   upload file progress bar asp.net   httpwebrequest   asp.net file upload progress bar   httpwebrequest httpwebresponse   xhtml-mp asp.net   encrypt querystring in asp.net





    Other Related and Popular Articles :

    Simple asp2 feedback form
    A simple way to get user feedback via webpage email.

    Designing a Membership Sign-Up and Login Page in ASP.NET
    How to design user interface for registration and login in ASP.NET

    Validate Email and Domain in a Web Form
    Simple method to validate using javascript and ASP.NET validation control

    Basics of XHTML-MP
    Basics of XHTML-MP

    Activate User Registration by Email in ASP.NET
    How to activate registered user using System.Net.Mail.SMTPClient class


    Author Profile : Hans Candra

    Click here to view Author Profile


    How would you rate the quality of this content?
    Poor Excellent

    Comments

    Leave New Comments


    Article Content copyright by Hans Candra
    Everything else Copyright © by WorldofASP.NET 2008

    Category
    .NET 3.5
    AJAX and ATLAS
    ASP.NET
    C# Programming
    Classic ASP
    Enterprise Systems
    General .NET
    VB.NET Programming
    Announcements
    Earn Cash by writing an article or review
    For more info Click here







    Legend : - Within 3 Days - Within 6 Days - Within 9 Days

    Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
    © 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
    Our Partners : ASP.NET Web Hosting | Windows Web Hosting | ASP.NET Hosting | Phone Card | PHP Directory | Bangkok Hotels |Calling Card