Captcha validation and Twitter Notification

by Mark Nijhof, in Twitter FubuMVC.Validation FubuMVC | Sunday, March 29, 2009 | 16 comments
Captcha and Twitter As you all know my blog is a huge work in progress project, I mean; just to be able to post this post I had to copy the text into an insert statement, generate some GUID’s, find my user id and put it all together. Needless to say is that my next addition will be adding the ability to manage blog posts without using SQL.

But for now I like to introduce two new features on my blog, I have already covered validation of user input in my previous post, what I have added since then is Captcha validation and Twitter notification.

Captcha validation

Maybe you had noticed but after some successful blog post some spammers found it fun to start flooding my posts with span comments. I was deleting on average 20 span comments a day. I was of course flattered by the attention, but it became a bit annoying. I figured to start with something simple and see how effective it was and came up with validation that requires some logic; simple calculations like adding and subtracting numbers. I created a question generator that would output questions like “3 + 5” or “5 - 7” it could also be a bit more challenging like “30 / 6 + 5 * 3 - 8” but I want comments so I kept it simple. After that I needed a way to validate the provided answer against the question, and at first I thought about splitting the string (because MVC is stateless I send the question along with the request), but then I remembered my early days in ASP using Jscript (Yes you see this right, no .Net extension to the name). There I remembered the powerful to easily misused function “eval” which evaluates Jscript code and executes it. Sort of your mini compiler, so I could pass in a text string “3 + 5 == 8” and the “eval” method would return “true” and “5 - 7 == -1” would return false. Now C# does not have the “eval” functionality (yet it is coming back in C# 4.0) so why is this interesting you ask? Because it is still available in Microsoft.Jscript library and this can be used from within your C# project. Currently the code looks like this:

    1 namespace FubuMVC.Validation.Captcha
    2 {
    3     public class CaptchaEvaluator
    4     {
    5         private readonly Type _evaluatorType;
    6         private const string _jscriptSource = 
    7             @"package CaptchaEvaluator
    8                 {
    9                     class CaptchaEvaluator
   10                     {
   11                         public function Eval(expr : String) : String 
   12                         { 
   13                             return eval(expr); 
   14                         }
   15                     }
   16                 }";
   17 
   18         public CaptchaEvaluator()
   19         {
   20             ICodeCompiler compiler = new JScriptCodeProvider().CreateCompiler();
   21 
   22             CompilerParameters parameters = new CompilerParameters {GenerateInMemory = true};
   23 
   24             CompilerResults results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);
   25 
   26             Assembly assembly = results.CompiledAssembly;
   27             _evaluatorType = assembly.GetType("CaptchaEvaluator.CaptchaEvaluator");
   28         }
   29 
   30         public bool IsValid(string statement)
   31         {
   32             try
   33             {
   34                 object evaluator = Activator.CreateInstance(_evaluatorType);
   35                 return Convert.ToBoolean(_evaluatorType.InvokeMember("Eval", BindingFlags.InvokeMethod, null, evaluator, new object[] { statement }));
   36             }
   37             catch (Exception)
   38             {
   39                 return false;
   40             }
   41         }
   42     }
   43 }

But I want to refactor this to be placed inside a Jscript library that then can be used from within the C# project without the need to compile some Jscript code. Of course StructureMap will only have this done as little as possible, but still.

So then I needed to extend the FubuMVC.Validation framework to be able to validate answers to Captcha questions. This was somewhat of a challenge because I had to suddenly be able to validate one property, the answer, using another property, the question. Anyway this was also solved meaning that now a validation rule can have as many properties injected in the constructor as needed for that specific rule. Having said that, it is ready for some refactoring.

Twitter notification

I got this idea from the sites like CodeBetter and Los Techies that notify people of new posts added to the main RSS feed by sending a Twitter message using their Twitter account (@codebetter, @lostechies), so everybody following these accounts would know about it. What I wanted is a way for people that leave a comment on my blog to be able to subscribe to new comments being added. E-mail is the obvious way especially since I already require this to be able to show a Gravatar image. But then I thought that it would be cool if my blog Twitter account would send a message to these people notifying them about a new comment being added to the thread they subscribed to. Another added bonus for me would be the ability to always send the author of the blog post (me) a Twitter message containing the same.

After this idea I created a test indicating what I wanted to happen, and during the implementation part of this Unit test I started looking at the Twitter API and soon discovered that there are several .Net implementations available from which I choose tweetsharp, basically the only reason for this is that I saw it was still getting check-ins even hours ago (yes this could also indicate that nothing would work yet, but for as little as I wanted now it definitely did the job). Then I searched for some example code to access the TinyUrl service and found an example made by Bram. Anyway look at the code below which is my TwiterClient, I could verify the result, but I am not going to do anything with it anyway.

    4 namespace Fohjin.Core.Services
    5 {
    6     public interface ITwitterClient 
    7     {
    8         bool SendReply(string twitterUserName, string twitterPassword, string twitterUserNameReceiver, string message);
    9     }
   10 
   11     public class TwitterClient : ITwitterClient
   12     {
   13         public bool SendReply(string twitterUserName, string twitterPassword, string twitterUserNameReceiver, string message)
   14         {
   15             var update = FluentTwitter.CreateRequest()
   16                 .AuthenticateAs(twitterUserName, twitterPassword)
   17                 .Statuses()
   18                 .Update("@{0} {1}".ToFormat(twitterUserNameReceiver, message))
   19                 .AsJson();
   20 
   21             update.Request();
   22 
   23             return true;
   24         }
   25     }
   26 }

So there you go one extra Twitter spammer in the world, if you would like to follow updates using Twitter just start following me.
Ryan Kelley (gravatar)

Mark,

Haven't even read whole post yet, but I have the dashboard/post management about 1/2 way done. Just need to wrap it up and check in!

Ryan Kelley, Sunday, March 29, 2009 at 3:32 AM

Mark Nijhof (gravatar)

Ryan,

looking forward to it, will definitely wait until you do. It is for Oxite right?

Mark Nijhof, Sunday, March 29, 2009 at 8:22 PM

Daniel (gravatar)

Hi Mark,

Thank you for the write-up on TweetSharp! You can actually shorten URLs automatically with TweetSharp, here is a code snippet - http://snipt.org/Qng. There are quite a few unit tests included and we dogfood it on our own projects. Hopefully it's useful to you, and if you have any gripes, have at it.

Daniel

Daniel, Friday, April 03, 2009 at 3:12 AM

Mark Nijhof (gravatar)

Daniel, That is really cool I didn't know that, will update my code soon to use that feature, so far I am really happy with TweetSharp!

Mark Nijhof, Friday, April 03, 2009 at 4:16 PM

dan (gravatar)

I am having problems with jpeg files exported from Lightroom 2.2 http://www.ebook-search-queen.com/ebook/ligh/lightroom-2.2.all.html . I dont think ImageGetExifMetadata working properly for LR images. I can see the all exif information with a different programs. One of the errors:"Element Focal Plane Y Resolution is undefined in a CFML structure referenced as part of an expression. ". "Element Focal Plane Y Resolution" is there but CF can't read it. I have tried all sorts with no luck.On the other hand it works for non LR jpg images. Any ideas?

dan, Friday, June 19, 2009 at 8:26 AM

lisa (gravatar)

Thanks a lot for this information. I've been trying to creat my blog recently. I found some books about it at the search engine http://rapid4me.com . My friends' advice was of great help, too. But here you paid my attention to quite different but very important details. And you wrote it in a simple way, and it's also a big plus. The information is of great value, indeed.

lisa, Saturday, October 31, 2009 at 2:15 PM

clavier arabe  (gravatar)

hii
I am having problems with jpeg files exported from Lightroom 2.2 http://www.ebook-search-queen.com/ebook/ligh/lightroom-2.2.all.html . I dont think ImageGetExifMetadata working properly for LR images. I can see the all exif information with a different programs. One of the errors:"Element Focal Plane Y Resolution is undefined in a CFML structure referenced as part of an expression. ". "Element Focal Plane Y Resolution" is there but CF can't read it. I have tried all sorts with no luck.On the other hand it works for non LR jpg images. Any ideas?.

clavier arabe , Monday, March 15, 2010 at 10:03 AM

Car Leasing (gravatar)

this was also solved meaning that now a validation rule can have as many properties injected in the constructor as needed for that specific rule. Having said that, it is ready for some refactoring. <a href="http://www.stickywebmedia.com/">Search Engine Optimization Services</a>

Car Leasing, Sunday, April 04, 2010 at 11:13 AM

Car Leasing (gravatar)

a great start getting prepaid phones. I would like to see better in the future.

Car Leasing, Tuesday, April 06, 2010 at 8:09 PM

Car Leasing (gravatar)

here is a code snippet - http://snipt.org/Qng. There are quite a few unit tests included and we dogfood it on our own projects. Hopefully it's useful to you

Car Leasing, Tuesday, April 06, 2010 at 8:10 PM

Alisha JOhn (gravatar)

Thanks a lot for this information. I've been trying to creat my blog recently. I found some books about it at the search engine http://rapid4me.com . My friends' advice was of great help, too. But here you paid my attention to quite different but very important details. And you wrote it in a simple way, and it's also a big plus. The information is of great value, indeed. You can get more information about it from <a href="http://www.webpagefx.com/">Internet Marketing Services</a> and <a href="http://www.walzerphotography.com">Tacoma Boudoir Photographer</a>.

Alisha JOhn, Saturday, April 10, 2010 at 7:34 AM

Internet Marketing Services (gravatar)

Thank you for the write-up on TweetSharp! You can actually shorten URLs automatically with TweetSharp, here is a code snippet - http://snipt.org/Qng. There are quite a few unit tests included and we dogfood it on our own projects. Hopefully it's useful to you, and if you have any gripes, have at it.

Internet Marketing Services, Saturday, April 10, 2010 at 7:37 AM

Bellevue Photographers (gravatar)

Ryan,

looking forward to it, will definitely wait until you do. It is for Oxite right?

Bellevue Photographers, Saturday, April 10, 2010 at 7:38 AM

Massage School chicago (gravatar)

great '''''''''The idea is to prevent spammers from using web bots to automatically post form data in order to create email accounts (for sending spam) or to submit feedback comments or guestbook entries containing spam messages. The text in the image is usually distorted to prevent the use of OCR (optical character reader) software to defeat the process. Hotmail, PayPal, Yahoo and a number of blog sites have employed this technique. Keep it up.

Massage School chicago, Saturday, April 10, 2010 at 9:43 PM

Car Leasing (gravatar)

the constructor as needed for that specific rule. Having said that, it is ready for some refactoring.

Car Leasing, Sunday, April 11, 2010 at 5:49 PM

Car Leasing (gravatar)

will definitely wait until you do. It is for Oxite right?

Car Leasing, Sunday, April 11, 2010 at 5:51 PM

Mark is reading

 
Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.