Friday, August 29, 2008

The Evolution of Delegates

In this post I'll discuss how delegates have evolved along with the evolution of .NET and C#. Specifically, how the introduction of anonymous methods and lambda expression helped make delegates more concise and useful.

This post is the first in a series of "Back-to-Basic" posts where I'll discuss basic .NET concepts and show how they have progressed with each new release of the .NET Framework.

I love delegates. If I had to come up with a list of my top 5 .NET features, delegates would definitely be high up on the list.

A Delegate, as defined by MSDN is:

"A type that defines a method signature, and can be associated with any method with a compatible signature. You can invoke (or call) the method through the delegate. Delegates are used to pass methods as arguments to other methods."

Delegates are first class citizens in the .NET framework and the C# language, and one of the fundamental types in the framework. They are used throughout the framework and enable important features such as events and asynchronous method calls.

In the old days, if we wanted a delegate that takes one parameter and returns void we had to declare one like this:

public delegate void DoWorkDelegate(string data);

Then we had to implement a method that conforms to the signature of the delegate:

private void DoSomeWork(string s)
{
// Do some work here
Console.WriteLine(s);
}

And finally, instantiate the delegate in our code:

DoWorkDelegate del = new DoWorkDelegate(DoSomeWork);

In .NET 2.0 we could use a simplified syntax to instantiate the delegate:

DoWorkDelegate del = DoSomeWork;

The introduction of Generics in .NET 2.0 introduces a generic delegate Action. Action encapsulates a delegate that returns void and accepts 0 to 4 parameters (there are actually 5 generic Action types defined: Action, Action<T>, Action<T1, T2>, Action<T1, T2, T3>, Action<T1, T2, T3, T4>). So in the above example, we could have saved us the trouble of defining our own custom delegate "DoWorkDelegate" and instead used this:

Action<string> del = DoSomeWork;

.NET 2.0 also introduced the concept of Anonymous Methods. This lets us avoid defining the "DoSomeWrok" method altogether and write it inline with the definition of the delegate:

Action<string> del = delegate(string s)
{
Console.WriteLine(s);
};

Finally, C# 3.0 introduced Lambda Expressions, which allow us to define the method inline like this:

Action<string> del = s =>
{
Console.WriteLine(s);
};

One more delegate worth mentioning is the Func delegate. Func was introduced in .NET 3.5 and just like its older brother, the Action, it encapsulates a delegate, but unlike Action Func encapsulates a delegate that takes 0 to 4 and returns a value. For example:

// Using Func we can replace this:
delegate int DoWorkDelegate(string data);

// with this:
Func<string, int> del;

In all the above samples (except for the last one) we end up with a "del" object. We could then use the "del" instance anywhere in our code to execute the "DoSomeWork" method. We could even pass "del" as an argument to other methods or objects that could also execute the same method:

// This is the verbose way:
del.Invoke("Do some work");

// This is a bit more concise
del("Do some work");

// This executes the method asynchronously
del.BeginInvoke("Do some work", null, null);

Next time on SapienCoder I will describe how to use delegates to implement Asynchronous programming patterns.

Read more...

Tuesday, August 26, 2008

Will reCAPTCHA Save Humanity?

Probably not, but it will make us more productive during the tedious process of proving our humanhood to some random web server.

Anyone who's using the internet these days for anything more involved than reading news knows those annoying sets of garbled characters that appear at the end of checkout and registration pages.

captcha

Those are called CAPTCHAs (an acronym for "completely automated public Turing test to tell computers and humans apart") and they are designed to test that we, the users of the web site are in fact human. Now, I don't disagree with the motivation behind CAPTCHAs. Today's Web is infested with crawling bots and other malicious agents running around causing all kinds of mayhem. But, it just seems like a terrible waste of time for something that aught to be straight forward (how many times have you mistyped a CAPTCHA and had to enter it over and over again until the server acknowledged your humanhood?).

Luis von Ahn, the inventor of the CAPTCHA, said in an interview recently that by his estimates people spend an average of 10 seconds solving one of those CAPTCHA puzzles. Multiply that by the number of CAPTCHAs solved daily (aprox. 200 million) and you come to the staggering number of approximately 500,000 hours per day world wide. Astonishing when you think about it in these terms.

That's exactly why he came up with the brilliant idea of the reCAPTCHA.

There is a growing number of libraries and archives who are working on digitizing their entire collections. The process involves scanning the printed document (book, newspaper, magazine, historical document, etc.) to an image file, and then running a software called OCR (for Optical Character Recognition) that tries to recognize the words in the scanned image and turns them into a searchable text document. It turns out that the OCR software can't "read" every document with 100% accuracy. That's where the power of crowd-sourcing comes in. recaptcha ReCAPTCHA uses the words that computers can't decipher with OCR software (therefore can't be "read" by malicious robots) and displays them to humans. Each reCAPTCHA actually consists of two words, one was successfully recognized by the computer and the other wasn't. Each image is also shown to several people to verify the accuracy of the translation. If they agree on the translation the transcription is considered accurate and will be added to the text it originally came from. Currently more than 40,000 web sites world wide are using reCAPTCHA technology including some you might have heard of like Ticketmaster, Facebook and CraigsList. There are plug-ins for WordPress, Joomla, Drupal and many other popular web applications, as well as APIs for PHP, ASP.NET, Java, Perl, Ruby etc. The implementation is simple and there are lots of resources available for site developers.

Next time you run into those squiggly characters when commenting on a blog, or signing up for an online email account, make sure your time is not wasted on a standard CAPTCHA text. Let the site owners know your time could be spent on saving humanity, or at least it's written word.

Read more...

Thursday, August 07, 2008

The Olympics on Your PC


When the Olympic flame is fired up in Beijing tomorrow, and the Games begin, many people will realize that they can't watch their favorite athlete or event because of the time zone difference with China. Well this year is the first time ever that most of the events will also be available in high quality HD directly on your PC at any time you like (yes, even at work when your boss is not looking).

NBC had partnered with Microsoft
to deliver the 2008 Beijing Summer Games over the internet. At first NBC considered going with Adobe Flash which is considered the industry standard for Web video, but Microsoft was able to convince NBC that their Silverlight technology will deliver better quality to the end user. They plan on streaming most of the events live, and also make them available as on-demand content for your viewing pleasure any time you like.

Thanks to Silverlight, NBC can offer a unique viewing experience not even available on high end TVs. For example, they will offer a picture-in-picture view of two simultaneous events, and, for the real sports junkies, a "control room" mode with four events streaming side by side on the screen.

I can't imagine the complexity involved in delivering such a massive amount of data to so many users in real-time. This drawing (taken form an interesting News.com article) tries to explain it:



It is interesting to see how this "experiment" turns out, and if the masses are ready for Web TV (and if the technology stack is there too).

Don't forget to check out the NBC Beijing 2008 site at NBC Olympics.

Read more...

Tuesday, August 05, 2008

StackOverflow Private Beta


I'm happy to announce that as of this morning I'm an official beta tester for the all new programmers Q&A site StackOverflow.


StackOverflow is the brainchild of Jeff Atwood and Joel Spolsky who have decided to create a new knowledge transfer site specifically for programmers (Knol for programmers if you will). The service is totally free and is designed both functionally and graphically in the spirit of Web 2.0 (and, yes, there's also a podcast).

Each question submitted to StackOverflow is tagged by topic. Users can then answer the question, vote on it (in a very Digg like way), add their own answer and vote on the existing answer. The idea is that by using this democratic process the most relevant/accurate/knowledgeable answers will rise to the top.



Users are rewarded for their participation with different badges that are added to their profile. Badges include Guru, Specialist, Teacher, Student and many more. The bagdes act as incentives that are supposed to encourage users to participate.



So far, the site looks very good. The volume is suprisingly high for the first day of the private beta (with only about 500 users), and the concept seems promising. We'll see how it unfolds.

Update: To apply for the beta, click here.

Read more...