asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Fighting Spambots with .NET and AI -- Cont'd
By Adnan Masood


  • email this article to a colleague
  • suggest an article

    Delivering and Invoking CAPTCHA from Web Services

    Web services, as my previous columns on 15seconds explains, are URI addressable software components. They can provide different services on various niches; in this section I'll demonstrate how to create a Web service to deliver CAPTCHA images to be used by other applications. It will demonstrate the techniques of exposing Web methods, transferring blob (binary large object) or base-64 encoded data, and invoking Web methods.

    The Web service we are about to discover is named captchaWebService. It contains three publicly exposed methods (web methods) i.e. getCaptcha, selectWord, and generateImage. The .NET Framework provides the facility to view the asmx file depicting methods signatures. Similar to invoke.aspx, this Web service can be executed from any Web application that needs to validate users by using images. This facility is not just limited to ASP.NET. Because it is a Web service, it provides cross platform support for virtually all other programming languages and platforms.

    This platform-neutral component architecture has another major benefit. The CAPTCHA algorithm can always be modified, enhanced, and made tougher to counter bots centrally, and all the clients will enjoy the fruit of its efforts. A CAPTCHA application service provider may charge a small fee for this service, a flat rate plan, or per verification; it entirely depends on the business-process model.

    Figure: 3.1 Demonstrates a web service operations listing page.

    The WSDL (web service description language) file for functions can be viewed here. This describes function signatures and parameter details along with respective data types.

    The functions getCaptcha, selectWord, and generateImage can be executed individually, and they internally also use each other to perform the complete operation.

    selectWord:

    [WebMethod(Description="Get an Word from OGDEN's dictionary")]

    public String selectWord ()

    This Web method is pretty much the same one we have used before; the only difference is using the WebMethod attribute exposes it to the public, so it could be invoked externally. It connects to the dictionary database and returns a random word as a string as shown in the figure below.

    Figure: 3.5 Demonstrate invocation for selectWord method.

    Click here to see the detailed SOAP request and response information for the selectWord Web method. This method could be invoked separately through GET, POST and SOAP requests.

    Below is another invocation of selectWord. Notice it returns a different word.

    Figure: 3.4 Demonstrates another invocation for selectWord method.

    generateImage():

     

    [WebMethod(Description="Generates a CAPTCHA Image and returns filename")]

    public String generateImage ()

    This method generates the image and physically stores it on disk. After successful generation, it returns the filename as seen in the screenshot below.

    Figure: example 3.6

    getCaptcha():

    [WebMethod(Description="Returns a CAPTCHA Image in Base64-Encoding")]

    publicbyte[] getCaptcha()

    getCaptcha is the core method which provides integrated functionality of this Web service. This is the method that should be invoked by applications needing to use CAPTCHA functionality. It returns a byte array, streaming the image to the client. invoke.aspx invokes this Web method and gets a CAPTCHA served.

    Figure: 3.7 Demonstrate invoke.aspx and getCaptcha method description.

    Below are various executions of invoke.aspx, which demonstrates different types of CAPTCHA images.


    The complete Web service is provided with this article, so feel free to implement it and try it out. However, the method for generating the proxy class and assembly is in process.bat, which is convenient for those not using Visual Studio.NET for generating proxy classes. The process should look like this.

    Figure: example 3.9

    Below are the listings of process.bat, invoke.aspx, and captchaWebService.asmx. The code is equipped with self-explanatory comments.

    wsdl /l:cs /o:captchaWebService.cs http://localhost/captchawebservice/captchaWebService.asmx?WSDL /n:captchaWebService

     

    csc /out:captchaWebService.dll /t:library /r:system.web.dll,system.xml.dll,system.web.services.dll captchaWebService.cs

     

    Listing: Process.bat

    <%@ Page Language="c#" debug="True" %>

    <%@ Import namespace="captchaWebService" %>

    <script language="c#" runat="server">

     

    publicvoid Page_Load(System.Object sender,System.EventArgs e)

    {

    Page.Response.BinaryWrite(new captchaWebService().getCaptcha());

    }

    </script>

     

    Listing: invoke.aspx

    <%@ webservice class="captchaWebService" language="c#" %>

     

    using System;

    using System.Collections;

    using System.ComponentModel;

    using System.Data;

    using System.Diagnostics;

    using System.Web;

    using System.Web.Services;

    using System.IO;

    using System.Data.OleDb;

    using System.Drawing;

    using System.Drawing.Imaging;

     

    ///<summary>

    /// This is the basic Service for CAPTCHA provision.

    ///</summary>

    [WebService(Namespace="http://axisebusiness.com/webservices/")]

    publicclass captchaWebService : System.Web.Services.WebService

    {

    [WebMethod(Description="Returns a CAPTCHA Image in Base64-Encoding")]

    publicbyte[] getCaptcha()

    {

    return getBytesFromRaster(Server.MapPath(generateImage()));

    }

    // Returns byte from Image file

    publicbyte[] getBytesFromRaster(string filename)

    {

    if(File.Exists(filename))

    {

    try

    {

    FileStream s =File.OpenRead(filename);

    byte[] bytes = newbyte[s.Length];

    s.Read(bytes, (int)0, (int)s.Length);

    return bytes;

    }

    catch(Exception e)

    {

    returnnewbyte[0];

    }

    }

    else

    {

    returnnewbyte[0];

    }

    }

     

    [WebMethod(Description="Generates a CAPTCHA Image and returns filename")]

    public String generateImage ()

    {

    //Reading the parameter from session this time

    String strText = selectWord ();// = Session("param")

    //Create the memory map

    Bitmap raster;

    System.Drawing.Imaging.PixelFormat pixFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb;

    // Select an memory image from file of 290x80px

    // in the backgrounds folder named backX.jpg

    Graphics graphicsObject;

    System.Drawing.Image imageObject = System.Drawing.Image.FromFile(Server.MapPath(@"backgrounds\back" + new Random().Next(9) + ".jpg"));

    // Creating the raster image object

    raster = new Bitmap (imageObject);

    //Creating graphics object

    graphicsObject = Graphics.FromImage(raster);

     

    // Instantiate object of brush with black color

    SolidBrush objBrush = new SolidBrush(Color.Black);

     

    Font objFont;

    int a;

    String myFont, str;

     

    //Creating an array for most readable yet cryptic fonts for OCR's

    // This is entirely up to developer's discretion

    String[] crypticFonts = new String[11];

    crypticFonts [0] = "Arial";

    crypticFonts [1] = "Verdana";

    crypticFonts [2] = "Comic Sans MS";

    crypticFonts [3] = "Impact";

    crypticFonts [4] = "Haettenschweiler";

    crypticFonts [5] = "Lucida Sans Unicode";

    crypticFonts [6] = "Garamond";

    crypticFonts [7] = "Courier New";

    crypticFonts [8] = "Book Antiqua";

    crypticFonts [9] = "Arial Narrow";

    crypticFonts [10] = "Estrangelo Edessa";

     

    //Loop to write the characters on image

    // with different fonts.

    for (a=0; a<=strText.Length-1; a++)

    {

    myFont = crypticFonts[new Random().Next(a)];

    objFont = new Font(myFont, 20, FontStyle.Bold);

    str = strText.Substring(a, 1);

    graphicsObject.DrawString(str, objFont, objBrush, a*20, 35);

    graphicsObject.Flush();

    }

    String filename= new Random().Next().ToString() + ".gif";

    raster.Save(Server.MapPath(filename), System.Drawing.Imaging.ImageFormat.Gif);

    raster.Dispose();

    graphicsObject=null;

    return filename;

    } // End of Function

     

    //*************************************

    // Select word web method

    // Return type String of random word from dictionary

    // Dictionary is based on OGDEN's BASIC ENGLISH

    // http://ogden.basic-english.org/basiceng.html

     

    [WebMethod(Description="Get an Word from OGDEN's dictionary")]

    public String selectWord ()

    {

    // The Connection string referencing the MDB file

    String ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("dictionary.mdb") + ";";

    // Datareader object

    OleDbDataReader objReader;

    // Creating an array of 26 characters (alphabets in dictionary database as columns)

    char[] columns = newchar[26];

    // Adding the column names in the array

    // uses the ASCII character conversion for selecting values

    // from A- Z

    for (int a=65; a<65+26; a++)

    columns[a-65] = (char)a;

    // Query String for selecting a random column from spelling list database

    String QuerySQL = "SELECT " + columns[(new Random().Next(26))] + " FROM spellList";

    // Opening the connection

    OleDbConnection objConn = new OleDbConnection(ConnectionString);

    // Creating new command object

    OleDbCommand objCmd = new OleDbCommand();

    // Assigning command text

    objCmd.CommandText = QuerySQL;

    // Assigning the connection to command object connection attribute

    objCmd.Connection = objConn;

    // Instantiating a random class object

    Random randomSeed = new Random();

    // Creating a random seed selector

    int randomSeedSelector=0;

    // An string character with maximum capacity for dictionary column

    String[] selectedIndex = new String[700];

    String str = "";

    // This code segment opens the connection and read the dictionary

    try

    {

    objConn.Open();

    objReader = objCmd.ExecuteReader();

    while (objReader.Read())

    {

    str = objReader.GetValue(0).ToString();

    if (str.Length != 0)

    {

    selectedIndex[randomSeedSelector] =str;

    randomSeedSelector++;

    }

    }// Ends While

    str = selectedIndex[randomSeed.Next(randomSeedSelector)];

    } // Ends Try

    catch (Exception Err)

    {

    // The Error Catching operations

    }

    finally

    {

    objConn.Close();

    }

    // Returns the selected string

    return (str);

    }// ends web method

    } // Ends Class

    Listing: captchaWebService.asmx

    <-- Writing Your Own CAPTCHA Application   Conclusion -->

  • Supporting Products/Tools
    AspEncrypt
    Built around the Microsoft CryptoAPI, AspEncrypt helps you harness all major encryption and hashing algorithms such as DES, Triple-DES, RC2, RC4, RSA, MD5 and SHA1 in just a few lines of code. The component can be used in tandem with AspEmail to send encrypted and signed mail in the industry-standard S/MIME format, or with AspUpload to encrypt files as they are being uploaded. AspEncrypt can also be used to issue and manage X.509 digital certificates.
    [Top]
    AspPDF
    AspPDF is an ASP/ASP.NET component which enables generation and management of documents in PDF format. Features include advanced text formatting, font embedding, form fill-in, images, tables, content and page extraction, document stitching, encryption, digital signatures, and more.
    [Top]
    Other Articles
    Feb 3, 2005 - ASP.NET Mixed Mode Authentication
    In many web applications it is desirable for both intranet users and external parties to be able to seamlessly log onto the system. The problem this raises is that it is not easy to allow intranet users to log in via Windows integrated authentication while also allowing external parties to log in to the same application using standard forms authentication. This article will show you one way to achieve the best of both worlds when it comes to authentication.
    [Read This Article]  [Top]
    Dec 8, 2004 - Designing Role-Based Security Models for .NET
    In this article, Michele Leroux Bustamante discusses authentication, authorization and role-based security in .NET. Along the way, he provides some best practices for implementing role-based security in some typical .NET application scenarios including rich clients, Web applications, and Web services.
    [Read This Article]  [Top]
    May 11, 2004 - SharePoint Security and .NET Impersonation
    When implementing custom components that require access to restricted resources, implicit impersonation must be used. Jay Nathan shows how to create a class that makes using .NET Impersonation a snap.
    [Read This Article]  [Top]
    Mar 10, 2004 - Intellectual Property Protection and Code Obfuscation
    Learn about the execution process of CLR-based programs and how to protect your applications from being easily disassembled back into source code.
    [Read This Article]  [Top]
    Feb 24, 2004 - How to Send Secure Mail in ASP-Based E-Commerce Applications - Part II
    Businesses that utilize encrypted e-mail may find Secure Multipurpose Internet Mail Extensions (S/MIME) to be somewhat restrictive. This article shows how to use security features in PDF as an alternative to S/MIME.
    [Read This Article]  [Top]
    Feb 2, 2004 - Fighting Spambots with .NET and AI
    Bill Gates, in a recent interview, predicted the end of spam by 2006. One of the methods he mentioned involved a challenge only a real live person could handle. Adnan Masood shows how to use AI and .NET to create a user verification scheme that incorporates similar concepts Gates alluded to.
    [Read This Article]  [Top]
    Jan 21, 2004 - Configuring .NET Code Access Security
    Code Access Security (CAS) is the .NET Framework security model that grants code permission to resources based on "evidence" pertaining to the encapsulating assembly. In this article, David Myers examines CAS and explains different configuration methods.
    [Read This Article]  [Top]
    Mar 10, 2003 - Platform Neutral and Transparent Encryption of Sensitive Customer Information
    Zhenlei Cai combines an open source C++ encryption library with SQL Server extended stored procedures to create a platform neutral, transparent encryption solution that resides at the database layer.
    [Read This Article]  [Top]
    Jan 15, 2003 - Exploring Machine.Config - User Security and More
    Christopher Spann offers a .NET configuration tip that should help ease system administrators' fears of security compromise and thus assuage growing developer demand for a .NET environment.
    [Read This Article]  [Top]
    Dec 10, 2002 - Encrypting Cookie Data with ASP.NET
    You don't have to be a cryptography expert or spend lots of money on third-party components to secure sensitive data in .NET. In this article, Wayne Plourde shows just how easy it is to encrypt cookie data using encryption classes in the .NET System.Security.Cryptography namespace.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers