C# 4.0 Named Arguments – example usage

Posted by – August 24, 2010

One of the new features introduced in C# 4.0 were named arguments. There was a lot of discussion in the Internet about them and theirs pros and cons. Of course named arguments can be abused like any other part of C# but I think that when used wisely are able to make your code more readable and easier to understand without the knowledge what is hidden behind the scene. Few days ago I was working on integration tests for REST API exposed by a startup I am working on with my team. Each test required some “execution context” and a way to inform “infrastructure” that after execution whole environment should be cleaned up (e.g. database). Because I use NUnit as a runner the first idea that came to my mind was to utilize [SetUp] and [TearDown] methods. But after some prototyping I realized that the solution is hard to understand and obfuscates the tests. Next day after short chat with @lesnikowski new idea popped into my mind: I can create “execution context” with lambdas and named arguments! The example below shows how I have changed the idea into real code.

[Test]
public void Add_WhenInvokedShouldAddNewExternalAudioFolder()
{
    Execute(test: () =>
    {
        var json = WebApiClient.ExternalAudioFolder.Add("My folder", "My description");
        var message = json.DeserializeJson<AddMessage>();

        Assert.That(message.Result, Is.EqualTo(Message.Success));
    },
    inContextOf: Account.Basic,
    cleanUpAfter: true);
}

What do you think about the code above? Do you have any additional ideas how to improve readability of this “execution context”?

Fluent NHibernate conventions II – example for enumerations

Posted by – May 20, 2010

Most of the time I do not have to touch Fluent NHibernate conventions I have created some time ago. But from time to time I find in mappings some common scenario which is a good candidate to become a convention. This time I found that every time I am mapping a property of enumeration type I have to specify its length manually.

Because I hate redundant work I have defined a Fluent NHibernate convention presented below.

using System;
using System.Linq;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.AcceptanceCriteria;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.Conventions.Instances;

namespace ExampleConventions
{
    public class EnumColumnLengthConvention
        : IPropertyConvention, IPropertyConventionAcceptance
    {
        public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
        {
            criteria.Expect(x => x.Property.PropertyType.IsEnum)
                .Expect(x => x.Length == 0);
        }

        public void Apply(IPropertyInstance instance)
        {
            var names = Enum.GetNames(instance.Property.PropertyType);
            instance.Length(names.Max(name => name.Length));
        }
    }
}

The convention is really simple. Its whole logic can be found in Apply method and I think it is self explanatory so there is nothing to describe here.

[BUG] invalid exec_format “ir”, no %s

Posted by – May 11, 2010

Today I’ve switched from the default, C based implementation of Ruby to new version of IronRuby (1.0). After installation I wanted to update gems, install rake tool and of course at this point problems started. Command for updating gems displayed below:

igem update --system

produced output like this:

Updating RubyGems
Updating rubygems-update
Successfully installed rubygems-update-1.3.6
Updating RubyGems to 1.3.6
Installing RubyGems 1.3.6
ERROR:  While executing gem ... (Gem::Exception)
       [BUG] invalid exec_format "ir", no %s

After some research turned out that RubyGems assumes that Ruby executable contains “ruby” word in the name. In case of IronRuby the name is “ir.exe” so in my opinion this strange behavior can be treated as a bug in RubyGems. I hope it will be fixed in next release but before that will happen here are the steps to workaround the problem and update gems:

1. Create path: [IronRuby folder]\Lib\ruby\1.8\rubygems\defaults
2. Create file ironruby.rb and add it to the path from step 1
3. Open ironruby.rb and add code from the snippet below

module Gem
  def self.default_exec_format
    exec_format = ConfigMap[:ruby_install_name].sub('ruby', '%s') rescue '%s'
    #unless exec_format =~ /%s/ then
    #  raise Gem::Exception,
    #    "[BUG] invalid exec_format #{exec_format.inspect}, no %s"
    #end
    exec_format
  end
end

That is it. Now RubyGems will use new implementation of default_exec_format and everything should work as expected.

Hope this helps.

Ruby for Windows with debug support

Posted by – February 10, 2010

I mentioned somewhere in previous posts I am playing a little with Ruby and Ruby on Rails. Because I do not have an experience yet, there are a lot of situations where I need a debugger to figure out how something works. Unfortunately before I was able to debug anything I spend a lot of time trying to enable debugging in RubyMine. The main problem was in Ruby gems responsible for debugging. This gems are native C libraries and have to be compiled before usage. Of course you can guess that compilation did not work as expected. After long fight and few hours with Google I have managed to prepare a version of Ruby which can be used with RubyMine to debug applications.

Because Ruby for Windows does not require any installation I am able to easily provide you the version I have build mostly in order to save your time and do not describe whole procedure I had to follow during compilation.

The package contains Ruby 1.8.7 for Windows with following gems:

  • actionmailer (2.3.5)
  • actionpack (2.3.5)
  • activerecord (2.3.5)
  • activeresource (2.3.5)
  • activesupport (2.3.5)
  • albacore (0.1.1, 0.1.0)
  • columnize (0.3.1)
  • linecache (0.43)
  • net-sftp (2.0.4)
  • net-ssh (2.0.19)
  • rack (1.1.0, 1.0.1)
  • rails (2.3.5)
  • rake (0.8.7)
  • RedCloth (4.2.2)
  • ruby-debug (0.10.3)
  • ruby-debug-base (0.10.3)
  • ruby-debug-ide (0.4.9)
  • rubyzip (0.9.4, 0.9.1)
  • sqlite3-ruby (1.2.5)

Installation is very simple. Uncompress files to C:\Ruby directory and add C:\Ruby\bin path to PATH environment variable.

Download Ruby 1.8.7 for Windows with debug support

IronRuby/RHTML based templates for .NET

Posted by – December 8, 2009

.NET Logo

During last few days I was prototyping some of new features I would like to add to ByteCarrot application. One of them is new template engine which will replace current XSLT based solution. I wanted something with more friendly syntax, something easy to create, change and maintain. I took a look at many template engines available for .NET platform but none of them met my needs. I thought that it would be nice to have solution with scripting support and syntax similar to this available in default ASP.NET MVC view engine.

After digging I have found an ASP.NET MVC application prototype with view engine based on IronRuby. It was created by Phil Haack‘s team and its syntax was exactly the same as RHTML used in Ruby on Rails views. It turned out that this engine was exactly what I needed, so I have taken parts of the code and adapted it to my scenario. The result is amazing because now I have fully functional templates engine with support of dynamic language where I can handle every possible HTML generation scenario.

As an attachment to this post I have added the code created during prototyping. The code contains few classes where the most important is RhtmlEngine. It has very simple, self-expanatory interface and acts as an “entry point” for using mentioned templates engine. Below you can find two samples showing capabilities of my solution but if you want to take a look at the implementation and make your hands dirty feel free to download the code and play with it for yourself.

public class RhtmlEngine
{
    public Result Render(object model, string temlateFile, string targetFile)
        ...
    public Result Render(object model, StreamReader rhtml, StreamWriter writer)
        ...
}

Simple template

The templates engine requires three things to be able to generate HTML:

  • Model representing the data which should be presented in form of HTML page,
  • Template defining how model should be presented,
  • Target where generated HTML page should be saved.

Listing below shows simple template generating a header and a list of hobbies. Notice that IronRuby blocks are embedded exactly the same as Visual Basic .NET or C# code is embedded in ASP.NET MVC views.

SimpleTemplate.rhtml

<html>
    <body>
        <h1>Hi! My name is: <%= model.FirstName %><%= model.LastName %></h2>
        I like:
        <ul>
        <% model.Hobbies.each do |hobby| %>
			<li><%= hobby %></li>
        <% end %>
        </ul>
    </body>
</html>

Template shown above can be used to generate an HTML representation of the following model:

var model = new SampleModel
{
    FirstName = "Marcin",
    LastName = "Obel",
    Hobbies = new List<string>
    {
        "yachting",
        "fishing",
        "cycling"
    }
};

As you can notice looking at listing below, because the templates engine is very simple, you need only one line to change the model into HTML page.

var result = new RhtmlEngine().Render(model, "SimpleTemplate.rhtml", "SimpleHtml.html");

In result (as shown below) the code above will produce clean HTML filled in with the data from model.

SimpleHtml.html

<html>
    <body>
        <h1>Hi! My name is: MarcinObel</h2>
        I like:
        <ul>
            <li>yachting</li>
            <li>fishing</li>
            <li>cycling</li>
        </ul>
    </body>
</html>

More advanced example

The example above does not show the most powerful part of this solution which is in fact inherited from IronRuby itself. Because templates are based on fully functional, dynamic language there is a possibility to extend basic features like loops and if statements (available in all templates engines) with things like functions, classes or even use some functionalities available in .NET Framework. Next example extends this one mentioned in previous section. In the listing below you can notice two new functions:

  • encode - uses HttpUtility class from .NET Framework to encode HTML code
  • render_li – renders an item of HTML list

AdvancedTemplate.rhtml

<%
require 'System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
include System::Web

def encode(text)
    HttpUtility.HtmlEncode(text)
end

def render_li(text)
    writer.Write "<li>#{text}</li>";
end
%>

<html>
    <body>
        <h1>Hi! My name is: <%= model.FirstName %><%= model.LastName %></h2>
        I like:
        <ul>
        <% model.Hobbies.each do |hobby|
                 render_li hobby
             end %>
        </ul>
        <pre>
            <%= encode model.UglyJavaScript %>
        </pre>
    </body>
</html>

In order to present a usage of custom IronRuby function added to the template, below you can find extended model from previous example. Now the model contains additional property named UglyJavaScript containing JavaScript code which should be encoded before it can be presented in HTML.

var model = new SampleModel
{
    FirstName = "Marcin",
    LastName = "Obel",
    Hobbies = new List<string>
    {
        "yachting",
        "fishing",
        "cycling"
    },
    UglyJavaScript = @"<script type='text/javascript'>window.close();</script>"
};

var result = new RhtmlEngine().Render(model, "AdvancedTemplate.rhtml", "AdvancedHtml.html");

Like in previous example after passing the model and the template into engine we receive an HTML.  This time as you can see it contains JavaScript code from model encoded using .NET Framework functionality in order to be able to display it.

<html>
    <body>
        <h1>Hi! My name is: MarcinObel</h2>
        I like:
        <ul>
        <li>yachting</li><li>fishing</li><li>cycling</li>
        </ul>
        <pre>
        &lt;script type='text/javascript'&gt;window.close();&lt;/script&gt;
        </pre>
    </body>
</html>

Resources

Fluent NHibernate conventions – examples

Posted by – November 26, 2009

Fluent NHibernateFluent NHibernate is my favorite extension for NHibernate. I am using it since early betas and I have to say that I love it. One of its underestimated features are conventions. I decided to extract some of them from one of my projects and provide real life examples how they can be used. My conventions are listed below but if you need more information visit Fluent NHibernate Wiki where this feature is described in detail.

ColumnNullabilityConvention – says that if nullability for column has not been specified explicitly, should be set to “NOT NULL”.

public class ColumnNullabilityConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Nullable, Is.Not.Set);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Not.Nullable();
    }
}

CreatedAtPropertyAccessConvention – says that every property named CreatedAt should be accessed through camel case field hidden behind it.

public class CreatedAtPropertyAccessConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.Name == "CreatedAt");
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Access.ReadOnlyPropertyThroughCamelCaseField(
            CamelCasePrefix.Underscore);
    }
}

ForeignKeyConstraintNameConvention – says that name of every foreign key constraint representing one to many relation should consist of names of entities for which it was specified.

public class ForeignKeyConstraintNameConvention
    : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance instance)
    {
        instance.Key.ForeignKey("{0}_{1}_FK".AsFormat(
        instance.Member.Name, instance.EntityType.Name));
    }
}

ForeignKeyNameConvention – says that name of every column containing foreign key id should consist of name of type which it points to with “Id” suffix.

public class ForeignKeyNameConvention : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance instance)
    {
        instance.Key.Column(instance.EntityType.Name + "Id");
    }
}

PrimaryKeyNameConvention - says that name of every column representing primary key should consist of entity name and “Id” suffix.

public class PrimaryKeyNameConvention : IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {
        instance.Column(instance.EntityType.Name + "Id");
    }
}

ReferenceConvention – says that name of column referenced in many to one convention should consist of entity name and “Id” suffix.

public class ReferenceConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        instance.Column(instance.Property.PropertyType.Name + "Id");
    }
}

StringColumnLengthConvention – says that if length for string column has not been specified, it should be set to 100.

public class StringColumnLengthConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Type == typeof(string))
            .Expect(x => x.Length == 0);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Length(100);
    }
}

TableNameConvention – says that if name for table has not been specified, it should be created using concatenation of entity name and “s” suffix.

public class TableNameConvention
    : IClassConvention, IClassConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IClassInspector> criteria)
    {
        criteria.Expect(x => x.TableName, Is.Not.Set);
    }

    public void Apply(IClassInstance instance)
    {
        instance.Table(instance.EntityType.Name + "s");
    }
}

At the end the most important thing which shows that such conventions make sense. With default Fluent NHibernate conventions DDL generated by NHibernate for MySQL looked like this:

alter table `Athlete`  drop foreign key FK9221C9B94070A6F0

drop table if exists Countries

drop table if exists `Athlete`

create table Countries (
     Id INTEGER NOT NULL AUTO_INCREMENT,
     Name VARCHAR(255),
     primary key (Id)
)

create table `Athlete` (
     Id INTEGER NOT NULL AUTO_INCREMENT,
     DisplayName VARCHAR(255),
     Email VARCHAR(255),
     Password VARCHAR(255),
     CreatedAt DATETIME,
     IsActive TINYINT(1),
     Country_id INTEGER,
     primary key (Id)
)

alter table `Athlete`
	add index (Country_id),
	add constraint FK9221C9B94070A6F0
	foreign key (Country_id)
	references Countries (Id)

When I have applied conventions mentioned above to my fluent mappings DDL looks like this:

alter table Athletes  drop foreign key Athletes_Country_FK

drop table if exists Athletes

drop table if exists Countries

create table Athletes (
     AthleteId INTEGER NOT NULL AUTO_INCREMENT,
     DisplayName VARCHAR(100) not null,
     Email VARCHAR(100) not null,
     Password VARCHAR(100) not null,
     CreatedAt DATETIME not null,
     IsActive TINYINT(1) not null,
     CountryId INTEGER,
     primary key (AthleteId)
)

create table Countries (
     CountryId INTEGER NOT NULL AUTO_INCREMENT,
     Name VARCHAR(100) not null,
     primary key (CountryId)
)

alter table Athletes
	add index (CountryId),
	add constraint Athletes_Country_FK
	foreign key (CountryId)
	references Countries (CountryId)

For me it looks much better. Additionally I have made it once and that is it. Now I have to care only about domain model and business logic without thinking about not so important stuff lake names of database objects.

MSpec BDD framework installer

Posted by – November 23, 2009

.NET LogoInstallation of MSpec BDD framework from source code is quite annoying. With each release you have to deploy everything manually one more time what in fact is hard to accept in 21th century. I know that work on Open Source project requires a lot of time (I have my own project called ByteCarrot) and you cannot do everything. Because of that I decided to help a little bit creators of MSpec and I have prepared an installer for this BDD framework. It is based on WiX and latest release of MSpec witch is version 0.3.

The installer is able to automatically integrate MSpec with TestDriven.NET and ReSharper (4.1, 4.5, 5.0). This is first version of the installer and of course like always there can be some bugs so please let me know if you find something.

Download installer for MSpec 0.3

Rake in .NET projects – installation and setup

Posted by – November 18, 2009

.NET Logo
Recently I have rewritten all MSBuild scripts which I used in ByteCarrot project to Rake. I made the decision about changing build solution mostly because I required something what works not only under Windows but also on other operating systems. After rewriting turned out that Rake is a great solution for tasks for which it was created and can be used not only with Ruby/RoR projects but also with other technologies like .NET and Mono. It is really awesome multi-purpose tool. Today I would like to show you how to install and configure Rake on Windows operating system in order to start using it in your projects. Ruby installation First of all, because Rake is based on Ruby language, you will need an interpreter. You can download Ruby distribution from its official website but I do not recommend that because there is only installer for version 1.8.6 which is quite old. Other packages for Windows on this website are in a form of compressed archives and do not contain some additional, required libraries. In my opinion the best option is to download one of preview version of installer for Ruby 1.9.1-p129 (rubyinstaller-1.9.1-p129-preview1.exe) available on RubyForge. ByteCarrot project to Rake. I made the decision about changing build solution mostly because I required something what works not only under Windows but also on other operating systems. After rewriting turned out that Rake is a great solution for tasks for which it was created and can be used not only with Ruby/RoR projects but also with other technologies like .NET and Mono. It is really awesome multi-purpose tool. Today I would like to show you how to install and configure Rake on Windows operating system in order to start using it in your projects.

Ruby installation

First of all, because Rake is based on Ruby language, you will need an interpreter. You can download Ruby distribution from its official website but I do not recommend that because there is only installer for version 1.8.6 which is quite old. Other packages for Windows on this website are in a form of compressed archives and do not contain some additional, required libraries. In my opinion the best option is to download one of preview version of installer for Ruby 1.9.1-p129 (rubyinstaller-1.9.1-p129-preview1.exe) available on RubyForge.

Ruby Logo

When the installer is on your hard drive, start installation. There is nothing magic in the installation process but you should remember that Rake does not work properly when Ruby in installed in C:\Program Files directory (probably because of space in the path). Because of that leave the default installation path or change it to something without spaces like for example C:\Ruby.

Last thing you should do to be able to use Ruby is adding the location of its binaries to the %Path% environment variable. In my case this variable was extended with C:\Ruby\bin path.

Now you can check if everything works by executing from command line two following commands:

ruby –v
gem -v

The output from console should be:

C:\>ruby –v
ruby 1.9.1p129 (2009-05-12 revision 23412) [i386-mingw32]
C:\>gem –v
1.3.4

Rake installation

Now, when Ruby is installed and you are sure that it works you can take care of Rake. The most popular and safe way to install Ruby extensions and libraries (including Rake) is mechanism called Gems. In order to install Rake using Gems execute following command from command line:

C:\>gem install --remote rake

The output from console should be:

C:\>gem install --remote rake
Successfully installed rake-0.8.7
1 gem installed
Installing ri documentation for rake-0.8.7...
Updating class cache with 0 classes...
Installing RDoc documentation for rake-0.8.7...

When the command will finish do not close command line window yet. At the end execute one more command to be sure that Rake is installed properly:

C:\>rake –V

The output from console should be:

C:\>rake –V
rake, version 0.8.3

Congratulations! You have managed to install Rake and you are ready to write your first build script. More about Rake can be found on official site of the project. Example Rake scripts can be found in ByteCarrot source code on CodePlex.

ASP.NET MVC 2 Beta – new features

Posted by – November 18, 2009

.NET LogoYesterday at PDC 09 Bob Muglia announced the release of ASP.NET MVC 2 Beta. This release contains a lot of new, interesting stuff. Below you can find a list of new features taken from official release notes.

New RenderAction method

Html.RenderAction (and its counterpart Html.Action) is an HTML helper method that calls into an action method from within a view and renders the output of the action method in place. Html.RenderAction writes directly to the response, whereas Html.Action returns a string with the output. RenderAction works only with actions that render views.

Strongly typed UI helpers

ASP.NET MVC 2 includes new expression-based versions of existing HTML helper methods. The new helpers include the following:

  • ValidationMessageFor
  • TextAreaFor
  • TextBoxFor
  • HiddenFor
  • DropDownListFor

TempDataDictionary improvements

The behavior of the TempDataDictionary class has been changed slightly to address scenarios where temp data was either removed prematurely or persisted longer than necessary. For example, in cases where temp data was read in the same request in which it was set, the temp data was persisting for the next request even though the intent was to remove it. In other cases, temp data was not persisted across multiple consecutive redirects.

To address these scenarios, the TempDataDictionary class was changed so that all the keys survive indefinitely until the key is read from the TempDataDictionary object. The Keep method was added to TempDataDictionary to let you indicate that the value should not be removed after reading. The RedirectToActionResult is an example where the Keep method is called in order to retain all the keys for the next request.

Client validation library

MicrosoftMvcAjax.js now includes a client-side validation library that is used to provide client validation for models in ASP.NET MVC. To enable client validation, include the following two scripts in your view.

  • MicrosoftAjax.js
  • MicrosoftMvcAjax.js

The following example shows a view with client validation enabled.

<script type="text/javascript" src="MicrosoftAjax.js"></script><script type="text/javascript" src="MicrosoftMvcAjax.js"></script>

  //...

“Add Area” dialog box

ASP.NET MVC 2 Beta includes a new Add Area context menu item when you right-click either the root project node or the Areas folder (if one exists). If a root Areas folder does not already exist, the command creates one, and it then creates the files and folders for the area that you specify.

Calling action methods asynchronously

The AsyncController class is a base class for controllers that enables action methods to be called asynchronously. This lets an action method call external services such as a Web service without blocking the current thread. For more information, see Using an Asynchronous Controller in ASP.NET MVC In the ASP.NET MVC 2 documentation.

Blank project template

In response to customer feedback, an empty ASP.NET MVC project template is now included with ASP.NET MVC 2 Beta. This empty project template contains a minimal set of files used to build a new ASP.NET MVC project.

Multiple model validator providers

ASP.NET MVC 2 Beta lets you register multiple validation providers. The following example shows how to register multiple providers.

protected void Application_Start() {
    ModelValidatorProviders.Providers.Add(new MyXmlModelValidatorProvider());
    ModelValidatorProviders.Providers.Add(new MyDbModelValidatorProvider());
    //...
}

Multiple value provider registration

In ASP.NET MVC 2 Beta, the single value provider that was available in ASP.NET MVC 1.0 has been split into multiple value providers, one for each source of request data. The new value providers include the following:

  • FormValueProvider
  • RouteDataValueProvider
  • QueryStringValueProvider
  • HttpFileCollectionValueProvider

These value providers are registered by default. You can register additional value providers that pull data from other sources. The following example shows how to register additional value providers in the in Global.asax file.

protected void Application_Start() {
    ValueProviders.Providers.Add(new JsonValueProvider());
    //...
}

Download full ASP.NET MVC 2 Beta Release Notes

Metadata based validation with jQuery

Posted by – October 8, 2009

jQuery Validation enabled form

Recently I spent some time prototyping my own validation for ASP.NET MVC. Why did not I reuse any of existing solutions? This is a story for another post so I did not want to bring this topic up now. One of the things which I had to figure out during prototyping was how to implement client side validation. Of course I wanted to utilize capabilities of some well known JavaScript framework (no I am not so crazy to write it for my own). I made small evaluation comparing available options and at the end I decided to incorporate jQuery and its Validation plugin. One of the things which were crucial to my decision was ability of this framework to use metadata stored as JSON in class attribute of HTML element. The concept of metadata available in jQuery is amazing and gives possibility to describe validation rules for specified input control inside itself. In my case this was very important feature because I wanted to render validation using my custom HtmlHelper extensions together with corresponding input controls. Second thing which convinced me to jQuery Validation was easy setup which I want to show you now.

If you want to use jQuery Validation in your project first of all you will need of course jQuery library which can be downloaded here, jQuery Metadata plugin which is available here and jQuery Validation plugin downloadable from here.

When you collected all required prerequisites you have to add reference to them in your HTML. Simply add code shown below to the body of tag but remember to ensure that paths lead to place where JavaScript files are located.

<script type="text/javascript" src="jquery-1.3.2.min.js"></script><script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery.metadata.js"></script>

When jQuery libraries are already where they should be you can specify validation rules using metadata. In order to do it extend your input control tag with class attribute and set its value to {required:true}. This will tell Validationplugin that this specified input control should contain a value before it can be send back to server. Of course this is very simple rule but below I have listed few more, complex definitions.

<input class="{required:true, maxlength:100, messages:{required:'This field is required.', maxlength:'This field can contain maximum 100 characters.'}}" type="text" />
<input class="{maxlength:50, email:true, equalTo:'#Email',  messages:{required:'This field is required.', maxlength:'This field can contain maximum 100 characters.', email:'This is not a valid email.', equalTo:'Value entered in this field should equal to value of Email field.'}}" type="text" />

Listing below shows this validation metadata in wider context.

</pre>
<form id="MyForm" action="/Registration" method="post"><label for="DisplayName">Username:</label> <input id="DisplayName" class="{required:true, maxlength:100, messages:{required:'This field is required.', maxlength:'This field can contain maximum 100 characters.'}}" type="text" name="DisplayName" /> <input type="submit" value="Submit!" /></form>
<pre>

At the end when you have defined all validation rules only thing you should do is adding following code after closing tag and that is it.

<script type="text/javascript">// <![CDATA[
    $("#MyForm").validate({
        errorElement: "span"
    });
// ]]></script>

Now when you will click Submit! button your form will be validated and in case of errors apropriate messages will be displayed below corresponding input control.

Because I know that described example can be not enough to fully understand how all it works I have prepared more complex, example form which can be downloaded from here: download.