Membuat Anti Spam di ASP.net — 2

Tentang anti spam ini, pernah saya tulis disini. Tulisan ini hanya merupakan modifikasi dari tulisan pertama. Di tulisan sebelumnya, captcha image di generate di file webpage (aspx). Setelah membaca berbagai literatur, menggunakan file aspx hanya untuk membuat image kecil sangatlah tidak efisien dan memerlukan resource yang besar. Seperti kita ketahui, file aspx menggunakan webcontrol untuk menampilkan suatu page, sedangkan untuk menampilkan image catcha, webcontrol ini tidak diperlukan. Karena itu,  saya merubah metode menampilkan image captcha menggunakan file handler.

Untuk membuat capthca image atau antispam, tambahan file generic handler dan beri nama SpamHandler.ashx.
Kemudian tambahkan kode berikut:

<%@ WebHandler Language="VB" Class="SpamHandler" %>

Imports System
Imports System.Web
Imports System.Drawing.Text
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging

Public Class SpamHandler : Implements IHttpHandler, IRequiresSessionState
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim teks As String = GenerateRandomCode()
        HttpContext.Current.Session.Add("KODESPAM", teks)

        Dim width, height As Integer
        If String.IsNullOrEmpty(context.Request.QueryString("w")) Or _
        CInt(context.Request.QueryString("w")) < 0 Then
            width = 100
        Else
            width = CInt(context.Request.QueryString("w"))
        End If

        If String.IsNullOrEmpty(context.Request.QueryString("h")) Or _
        CInt(context.Request.QueryString("h")) < 0 Or _
        CInt(context.Request.QueryString("h")) >= CInt(context.Request.QueryString("w")) Then
            height = CInt(0.3 * width)
        Else
            height = CInt(context.Request.QueryString("h"))
        End If

        Dim bitmap As New Bitmap(width, height, PixelFormat.Format32bppPArgb)
        'buat bingkai
        Dim g As Graphics = Graphics.FromImage(bitmap)
        g.SmoothingMode = SmoothingMode.AntiAlias
        Dim r As Rectangle = New Rectangle(0, 0, width, height)

        'buat background
        Dim hb As HatchBrush = New HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White)
        g.FillRectangle(hb, r)

        'set teks font
        Dim size As SizeF
        Dim ukuranFont As Single = r.Height + 1
        Dim nmFont As Font
        'atur ukuran font agar tepat sesuai dg box image
        Do
            ukuranFont -= 1
            nmFont = New Font(System.Drawing.FontFamily.GenericSansSerif.Name, ukuranFont, FontStyle.Bold)
            size = g.MeasureString(teks, nmFont)
        Loop While size.Width > r.Width

        'format teks
        Dim format As StringFormat = New StringFormat()
        format.Alignment = StringAlignment.Center
        format.LineAlignment = StringAlignment.Center

        Dim path As GraphicsPath = New GraphicsPath()
        path.AddString(teks, nmFont.FontFamily, CType(nmFont.Style, Integer), nmFont.Size, r, format)

        'gambar teks
        hb = New HatchBrush(HatchStyle.ZigZag, Color.LightGray, Color.Blue)
        g.FillPath(hb, path)

        'bintik2 acak
        Dim acak As New Random()
        Dim m As Integer = Math.Max(r.Width, r.Height)
        For i As Integer = 0 To (r.Width * r.Height / 30.0F)
            Dim x As Integer = acak.Next(r.Width)
            Dim y As Integer = acak.Next(r.Height)
            Dim w As Integer = acak.Next(m / 50)
            Dim h As Integer = acak.Next(m / 50)
            g.FillEllipse(hb, x, y, w, h)
        Next
        nmFont.Dispose()
        hb.Dispose()
        g.Dispose()

        context.Response.Clear()
        context.Response.ContentType = "image/jpeg"
        bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg)
        bitmap.Dispose()
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Private Function GenerateRandomCode() As String
        Dim builder As New StringBuilder()
        Dim random As New Random()
        Dim ch As Char
        Dim i As Integer
        For i = 0 To 5
            ch = Convert.ToChar(Convert.ToInt32((9 * random.NextDouble() + 48)))
            builder.Append(ch)
        Next
        'HttpContext.Current.Session.Add("KODESPAM", builder.ToString())
        Return builder.ToString()
    End Function
End Class

Gunakan file handler ini di imagewebcontrol. dan set property ImageUrl

Image1.ImageUrl = "spamhandler.ashx"

Untuk menentukan panjang dan lebar dari image yang kita buat, bisa ditambahkan parameter w (width) dan h (height)

Image1.ImageUrl = "spamhandler.ashx?w=200&h=50"

Tambahan file webpage

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>DEMO ANTI SPAM</h2>
        Nama : &nbsp;
        <asp:TextBox ID="tbNama" runat="server" Width="200px"></asp:TextBox><br />
        <br />
        <asp:Image ID="Image1" runat="server" Visible="false" /><br />
        Masukkan kode diatas : &nbsp;
        <asp:TextBox ID="tbKodeSpam" runat="server" Width="150px"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Submit" Width="100px" /><br />
        <br />
        <asp:Label ID="result" runat="server" Font-Bold="True"></asp:Label>
    </div>
    </form>
</body>
</html>

code behind:

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            result.Text = ""
            Image1.Visible = True
            Image1.ImageUrl = "spamhandler.ashx?w=200&h=50"
        End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        If tbKodeSpam.Text = Session("KODESPAM").ToString() Then
            result.Text = "Selamat datang " & tbNama.Text & ", anda benar-benar manusia"
            Session.Remove("KODESPAM")
            Image1.Visible = False
        Else
            result.Text = tbNama.Text & ", apakah anda makhluk halus? Silahkan masukkan lagi kodenya"
        End If
    End Sub
End Class

Semoga bermanfaat
Happy coding

Download Sample

About Yuniar

Penulis sekarang lebih banyak bekerja menggunakan teknologi Microsoft .NET secara umum dan TIDAK lagi menggunakan aplikasi MapXtreme.net dari MapInfo. Karena itu mohon maaf, jika pertanyaan-pertanyaan mengenai MapXtreme sudah tidak bisa saya jawab lagi.

Posted on 17 Januari 2010, in ASP.net and tagged , , , . Bookmark the permalink. 6 Komentar.

  1. gan knp keluar gini yah

    Server Error in ‘/’ Application.

    The length of the query string for this request exceeds the configured maxQueryStringLength value.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: The length of the query string for this request exceeds the configured maxQueryStringLength value.

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

  2. sori bos.. OOT nie…

    aplikasi saya error dengan pesannya :

    The type ‘System.Web.UI.UpdatePanel’ is ambiguous: it could come from assembly ‘E:\SAMPEL\FINAL\App_Gas\bin\System.Web.Extensions.DLL’ or from assembly ‘C:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0__31bf3856ad364e35\System.Web.Extensions.dll’. Please specify the assembly explicitly in the type name.

    gimana ya benerinnya ?

    thanks b4🙂

  3. palingan query insert into doang gan ane pake’a…… emang ngaruh yak query buat masukin data sama captcha’a??

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: