Add Captcha to BlogEngine.Net to kill SPAM comments

by ambarreira 14. março 2010 00:00

Add Captcha to BlogEngine.Net to kill SPAM comments
This is English version.
The Captcha support ajax.


(0) Modified web.config. Change EnableSessionState="True" in the page section.

(1) Add a new file to the site root directory. The file is named Image.aspx and the code file is Image.aspx.cs.

This is the code.

Image.aspx

01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Image.aspx.cs" Inherits="Image" %>

Image.aspx.cs

01.using System;
02.using System.Data;
03.using System.Configuration;
04.using System.Collections;
05.using System.Web;
06.using System.Web.Security;
07.using System.Web.UI;
08.using System.Web.UI.WebControls;
09.using System.Web.UI.WebControls.WebParts;
10.using System.Web.UI.HtmlControls;
11.using System.Drawing;
12.using System.Drawing.Drawing2D;
13.public partial class Image : System.Web.UI.Page
14.{
15.    protected void Page_Load(object sender, EventArgs e)
16.    {
17.        CreateCheckCodeImage(GenCode(4));
18.    }
19.   
20.    private string GenCode(int num)
21.    {      
22.        string[] source ={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "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" };
23.        string code = "";
24.        Random rd = new Random();
25.        int i;
26.        for (i = 0; i < num; i++)
27.        {
28.            code += source[rd.Next(0, source.Length)];          
29.        }
30.        return code;
31.
32.    }
33.
34.    private void CreateCheckCodeImage(string checkCode)
35.    {
36.        if (checkCode.Trim() == "" || checkCode == null)
37.            return;
38.        Session["AlphaCaptchaCode"] = checkCode;
39.        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)(checkCode.Length * 19), 22);
40.        Graphics g = Graphics.FromImage(image);
41.        try
42.        {
43.           
44.            Random random = new Random();
45.
46.            g.Clear(Color.White);
47.
48.            int i;
49.            for (i = 0; i < 25; i++)
50.            {
51.                int x1 = random.Next(image.Width);
52.                int x2 = random.Next(image.Width);
53.                int y1 = random.Next(image.Height);
54.                int y2 = random.Next(image.Height);
55.                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
56.            }
57.
58.            Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold));
59.            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);
60.            g.DrawString(checkCode, font, brush, 4, 1);
61.
62.            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
63.            System.IO.MemoryStream ms = new System.IO.MemoryStream();
64.            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
65.            Response.ClearContent();
66.            Response.ContentType = "image/jpg";
67.            Response.BinaryWrite(ms.ToArray());
68.
69.        }
70.        catch
71.        {
72.            g.Dispose();
73.            image.Dispose();
74.        }
75.
76.    }
77.}

(2) Modify the CommentView.ascx

(2.1) On the top of the line’<span class="bbcode" title="BBCode tags"><%=BBCodes() %></span>’.Add the code of below.
ATTENCION: in src="/Image.aspx" you need use absolute link, src="http://blog.ambarreira.com/Image.aspx"

01.<label for="<%=txtCaptcha.ClientID %>">Captcha*</label>
02.      <img src="/Image.aspx" alt="Click to change captcha" style="width: 82px; height: 23px" onclick="this.src=RefreshCaptcha(this.src)" />
03.      <asp:TextBox runat="Server" ID="txtCaptcha" TabIndex="4" MaxLength="4" Width="60px" onblur="DoCheckCaptcha()"/><span id="CaptchaMsg"></span><asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtCaptcha" ErrorMessage="<%$Resources:labels, required %>" Display="dynamic" ValidationGroup="AddComment" /><br />


(2.2) Add Checker to the button Save. Change the save button code to this:(This is IMPORTANT)

01.<input type="button" id="btnSaveAjax" value="<%=Resources.labels.saveComment %>" onclick="if(Page_ClientValidate('AddComment')&&checkCaptchaResult){AddComment()}" tabindex="7" />

(2.3) On the top of the line’<asp:label runat="server" id="lbCommentsDisabled" visible="false"><%=Resources.labels.commentsAreClosed %></asp:label>’,Add the code of below.

01.<script type="text/javascript">
02.    
03.        function DoCheckCaptcha() {
04.            var code = document.getElementById("<%=txtCaptcha.ClientID %>").value;
05.            checkCaptcha(code);
06.        }
07.        var checkCaptchaResult=false;
08.        function ReceiveServerData(CheckResult) {
09.            document.getElementById("CaptchaMsg").innerHTML = "";
10.            if (CheckResult == 1) {
11.                checkCaptchaResult = true;
12.                document.getElementById("CaptchaMsg").innerHTML = "<font color=green>Captcha OK</font>";
13.            }
14.            else if (CheckResult == -1) {
15.                checkCaptchaResult = false;
16.                //document.getElementById("CaptchaMsg").innerHTML = "<font color=red>Captcha Error</font>";
17.            }
18.            else {
19.                checkCaptchaResult = false;
20.                document.getElementById("CaptchaMsg").innerHTML = "<font color=red>Captcha Error</font>";
21.            }
22.        }
23.        function RefreshCaptcha(url) {
24.            if (url.toString().indexOf("?",0) > 0) {
25.                url = url.toString().substring(0, url.toString().indexOf("?", 0)) + "?" + new Date().toUTCString();
26.            }
27.            else{
28.                url = url.toString() + "?" + new Date().toUTCString();
29.            }
30.            return url;
31.            
32.        }
33.    </script>


(3) Modify the file named CommentView.ascx.cs

(3.1) In the function RaiseCallbackEvent,Add the below on the top of the function.

01.if (eventArgument.Length < 1)
02.  {
03.      _Callback = "-1";
04.      return;
05.  }
06.  if (eventArgument.LastIndexOf("-|-") < 0)
07.  {
08.      string img = Session["AlphaCaptchaCode"].ToString().ToLower(); ;
09.      if (eventArgument.ToLower().Equals(img))
10.      {
11.          _Callback = "1";
12.      }
13.      else
14.      {
15.          _Callback = "0";
16.      }          
17.      return;
18.  }


(3.2) In the function Page_Load,Add the below code on the bottom of the line’//InititializeCaptcha();’.

01.string cbReference = Page.ClientScript.GetCallbackEventReference(this, "CheckResult", "ReceiveServerData", "");
02.string callbackScript = "function checkCaptcha(CheckResult){" + cbReference + ";}";                                    
03.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "checkCaptcha", callbackScript, true);


That's it!!! Cool

FONTE

Tags: , , , ,

C#ASP.NET | HTML | Info | Internet | JavaScript | Microsoft

Expression Studio 3

by ambarreira 3. novembro 2009 00:00

If you think and design visually, Expression Studio is a perfect tool to enable you to create compelling, impactful and expressive designs for the desktop and the web. The visually rich technologies in Silverlight and .NET offer amazing possibilities to bring your creative ideas to life using a range of design tools purpose built for the task.

Expression Web

Expression Web makes creating compliant standards-based Web sites faster and easier. With a state-of-the-art design surface that generates clean CSS, you can make design decisions on the fly, knowing that you're seeing a faithful representation of the final browser-rendered page.

Expression Blend

Expression Blend™ is the tool for interaction design on the Silverlight and .NET platforms and enables user experience concepts to be delivered with full fidelity, from the initial prototype to the completed project.

SketchFlow

SketchFlow prototypes are fast, easy and inexpensive to build, making it possible to create, explore and compare multiple ideas before moving forward with a solution.

Expression Design

Expression Design is a professional design tool for creating graphics content that can be used within the authoring applications in Expression Studio: Expression Blend and Expression Web.

Expression Encoder 3

Expression Encoder 3 provides the power of industry leading encoding, in a simple approachable interface to make it easy to prepare video for use in a variety of ways, including Silverlight on the Web.

To more info,
http://www.microsoft.com/expression/Default.aspx

Tags: ,

Microsoft | Tecnologia

Lançamento do Microsoft Windows 7

by ambarreira 22. outubro 2009 00:00

O novo Windows 7, que tem hoje lançamento oficial em todo o mundo!

Todos os computadores com menos de 3 anos suportam o Windows 7, que traz vantagens de facilidade de utilização e melhor desempenho, para além de garantir uma gestão mais eficiente da bateria nos portáteis, características que certamente agradarão aos utilizadores.

Nas versões já à venda os preços de lançamento para o Windows Home Premium 219,99 euros, o Professional 349,99 e o Ultimate 364,99 euros. Os upgrades custam 134,99€, 324,99€ e 339,99€, respectivamente.

Descubram todas as novidades deste novo Sistema Operativo em,

http://windows.microsoft.com/pt-PT/windows/discover

Divirtam-se,
Cool

Tags: ,

Microsoft | Tecnologia

Visual Studio 2010 and Framework 4.0 BETA 2

by ambarreira 13. outubro 2009 00:00

Já está disponivel para download. Já se pode começar a testar as novas funcionalidades quer do VS2010, quer da nova Framework 4.0 da Microsoft.

Mais infos em:
http://msdn.microsoft.com/en-us/vstudio/default.aspx

Download em:
http://msdn.microsoft.com/pt-pt/vstudio/dd582936%28en-us%29.aspx

Video Turturial(Downloading and Installing Visual Studio 2010 Beta 2):
http://channel9.msdn.com/shows/10-4/10-4-Episode-33-Downloading-and-Installing-Visual-Studio-2010-Beta-2/

Divirtam-se,
AlexLaughing

Tags: ,

C#ASP.NET | Microsoft

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen