<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Marcin Obel &#187; Marcin Obel</title>
	<atom:link href="http://marcinobel.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://marcinobel.com</link>
	<description>.NET, ASP.NET MVC, jQuery, Ruby, Ruby on Rails, Test Driven Development, Agile</description>
	<lastBuildDate>Mon, 15 Aug 2011 12:53:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>C# 4.0 Named Arguments &#8211; example usage</title>
		<link>http://marcinobel.com/index.php/csharp-4-0-named-arguments-usage/</link>
		<comments>http://marcinobel.com/index.php/csharp-4-0-named-arguments-usage/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 18:06:57 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=314</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-21" title=".NET Logo" src="http://marcinobel.com/wp-content/uploads/2009/08/net_logo.png" alt="" width="240" height="74" />One of the new features introduced in C# 4.0 were <strong><a title="Named Arguments in C# 4.0" href="http://msdn.microsoft.com/en-us/library/dd264739.aspx" target="_blank">named arguments</a></strong>. 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 &#8220;execution context&#8221; and a way to inform &#8220;infrastructure&#8221; 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 <a href="http://twitter.com/lesnikowski" target="_blank"><strong>@lesnikowski</strong></a> new idea popped into my mind: I can create &#8220;execution context&#8221; with lambdas and named arguments! The example below shows how I have changed the idea into real code.</p>
<pre class="brush: csharp; title: ; notranslate">
[Test]
public void Add_WhenInvokedShouldAddNewExternalAudioFolder()
{
    Execute(test: () =&gt;
    {
        var json = WebApiClient.ExternalAudioFolder.Add(&quot;My folder&quot;, &quot;My description&quot;);
        var message = json.DeserializeJson&lt;AddMessage&gt;();

        Assert.That(message.Result, Is.EqualTo(Message.Success));
    },
    inContextOf: Account.Basic,
    cleanUpAfter: true);
}
</pre>
<p>What do you think about the code above? Do you have any additional ideas how to improve readability of this &#8220;execution context&#8221;?</p>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/csharp-4-0-named-arguments-usage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fluent NHibernate conventions II &#8211; example for enumerations</title>
		<link>http://marcinobel.com/index.php/fluent-nhibernate-conventions-ii-enumerations/</link>
		<comments>http://marcinobel.com/index.php/fluent-nhibernate-conventions-ii-enumerations/#comments</comments>
		<pubDate>Thu, 20 May 2010 14:25:36 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=306</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-210" style="margin-right: 10px;" title="Fluent NHibernate" src="http://marcinobel.com/wp-content/uploads/fluent-nhibernate.png" alt="" width="360" height="117" />Most of the time I do not have to touch <strong><a title="Fluent NHibernate" href="http://fluentnhibernate.org/" target="_blank">Fluent NHibernate</a></strong> 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.</p>
<p>Because I hate redundant work I have defined a <strong>Fluent NHibernate convention</strong> presented below.</p>
<pre class="brush: csharp; title: ; notranslate">
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&lt;IPropertyInspector&gt; criteria)
        {
            criteria.Expect(x =&gt; x.Property.PropertyType.IsEnum)
                .Expect(x =&gt; x.Length == 0);
        }

        public void Apply(IPropertyInstance instance)
        {
            var names = Enum.GetNames(instance.Property.PropertyType);
            instance.Length(names.Max(name =&gt; name.Length));
        }
    }
}
</pre>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/fluent-nhibernate-conventions-ii-enumerations/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[BUG] invalid exec_format &#8220;ir&#8221;, no %s</title>
		<link>http://marcinobel.com/index.php/bug-invalid-exec_format-ir/</link>
		<comments>http://marcinobel.com/index.php/bug-invalid-exec_format-ir/#comments</comments>
		<pubDate>Tue, 11 May 2010 07:03:44 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=288</guid>
		<description><![CDATA[Today I&#8217;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: produced output like this: After some research turned out that RubyGems assumes that Ruby [...]]]></description>
			<content:encoded><![CDATA[<p>Today I&#8217;ve switched from the default, C based implementation of <strong>Ruby</strong> to new version of <strong>IronRuby</strong> (1.0). After installation I wanted to update <strong>gems</strong>, install <strong>rake</strong> tool and of course at this point problems started. Command for updating <strong>gems</strong> displayed below:</p>
<pre class="brush: php; title: ; notranslate">
igem update --system
</pre>
<p>produced output like this:</p>
<pre class="brush: php; title: ; notranslate">
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 &quot;ir&quot;, no %s
</pre>
<p>After some research turned out that <strong>RubyGems</strong> assumes that <strong>Ruby</strong> executable contains <em>&#8220;ruby&#8221;</em> word in the name. In case of <strong>IronRuby</strong> the name is <em>&#8220;ir.exe&#8221;</em> so in my opinion this strange behavior can be treated as a bug in <strong>RubyGems</strong>. I hope it will be fixed in next release but before that will happen here are the steps to workaround the problem and update <strong>gems</strong>:</p>
<p>1. Create path:<em> <strong>[IronRuby folder]\Lib\ruby\1.8\rubygems\defaults</strong></em><br />
2. Create file <strong><em>ironruby.rb</em></strong> and add it to the path from step 1<br />
3. Open <strong><em>ironruby.rb</em></strong> and add code from the snippet below</p>
<pre class="brush: ruby; title: ; notranslate">
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,
    #    &quot;[BUG] invalid exec_format #{exec_format.inspect}, no %s&quot;
    #end
    exec_format
  end
end
</pre>
<p>That is it. Now RubyGems will use new implementation of default_exec_format and everything should work as expected.</p>
<p>Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/bug-invalid-exec_format-ir/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Ruby for Windows with debug support</title>
		<link>http://marcinobel.com/index.php/ruby-windows-debug-support/</link>
		<comments>http://marcinobel.com/index.php/ruby-windows-debug-support/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 13:56:36 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=283</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="size-full wp-image-16 alignleft" title="Ruby Logo" src="http://marcinobel.com/wp-content/uploads/2009/08/ruby_logo.png" alt="" width="106" height="109" />I mentioned somewhere in previous posts I am playing a little with <a href="http://www.ruby-lang.org/en/" target="_blank"><strong>Ruby</strong></a> and <strong><a href="http://rubyonrails.org/" target="_blank">Ruby on Rails</a></strong>. 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 <a href="http://www.jetbrains.com/ruby/" target="_blank"><strong>RubyMine</strong></a>. 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.</p>
<p>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.</p>
<p>The package contains <strong>Ruby 1.8.7 for Windows </strong>with following gems:</p>
<ul>
<li>actionmailer (2.3.5)</li>
<li>actionpack (2.3.5)</li>
<li>activerecord (2.3.5)</li>
<li>activeresource (2.3.5)</li>
<li>activesupport (2.3.5)</li>
<li>albacore (0.1.1, 0.1.0)</li>
<li>columnize (0.3.1)</li>
<li>linecache (0.43)</li>
<li>net-sftp (2.0.4)</li>
<li>net-ssh (2.0.19)</li>
<li>rack (1.1.0, 1.0.1)</li>
<li>rails (2.3.5)</li>
<li>rake (0.8.7)</li>
<li>RedCloth (4.2.2)</li>
<li><strong>ruby-debug</strong> (0.10.3)</li>
<li><strong>ruby-debug-base</strong> (0.10.3)</li>
<li><strong>ruby-debug-ide</strong> (0.4.9)</li>
<li>rubyzip (0.9.4, 0.9.1)</li>
<li>sqlite3-ruby (1.2.5)</li>
</ul>
<p>Installation is very simple. Uncompress files to <em>C:\Ruby</em> directory and add <em>C:\Ruby\bin</em> path to <em>PATH</em> environment variable.</p>
<h2><a href="http://marcinobel.com/download/Ruby.1.8.7.zip">Download Ruby 1.8.7 for Windows with debug support</a></h2>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/ruby-windows-debug-support/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>IronRuby/RHTML based templates for .NET</title>
		<link>http://marcinobel.com/index.php/ironruby-rhtml-based-templates-for-net/</link>
		<comments>http://marcinobel.com/index.php/ironruby-rhtml-based-templates-for-net/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 23:09:20 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=225</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://marcinobel.com/wp-content/uploads/2009/08/net_logo.png"><img class="alignleft size-full wp-image-21" title=".NET Logo" src="http://marcinobel.com/wp-content/uploads/2009/08/net_logo.png" alt=".NET Logo" width="240" height="74" /></a></p>
<p>During last few days I was prototyping some of new features I would like to add to <a title="ByteCarrot Project" href="http://bytecarrot.com" target="_blank"><strong>ByteCarrot </strong></a>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 <strong><a title="ASP.NET MVC" href="http://www.asp.net/mvc/" target="_blank">ASP.NET MVC</a></strong> view engine.</p>
<p>After digging I have found an <strong>ASP.NET MVC</strong> application prototype with view engine based on <strong><a title="IronRuby" href="http://ironruby.net/" target="_blank">IronRuby</a></strong>. It was created by <strong><a title="Phil Haack" href="http://haacked.com/" target="_blank">Phil Haack</a></strong>&#8216;s team and its syntax was exactly the same as <strong>RHTML </strong>used in <strong><a title="Ruby on Rails" href="http://rubyonrails.org/" target="_blank">Ruby on Rails</a></strong> 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.</p>
<p>As an attachment to this post I have added the code created during prototyping. The code contains few classes where the most important is <em>RhtmlEngine</em>. It has very simple, self-expanatory interface and acts as an &#8220;entry point&#8221; 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.</p>
<pre class="brush: csharp; title: ; notranslate">
public class RhtmlEngine
{
    public Result Render(object model, string temlateFile, string targetFile)
        ...
    public Result Render(object model, StreamReader rhtml, StreamWriter writer)
        ...
}
</pre>
<h2>Simple template</h2>
<p>The templates engine requires three things to be able to generate HTML:</p>
<ul>
<li><strong>Model</strong> representing the data which should be presented in form of HTML page,</li>
<li><strong>Template</strong> defining how model should be presented,</li>
<li><strong>Target</strong> where generated HTML page should be saved.</li>
</ul>
<p>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.</p>
<p><strong>SimpleTemplate.rhtml</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
    &lt;body&gt;
        &lt;h1&gt;Hi! My name is: &lt;%= model.FirstName %&gt;&lt;%= model.LastName %&gt;&lt;/h2&gt;
        I like:
        &lt;ul&gt;
        &lt;% model.Hobbies.each do |hobby| %&gt;
			&lt;li&gt;&lt;%= hobby %&gt;&lt;/li&gt;
        &lt;% end %&gt;
        &lt;/ul&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Template shown above can be used to generate an HTML representation of the following model:</p>
<pre class="brush: csharp; title: ; notranslate">
var model = new SampleModel
{
    FirstName = &quot;Marcin&quot;,
    LastName = &quot;Obel&quot;,
    Hobbies = new List&lt;string&gt;
    {
        &quot;yachting&quot;,
        &quot;fishing&quot;,
        &quot;cycling&quot;
    }
};
</pre>
<p>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.</p>
<pre class="brush: csharp; title: ; notranslate">
var result = new RhtmlEngine().Render(model, &quot;SimpleTemplate.rhtml&quot;, &quot;SimpleHtml.html&quot;);
</pre>
<p>In result (as shown below) the code above will produce clean HTML filled in with the data from model.</p>
<p><strong>SimpleHtml.html</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
    &lt;body&gt;
        &lt;h1&gt;Hi! My name is: MarcinObel&lt;/h2&gt;
        I like:
        &lt;ul&gt;
            &lt;li&gt;yachting&lt;/li&gt;
            &lt;li&gt;fishing&lt;/li&gt;
            &lt;li&gt;cycling&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>More advanced example</h2>
<p>The example above does not show the most powerful part of this solution which is in fact inherited from <strong>IronRuby </strong>itself. Because templates are based on fully functional, dynamic language there is a possibility to extend basic features like <em>loops</em> and <em>if</em> 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:</p>
<ul>
<li><strong>encode </strong>- uses <em>HttpUtility </em>class from .NET Framework to encode HTML code</li>
<li><strong>render_li</strong> &#8211; renders an item of HTML list</li>
</ul>
<p><strong>AdvancedTemplate.rhtml</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;%
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 &quot;&lt;li&gt;#{text}&lt;/li&gt;&quot;;
end
%&gt;

&lt;html&gt;
    &lt;body&gt;
        &lt;h1&gt;Hi! My name is: &lt;%= model.FirstName %&gt;&lt;%= model.LastName %&gt;&lt;/h2&gt;
        I like:
        &lt;ul&gt;
        &lt;% model.Hobbies.each do |hobby|
                 render_li hobby
             end %&gt;
        &lt;/ul&gt;
        &lt;pre&gt;
            &lt;%= encode model.UglyJavaScript %&gt;
        &lt;/pre&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In order to present a usage of custom <strong>IronRuby </strong>function added to the template, below you can find extended model from previous example. Now the model contains additional property named <em>UglyJavaScript </em>containing JavaScript code which should be encoded before it can be presented in HTML.</p>
<pre class="brush: csharp; title: ; notranslate">
var model = new SampleModel
{
    FirstName = &quot;Marcin&quot;,
    LastName = &quot;Obel&quot;,
    Hobbies = new List&lt;string&gt;
    {
        &quot;yachting&quot;,
        &quot;fishing&quot;,
        &quot;cycling&quot;
    },
    UglyJavaScript = @&quot;&lt;script type='text/javascript'&gt;window.close();&lt;/script&gt;&quot;
};

var result = new RhtmlEngine().Render(model, &quot;AdvancedTemplate.rhtml&quot;, &quot;AdvancedHtml.html&quot;);
</pre>
<p>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.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
    &lt;body&gt;
        &lt;h1&gt;Hi! My name is: MarcinObel&lt;/h2&gt;
        I like:
        &lt;ul&gt;
        &lt;li&gt;yachting&lt;/li&gt;&lt;li&gt;fishing&lt;/li&gt;&lt;li&gt;cycling&lt;/li&gt;
        &lt;/ul&gt;
        &lt;pre&gt;
        &amp;lt;script type='text/javascript'&amp;gt;window.close();&amp;lt;/script&amp;gt;
        &lt;/pre&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Resources</h2>
<ul>
<li><a title="RHTML templates engine source code" href="http://marcinobel.com/wp-content/uploads/Rhtml.Sample.zip" target="_blank">RHTML templates engine source code</a></li>
<li><a title="IronRuby official website" href="http://ironruby.net/" target="_blank">IronRuby official website</a></li>
<li><a title="Phil Haack" href="http://haacked.com/" target="_blank">Phil Haack&#8217;s blog</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/ironruby-rhtml-based-templates-for-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Fluent NHibernate conventions &#8211; examples</title>
		<link>http://marcinobel.com/index.php/fluent-nhibernate-conventions-examples/</link>
		<comments>http://marcinobel.com/index.php/fluent-nhibernate-conventions-examples/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 22:22:59 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=195</guid>
		<description><![CDATA[Fluent 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 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://marcinobel.com/wp-content/uploads/fluent-nhibernate.png"><img class="alignleft size-full wp-image-210" title="Fluent NHibernate" src="http://marcinobel.com/wp-content/uploads/fluent-nhibernate.png" alt="Fluent NHibernate" width="360" height="117" /></a><strong><a title="Fluent NHibernate" href="http://fluentnhibernate.org/" target="_blank">Fluent NHibernate</a></strong> is my favorite extension for <strong><a title="NHibernate" href="http://nhforge.org/" target="_blank">NHibernate</a></strong>. 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 <strong><a title="Fluent NHibernate Documentation" href="http://wiki.fluentnhibernate.org/Conventions" target="_blank">Fluent NHibernate Wiki</a><span style="font-weight: normal;"> where this feature is described in detail</span></strong>.</p>
<p><strong>ColumnNullabilityConvention</strong> &#8211; says that if nullability for column has not been specified explicitly, should be set to &#8220;NOT NULL&#8221;.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ColumnNullabilityConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria&lt;IPropertyInspector&gt; criteria)
    {
        criteria.Expect(x =&gt; x.Nullable, Is.Not.Set);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Not.Nullable();
    }
}
</pre>
<p><strong>CreatedAtPropertyAccessConvention</strong> &#8211; says that every property named <span style="text-decoration: underline;">CreatedAt </span>should be accessed through camel case field hidden behind it.</p>
<pre class="brush: csharp; title: ; notranslate">
public class CreatedAtPropertyAccessConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria&lt;IPropertyInspector&gt; criteria)
    {
        criteria.Expect(x =&gt; x.Property.Name == &quot;CreatedAt&quot;);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Access.ReadOnlyPropertyThroughCamelCaseField(
            CamelCasePrefix.Underscore);
    }
}
</pre>
<p><strong>ForeignKeyConstraintNameConvention</strong> &#8211; says that name of every foreign key constraint representing one to many relation should consist of names of entities for which it was specified.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ForeignKeyConstraintNameConvention
    : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance instance)
    {
        instance.Key.ForeignKey(&quot;{0}_{1}_FK&quot;.AsFormat(
        instance.Member.Name, instance.EntityType.Name));
    }
}
</pre>
<p><strong>ForeignKeyNameConvention</strong> &#8211; says that name of every column containing foreign key id should consist of name of type which it points to with &#8220;Id&#8221; suffix.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ForeignKeyNameConvention : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance instance)
    {
        instance.Key.Column(instance.EntityType.Name + &quot;Id&quot;);
    }
}
</pre>
<p><strong>PrimaryKeyNameConvention </strong>- says that name of every column representing primary key should consist of entity name and &#8220;Id&#8221; suffix.</p>
<pre class="brush: csharp; title: ; notranslate">
public class PrimaryKeyNameConvention : IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {
        instance.Column(instance.EntityType.Name + &quot;Id&quot;);
    }
}
</pre>
<p><strong>ReferenceConvention</strong> &#8211; says that name of column referenced in many to one convention should consist of entity name and &#8220;Id&#8221; suffix.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ReferenceConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        instance.Column(instance.Property.PropertyType.Name + &quot;Id&quot;);
    }
}
</pre>
<p><strong>StringColumnLengthConvention</strong> &#8211; says that if length for string column has not been specified, it should be set to 100.</p>
<pre class="brush: csharp; title: ; notranslate">
public class StringColumnLengthConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria&lt;IPropertyInspector&gt; criteria)
    {
        criteria.Expect(x =&gt; x.Type == typeof(string))
            .Expect(x =&gt; x.Length == 0);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Length(100);
    }
}
</pre>
<p><strong>TableNameConvention</strong> &#8211; says that if name for table has not been specified, it should be created using concatenation of entity name and &#8220;s&#8221; suffix.</p>
<pre class="brush: csharp; title: ; notranslate">
public class TableNameConvention
    : IClassConvention, IClassConventionAcceptance
{
    public void Accept(IAcceptanceCriteria&lt;IClassInspector&gt; criteria)
    {
        criteria.Expect(x =&gt; x.TableName, Is.Not.Set);
    }

    public void Apply(IClassInstance instance)
    {
        instance.Table(instance.EntityType.Name + &quot;s&quot;);
    }
}
</pre>
<p><strong>At the end the most important thing</strong> which shows that such conventions make sense. With default <strong>Fluent NHibernate</strong> conventions DDL generated by NHibernate for MySQL looked like this:</p>
<pre class="brush: sql; title: ; notranslate">
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)
</pre>
<p>When I have applied conventions mentioned above to my fluent mappings DDL looks like this:</p>
<pre class="brush: sql; title: ; notranslate">
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)
</pre>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/fluent-nhibernate-conventions-examples/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>MSpec BDD framework installer</title>
		<link>http://marcinobel.com/index.php/mspec-bdd-installer/</link>
		<comments>http://marcinobel.com/index.php/mspec-bdd-installer/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 11:23:35 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=186</guid>
		<description><![CDATA[Installation 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 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://marcinobel.com/wp-content/uploads/2009/08/net_logo.png"><img class="alignleft size-full wp-image-21" title=".NET Logo" src="http://marcinobel.com/wp-content/uploads/2009/08/net_logo.png" alt=".NET Logo" width="240" height="74" /></a>Installation of <strong>MSpec</strong> 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 <strong>Open Source</strong> project requires a lot of time (I have my own project called <a title="ByteCarrot Project" href="http://bytecarrot.com" target="_blank"><strong>ByteCarrot</strong></a>) and you cannot do everything. Because of that I decided to help a little bit creators of <strong>MSpec </strong>and I have prepared an installer for this BDD framework. It is based on <strong>WiX </strong>and latest release of <strong>MSpec </strong>witch is version <strong>0.3</strong>.</p>
<p>The installer is able to automatically integrate <strong>MSpec</strong> with <strong>TestDriven.NET</strong> and <strong>ReSharper</strong> (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.</p>
<h2><a title="Download installer for MSpec 0.3" href="http://marcinobel.com/download/MSpec-0.3.msi" target="_self">Download installer for MSpec 0.3</a></h2>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/mspec-bdd-installer/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Rake in .NET projects – installation and setup</title>
		<link>http://marcinobel.com/index.php/rake-net-projects-installation-setup/</link>
		<comments>http://marcinobel.com/index.php/rake-net-projects-installation-setup/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 18:10:27 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=169</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-21" title=".NET Logo" src="http://marcinobel.com/wp-content/uploads/2009/08/net_logo.png" alt=".NET Logo" width="240" height="74" /><br />
Recently I have rewritten all <em><strong>MSBuild </strong></em>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. <strong>ByteCarrot</strong><em><strong> </strong></em>project to <a title="Rake project" href="http://rake.rubyforge.org/" target="_blank"><em><strong>Rake</strong></em></a>. I made the decision about changing build solution mostly because I required something what works not only under <em>Windows </em>but also on other operating systems. After rewriting turned out that <em>Rake </em>is a great solution for tasks for which it was created and can be used not only with <em><strong>Ruby/RoR</strong></em> projects but also with other technologies like <strong>.</strong><em><strong>NET</strong></em><em> </em>and <em><strong>Mono</strong></em>. It is really awesome multi-purpose tool. Today I would like to show you how to install and configure <em>Rake </em>on <em>Windows </em>operating system in order to start using it in your projects.</p>
<h2>Ruby installation</h2>
<p>First of all, because <em>Rake </em>is based on <em>Ruby </em>language, you will need an interpreter. You can download <em>Ruby </em>distribution from its <em><a title="Ruby Language" href="http://ruby-lang.org/" target="_blank">official website</a></em> but I do not recommend that because there is only installer for version 1.8.6 which is quite old. Other packages for <em>Windows </em>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 <em>Ruby </em>1.9.1-p129 <em>(rubyinstaller-1.9.1-p129-preview1.exe)</em> available on <em><a title="RubyForge" href="http://rubyforge.org/frs/?group_id=167" target="_blank"><strong>RubyForge</strong></a></em>.</p>
<p><img class="alignright size-full wp-image-16" title="Ruby Logo" src="http://marcinobel.com/wp-content/uploads/2009/08/ruby_logo.png" alt="Ruby Logo" width="106" height="109" /></p>
<p>When the installer is on your hard drive, start installation. There is nothing magic in the installation process but you should remember that <em>Rake</em> does not work properly when <em>Ruby</em> in installed in <em>C:\Program Files</em> 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 <em>C:\Ruby</em>.</p>
<p>Last thing you should do to be able to use <em>Ruby </em>is adding the location of its binaries to the <em>%Path%</em> environment variable. In my case this variable was extended with <em>C:\Ruby\bin</em> path.</p>
<p>Now you can check if everything works by executing from command line two following commands:</p>
<pre class="brush: csharp; title: ; notranslate">
ruby –v
gem -v
</pre>
<p>The output from console should be:</p>
<pre class="brush: csharp; title: ; notranslate">
C:\&gt;ruby –v
ruby 1.9.1p129 (2009-05-12 revision 23412) [i386-mingw32]
C:\&gt;gem –v
1.3.4
</pre>
<h2>Rake installation</h2>
<p>Now, when <em>Ruby </em>is installed and you are sure that it works you can take care of <em>Rake</em>. The most popular and safe way to install <em>Ruby </em>extensions and libraries (including <em>Rake</em>) is mechanism called <em><strong>Gems</strong></em>. In order to install <em>Rake </em>using <em>Gems </em>execute following command from command line:</p>
<pre class="brush: csharp; title: ; notranslate">
C:\&gt;gem install --remote rake
</pre>
<p>The output from console should be:</p>
<pre class="brush: csharp; title: ; notranslate">
C:\&gt;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...
</pre>
<p>When the command will finish do not close command line window yet. At the end execute one more command to be sure that <em>Rake </em>is installed properly:</p>
<pre class="brush: csharp; title: ; notranslate">
C:\&gt;rake –V
</pre>
<p>The output from console should be:</p>
<pre class="brush: csharp; title: ; notranslate">
C:\&gt;rake –V
rake, version 0.8.3
</pre>
<p>Congratulations! You have managed to install <em>Rake </em>and you are ready to write your first build script. <strong>More about Rake can be found on </strong><a title="Rake project" href="http://rake.rubyforge.org/" target="_blank"><em><strong>official site</strong></em></a><strong> of the project</strong>. Example <em>Rake </em>scripts can be found in <em><a title="ByteCarrot source code" href="http://bytecarrot.codeplex.com/SourceControl/ListDownloadableCommits.aspx" target="_blank"><strong>ByteCarrot source code on CodePlex</strong></a></em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/rake-net-projects-installation-setup/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC 2 Beta &#8211; new features</title>
		<link>http://marcinobel.com/index.php/aspnet-mvc-2-beta-features/</link>
		<comments>http://marcinobel.com/index.php/aspnet-mvc-2-beta-features/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 12:38:57 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=134</guid>
		<description><![CDATA[Yesterday 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 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://marcinobel.com/wp-content/uploads/2009/08/net_logo.png"><img class="alignleft size-full wp-image-21" title=".NET Logo" src="http://marcinobel.com/wp-content/uploads/2009/08/net_logo.png" alt=".NET Logo" width="240" height="74" /></a>Yesterday at <strong><a title="PDC 09" href="http://microsoftpdc.com/" target="_blank">PDC 09</a></strong> Bob Muglia announced the release of <strong><a title="ASP.NET MVC 2 Beta" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=4817cdb2-88ea-4af4-a455-f06b4c90fd2c&amp;displaylang=en" target="_blank">ASP.NET MVC 2 Beta</a></strong>. This release contains a lot of new, interesting stuff. Below you can find a list of new features taken from official release notes.</p>
<h2>New RenderAction method</h2>
<p><em>Html.RenderAction</em> (and its counterpart <em>Html.Action</em>) 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. <em>Html.RenderAction</em> writes directly to the response, whereas <em>Html.Action</em> returns a string with the output. <em>RenderAction</em> works only with actions that render views.</p>
<h2>Strongly typed UI helpers</h2>
<p>ASP.NET MVC 2 includes new expression-based versions of existing HTML helper methods. The new helpers include the following:</p>
<ul>
<li><em>ValidationMessageFor</em></li>
<li><em>TextAreaFor</em></li>
<li><em>TextBoxFor</em></li>
<li><em>HiddenFor</em></li>
<li><em>DropDownListFor</em></li>
</ul>
<h2>TempDataDictionary improvements</h2>
<p>The behavior of the <em>TempDataDictionary</em> 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.</p>
<p>To address these scenarios, the <em>TempDataDictionary </em>class was changed so that all the keys survive indefinitely until the key is read from the <em>TempDataDictionary </em>object. The Keep method was added to <em>TempDataDictionary </em>to let you indicate that the value should not be removed after reading. The <em>RedirectToActionResult </em>is an example where the <em>Keep </em>method is called in order to retain all the keys for the next request.</p>
<h2>Client validation library</h2>
<p>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.</p>
<ul>
<li>MicrosoftAjax.js</li>
<li>MicrosoftMvcAjax.js</li>
</ul>
<p>The following example shows a view with client validation enabled.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;MicrosoftAjax.js&quot;&gt;&lt;/script&gt;&lt;script type=&quot;text/javascript&quot; src=&quot;MicrosoftMvcAjax.js&quot;&gt;&lt;/script&gt;

  //...
</pre>
<h2>&#8220;Add Area&#8221; dialog box</h2>
<p>ASP.NET MVC 2 Beta includes a new <em>Add Area</em> 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.</p>
<h2>Calling action methods asynchronously</h2>
<p>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 <a title="Using an Asynchronous Controller in ASP.NET MVC " href="http://go.microsoft.com/fwlink/?LinkId=177780" target="_blank">Using an Asynchronous Controller in ASP.NET MVC</a> In the ASP.NET MVC 2 documentation.</p>
<h2>Blank project template</h2>
<p>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.</p>
<h2>Multiple model validator providers</h2>
<p>ASP.NET MVC 2 Beta lets you register multiple validation providers. The following example shows how to register multiple providers.</p>
<pre class="brush: csharp; title: ; notranslate">
protected void Application_Start() {
    ModelValidatorProviders.Providers.Add(new MyXmlModelValidatorProvider());
    ModelValidatorProviders.Providers.Add(new MyDbModelValidatorProvider());
    //...
}
</pre>
<h2>Multiple value provider registration</h2>
<p>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:</p>
<ul>
<li><em>FormValueProvider</em></li>
<li><em>RouteDataValueProvider</em></li>
<li><em>QueryStringValueProvider</em></li>
<li><em>HttpFileCollectionValueProvider</em></li>
</ul>
<p>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.</p>
<pre class="brush: csharp; title: ; notranslate">
protected void Application_Start() {
    ValueProviders.Providers.Add(new JsonValueProvider());
    //...
}
</pre>
<p><a title="ASP.NET MVC 2 Beta Release Notes" href="http://go.microsoft.com/fwlink/?LinkID=157069">Download full ASP.NET MVC 2 Beta Release Notes</a></p>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/aspnet-mvc-2-beta-features/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Metadata based validation with jQuery</title>
		<link>http://marcinobel.com/index.php/metadata-based-validation-with-jquery/</link>
		<comments>http://marcinobel.com/index.php/metadata-based-validation-with-jquery/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 19:36:36 +0000</pubDate>
		<dc:creator>Marcin Obel</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://marcinobel.com/?p=75</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://marcinobel.com/wp-content/uploads/2009/10/jquery.validation.png"><img class="alignleft size-full wp-image-76" title="jQuery Validation enabled form" src="http://marcinobel.com/wp-content/uploads/2009/10/jquery.validation.png" alt="jQuery Validation enabled form" width="353" height="498" /></a></p>
<p>Recently I spent some time prototyping my own validation for <a href="http://www.asp.net/mvc/" target="_blank"><strong>ASP.NET MVC</strong></a>. 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 <strong>JavaScript</strong> 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 <a href="http://jquery.com/" target="_blank"><strong>jQuery</strong></a> and its <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" target="_blank"><strong>Validation</strong></a> plugin. One of the things which were crucial to my decision was ability of this framework to use metadata stored as <strong>JSON</strong> in class attribute of <strong>HTML</strong> element. The concept of metadata available in<strong> jQuery</strong> 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 <strong>jQuery Validation</strong> was easy setup which I want to show you now.</p>
<p>If you want to use <strong>jQuery Validation</strong> in your project first of all you will need of course <strong>jQuery</strong> library which can be downloaded <a href="http://jquery.com/" target="_blank"><strong>here</strong><strong></strong></a>, <strong>jQuery Metadata</strong> plugin which is available <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" target="_blank"><strong>here</strong></a> and <strong>jQuery Validation</strong> plugin downloadable from <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" target="_blank"><strong>here</strong></a>.</p>
<p>When you collected all required prerequisites you have to add reference to them in your <strong>HTML</strong>. Simply add code shown below to the body of <em><strong></strong></em> tag but remember to ensure that paths lead to place where <strong>JavaScript</strong> files are located.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;&lt;script type=&quot;text/javascript&quot; src=&quot;jquery.validate.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;jquery.metadata.js&quot;&gt;&lt;/script&gt;
</pre>
<p>When<strong> jQuery</strong> 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 <em><strong>class</strong></em> attribute and set its value to <strong><em>{required:true}</em></strong>. This will tell <strong>Validation</strong>plugin 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.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;input class=&quot;{required:true, maxlength:100, messages:{required:'This field is required.', maxlength:'This field can contain maximum 100 characters.'}}&quot; type=&quot;text&quot; /&gt;
&lt;input class=&quot;{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.'}}&quot; type=&quot;text&quot; /&gt;
</pre>
<p>Listing below shows this validation metadata in wider context.</p>
<pre class="brush: xml; title: ; notranslate">&lt;/pre&gt;
&lt;form id=&quot;MyForm&quot; action=&quot;/Registration&quot; method=&quot;post&quot;&gt;&lt;label for=&quot;DisplayName&quot;&gt;Username:&lt;/label&gt; &lt;input id=&quot;DisplayName&quot; class=&quot;{required:true, maxlength:100, messages:{required:'This field is required.', maxlength:'This field can contain maximum 100 characters.'}}&quot; type=&quot;text&quot; name=&quot;DisplayName&quot; /&gt; &lt;input type=&quot;submit&quot; value=&quot;Submit!&quot; /&gt;&lt;/form&gt;
&lt;pre&gt;
</pre>
<p>At the end when you have defined all validation rules only thing you should do is adding following code after closing <em><strong></strong></em>tag and that is it.</p>
<pre class="brush: xml; title: ; notranslate">&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
    $(&quot;#MyForm&quot;).validate({
        errorElement: &quot;span&quot;
    });
// ]]&gt;&lt;/script&gt;
</pre>
<p>Now when you will click <em>Submit!</em> button your form will be validated and in case of errors apropriate messages will be displayed below corresponding input control.</p>
<p>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: <a href="http://marcinobel.com/wp-content/uploads/2009/10/jQuery.Validation.Sample.zip"><strong>download</strong></a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://marcinobel.com/index.php/metadata-based-validation-with-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

