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:5486

BlogEngine.NET

Comments

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

lioz

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

lioz People's Republic of China |

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

Alpha

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

Alpha People's Republic of China |

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 |

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

Nick

Same problem here. Did you already fix?

Nick Netherlands |

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 |

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 |

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 |

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 |

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

SANJAY

TEST

SANJAY United States |

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 |

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 |

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

test

test

test United States |

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 |

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 |

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

nipun

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

nipun United States |

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 |

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

Alpha

Update your Blog to 1.5.And try it again.

Alpha People's Republic of China |

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

nipun

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

nipun |

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

Alpha

^_^.

Alpha People's Republic of China |

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 |

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 |

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 |

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 |

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 |

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 |

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 |

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 |

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 |

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 |

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 |

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

Bryian Tan

here is the second post because checkCaptchaResult = true

Bryian Tan United States |

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 |

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 |

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

pabx panasonic

very nice thank's Smile

pabx panasonic Indonesia |

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

Acai

Captcha works well, thanks.

Acai United Kingdom |

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 |

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

Webthesurfi Rugs Webdesign

very entertaining and informative blog. Ill be back..

Webthesurfi Rugs Webdesign United States |

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

trackback

给BlogEngine.Net添加上验证码

给BlogEngine.Net添加上验证码

神秘园 CaBeta.com |

3/14/2010 2:00:40 AM #

hospedagem de sites

I cant get a captcha image.
Has anybody a tip for me?

hospedagem de sites Brazil |

3/21/2010 1:39:14 AM #

pabx panasonic

very nice thank's Smile

pabx panasonic Indonesia |

4/2/2010 11:47:59 PM #

best fake tan

Great post, ive subscribed Smile

Regards

best fake tan United Kingdom |

4/4/2010 1:26:59 PM #

GPS FOR TRUCKS

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.

GPS FOR TRUCKS United States |

4/5/2010 3:18:13 AM #

How to make your boobs bigger

Thanks for the info

How to make your boobs bigger Egypt |

4/6/2010 9:53:21 PM #

Ecommerce Calabasas

It’s a great method for backlinks which are soooo important! Let me know what terms you are trying to get in the search engines for and I can also take a look at your site and your code and see if there’s something else you would want to do to better your chances! I’d love to help …

Ecommerce Calabasas United States |

4/10/2010 9:05:29 AM #

Maksimys23

Thanks for you information.

Maksimys23 Russia |

4/11/2010 3:08:05 PM #

Gadgets Article

hi, i am here again. waiting for the next post. I wanted to post a comment and say I like what you're sayin'! You've got some good ideas and while I don't dislike everything you've said I think you make a strong case. Keep up the good work 'cus I'll be checkin' up on you later. You're on my radar now and I'm interested to see where things go.

Gadgets Article United States |

4/17/2010 8:13:11 PM #

trackback

BlogEngine.NET Setup and Customization Adventures

BlogEngine.NET Setup and Customization Adventures

Incremental Coding |

4/18/2010 4:17:53 PM #

free vector

nice info. letz go to download free vector

free vector United States |

4/25/2010 8:43:15 PM #

anna sui perfume

For some reason your blog does not render properly in Firefox 3.0.7

anna sui perfume United Kingdom |

4/27/2010 4:42:38 PM #

evolv water

Nice implementation. I would be more glad if you give an example or specific data. But rather nice work! Good job!

evolv water United States |

4/28/2010 4:42:04 PM #

Yachtcharter Griechenland

Wow, I never knew that Add Captcha to BlogEngine.Net. That's pretty interesting...

Yachtcharter Griechenland Germany |

5/1/2010 11:22:33 AM #

evolv

Excellent idea and concept. Absolutely a noble post. Looking forward to see more of your post soon. Keep it up!

evolv United States |

5/6/2010 2:44:02 AM #

active wear

The final things you need to do are to restart the Office Communicator Front End service and on the client machine then log out and then log back in.

active wear United Kingdom |

5/6/2010 8:08:05 PM #

banjarmasin

thanks about your post. very gud.

banjarmasin Indonesia |

5/7/2010 3:09:23 AM #

Skincare

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

Skincare United Kingdom |

5/8/2010 4:11:53 AM #

Portable GPS Navigator

thanks for sharing the information

Portable GPS Navigator United States |

5/15/2010 5:56:33 PM #

backbraces

I need to extend security in BE just a little. I need to make a user registration form and disable comments for non-registered users. Has anyone done this? What difficulties might arise?

backbraces United Kingdom |

5/20/2010 5:59:42 AM #

garmin nuvi

Thanks for the great advice.

garmin nuvi United States |

5/20/2010 7:56:12 PM #

Indonesia Furniture Handicraft Wholesale Marketplace

Your post really cool. I glad to be here. I enjoyed reading your articles and if allowed I want to bookmark your posts.

regards

Indonesia Furniture Handicraft Wholesale Marketplace United States |

5/20/2010 7:56:49 PM #

Sport Supplement

hi buddy, I like this page. I have read it carefully and wow really awesome.

Sport Supplement United States |

5/20/2010 11:36:04 PM #

How to Make Your Breasts Bigger

Thanks for taking time to share this information

How to Make Your Breasts Bigger Egypt |

5/22/2010 12:59:36 PM #

kronkTonic

I spend more time in reading some of your posts and honestly speaking I gain some knowledge from it. Very informative.

kronkTonic Republic of the Philippines |

5/24/2010 9:02:21 PM #

meranti batu decking

Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.

meranti batu decking United States |

5/24/2010 9:42:45 PM #

trackback

Adding CAPTCHA to BlogEngine.NET, aka I hate spam.

Adding CAPTCHA to BlogEngine.NET, aka I hate spam.

David Sandor |

6/6/2010 12:58:34 AM #

health tips

thanks for this info

health tips United States |

6/6/2010 12:59:12 AM #

agnes diana

this is what is was looking for, thanks!

agnes diana United States |

6/6/2010 4:17:08 PM #

Cover Duvet

Well, this is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

Cover Duvet United States |

6/9/2010 11:06:45 PM #

cheap used cars

Thank you for your sharing

cheap used cars Turkey |

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

关于作者

Alpha

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

Calendar

<<  September 2010  >>
MondayTuesdayWednesdayThursdayFridaySaturdaySunday
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

RecentComments

Comment RSS