
In this second part, i will show how to make an ASP.NET Validation control that uses the reCaptcha framework.
I named this control ReCaptchaValidator. This validator extends the abstract class BaseValidator. And so soon we arrived to the first point.
ReCaptchaValidator could implement the interface IValidator, but he would lose a functionality that is very useful. the property ValidationGroup. This property allows you to tell the validator that he will only make the validation when an input with the same validation group makes a post back.
Example
<asp:Button ValidationGroup="test" runat="server"/>
When the above control makes a post back to the server, only the controls in the validation group named “test” will be called.
So, the ReCaptchaValidater extends BaseValidator. Starting explanation, all the action will occur in the EvaluateIsValid, a method inherited from BaseValidator:
protected override bool EvaluateIsValid() {
string parameters = ReCaptchaParameters();
string result = ValidateCaptcha(parameters);
bool isValid = result.Equals("true\nsuccess");
if( !isValid ) {
ErrorMessage = "Your are not a human!";
Controls.Add( new LiteralControl(ErrorMessage));
}
return isValid;
}
This method will call the private method ReCaptchaParameters that will return all the parameters needed to make the Web Request to the reCaptcha url. This Web Request will be made by the method ValidateCaptcha to which the parameters are passed. (ReCaptchaParameters and ValidateCaptcha are defined below)
Then the result of the Web Request is validated. If the result is different from the string “true\nsuccess”, then the user didn’t inserted the captcha correctly (or a BOT is trying to register in your site).
/// <summary>
/// Gathers the parameters for reCaptchaValidator
/// </summary>
/// <returns></returns>
private static string ReCaptchaParameters() {
string response = GetFormValue("recaptcha_response_field");
string challenge = GetFormValue("recaptcha_challenge_field");
string IP = HttpContext.Current.Request.UserHostName;
StringBuilder builder = new StringBuilder();
builder.AppendFormat( "privatekey={0}&", PrivateKey );
builder.AppendFormat( "remoteip={0}&", IP );
builder.AppendFormat( "challenge={0}&", challenge );
builder.AppendFormat( "response={0}", response );
return builder.ToString();
}
/// <summary>
/// Validates the capcha inserted by the user
/// </summary>
/// <param name="parameters">parameters to verify</param>
/// <returns>response of the capcth</returns>
private static string ValidateCaptcha( string parameters ) {
try {
WebRequest request =
WebRequest.Create( "http://api-verify.recaptcha.net/verify" );
request.ContentType = "application/x-www-form-urlenpred";
request.Method = "POST";
StreamWriter writer =
new StreamWriter( request.GetRequestStream() );
writer.Write( parameters );
writer.Close();
//Response
HttpWebResponse webResponse =
(HttpWebResponse)request.GetResponse();
StreamReader myReader =
new StreamReader( webResponse.GetResponseStream() );
string response = myReader.ReadToEnd();
myReader.Close();
webResponse.Close();
return response;
}catch( WebException ) {
//Do Some Exception threatment
return string.Empty;
}
}
In the Render method we will render all the code necessary to show the reCaptcha validator:
/// <summary>
/// Writes the javascript to show the validation Captcha
/// </summary>
/// <param name="writer"></param>
protected override void Render(HtmlTextWriter writer) {
writer.Write(
@"
<script>
var RecaptchaOptions = {{theme : 'blackglass', tabindex : 2}};
</script>
<script type='text/javascript'
src='http://api.recaptcha.net/challenge?k={0}'&
gt;</script>
<noscript>
<iframe src='http://api.recaptcha.net/noscript?k={0}'
height='300' width='500'
frameborder='0'></iframe><br/>
<textarea name='recaptcha_challenge_field' rows='3'
cols='40'></textarea>
<input type='hidden' name='recaptcha_response_field'
value='manual_challenge'>
</noscript>", PublicKey );
dummy.Visible = false;
base.Render(writer);
}
Noticed the dummy.Visible = false in the render? This is the second point i wanted to talk about. The validators that inherit from BaseValidator were made to validate other controls. In this case, we don’t want to validate any asp.net control. The control we want to validate is provided by a third party code (all the javascript in the render method).
Because of this fact, the validator has an hack. A TextBox with the name “dummy” is created and it’s ID is passed to the property of BaseValidator, ControlToValidate. This way we can surpass the limitation of BaseValidator. Notice that, if this validator didn’t extend BaseValidator, but implemented IValidator, this hack would not be needed.
I made this hack on the event OnInit:
protected override void OnInit(EventArgs e) {
dummy.ID = "aaa";
Controls.Add(dummy);
ControlToValidate = "aaa";
base.OnInit(e);
}
An that’s it. A free captcha control that you can use in all yout web applications.
For your commodity, the ReCaptchaValidator code is available here (in C#) and here (in VB) (Note: the VB code was created using a converter so it might not be exactly like the C# original file).

reCaptcha is a Captcha program that can tell the difference between a human and a machine. And Plus, it helps to digitalize books. And how does it do it?
Recapcha uses a 2 word challenge. A first word, that is an already known word, and a second word that comes from a digitalized book. If the user inserts the known word correctly, then the second word is assumed as correct and you helped to translate a digitalize one word.
A more complete explanation can be found here, at reCaptcha official page.
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=your_public_key"> </script> <noscript> <iframe src="http://api.recaptcha.net/noscript?k=your_public_key" height="300" width="500" frameborder="0"></iframe><br> <textarea name="recaptcha_challenge_field" rows="3" cols="40"> </textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"> </noscript>
And a box, similar to the one below, will appear.

Then, for this process to work, a request must be made to http://api-verify.recaptcha.net/verify with the right parameters in order to validate the captcha.
The steps to do this are:
The Web request you make to the above url will retrieve a response separated by a \n. In the first part of the response, the possible values are true or false. If the first part has the value false, then the second part is the error code. You can find the list of error codes here in the section “Error Code Reference”. This page also has all the information you need make your implementation.
In Part 2 of this article i will show how to implement an ASP.NET Validator control that uses this API.
In the end of 2007, i worked for a big company that still used in their sites asp.net 1.1. In fact, in their main site, the entire middleware is made in C# 1.1 (their site was launch at the beginning of 2008).
For this reason, there must still exist several applications made in ASP.NET 1.1 that will need some maintenance and new developments.
The challenge here is to develop a control that can simulate master pages in asp.net 1.1 similar to the one that exists in asp.net 2.0+. You make the master page using a .ascx control and make a .aspx webform has you would make in asp.net 2.0, meaning:
<asp:placeholder id='placeholder' runat="server"/>
<ctrl:contentplaceholder master="Master.ascx" runat="server"> YOUR CONTENT </ctrl:contentplaceholder>
where contentplaceholder is the control described below and master the name of the file of your master page. Has you will see below in the code, you can also omit this field and configure it’s value in the app settings of the web.config:
The code control is simple has below:
public class ContentPlaceholder : Control {
private string masterPage;
public string MasterPage {
get {
if( masterPage == null ||
masterPage == string.Empty ) {
return "~/" +
ConfigurationSettings.AppSettings["MasterPage"];
}
return masterPage;
}
set { masterPage = value; }
}
private void ChangeControls( Control src, Control dst ) {
while( src.Controls.Count > 0 ){
Control c = src.Controls[0];
src.Controls.Remove( c );
dst.Controls.Add( c );
}
}
private void LoadMaster( Control master ) {
PlaceHolder contentPlaceholder = (PlaceHolder)
master.FindControl( “placeholder” );
ChangeControls( this, contentPlaceholder );
ChangeControls( master, this );
}
protected override void OnInit(EventArgs e) {
Control master = Page.LoadControl( MasterPage );
LoadMaster( master );
}
}
In Resume, in the OnInit event the controls of the web page are removed from the aspx page, the content of the master page is inserted in the aspx, and the content previously removed is inserted in the placeholder of the master page:
I hope this example helps someone that still work with the old framework 1.1. This can be handy in big projects where you have hundreds of aspx to change.
At the end of my second day of full time development of the new version of Orion’s Belt, there is only one thing that i can say: I’m happy
My part is the battle (here is a shot for you that don’t know what the hell i am talking about). In some few words, the battle is no more than a chess like board game, with 8 different units on each side. Each one of them has it’s own attack, defense, range, special abilities and bonus.
In this 3rd version we decided not to change anything in terms of gameplay. The great optimizations will be in the Battle Core and in the Design. Why you ask? Because we consider that we have a pretty mature game, with a very strategic gameplay that our few (but very addicted) players love.
In the engine and in the design are our flaws.
The Engine is not extensible enough and all the Orion’s Belt Core is going to change. So, this is a good chance to upgrade all the code (meaning rewrite 90% of what we made in the past). Rewriting the code means:
All of this using .NET 2.0 (the use of generics will boost the Battle Core performance).
The new design will also help a lot. We want to make the battle page one of the most cool pages of the new Orion’s Belt version (never forgetting that this page must be cool and usable at the same time). Must be something that the players see and say: WOOOOOOOO.
And who is the guy that going to make this happen? Marco Vale.
Visit his site: it’s worth the time spent
Some minutes ago, i used a wonderful new feature of ASP.NET 2.0+, the offline page.
We just need to create a file named app_offline.htm and put it in the root directory of our web application.
If the file exists, every request is redirected to that file. As simple as that ![]()
Has a web developer, there are several frameworks i can use to accomplish my goal.
The smashmagazine blog published a post with a list of the main frameworks we can use for web development. I recommend the reading.
From the ones listed in the post above, i use:
I still don’t use any CSS framework… maybe is time to investigate this a little…
My friend Tiago finally released his website about birds.
It has a Portuguese and an English version (I think the english version is still under construction…). It needs some content but i think it’ a good start.
You can check it at aves.zi-yu.com (I must change this name… is not international… )
PS: Isn’t the banner Cool? ( I made it :D! )
The name is MooTools, a very cool Javascript Library with object oriented and Ajax support. It simplifies the way you write your scripts because it has a very simple syntax and a lot of features integrated (like effects, Drag and drops, scrolls, Tooltips, etc, etc).
To test the framework, I started yesterday an Star Rating control in ASP.NET. I Clearly needed 2 things
The first was easy. I made a little search and found 2 very simple that i recommend: Komodomedia and pmob.
For this example I used the second. Both are well done, so i just picked one of them.
The second: do some code using mootools (Also very easy like is expected of any javascript framework)).
First Step: The creation of the control
The first thing to do is to to create a control that renders the star rating. The method GetRating is something abstract because, according to your implementation (and context of usage) this information will come from a specific place.
Let's just suppose that the we are in a context of an blog and the rating goes to a database and get's the average rating of the current post.
NOTE: for test proposes the method can return the value '3' (just to see some stars).
After create this control, create and aspx and insert insert the control into an ASPX test page. Don't forget to add the css of the star rating to the aspx. This css is available at http://www.pmob.co.uk/temp/star-rating.htm ( or simply download the zip at the end of the page
).
then compile and run the project. You should see something like this:
Second Step: The javascript
Now that we have the control running, we need to add to each star and event onclick so we can handle the user rating. To do this, we will the following script:
The Ajax type has an event named "update". This is very useful because you can simply put the html element you want there (In the example above I inserted the element "ratingMessage') and the response of the request will simply be inserted into the element.
After this step you will not be able to see anything moving (yet!) because the page that handles the ajax request, Formatter.aspx, isn't created.
Third Step: Process the Ajax request
Finally the page responsible for receiving the ajax request, the Formatter.aspx (to make the example simple, I used an aspx page but you can also any type of file).
The page only receives the value of rating (to simplify the example) and returns a text indicating which rating we choose.
You can download this example here

Google has a tool for companies that consists in a server that craws all the information in the company and indexes it.
Today i passed all the afternoon playing (user perspective) with that little powerful thing.
The usage is simple. The machine is configure to have several types of indexes. So, when you request the information, the machine only returns the information about the specific thing you are searching for.
The Request is simple. Is a Http Request to the specified url were you pass, via query string, the information about your search (search key and several configuration parameters).
My implementation was very simple. A class, that i called it GSA (stands for Google Search Appliance
), with a method called Search. This method receives 3 parameters: the string to search, the start item and a filter parameter.
The filter is the more strange parameter here. It is used to return or the most relevant information, or all the results. The start item is the index of the first element that GSA must return( ie. Give me the elements starting at index 10). Finally the string to search... obvious...
When the Search method is called, i make an Http Request to the server, obtain the information (in a XML format), parse the information using Xpath, return the array of results to the class that invoked GSA (in my case a ASP.NET page) and render all the information.
Simple right?
Well, that is not necessarily right. The initial idea of the manager of my project was to copy a code of someone that already implemented a similar thing. Let's just say that the boy that implemented it didn't know how to program. Mixed all the fundamentals of programming (divide the application in Layers for instance). The boy inserted all the code in the Load event of the page, in a single method... no comments...
Unfortunately, in Portugal at least, the programming companies only want what we usually call a Code Monkey and, for that reason, the clients spend millions of euros trying to fix something that could be made correctly at first time.
I'm developing a website (still top secret) that needs a star rating system. I googled for simple ajax rating systems but didn't found anything decent (maybe i didn't googled well).
Pre send me this link. A very cool Star rating system using CSS. Very light and exactly
what i needed!
Here is the link to the "How To". Maybe i'll integrate this in an ASP.NET control and publish the code her.