Add Captcha to BlogEngine.Net

by Alpha 27. August 2009 23:35

Chinese Version is Here.

This is English version.I hope you can understand me.

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

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

Image.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
public partial class Image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateCheckCodeImage(GenCode(4));
    }
   
    private string GenCode(int num)
    {        
        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" };
        string code = "";
        Random rd = new Random();
        int i;
        for (i = 0; i < num; i++)
        {
            code += source[rd.Next(0, source.Length)];            
        }
        return code;

    }

    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode.Trim() == "" || checkCode == null)
            return;
        Session["AlphaCaptchaCode"] = checkCode; 
        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)(checkCode.Length * 19), 22);
        Graphics g = Graphics.FromImage(image);
        try
        {
           
            Random random = new Random();

            g.Clear(Color.White);

            int i;
            for (i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold));
            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);
            g.DrawString(checkCode, font, brush, 4, 1);

            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/jpg";
            Response.BinaryWrite(ms.ToArray());

        }
        catch
        {
            g.Dispose();
            image.Dispose();
        }

    }
}

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.

<label for="<%=txtCaptcha.ClientID %>">Captcha*</label>
      <img src="/Image.aspx" alt="Click to change captcha" style="width: 82px; height: 23px" onclick="this.src=RefreshCaptcha(this.src)" />
      <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)

<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.

<script type="text/javascript">
    
        function DoCheckCaptcha() {
            var code = document.getElementById("<%=txtCaptcha.ClientID %>").value;
            checkCaptcha(code);
        }
        var checkCaptchaResult=false;
        function ReceiveServerData(CheckResult) {
            document.getElementById("CaptchaMsg").innerHTML = "";
            if (CheckResult == 1) {
                checkCaptchaResult = true;
                document.getElementById("CaptchaMsg").innerHTML = "<font color=green>Captcha OK</font>";
            }
            else if (CheckResult == -1) {
                checkCaptchaResult = false;
                //document.getElementById("CaptchaMsg").innerHTML = "<font color=red>Captcha Error</font>";
            }
            else {
                checkCaptchaResult = false;
                document.getElementById("CaptchaMsg").innerHTML = "<font color=red>Captcha Error</font>";
            }
        }
        function RefreshCaptcha(url) {
            if (url.toString().indexOf("?",0) > 0) {
                url = url.toString().substring(0, url.toString().indexOf("?", 0)) + "?" + new Date().toUTCString();
            }
            else{
                url = url.toString() + "?" + new Date().toUTCString();
            }
            return url;
            
        }
    </script>

3.Modify the file named CommentView.ascx.cs

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

      if (eventArgument.Length < 1)
        {
            _Callback = "-1";
            return;
        }
        if (eventArgument.LastIndexOf("-|-") < 0)
        {
            string img = Session["AlphaCaptchaCode"].ToString().ToLower(); ;
            if (eventArgument.ToLower().Equals(img))
            {
                _Callback = "1";
            }
            else
            {
                _Callback = "0";
            }            
            return;
        }

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

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

 

This ALL.

Tags: Views:2521

BlogEngine.NET

Comments

8/28/2009 8:40:03 AM #

lioz

吴老师,下学期学校里开始要用那个闪讯了,您能为全校上万的学生做下实惠点的事情,破解那个闪讯吗?用路由寝室人一起上网还是很经济的

lioz People's Republic of China | Reply

8/29/2009 4:22:04 PM #

Alpha

闪讯?没有听说过这个东东,电信推出来的?估计不好破解吧。

Alpha People's Republic of China | Reply

9/3/2009 2:53:32 PM #

celiker bahceci

I use it, step-step. But it is working when write anything to txtCaptcha.
What is the problem ?

checkCaptcha JS function is in page. But it is dont check Smile
it is only working like a RequiredFieldValidator.

What is the problem mann?

celiker bahceci Turkey | Reply

11/11/2009 5:30:49 PM #

Nick

Same problem here. Did you already fix?

Nick Netherlands | Reply

11/12/2009 9:59:09 PM #

Alpha

It Work with 1.5.0.7.I didn't test it on other version.Update your blog to the version and try it again.

Good luck.

Alpha People's Republic of China | Reply

11/15/2009 5:11:01 PM #

Alpha

Sorry.I forget a important condition. Now I have updated the post.You can follow it step by step.

Alpha People's Republic of China | Reply

9/15/2009 8:44:07 AM #

payday online

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.Any way Ill be subscribing to your feed and I hope you post again soon

payday online United States | Reply

9/16/2009 5:53:12 PM #

payday loans

Easy option to get useful information as well as share good stuff with good ideas and concepts

payday loans United States | Reply

9/25/2009 11:07:28 PM #

SANJAY

TEST

SANJAY United States | Reply

10/19/2009 3:58:59 AM #

Yağız Gönüler

error line: Session["AlphaCaptchaCode"] = checkCode;

enableSessionState error..

why?

Yağız Gönüler Turkey | Reply

10/19/2009 7:40:42 PM #

kliszaq

Add the EnableSessionState="True" to the page directive of the Image.aspx like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CaptchaImage.aspx.cs" Inherits="CaptchaImage" EnableSessionState="True"%>

kliszaq Poland | Reply

11/26/2009 9:00:41 AM #

test

test

test United States | Reply

11/26/2009 9:02:09 AM #

nipun

I tried it and after the save comment it just hangs...nothing happens!..pl help!

nipun United States | Reply

11/26/2009 11:31:51 AM #

Alpha

Are you use it step by step? "2.2" is important step.

Alpha People's Republic of China | Reply

11/28/2009 12:26:12 PM #

nipun

yea..but still..it just works as a req field validator..

nipun United States | Reply

11/28/2009 12:59:07 PM #

nipun

I think the blogengine does not support ajax, cuz my save button is btnSave. not btnSaveAjax..could that be, if yes..then is there any solution?..any help will be greatly appreciated

nipun | Reply

11/28/2009 1:04:39 PM #

Alpha

Update your Blog to 1.5.And try it again.

Alpha People's Republic of China | Reply

11/30/2009 10:28:35 PM #

nipun

Hey..its working..thanks a lot!...great post!

nipun | Reply

11/30/2009 11:56:21 PM #

Alpha

^_^.

Alpha People's Republic of China | Reply

12/22/2009 8:15:40 PM #

Cézar Velázquez

Hello Alpha

Can I make a question?The captcha image is not generate in my tests,maybe some need configuration are missing?or some blogengine configuration are wrong?

thank´s by attention!

Cézar Velázquez Brazil | Reply

12/23/2009 1:01:23 PM #

Alpha

Hi.
Can you get the image when visit http://cezarvelazquez.com.br/image.aspx
If not,modified web.config. Change EnableSessionState="True" in the page section.

Alpha People's Republic of China | Reply

1/22/2010 6:35:31 AM #

Peter

Hi,
I have the same Problem: when loading there is no captcha image. I have the newest version of BlogEngine, EnableSessionState="True" in the page and controled all the coding twice.
Do you have any idea?
So long - Peter

Peter Germany | Reply

1/23/2010 1:07:10 AM #

Peter

Sorry, but I cant get a captcha image. Even with the image from the link above it will give me no image.
Has anybody a tip for me?

Peter Germany | Reply

1/24/2010 11:27:16 PM #

Alpha

comment Session["AlphaCaptchaCode"] = checkCode; then visit the image.aspx in browser.

Alpha People's Republic of China | Reply

1/25/2010 12:19:50 AM #

Peter

Thanks for reply, but could you please give me a little bit more help, because I'm programming in VB.NET and still not so experienced:
Do I have to insert 'comment Session["AlphaCaptchaCode"] = checkCode;' in one of the programms you completed? And when I have then to visit image.aspx in browser?

Peter Germany | Reply

1/26/2010 1:11:51 PM #

Alpha

Add "//" before Session["AlphaCaptchaCode"] = checkCode;.
Like this:
//Session["AlphaCaptchaCode"] = checkCode;

And visit image.aspx in browser.

Alpha People's Republic of China | Reply

1/26/2010 9:15:48 PM #

Peter

When I do so, there is an error in this sense:
The XML-Page (XML-input) can't be viewed when stylesheet is used.
When I look at the generated browser-sourcecode, there are lots of cryptic characters.

Peter Germany | Reply

1/20/2010 12:09:27 AM #

trackback

How to Block Spam Comments in BlogEngine.NET

How to Block Spam Comments in BlogEngine.NET

Code Capers | Reply

1/26/2010 1:29:41 PM #

SUN ENERGY

I like this blog. interesting and useful for me. I am so increased knowledge.thanks and godbless

SUN ENERGY United States | Reply

1/27/2010 11:14:21 AM #

Bryian Tan

Thanks for this great post. Just a few notes:

1) if you don't see the image, check the image src. In my case, I use absolute link to the image.aspx

&lt;img src="http://blog.ysatech.com/Image.aspx" alt="Click to change captcha" style="width: 82px; height: 23px" onclick="this.src=RefreshCaptcha(this.src)" />

2) make sure you have BlogEngine.addComment() in the btnSaveAjax instead of Addcomment()

3) make sure to set checkCaptchaResult = false; after BlogEngine.addComment() to prevent user from constantly hitting the button with the save captcha image.

Thanks,
Bryian Tan

Bryian Tan United States | Reply

1/27/2010 11:14:54 AM #

Bryian Tan

here is the second post because checkCaptchaResult = true

Bryian Tan United States | Reply

1/27/2010 10:10:54 PM #

Peter

Thanks Alpha and thanks Bryian!
With the complete URL for the Image.aspx (Bryian top 1 )it works now and I get the image.

Peter Germany | Reply

1/30/2010 9:51:22 AM #

sikat ang pinoy

I like blogengine.net powered by asp.net because this is the free technology that i can create modern website for my personal use or for business use. I would like to thank you for sharing your thoughts and time into the stuff you post!! Thumbs up!

sikat ang pinoy United States | Reply

2/1/2010 9:12:26 AM #

pabx panasonic

very nice thank's Smile

pabx panasonic Indonesia | Reply

2/2/2010 3:38:41 AM #

Acai

Captcha works well, thanks.

Acai United Kingdom | Reply

3/1/2010 8:14:00 AM #

Watch Pacquiao Vs Clottey Live

your blog is very imformative and i learn a lot from it.
Thanks for sharing.

regards,

rosela

Watch Pacquiao Vs Clottey Live United States | Reply

3/1/2010 8:14:20 AM #

Webthesurfi Rugs Webdesign

very entertaining and informative blog. Ill be back..

Webthesurfi Rugs Webdesign United States | Reply

3/4/2010 3:19:16 AM #

trackback

给BlogEngine.Net添加上验证码

给BlogEngine.Net添加上验证码

神秘园 CaBeta.com | Reply

Add comment




  Country flag

看不清?点击图片看看
biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen  浙ICP备09023819号  

关于作者

Alpha

1.男
2.已婚
3.网虫
4.宝宝叫yoyo

Calendar

<<  March 2010  >>
MondayTuesdayWednesdayThursdayFridaySaturdaySunday
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

RecentComments

Comment RSS