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

How To Make Directory In ASP.NET?

by ambarreira 1. março 2010 00:00

Is very simple create(make) directory in ASP.NET!
Try this simple code,

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string NewDir = Server.MapPath("New Folder");
        // Call function for creating a directory
        MakeDirectoryIfExists(NewDir);
    }
 
    private void MakeDirectoryIfExists(string NewDirectory)
    {
        try
        {
            // Check if directory exists
            if (!Directory.Exists(NewDirectory))
            {
                // Create the directory.
                Directory.CreateDirectory(NewDirectory);
            }
        }
        catch (IOException _ex)
        {
            Response.Write(_ex.Message);
        }
    }

}

Tags:

C#ASP.NET

How to create a "Processing" modal window using UpdateProgress and ModalPopup ASP.net AJAX controls - Português

by ambarreira 7. janeiro 2010 00:00

//Incluir as referencias ASP.net AJAX controls
// do AJAX e Toolkit

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

// Incluir ScriptManager tag na página (.aspx, .ascx, etc)

<asp:ScriptManager ID="ScriptManager1" runat="server" />

// Incluir UpdateProgress Control dentro de Panel Control 
// e da ModalPopupExtender Control

<asp:Panel ID="panelUpdateProgress" runat="server" CssClass="updateProgress">
    <asp:UpdateProgress ID="UpdateProg1" DisplayAfter="0" runat="server">
      <ProgressTemplate>
        <div style="position: relative; top: 30%; text-align: center;">
          <img src="loading.gif" style="vertical-align: middle" alt="Processing" />
          Processing ...
        </div>
      </ProgressTemplate>
    </asp:UpdateProgress>
  </asp:Panel>

<ajaxToolkit:ModalPopupExtender ID="ModalProgress" runat="server" TargetControlID="panelUpdateProgress" BackgroundCssClass="modalBackground" PopupControlID="panelUpdateProgress" />

São necessárias duas fuções javascript para executar os pedidos do  AJAX.

//JavaScript code que pode ser incluido em jsUpdateProgress.js
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginReq);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endReq);   
function beginReq(sender, args){
    // shows the Popup
    $find(ModalProgress).show();       
}
function endReq(sender, args) {
    //  shows the Popup
    $find(ModalProgress).hide();
}

Nas páginas asp.net deve ser clocado na head o seguinte código, para que seja incluido o javascript,

<script type="text/javascript" language="javascript">
      var ModalProgress ='<%= ModalProgress.ClientID %>';        
</script>
<script type="text/javascript" src="jsUpdateProgress.js"></script>

Pode ser colocado um estilo para que tudo fique mais bonito,

.modalBackground
{
    background-color: Gray;
    filter: alpha(opacity=50);
    opacity: 0.50;
}
.updateProgress
{
    border-width: 1px;
    border-style: solid;
    background-color: #FFFFFF;
    position: absolute;
    width: 180px;
    height: 65px;
}

POST ORIGINAL (Espanhol)

POST ORIGINAL (Inglês)

Código Fonte (C#, VB):
http://weblogs.asp.net/blogs/guillermo/Code/modalExample.zip

TeclaHost post:
http://forum.teclahost.com/index.php?topic=216.msg242#msg242

Espero que seja útil e que ajude muita gente,
Alex

Tags: , ,

C#ASP.NET | JavaScript | AJAX

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

Page Rank - Verificar o Page Rank do meu site.

by ambarreira 11. outubro 2009 00:00

Boas, hoje criei um Google Page Rank,

http://pagerank.ambarreira.com

PageRank™ é uma família de algoritmos de análise de rede que dá pesos numéricos a cada elemento de uma coleção de documentos hiperligados, como as páginas da Internet, com o propósito de medir a sua importância nesse grupo por meio de um motor de busca. O algoritmo pode ser aplicado a qualquer coleção de objetos com ligações recíprocas e referências. O peso numérico dado a cada elemento E é chamado PageRank de E e notado como PR(E).

Suas propriedades são muito discutidas por especialistas em optimização dos motores de busca (SEO, sigla em inglês para search engine optimization).

O processo do PageRank™ foi patenteado pela Universidade de Stanford nos Estados Unidos da América sob o número 6.285.999. Somente o nome PageRank™ é uma marca registada Google. do

By Wiki

 

Desenvolvido em asp.net C#.
Versão 1.0


Laughing

Tags: , ,

Internet | Tecnologia | C#ASP.NET

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen