<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/atom10full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"><id>tag:blogger.com,1999:blog-3198935374994345981</id><updated>2008-07-06T17:31:08.029+02:00</updated><title type="text">Coding Instinct</title><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default?start-index=26&amp;max-results=25&amp;redirect=false" /><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/posts/default" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>27</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><link rel="self" href="http://feeds.feedburner.com/codinginstinct" type="application/atom+xml" /><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-3060053344671601673</id><published>2008-07-03T18:39:00.001+02:00</published><updated>2008-07-03T21:16:24.395+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="NHibernate" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title type="text">NHibernate CritieraTransformer</title><content type="html">&lt;p&gt;NHibernate 2.0 beta1 was release a couple of days ago, so I thought it was time to go through some more new stuff that has been added since version 1.2.&amp;#160; I found a new useful helper class named CritieraTransformer which can be used to clone ICritiera queries. This is very useful if you want to perform multiple queries with small variations (in the where clause for example). It also has a useful function that adds a row count projection to a query.&lt;/p&gt;  &lt;p&gt;Example: &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; customersCritiera = session.CreateCritiera(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="type"&gt;Customer&lt;/span&gt;));
&lt;span class="kwrd"&gt;var&lt;/span&gt; totalCustomersCritiera =  &lt;span class="type"&gt;CriteriaTransformer&lt;/span&gt;.TransformToRowCount(customersCritiera);

&lt;span class="kwrd"&gt;var&lt;/span&gt; inGroupCriteria = 
  &lt;span class="type"&gt;CriteriaTransformer&lt;/span&gt;.Clone(customersCritiera)
    .Add(&lt;span class="type"&gt;Expression&lt;/span&gt;.Eq(&lt;span class="str"&gt;&amp;quot;Group&amp;quot;&lt;/span&gt;, group));

&lt;span class="kwrd"&gt;var&lt;/span&gt; goldenInGroupCritiera = 
  &lt;span class="type"&gt;CriteriaTransformer&lt;/span&gt;.Clone(inGroupCriteria)
    Add(&lt;span class="type"&gt;Expression&lt;/span&gt;.Eq(&lt;span class="str"&gt;&amp;quot;IsGold&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;true&lt;/span&gt;);                          
                
&lt;span class="kwrd"&gt;IList&lt;/span&gt; results = session.CreateMultiCriteria()  
     .Add(inGroupCriteria)
     .Add(goldenInGroupCritiera)
     .Add(totalCustomersCritiera)
     .List();

&lt;span class="type"&gt;IList&lt;/span&gt; inGroupCustomers = (&lt;span class="type"&gt;IList&lt;/span&gt;)results[0];
&lt;span class="type"&gt;IList&lt;/span&gt; customers = (&lt;span class="type"&gt;IList&lt;/span&gt;)results[1];
&lt;span class="type"&gt;IList&lt;/span&gt; counts = (&lt;span class="type"&gt;IList&lt;/span&gt;)results[2];
&lt;span class="type"&gt;int&lt;/span&gt; count = (&lt;span class="kwrd"&gt;int&lt;/span&gt;)counts[0]; &lt;/pre&gt;

&lt;p&gt;The multi criteria feature allows you peform multiple database queries in a single database call, the downside is that the IMultiCritiera interface does not support generic lists. &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/07/nhibernate-critieratransformer.html" title="NHibernate CritieraTransformer" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=3060053344671601673" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/3060053344671601673/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3060053344671601673" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3060053344671601673" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-4643921913692683449</id><published>2008-05-27T21:25:00.001+02:00</published><updated>2008-05-28T08:48:10.183+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET MVC" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title type="text">Descriptive comments for null arguments</title><content type="html">&lt;p&gt;ASP.NET MVC Preview 3 was released today and while browsing through the code I saw something which I have seen before but never really reflected on. &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;internal&lt;/span&gt; ViewResult View() {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(&lt;span class="kwrd"&gt;null&lt;/span&gt; &lt;span class="rem"&gt;/* viewName */&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt; &lt;span class="rem"&gt;/* masterName */&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt; &lt;span class="rem"&gt;/* model */&lt;/span&gt;);
}

&lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;internal&lt;/span&gt; ViewResult View(&lt;span class="kwrd"&gt;object&lt;/span&gt; model) {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(&lt;span class="kwrd"&gt;null&lt;/span&gt; &lt;span class="rem"&gt;/* viewName */&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt; &lt;span class="rem"&gt;/* masterName */&lt;/span&gt;, model);
}&lt;/pre&gt;

&lt;p&gt;See how they have an inline comment with the argument name for the null arguments? This is a really nice practice as it makes function calls where nulls are passed much more readable and understandable. Functions that take in objects that can be null or booleans can often be very cryptic since you don't know what argument they represent. In some languages like ruby you can optionally name arguments: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;def&lt;/span&gt; View(model)
  &lt;span class="kwrd"&gt;return&lt;/span&gt; View(viewName: nil, masterName: nil, model: nil)
end&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
For functions taking in booleans you have the option to instead use an enum, this can in some cases make function calls a lot more understandable. For example: 

&lt;p&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="type"&gt;FileStream&lt;/span&gt; stream  = &lt;span class="type"&gt;File&lt;/span&gt;.Open (&amp;#8220;foo.txt&amp;#8221;, &lt;span class="kwrd"&gt;true&lt;/span&gt;, &lt;span class="kwrd"&gt;false&lt;/span&gt;);
&lt;span class="type"&gt;FileStream&lt;/span&gt; stream  = &lt;span class="type"&gt;File&lt;/span&gt;.Open (&amp;#8220;foo.txt&amp;#8221;, &lt;span class="type"&gt;CasingOptions&lt;/span&gt;.CaseSenstative, &lt;span class="type"&gt;FileMode&lt;/span&gt;.Open);&lt;/pre&gt;

&lt;p&gt;For parameters that can be null you could instead use the &lt;a href="http://en.wikipedia.org/wiki/Null_Object_pattern"&gt;null object pattern&lt;/a&gt; but this might not be feasible in many scenarios so I think that having a short comment like in the first code snippet is a nice way to handle this. &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/descriptive-comments-for-null-functions.html" title="Descriptive comments for null arguments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=4643921913692683449" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/4643921913692683449/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/4643921913692683449" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/4643921913692683449" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-9019398449831537744</id><published>2008-05-26T22:22:00.001+02:00</published><updated>2008-05-27T10:35:18.660+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Reviews" /><category scheme="http://www.blogger.com/atom/ns#" term="Science" /><title type="text">The Language Instinct Review</title><content type="html">&lt;a href="http://lh4.ggpht.com/torkel.odegaard/SDscCiEa-gI/AAAAAAAAAZg/bAeCVtIJ0bA/s1600-h/image%5B6%5D.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; float: right; border-bottom-width: 0px; border-right-width: 0px" height="240" alt="image" src="http://lh6.ggpht.com/torkel.odegaard/SDscECEa-hI/AAAAAAAAAZo/stlAg2M9d8g/image_thumb%5B4%5D.png?imgmax=800" width="158" /&gt;&lt;/a&gt;   &lt;p&gt;A couple of weeks ago I finished a great book named &lt;a href="http://www.amazon.com/Language-Instinct-Creates-Perennial-Classics/dp/0060958332"&gt;The Language Instinct: How the Mind Creates Language&lt;/a&gt; by the psychologist and cognitive scientist Steven Pinker. It is not a book directly related to programming, but if you are interested in languages (be that human or computer languages) or just popular science in general I think you will enjoy it. It covers the theory that all human language share a common &lt;a href="http://en.wikipedia.org/wiki/Universal_grammar"&gt;universal grammar&lt;/a&gt;, and that this grammar is innately encoded in the human brain. &lt;/p&gt;  &lt;p&gt;It goes into great detail on how children learn language, a feat that every human child do by just listing to adults talk. The book can be quite technical with a lot linguistic jargon sometimes, but it is still very readable. I really like the chapter about how creole languages evolve from pidgin languages. &lt;/p&gt;  &lt;p&gt;A pidgin language is (wikipedia):&lt;/p&gt;  &lt;blockquote&gt;&lt;i&gt;A pidgin is a simplified language that develops as a means of communication between two or more groups that do not have a language in common, in situations such as trade. Pidgins are not the native language of any speech community, but are instead learned as second languages.&lt;/i&gt;&lt;/blockquote&gt;  &lt;p&gt;A pidgin is a language with a very simplified or non existent grammar which require a lot of context to be understandable (like physically pointing to what or who are are talking about). A creole language is a well defined and stable language that has evolved from a pidgin language. A popular theory (the one discussed in the book) describes how creole languages are created by young children learning a pidgin language as a native language, and in that process creates a more complex grammar, with fixed phonology, syntax, morphology, and syntactic embedding. I think it is amazing that children can create a fully developed language in only a single generation. &lt;/p&gt;  &lt;p&gt;The book also covers the evolution of the human language ability, how languages change over time and how brain damage effects speech and speech recognition. &lt;/p&gt;  &lt;p&gt;Sorry for a post about non .net/programming, but I just wanted to share this, and yes I was reading this book when I came up with the title for this blog, oh.. and while I am at it here are some other great popular science books that I read recently which I can highly recommend: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.amazon.co.uk/Mind-Works-Penguin-Press-Science/dp/0140244913/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1211832334&amp;amp;sr=8-1"&gt;How the Mind Works&lt;/a&gt; by Steven Pinker &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.amazon.co.uk/Selfish-Gene-Richard-Dawkins/dp/0199291152/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1211832379&amp;amp;sr=1-1"&gt;The Selfish Gene&lt;/a&gt; by Richard Dawkins &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.amazon.co.uk/Blind-Watchmaker-Richard-Dawkins/dp/0141026162/ref=sr_1_6?ie=UTF8&amp;amp;s=books&amp;amp;qid=1211832379&amp;amp;sr=1-6"&gt;The Blind Watchmaker&lt;/a&gt; by Richard Dawkins &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.amazon.co.uk/Genome-Autobiography-Species-23-Chapters/dp/185702835X/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1211832491&amp;amp;sr=1-1"&gt;Genome&lt;/a&gt; by Matt Ridley &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.amazon.co.uk/Musicophilia-Tales-Music-Oliver-Sacks/dp/0330418378/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1211832539&amp;amp;sr=1-1"&gt;Musicophilia: Tales of Music and the Brain&lt;/a&gt; by Oliver Sacks &lt;/li&gt; &lt;/ul&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/language-instinct-review.html" title="The Language Instinct Review" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=9019398449831537744" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/9019398449831537744/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/9019398449831537744" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/9019398449831537744" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-3476834812660083461</id><published>2008-05-23T08:41:00.001+02:00</published><updated>2008-05-23T08:44:15.948+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Git" /><category scheme="http://www.blogger.com/atom/ns#" term="Boo" /><title type="text">Boo in Visual Studio</title><content type="html">&lt;p&gt;There is new project on codeplex called &lt;a href="http://www.codeplex.com/BooLangStudio" target="_blank"&gt;BooLangStudio&lt;/a&gt; that adds Boo as supported language in Visual Studio 2008. It is still in it's infancy but the basics are there, Class Library and Console Application projects are support, as is basic syntax highlighting. The project was created by Jeff Olson, but there are other contributors, for example James Gregory who has begun porting over some intellisense support from his Boo Visual Studio plugin.&lt;/p&gt;  &lt;p&gt;The progress is looking good: &lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh6.ggpht.com/torkel.odegaard/SDZnBSEa-YI/AAAAAAAAAZA/gaJQAwH0RlU/s1600-h/image%5B30%5D.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="515" alt="image" src="http://lh5.ggpht.com/torkel.odegaard/SDZnCCEa-ZI/AAAAAAAAAZE/FV1VPNhR9jY/image_thumb%5B22%5D.png?imgmax=800" width="600" border="0" /&gt;&lt;/a&gt;&amp;#160; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;I have been wishing for some Boo visual studio integration for a long time. I thought I would try to contribute to BooLangStudio, however the source is on &lt;a href="http://github.com" target="_blank"&gt;github&lt;/a&gt;. That means I had to learns some Git :) &lt;/p&gt;  &lt;p&gt;It wasn't that bad actually, I downloaded &lt;a href="http://code.google.com/p/msysgit/" target="_blank"&gt;msysgit&lt;/a&gt; and followed this &lt;a href="http://kylecordes.com/2008/04/30/git-windows-go/" target="_blank"&gt;Guide&lt;/a&gt;. The cool thing about Git is it's distributed nature which makes it very different from Subversion. The first thing I did, since I wanted to contribute was to fork Jeff Olson's repository. This is very simple, just register on github and you click the fork button:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh3.ggpht.com/torkel.odegaard/SDZnCiEa-aI/AAAAAAAAAYQ/400uX_PbMxY/s1600-h/image%5B10%5D.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="282" alt="image" src="http://lh6.ggpht.com/torkel.odegaard/SDZnDSEa-bI/AAAAAAAAAYY/mmhIoq34kuA/image_thumb%5B6%5D.png?imgmax=800" width="573" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;When you fork a github repository you get your own remote repository that you can push commits two. After I had created my fork I could ask git to create local clone of that repository. Git does not have local &amp;quot;working copies&amp;quot; but local full repositories. This means that you can view history logs, do commits, merges, branching all locally, without any network connection. &lt;/p&gt;  &lt;p&gt;When I had done a commit I did a push to my github remote repository. Github has very nice commit/diff visualizations:&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;a href="http://lh4.ggpht.com/torkel.odegaard/SDZnDyEa-cI/AAAAAAAAAYg/WBctlmyBqUw/s1600-h/image%5B25%5D.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="311" alt="image" src="http://lh6.ggpht.com/torkel.odegaard/SDZnESEa-dI/AAAAAAAAAYo/YACRCcNugCw/image_thumb%5B17%5D.png?imgmax=800" width="400" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;In your local repository you can configure a list of other remote repositories that you can pull from (pull = fetch+merge). I noticed that James Gregory had a fork where he committed his initial work on intellisense, and I wanted to try this out. So I created a local branch, added James Gregory's fork as a remote repository and pulled his changes into that branch. The cool thing is that merging in git keeps the complete history of the commits you merge, it almost looks like James Gregory committed directly to my repository. &lt;/p&gt;  &lt;p&gt;Everything is done at the command line, there is a TortoiseGit in the works I think but I am not sure what state it is in. Here is an example of how you can merge changes from a remote repository: &lt;/p&gt;  &lt;pre&gt;$ git remote add jagregory git://github.com/jagregory/boolangstudio.git
$ git checkout -b jagrefory/master
$ git pull jagregory master
$ git checkout master
$ git merge jagregory/master&lt;/pre&gt;

&lt;p&gt;Github has a very cool network graph that shows forks and commits and where they came from: &lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh5.ggpht.com/torkel.odegaard/SDZnFCEa-eI/AAAAAAAAAYw/AQ3MEf1piKo/s1600-h/image%5B29%5D.png"&gt;&lt;img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="258" alt="image" src="http://lh3.ggpht.com/torkel.odegaard/SDZnFiEa-fI/AAAAAAAAAY4/lytHrxs9zdw/image_thumb%5B21%5D.png?imgmax=800" width="632" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The red dots on my line represents the commits that I merged from the jagregory branch. If you hover over a a dot it will show the commit info! Git and the whole concept of a distributed source control system is very cool and interesting. The usability aspects are not quite there yet, it's a lot of git commands and parameters to learn, and it takes some time to get how the concepts work. &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/boo-in-visual-studio.html" title="Boo in Visual Studio" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=3476834812660083461" title="9 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/3476834812660083461/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3476834812660083461" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3476834812660083461" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-1294079598876164056</id><published>2008-05-20T20:02:00.001+02:00</published><updated>2008-05-20T20:02:35.333+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Design" /><title type="text">The Path of Least Resistance</title><content type="html">&lt;p&gt;At developer summit in Stockholm a couple of weeks ago I attended a great talk by Jim Webber titled &amp;quot;Guerrilla SOA&amp;quot;. On one slide he listed some causes for why SOA and ESB solutions quickly degrade to a pile of spaghetti.&amp;#160; One of the causes was that developers take:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;i&gt;&amp;quot;&lt;/i&gt;&lt;i&gt;The Path of least resistance for individual applications&amp;quot;&lt;/i&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This line really resonated with how I feel, not in a SOA scenario but for application architecture or just code in general. When you write code you constantly fight either your own design/architecture or some framework and what many developer end up doing (including me sometimes) is taking the path of least resistance, and depending on the application design this might often not be the right path. &lt;/p&gt;  &lt;p&gt;Ayende had a post a couple of days ago about &lt;a href="http://www.ayende.com/Blog/archive/2008/05/16/Zero-Friction--Maintainability.aspx"&gt;zero friction &amp;amp; maintainability&lt;/a&gt; in which he writes: &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;i&gt;&amp;quot;As it turn out, while code may not rot, the design of the application does. But why? &lt;/i&gt;&lt;/p&gt;    &lt;p&gt;&lt;i&gt;If you have an environment that has friction in it, there is an incentive for the developers to subvert the design in order to produce a quick fix or hack a solution to solve a problem. Creating a zero friction environment will produce a system where there is no incentive to corrupt the design, the easiest thing to do is the right thing to do. &lt;/i&gt;&lt;/p&gt;    &lt;p&gt;&lt;i&gt;By reducing the friction in the environment, you increase the system maintainability&amp;quot;&lt;/i&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;A big goal when designing an application or framework should be to make the &lt;em&gt;path of least resistance &lt;/em&gt;the right path&lt;em&gt;. &lt;/em&gt;This is of course easier said than done and I think you will never get the perfect design where every right way is the easy way. So when we head down the path of least resistance knowing it is the wrong way, why do we do it? It could be time constraints, plain laziness or some other hurdle. When making the decision it is important to weigh in possible future problems and maintainability issues that could potentially be very costly. &lt;/p&gt;  &lt;p&gt;Well that is all I had to say about this for now, stay away from the path of least resistance (unless it is the right path!). &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/path-of-least-resistance.html" title="The Path of Least Resistance" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=1294079598876164056" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/1294079598876164056/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/1294079598876164056" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/1294079598876164056" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-5199821697968192221</id><published>2008-05-19T21:33:00.001+02:00</published><updated>2008-05-19T21:40:42.395+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="NHibernate" /><category scheme="http://www.blogger.com/atom/ns#" term="MonoRail" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title type="text">NHibernate Validator</title><content type="html">&lt;p&gt;There is a new framework in the NHibernate Contrib project named NHibernate.Validator. The project began as port of the java Hibernate.Validator project and is started by &lt;a href="http://darioquintana.com.ar/blogging"&gt;Dario Quintana&lt;/a&gt;. This framework allows you to validate objects in a similar way to other validation frameworks except that it has out of the box integration with the NHibernate's entity lifecycle. This means that you can configure it to do validation on entity insert/updates. The integration with NHibernate is not required however. &lt;/p&gt;  &lt;p&gt;You can specify the validation rules either as property/field attributes directly in the code or in a separate xml file with a schema similar to that used in NHibernate mapping files. &lt;/p&gt;  &lt;p&gt;Example:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;User&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;virtual&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Id
  {
      &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; id; }
  }

  [&lt;span class="type"&gt;NotEmpty&lt;/span&gt;, &lt;span class="type"&gt;NotNull&lt;/span&gt;]
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;virtual&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; UserName
  {
      &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; userName; }
      &lt;span class="kwrd"&gt;set&lt;/span&gt; { userName = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  [&lt;span class="type"&gt;Email&lt;/span&gt;]
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;virtual&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Email
  {
      &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; email; }
      &lt;span class="kwrd"&gt;set&lt;/span&gt; { email = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  [&lt;span class="type"&gt;Past&lt;/span&gt;]
  &lt;span class="kwrd"&gt;public&lt;/span&gt; DateTime CreatedDate
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; createdDate; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { createdDate = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  [&lt;span class="type"&gt;Min&lt;/span&gt;(18, Message=&lt;span class="str"&gt;&amp;quot;You are to young!&amp;quot;&lt;/span&gt;)]
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Age
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; age; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { age = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  [&lt;span class="type"&gt;CreditCardNumber&lt;/span&gt;]
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; CreditCardNumber
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; creditCardNumber; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { creditCardNumber = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }
  
  &lt;span class="rem"&gt;///... &lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;If you don't like to clutter your code with attributes you can use the xml config option, example: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;nhv-mapping&lt;/span&gt; &lt;span class="x_attr"&gt;xmlns&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;urn:nhibernate-validator-1.0&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;class&lt;/span&gt; &lt;span class="x_attr"&gt;name&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;NHibernate.Validator.Demo.Winforms.Model.Customer, NHibernate.Validator.Demo.Winforms&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;property&lt;/span&gt; &lt;span class="x_attr"&gt;name&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;FirstName&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;not-empty&lt;/span&gt;&lt;span class="x_kwrd"&gt;/&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;not-null&lt;/span&gt;&lt;span class="x_kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;property&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
   
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;property&lt;/span&gt; &lt;span class="x_attr"&gt;name&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;Email&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;email&lt;/span&gt;&lt;span class="x_kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;property&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;property&lt;/span&gt; &lt;span class="x_attr"&gt;name&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;Zip&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;pattern&lt;/span&gt;  &lt;span class="x_attr"&gt;regex&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;^[A-Z0-9-]+$&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;message&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;Examples of valid matches: 234G-34DA | 3432-DF23&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;/&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;pattern&lt;/span&gt;  &lt;span class="x_attr"&gt;regex&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;^....-....$&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;message&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;Must match ....-....&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;property&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
    
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;class&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;  
&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;nhv-mapping&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Personally I can barley stand the NHibernate xml mapping files (don't like to poke around in xml files that much) so I think I prefer the attribute version. But it is nice to have this option. It makes it possible to validate objects in third party assemblies that you do not have the code for. There are many more validators than the ones used above and it is very easy to create custom validators. &lt;/p&gt;

&lt;p&gt;You can configure the validation engine in code or in app/web.config, this is how you can do it in code: &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="type"&gt;NHVConfiguration&lt;/span&gt; nhvc = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;NHVConfiguration&lt;/span&gt;();
nhvc.Properties[Environment.ApplyToDDL] = &lt;span class="str"&gt;&amp;quot;false&amp;quot;&lt;/span&gt;;
nhvc.Properties[Environment.AutoregisterListeners] = &lt;span class="str"&gt;&amp;quot;true&amp;quot;&lt;/span&gt;;
nhvc.Properties[Environment.ValidatorMode] = &lt;span class="str"&gt;&amp;quot;UseAttribute&amp;quot;&lt;/span&gt;;
nhvc.Mappings.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;MappingConfiguration&lt;/span&gt;(&lt;span class="str"&gt;&amp;quot;NHibernate.ValidatorDemo.Model&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;));

&lt;span class="type"&gt;ValidatorEngine&lt;/span&gt; validator = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;ValidatorEngine&lt;/span&gt;();
validator.Configure(nhvc);&lt;/pre&gt;

&lt;p&gt;Since NHibernate.Validator uses the event listener system I think you have to use NHibernate 2.0 if you want the NHibernate integration. To validate an object you simply use the Validate function, here is a simple example (using MonoRail): &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Create([&lt;span class="type"&gt;DataBind&lt;/span&gt;(&lt;span class="str"&gt;&amp;quot;user&amp;quot;&lt;/span&gt;)] &lt;span class="type"&gt;User&lt;/span&gt; user)
{
  &lt;span class="type"&gt;InvalidValue&lt;/span&gt;[] errors = validator.Validate(user);

  &lt;span class="kwrd"&gt;if&lt;/span&gt; (errors.Length &amp;gt; 0)
  {
    Flash[&lt;span class="str"&gt;&amp;quot;errors&amp;quot;&lt;/span&gt;] = errors;
    RedirectToAction(&lt;span class="str"&gt;&amp;quot;index&amp;quot;&lt;/span&gt;);
  }
  &lt;span class="kwrd"&gt;else&lt;/span&gt;
  {
    repository.Create(user);
  }
}&lt;/pre&gt;

&lt;p&gt;And here is the view: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;div&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;h2&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;Create user&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;h2&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
    
    ${Html.FormToAttributed(&amp;quot;Home&amp;quot;, &amp;quot;Create&amp;quot;, {@id: &amp;quot;create-form&amp;quot;})}
    
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;p&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
        &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;label&lt;/span&gt; &lt;span class="x_attr"&gt;for&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;UserName&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;UserName:&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;label&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        ${Form.TextField(&amp;quot;user.UserName&amp;quot;)}
        
        &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;label&lt;/span&gt; &lt;span class="x_attr"&gt;for&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;UserName&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;Email:&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;label&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        ${Form.TextField(&amp;quot;user.Email&amp;quot;)}
        
        ${Html.SubmitButton(&amp;quot;Submit&amp;quot;)}
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;p&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
            
    ${Html.EndForm()}
    
    
    &lt;span class="x_kwrd"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="x_html"&gt;brail&lt;/span&gt; &lt;span class="x_attr"&gt;if&lt;/span&gt; &lt;span class="x_attr"&gt;IsDefined&lt;/span&gt;(&lt;span class="x_kwrd"&gt;&amp;quot;errors&amp;quot;&lt;/span&gt;)&lt;span class="x_attr"&gt;:&lt;/span&gt; ?&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;ul&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="x_kwrd"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="x_html"&gt;brail&lt;/span&gt; &lt;span class="x_attr"&gt;for&lt;/span&gt; &lt;span class="x_attr"&gt;error&lt;/span&gt; &lt;span class="x_attr"&gt;in&lt;/span&gt; &lt;span class="x_attr"&gt;errors:&lt;/span&gt; ?&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;li&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;${error.PropertyName}: ${error.Message}&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;li&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
        &lt;span class="x_kwrd"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="x_html"&gt;brail&lt;/span&gt; &lt;span class="x_attr"&gt;end&lt;/span&gt; ?&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;ul&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt; 
    &lt;span class="x_kwrd"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="x_html"&gt;brail&lt;/span&gt; &lt;span class="x_attr"&gt;end&lt;/span&gt; ?&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;div&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;This is of course a very simple example. You probably want to have the error message after each field and some client based validation. I think I will do another post about trying to integrate NHiberante Validator with JQuery validation. &lt;/p&gt;

&lt;p&gt;If you want to try NHibernate validator and do not want to build it from the trunk there is a 1.0 alpha release &lt;a href="http://sourceforge.net/project/showfiles.php?group_id=216446&amp;amp;package_id=275108&amp;amp;release_id=597674"&gt;available on sourceforge&lt;/a&gt;. The release contains a WinForms examples that shows how to integrate it with the WinForms error provider system. &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/nhibernate-validator.html" title="NHibernate Validator" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=5199821697968192221" title="5 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/5199821697968192221/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/5199821697968192221" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/5199821697968192221" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-7056699114019777817</id><published>2008-05-12T22:52:00.001+02:00</published><updated>2008-05-12T23:25:41.039+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Design By Contract" /><category scheme="http://www.blogger.com/atom/ns#" term="AOP" /><title type="text">Argument validation using attributes and method interception</title><content type="html">&lt;p&gt;Last week Fredrik Norm&amp;#233;n had a couple of &lt;a href="http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx"&gt;nice posts&lt;/a&gt; on argument validation using C# extension methods. It got me thinking on a different approach where a method interceptor could handle the validation. &lt;/p&gt;  &lt;p&gt;First a short recap on argument validation. I guess everyone have seen or written code with some kind of argument validation, like this for example: &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Add(&lt;span class="kwrd"&gt;string&lt;/span&gt; value)
{
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrEmpty(value)) 
      &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;ArgumentException&lt;/span&gt;(&lt;span class="str"&gt;&amp;quot;The value can't be null or empty&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value&amp;quot;&lt;/span&gt;);
    
  &lt;span class="rem"&gt;///...&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;To make argument validation easier I have (to a small extent) used a modified version of &lt;a href="http://www.codeproject.com/KB/cs/designbycontract.aspx"&gt;this&lt;/a&gt; design by contract utility class. This utility class lets you write argument validation like this: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Add(&lt;span class="kwrd"&gt;string&lt;/span&gt; value)
{
  &lt;span class="type"&gt;Check&lt;/span&gt;.Require(value != &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value should not be null&amp;quot;&lt;/span&gt;);
    
  &lt;span class="rem"&gt;///...&lt;/span&gt;
  
  &lt;span class="type"&gt;Check&lt;/span&gt;.Ensure(Count &amp;gt; 0);
}&lt;/pre&gt;

&lt;p&gt;So this got me thinking on how you could handle argument validation using method interception. With a method interceptor you could inspect the function arguments checking for validation attributes. I envisioned code looking like this:&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[&lt;span class="type"&gt;Ensure&lt;/span&gt;(() =&amp;gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.Count &amp;gt; 0)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Register([&lt;span class="type"&gt;NotNull&lt;/span&gt;] &lt;span class="kwrd"&gt;string&lt;/span&gt; name, [&lt;span class="type"&gt;InRange&lt;/span&gt;(5,10)] &lt;span class="kwrd"&gt;int&lt;/span&gt; value)
{
  &lt;span class="rem"&gt;///...&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;Getting the ensure post condition to work like that will be impossible since you can only use constant expressions in attribute constructors. This is something I think they should look at for C# 4.0, being able to define lambdas in attribute arguments would make interesting scenarios possible (like this). The NotNull and InRange attributes were very simple to implement:&amp;#160; &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;ArgumentValidationAttribute&lt;/span&gt; : &lt;span class="type"&gt;Attribute&lt;/span&gt;
{        
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Validate(&lt;span class="kwrd"&gt;object&lt;/span&gt; value, &lt;span class="kwrd"&gt;string&lt;/span&gt; argumentName);
}

[&lt;span class="type"&gt;AttributeUsage&lt;/span&gt;(AttributeTargets.Parameter)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;NotNullAttribute&lt;/span&gt; : &lt;span class="type"&gt;ArgumentValidationAttribute&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Validate(&lt;span class="kwrd"&gt;object&lt;/span&gt; value, &lt;span class="kwrd"&gt;string&lt;/span&gt; argumentName)
  {
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (value == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;ArgumentNullException&lt;/span&gt;(argumentName);
    }
  }    
}    

[&lt;span class="type"&gt;AttributeUsage&lt;/span&gt;(AttributeTargets.Parameter)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;InRangeAttribute&lt;/span&gt; : &lt;span class="type"&gt;ArgumentValidationAttribute&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; min;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; max;

  &lt;span class="kwrd"&gt;public&lt;/span&gt; InRangeAttribute(&lt;span class="kwrd"&gt;int&lt;/span&gt; min, &lt;span class="kwrd"&gt;int&lt;/span&gt; max)
  {
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.min = min;
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.max = max;
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Validate(&lt;span class="kwrd"&gt;object&lt;/span&gt; value, &lt;span class="kwrd"&gt;string&lt;/span&gt; argumentName)
  {
    &lt;span class="kwrd"&gt;int&lt;/span&gt; intValue = (&lt;span class="kwrd"&gt;int&lt;/span&gt;)value;
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (intValue &amp;lt; min || intValue &amp;gt; max)
    {
      &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;ArgumentOutOfRangeException&lt;/span&gt;(argumentName, &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;min={0}, max={1}&amp;quot;&lt;/span&gt;, min, max));
    }
  }
}&lt;/pre&gt;

&lt;p&gt;This is of course the easy part. It is the actual interceptor that is making the magic happen. This implementation is just a proof of concept, and not optimal from a performance stand point.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;ValidationInterceptor&lt;/span&gt; : &lt;span class="type"&gt;IInterceptor&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Intercept(&lt;span class="type"&gt;IInvocation&lt;/span&gt; invocation)
  {
    &lt;span class="type"&gt;ParameterInfo&lt;/span&gt;[] parameters = invocation.Method.GetParameters(); 
    &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; index = 0; index &amp;lt; parameters.Length; index++)
    {
      &lt;span class="kwrd"&gt;var&lt;/span&gt; paramInfo = parameters[index];
      &lt;span class="kwrd"&gt;var&lt;/span&gt; attributes = paramInfo.GetCustomAttributes(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="type"&gt;ArgumentValidationAttribute&lt;/span&gt;), &lt;span class="kwrd"&gt;false&lt;/span&gt;);

      &lt;span class="kwrd"&gt;if&lt;/span&gt; (attributes.Length == 0)
        &lt;span class="kwrd"&gt;continue&lt;/span&gt;;

      &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="type"&gt;ArgumentValidationAttribute&lt;/span&gt; attr &lt;span class="kwrd"&gt;in&lt;/span&gt; attributes)
      {    
        attr.Validate(invocation.Arguments[index], paramInfo.Name);
      }            
    }

    invocation.Proceed();
  }        
}&lt;/pre&gt;

&lt;p&gt;To make this interceptor more feasible for production you would probably have to add some smart caching mechanism. This interceptor based argument validation is of course somewhat limited in applicability. You have to use a dynamic proxy generator to get the interceptor functionality and only interface and virtual functions can be intercepted. But it is an interesting idea and shows another nice usage scenario for method interception. &lt;/p&gt;

&lt;p&gt;The concept of being able to intercept method calls is something that would be great if it was built into a future version of the CLR runtime. That way static and non virtual methods could be intercepted. It is a nice way to implement cross-cutting concerns (like validation). But until then we will have to live with proxy generators, it works nicely for interfaces:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; &lt;span class="type"&gt;IRegistrationService&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;void&lt;/span&gt; Register([&lt;span class="type"&gt;NotNull&lt;/span&gt;] &lt;span class="kwrd"&gt;string&lt;/span&gt; name, [&lt;span class="type"&gt;InRange&lt;/span&gt;(5, 10)] &lt;span class="kwrd"&gt;int&lt;/span&gt; value);

  &lt;span class="kwrd"&gt;void&lt;/span&gt; Register([&lt;span class="type"&gt;NotNullOrEmpty&lt;/span&gt;] &lt;span class="kwrd"&gt;string&lt;/span&gt; name);
}&lt;/pre&gt;

&lt;p&gt;If you specify the attributes on an interface you do not need to duplicate them on the implementation methods! A small update to the interceptor to support validation of the return value would allow something like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; &lt;span class="type"&gt;IUserRepository&lt;/span&gt;
{
  [&lt;span class="kwrd"&gt;return&lt;/span&gt;: &lt;span class="type"&gt;NotNull&lt;/span&gt;]
  &lt;span class="type"&gt;User&lt;/span&gt; GetById([&lt;span class="type"&gt;GreaterThanZero&lt;/span&gt;] &lt;span class="kwrd"&gt;int&lt;/span&gt; id);
  
  &lt;span class="rem"&gt;///...&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;The syntax for attributes on return values are kind of funky. If Spec# isn't the future (I hope it is) then maybe something like this can be :) &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/argument-validation-using-attributes.html" title="Argument validation using attributes and method interception" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=7056699114019777817" title="3 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/7056699114019777817/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/7056699114019777817" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/7056699114019777817" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-2860799531144668088</id><published>2008-05-09T08:51:00.001+02:00</published><updated>2008-05-09T11:13:33.338+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Boo" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Design By Contract" /><title type="text">Spec# and ideas for C# 4.0</title><content type="html">&lt;p&gt;The ideas and concepts that the Microsoft research team has realized in spec# are too great not to be included in a future version of C# ! &lt;/p&gt;  &lt;p&gt;Just look a this example:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Subtract(&lt;span class="kwrd"&gt;int&lt;/span&gt; x, &lt;span class="kwrd"&gt;int&lt;/span&gt; y)
     &lt;span class="kwrd"&gt;requires&lt;/span&gt; x &amp;gt; y;
     &lt;span class="kwrd"&gt;ensures&lt;/span&gt; result &amp;gt; y;
{
     &lt;span class="kwrd"&gt;return&lt;/span&gt; x - y;
}&lt;/pre&gt;

&lt;p&gt;It is not only the runtime aspects of spec# that are exiting. It is the amazing level of static analysis that they have implemented that at compile time validates (across many method boundaries) that requirements are uphold. &lt;/p&gt;

&lt;p&gt;C# has really evolved a lot in the last two iterations (especially in 3.0), and think this fast evolution has given it a good edge compared to other static languages (java). But why stop now? Here are a few more things I would like in C# 4.0 :) &lt;/p&gt;

&lt;p&gt;&lt;u&gt;Extensible compilation pipeline:&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;The Boo .NET language has this concept of an extensible compilation pipeline that allows for really powerful usage scenarios. With it you can extend the language with new keyword constructs and attributes that actually manipulate the abstract syntax tree (AST). Here is an example where I have extended Boo with some constructs for design by contract:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[ensures(total &amp;gt; 0)] 
def Add(&lt;span class="kwrd"&gt;int&lt;/span&gt; value):
    &lt;span class="kwrd"&gt;requires&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt; &amp;gt; 0
    total += value&lt;/pre&gt;

&lt;p&gt;Extending the Boo language like this is very trivial. For example the requires keyword is implemented like this: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;macro&lt;/span&gt; requires:
  &lt;span class="kwrd"&gt;return&lt;/span&gt; [|
    &lt;span class="kwrd"&gt;if&lt;/span&gt; $(requires.Arguments[0]) == &lt;span class="kwrd"&gt;false&lt;/span&gt;:
        &lt;span class="kwrd"&gt;raise&lt;/span&gt; ArgumentException(&lt;span class="str"&gt;&amp;quot;requires precondition failed&amp;quot;&lt;/span&gt;)
    |]&lt;/pre&gt;

&lt;p&gt;This is just a simple example, you can do more powerful stuff. A Boo macro is very different from C++ macros. The Boo macros operate on the compiler's AST and can query the object model and modify it in very powerful ways. The open compiler architecture makes Boo a language suitable for writing &lt;a href="http://www.infoq.com/articles/dsl-on-the-clr" target="_blank"&gt;domain specific languages&lt;/a&gt;. I doubt that something like this will be implemented in C# though since new compiler features are more likely to break existing implementations. Something I think the C# team are not allowed to do. &lt;/p&gt;
&lt;u&gt;Dynamic method invocation and duck typing:&lt;/u&gt; 

&lt;p&gt;If a class implements the IQuackFu interface in Boo you can call methods on it that are resolved at runtime. This is similar to &lt;a href="http://rubysnips.com/method-missing" target="_blank"&gt;method missing&lt;/a&gt; in ruby. The IQuackFu interface looks like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IQuackFu
{
  &lt;span class="kwrd"&gt;object&lt;/span&gt; QuackGet(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;object&lt;/span&gt;[] parameters);
  &lt;span class="kwrd"&gt;object&lt;/span&gt; QuackSet(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;object&lt;/span&gt;[] parameters, &lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;);
  &lt;span class="kwrd"&gt;object&lt;/span&gt; QuackInvoke(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;params&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt;[] args);
}&lt;/pre&gt;

&lt;p&gt;This interface can for example be used as front to an xml document, allowing you to access elements as properties. I think the C# team is actually considering something like this if you are to believe the rumours from the MVP Summit. &lt;/p&gt;

&lt;p&gt;Anyone else having ideas or a whish list for C# 4.0? &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/spec-and-ideas-for-c-40.html" title="Spec# and ideas for C# 4.0" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=2860799531144668088" title="4 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/2860799531144668088/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/2860799531144668088" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/2860799531144668088" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-7156932414392791527</id><published>2008-05-08T07:14:00.001+02:00</published><updated>2008-05-10T08:49:29.295+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Javascript" /><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET" /><title type="text">JQuery and Separation of Concerns</title><content type="html">&lt;p&gt;I am constantly surprised by the power and elegance of of JQuery and how using it can change they way you create web applications. &lt;/p&gt;  &lt;p&gt;JQuery is not just a simple javascript library that makes ajax and javascript coding easier to write, it also allows you to separate your client-side logic from your html, making it much more cleaner and easier to maintain. &lt;/p&gt;  &lt;p&gt;Lets see how JQuery can improve your html with a concrete example. The requirements are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;A html table that lists tickets &lt;/li&gt;    &lt;li&gt;Table rows should be alternating (colored) &lt;/li&gt;    &lt;li&gt;Table rows should have a mouseover highlight effect &lt;/li&gt;    &lt;li&gt;If you click a row a ticket detail should be shown &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;First I will show how a non JQuery solution could look like, here is simple solution using a web forms repeater (chosen for good effect).&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;asp:Repeater&lt;/span&gt; &lt;span class="x_attr"&gt;ID&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;ticketRepeater&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;runat&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;server&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;HeaderTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;table&lt;/span&gt; &lt;span class="x_attr"&gt;class&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;ticket-table&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;border&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;0&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;Id&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                        
        &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;Description&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                        
      &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;HeaderTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;ItemTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt; &lt;span class="x_attr"&gt;class&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;even&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;onmouseover&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;highlight_over(this);&amp;quot;&lt;/span&gt; 
             &lt;span class="x_attr"&gt;onmouseout&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;highlight_out(this);&amp;quot;&lt;/span&gt;
             &lt;span class="x_attr"&gt;onclick&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;selectTicket(&amp;lt;%# Eval(&amp;quot;Id&amp;quot;) %&amp;gt;)&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;span class="x_asp"&gt;&amp;lt;%&lt;/span&gt;# Eval(&amp;quot;Id&amp;quot;) &lt;span class="x_asp"&gt;%&amp;gt;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;span class="x_asp"&gt;&amp;lt;%&lt;/span&gt;# Eval(&lt;span class="x_str"&gt;&amp;quot;Description&amp;quot;&lt;/span&gt;) &lt;span class="x_asp"&gt;%&amp;gt;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;ItemTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;AlternatingItemTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt; &lt;span class="x_attr"&gt;class&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;odd&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;onmouseover&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;highlight_over(this);&amp;quot;&lt;/span&gt; 
            &lt;span class="x_attr"&gt;onmouseout&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;highlight_out(this);&amp;quot;&lt;/span&gt;
            &lt;span class="x_attr"&gt;onclick&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;selectTicket(&amp;lt;%# Eval(&amp;quot;Id&amp;quot;) %&amp;gt;)&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;span class="x_asp"&gt;&amp;lt;%&lt;/span&gt;# Eval(&lt;span class="x_str"&gt;&amp;quot;Id&amp;quot;&lt;/span&gt;) &lt;span class="x_asp"&gt;%&amp;gt;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;span class="x_asp"&gt;&amp;lt;%&lt;/span&gt;# Eval(&lt;span class="x_str"&gt;&amp;quot;Description&amp;quot;&lt;/span&gt;) &lt;span class="x_asp"&gt;%&amp;gt;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;AlternatingItemTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
              
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;FooterTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;table&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;FooterTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;asp:Repeater&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    &lt;/pre&gt;

&lt;p&gt;The worst part of the above code is the complete duplication of the entire item template, completely unnecessary in this case as the class name is only difference. I have seen the repeater being used like this in numerous examples and in real applications. The mouseover and mouseout part is something that could be handled by &amp;quot;:hover&amp;quot; css selector, however this is not supported by IE (without resorting to javascript methods). &lt;/p&gt;

&lt;p&gt;Here is the above markup but now taking advantage of JQuery: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;asp:Repeater&lt;/span&gt; &lt;span class="x_attr"&gt;ID&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;ticketRepeater2&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;runat&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;server&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;HeaderTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;table&lt;/span&gt; &lt;span class="x_attr"&gt;class&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;ticket-table&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;border&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;0&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;thead&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;Id&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                        
          &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;Description&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                        
        &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;thead&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tbody&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;HeaderTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;ItemTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;span class="x_asp"&gt;&amp;lt;%&lt;/span&gt;# Eval(&lt;span class="x_str"&gt;&amp;quot;Id&amp;quot;&lt;/span&gt;) &lt;span class="x_asp"&gt;%&amp;gt;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;span class="x_asp"&gt;&amp;lt;%&lt;/span&gt;# Eval(&lt;span class="x_str"&gt;&amp;quot;Description&amp;quot;&lt;/span&gt;) &lt;span class="x_asp"&gt;%&amp;gt;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;ItemTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                
              
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;FooterTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
      &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tbody&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;table&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;FooterTemplate&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;asp:Repeater&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;    &lt;/pre&gt;

&lt;p&gt;The alternating template is removed, so it the mouseover, mouseout and click event handler. How do we restore this missing functionality? Here is the JQuery javascript code that restores it:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;script&lt;/span&gt; &lt;span class="x_attr"&gt;type&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;text/javascript&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        
        $(document).ready(&lt;span class="kwrd"&gt;function&lt;/span&gt;() {
            
            $(&lt;span class="str"&gt;&amp;quot;.ticket-table tbody tr:not([th]):odd&amp;quot;&lt;/span&gt;).addClass(&lt;span class="str"&gt;&amp;quot;odd&amp;quot;&lt;/span&gt;);
            $(&lt;span class="str"&gt;&amp;quot;.ticket-table tbody tr:not([th]):even&amp;quot;&lt;/span&gt;).addClass(&lt;span class="str"&gt;&amp;quot;even&amp;quot;&lt;/span&gt;);
            
            $(&lt;span class="str"&gt;&amp;quot;.ticket-table tbody tr&amp;quot;&lt;/span&gt;).mouseover( &lt;span class="kwrd"&gt;function&lt;/span&gt;() {                    
                    $(&lt;span class="kwrd"&gt;this&lt;/span&gt;).addClass(&lt;span class="str"&gt;&amp;quot;hover&amp;quot;&lt;/span&gt;);
            }).mouseout( &lt;span class="kwrd"&gt;function&lt;/span&gt;() {
                    $(&lt;span class="kwrd"&gt;this&lt;/span&gt;).removeClass(&lt;span class="str"&gt;&amp;quot;hover&amp;quot;&lt;/span&gt;);
            });
            
            $(&lt;span class="str"&gt;&amp;quot;.ticket-table tbody tr&amp;quot;&lt;/span&gt;).click(&lt;span class="kwrd"&gt;function&lt;/span&gt;() {
                &lt;span class="kwrd"&gt;var&lt;/span&gt; id = $(&lt;span class="str"&gt;&amp;quot;td:first&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;this&lt;/span&gt;)[0].innerHTML;
                &lt;span class="rem"&gt;// handle the selection of this ticket id                                &lt;/span&gt;
            });
            
        });
        
 &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;script&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;JQuery's strength is built around it's css based element selection expressions. The $() function is a JQuery function, which returns a list of elements that matched a JQuery &amp;quot;query&amp;quot;. The list returned is a JQuery object which has a long list of useful functions (like addClass, hide, show, etc). The cool thing is that when you call a function like addClass, this action will be applied to all elements which the JQuery expression selected. Good bye to unnecessary loops! The mouseover/mouseout JQuery functions takes as an argument the handler for the event, and here you can just use a javascript closure. Fetching an id from the content of a table cell is perhaps not a recommended approach. It would be better to store it in the row element id.&lt;/p&gt;

&lt;p&gt;The new solution introduced some extra lines of javascript code, but your html is much cleaner. The most important aspect is that you separate the behavior from the markup which will (hopefully) make the solution more maintainable.&amp;#160; The web forms repeater is a little verbose , it is surprising how much cleaner it can be if you just use inline scripting.&amp;#160; Here is how it would look like if you used MonoRails brail view engine:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;table&lt;/span&gt; &lt;span class="x_attr"&gt;class&lt;/span&gt;&lt;span class="x_attr_v"&gt;=&amp;quot;ticket-table&amp;quot;&lt;/span&gt; &lt;span class="x_attr"&gt;border&lt;/span&gt;&lt;span class="x_kwrd"&gt;=&amp;quot;0&amp;quot;&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;thead&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;Id&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                        
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;Description&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;th&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                        
    &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;thead&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tbody&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  
  &lt;span class="x_kwrd"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="x_html"&gt;brail&lt;/span&gt; &lt;span class="x_attr"&gt;for&lt;/span&gt; &lt;span class="x_attr"&gt;ticket&lt;/span&gt; &lt;span class="x_attr"&gt;in&lt;/span&gt; &lt;span class="x_attr"&gt;tickets:&lt;/span&gt; ?&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;${ticket.Id}&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
        &lt;span class="x_kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;${ticket.Description}&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;td&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;                    
      &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tr&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="x_kwrd"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="x_html"&gt;brail&lt;/span&gt; &lt;span class="x_attr"&gt;end&lt;/span&gt; ?&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
  
  &lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;tbody&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="x_kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="x_html"&gt;table&lt;/span&gt;&lt;span class="x_kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Another aspect where JQuery can be a big help is in web forms applications where element ids often complicate javascript code. I found that JQuery's element selection could in many cases work around this problem (by finding elements based on class name for example). &lt;/p&gt;

&lt;p&gt;There is also a very &lt;a href="http://plugins.jquery.com/"&gt;large list&lt;/a&gt; of JQuery pluggins / extensions, here are two which I can recommend:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://docs.jquery.com/Plugins/Validation"&gt;Validation&lt;/a&gt; (very feature rich client side form validation) &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://docs.jquery.com/Plugins/Metadata"&gt;Metadata&lt;/a&gt; (allows you to have json metadata embedded in the html class attribute) &lt;/li&gt;
&lt;/ul&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/jquery-and-separation-of-concerns.html" title="JQuery and Separation of Concerns" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=7156932414392791527" title="5 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/7156932414392791527/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/7156932414392791527" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/7156932414392791527" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-3890529977809561898</id><published>2008-05-05T21:24:00.001+02:00</published><updated>2008-05-05T21:36:50.530+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="IoC" /><category scheme="http://www.blogger.com/atom/ns#" term="Benchmarks" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title type="text">IoC Container Benchmark ReRevisted - Ninject updated, Autofac added</title><content type="html">&lt;p&gt;Nate Kohari informed me that he fixed the performance issue that I discovered in my last &lt;a href="http://www.codinginstinct.com/2008/04/ioc-benchmark-revisited-ninject.html"&gt;test&lt;/a&gt;, so I thought I rerun the benchmark against the trunk version (revision 62) of Ninject. &lt;/p&gt;  &lt;p&gt;I have also included another new container named &lt;a href="http://code.google.com/p/autofac/"&gt;Autofac&lt;/a&gt;, written by &lt;a href="http://ubik.com.au/blog"&gt;Nicholas Blumhardt&lt;/a&gt; and &lt;a href="http://rabdullin.com/projects/autofac/"&gt;Rinat Abdullin&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;This container has nice list of features, here are a few:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Autowiring (with out any intrusive attributes) &lt;/li&gt;    &lt;li&gt;XML Configuration Support &lt;/li&gt;    &lt;li&gt;Nice C# registration API (including possibility to create components with expressions) &lt;/li&gt;    &lt;li&gt;Module system (nice way to structure parts of your application) &lt;/li&gt;    &lt;li&gt;Nested containers &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The registration API is at first glance like any other IoC container except it also provides the ability to override the autowiring by defining how components are created by using lambda expressions. Here is an example:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;// using autowiring&lt;/span&gt;
builder.Register&amp;lt;&lt;span class="type"&gt;UserController&lt;/span&gt;&amp;gt;().FactoryScoped();
&lt;span class="rem"&gt;// using expressions&lt;/span&gt;
builder.Register(c =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;UserController&lt;/span&gt;(c.Resolve&amp;lt;&lt;span class="type"&gt;IUserRepository&lt;/span&gt;&amp;gt;(), c.Resolve&amp;lt;&lt;span class="type"&gt;IAuthentificationService&lt;/span&gt;&amp;gt;()))
  .FactoryScoped();&lt;/pre&gt;

&lt;p&gt;The second method could potentially be a lot faster since in it you create a anonymous method that creates the object directly. There is a lot more code to write and if you change the constructor you need to update the registration code, so I am not sure you would want to use it to for most components. To be fair to the other containers in the test I tested Autofac with both autowiring registration and with expression based registration. For more detail on how the benchmark works please view the first &lt;a href="http://www.codinginstinct.com/2008/04/ioc-container-benchmark-unity-windsor.html"&gt;benchmark post&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Another interesting feature of Autofac is it's support for nested containers with predicable component cleanup.&amp;#160; &lt;/p&gt;

&lt;pre class="csharpcode"&gt;var container = &lt;span class="rem"&gt;// ...&lt;/span&gt;
&lt;span class="kwrd"&gt;using&lt;/span&gt; (var context = container.CreateInnerContainer())
{
  var controller = context.Resolve&amp;lt;&lt;span class="type"&gt;IController&lt;/span&gt;&amp;gt;();
  controller.Execute(); &lt;span class="rem"&gt;// use controller..&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;In the above example the controller and all it's dependencies that implements IDisposable will be disposed. &lt;/p&gt;

&lt;p&gt;Here are the results: &lt;/p&gt;
&lt;img style="display: block; margin-left: auto; margin-right: auto" height="361" alt="IoCSingleton_Autofac" src="http://lh4.ggpht.com/torkel.odegaard/SB9e1OM82BI/AAAAAAAAAXw/JxBb8m-8AFM/IoCSingleton_Autofac%5B5%5D.png?imgmax=800" width="595" border="0" /&gt; 

&lt;p&gt;&lt;img style="display: block; margin-left: auto; margin-right: auto" height="323" alt="IoCTransient_Autofac" src="http://lh4.ggpht.com/torkel.odegaard/SB9e2OM82CI/AAAAAAAAAX4/uX8Y2oIiSEI/IoCTransient_Autofac%5B5%5D.png?imgmax=800" width="587" border="0" /&gt; &lt;/p&gt;

&lt;p&gt;It is nice to see that the Ninject problem has been solved. When using Autofacs expression (lambda) based registration API the results are, not surprising, a lot quicker than the other containers. I would have almost through that the performance difference was going be bigger, seeing how fast the new operator was in my first benchmark (where I made a crude comparison with using the new operator directly to create all the instances).&amp;#160;&amp;#160; &lt;/p&gt;

&lt;p&gt;My conclusion is the same as after the first test, the performance difference is not significant to warrant consideration when choosing a IoC container. Unless you create a incredibly large amount of transient components (not recommended), then maybe use Autofac :)&lt;/p&gt;

&lt;p&gt;It was fun to try out Autofac, it is looking like an interesting contender, and might even replace Castle Windsor as my favorite. I doubt it though, Castle Windsor probably has the largest user base and I am pretty familiar with it's codebase / extension points. But who knows, you shouldn't always stick to what you know :) &lt;/p&gt;

&lt;p&gt;For the benchmark code: &lt;a href="http://www.codinginstinct.com-a.googlepages.com/IoCBenchmark_ReRevisted.zip"&gt;IoCBenchmark_ReRevisted.zip&lt;/a&gt;&lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/ioc-container-benchmark-rerevisted.html" title="IoC Container Benchmark ReRevisted - Ninject updated, Autofac added" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=3890529977809561898" title="2 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/3890529977809561898/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3890529977809561898" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3890529977809561898" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-3796473144293903251</id><published>2008-05-05T09:36:00.001+02:00</published><updated>2008-05-05T09:36:01.615+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="WatiN" /><category scheme="http://www.blogger.com/atom/ns#" term="TDD" /><title type="text">WaitN and xUnit.NET Integration testing</title><content type="html">&lt;p&gt;If you want to automate some of your manual integration testing I can highly recommend WatiN. It is a great library for doing browser automation. The new version allows you to automate Internet Explorer and Firefox through a common interface. &lt;/p&gt;  &lt;p&gt;example:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;[&lt;span class="type"&gt;Fact&lt;/span&gt;]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SearchForCodingInstinctOnGoogle()
{
  &lt;span class="kwrd"&gt;using&lt;/span&gt; (&lt;span class="type"&gt;IBrowser&lt;/span&gt; ie = &lt;span class="type"&gt;BrowserFactory&lt;/span&gt;.Create(&lt;span class="type"&gt;BrowserType&lt;/span&gt;.InternetExplorer))
  {
    ie.GoTo(&lt;span class="str"&gt;&amp;quot;http://www.google.com&amp;quot;&lt;/span&gt;);
    ie.TextField(&lt;span class="type"&gt;Find&lt;/span&gt;.ByName(&lt;span class="str"&gt;&amp;quot;q&amp;quot;&lt;/span&gt;)).Value = &lt;span class="str"&gt;&amp;quot;Coding Instinct&amp;quot;&lt;/span&gt;;
    ie.Button(&lt;span class="type"&gt;Find&lt;/span&gt;.ByName(&lt;span class="str"&gt;&amp;quot;btnG&amp;quot;&lt;/span&gt;)).Click();
    &lt;span class="type"&gt;Assert&lt;/span&gt;.True(ie.ContainsText(&lt;span class="str"&gt;&amp;quot;Coding Instinct&amp;quot;&lt;/span&gt;));
  }
}&lt;/pre&gt;

&lt;p&gt;I am using xUnit.NET in the above example (Fact = Test). xUnit.NET has been mentioned in a lot of blogs lately and I think for good reasons. It comes bundled with a very nice set of extensions that are very useful, especially for integration testing. &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;
&lt;u&gt;ExcelData:&lt;/u&gt; 

&lt;p&gt;One of the extensions that comes with xUnit is an attribute that lets you fetch test data from an excel file, xUnit will then execute your test method for each row in the excel file. Here is an interesting usage scenario: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;[&lt;span class="type"&gt;Theory&lt;/span&gt;, &lt;span class="type"&gt;ExcelData&lt;/span&gt;(&lt;span class="str"&gt;@&amp;quot;Resources\PortalUrls.xls&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;select * from PortalUrls&amp;quot;&lt;/span&gt;)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; UrlShowsExptectedContent(&lt;span class="kwrd"&gt;string&lt;/span&gt; url, &lt;span class="kwrd"&gt;string&lt;/span&gt; contentText, &lt;span class="kwrd"&gt;bool&lt;/span&gt; requireLogin)
{
  InitBrowser(url);
  
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (requireLogin)
  {
    &lt;span class="type"&gt;LoginAction&lt;/span&gt;.WithAS();
  }

  &lt;span class="type"&gt;Assert&lt;/span&gt;.True(Browser.Text.Contains(contentText), &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;\&amp;quot;{0}\&amp;quot; was not found&amp;quot;&lt;/span&gt;, contentText));
}&lt;/pre&gt;

&lt;p&gt;My current customer is using a portal application to host a number of separate applications (that use a common SSO). With this simple test I was able to check all portal URLs and with a very simple validation check that the applications (and the login) was up and running. &lt;/p&gt;

&lt;p&gt;The excel file:&lt;/p&gt;
&lt;img style="display: block; margin-left: auto; margin-right: auto" src="http://lh3.ggpht.com/torkel.odegaard/SB644OM82AI/AAAAAAAAAXo/r1y_550CeDk/image_thumb%5B2%5D.png?imgmax=800" border="0" /&gt; 

&lt;p&gt;In the excel file you must use the function &amp;quot;Name a Range&amp;quot;. This function can be found by selecting the table, including the header and right clicking. It is also found under the &amp;quot;Formulas&amp;quot; tab (Define Name, Name Manager). &lt;/p&gt;

&lt;p&gt;The test above is of course a very simple test, It only checks that the portal is configured correctly and that all applications are up and running, but it is a good start. Now I can go into each application/feature and write automated tests for each of the manual test cases. &lt;/p&gt;
&lt;u&gt;UI test fragility:&lt;/u&gt; 

&lt;p&gt;When writing browser tests you need to do a lot of html element selections so the tests become very fragile to UI changes, this is especially true for WebForm applications where element names and ids are constantly changed for minor UI changes. &lt;/p&gt;

&lt;p&gt;To combat this problem I tend to place most of the element selections in static helper classes. I also use a RegEx to identify elements. The reason for using a RegEx is to ignore a large part of the id prefix that the WebForm html renderer so gladly adds. example: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;LoginAction&lt;/span&gt; : &lt;span class="type"&gt;ActionBase&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; WithAS()
  {
    Browser.TextField(&lt;span class="kwrd"&gt;new&lt;/span&gt; Regex(&lt;span class="str"&gt;&amp;quot;.*txtUserName&amp;quot;&lt;/span&gt;)).Value = &lt;span class="str"&gt;&amp;quot;xxxx&amp;quot;&lt;/span&gt;;
    Browser.TextField(&lt;span class="kwrd"&gt;new&lt;/span&gt; Regex(&lt;span class="str"&gt;&amp;quot;.*txtPassword&amp;quot;&lt;/span&gt;)).Value = &lt;span class="str"&gt;&amp;quot;xxxx&amp;quot;&lt;/span&gt;;
    Browser.Button(&lt;span class="kwrd"&gt;new&lt;/span&gt; Regex(&lt;span class="str"&gt;&amp;quot;.*btnLogin&amp;quot;&lt;/span&gt;)).Click();
  }
}&lt;/pre&gt;

&lt;p&gt;There are many more useful xUnit extension attributes, for example: InlineData, PropertyData and SqlServerData. For more information on WatiN and xUnit.NET here are some links:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;WatiN homepage: &lt;a href="http://watin.sourceforge.net/" target="_blank"&gt;watin.sourceforge.net&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;xUnit.NET homepage: &lt;a title="http://www.codeplex.com/xunit/" href="http://www.codeplex.com/xunit/"&gt;www.codeplex.com/xunit/&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blog.benhall.me.uk/2008/01/introduction-to-xunit.html" target="_blank"&gt;Introdution to xUnit&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blog.benhall.me.uk/2008/01/introduction-to-xunitnet-extensions.html" target="_blank"&gt;Introduction to XUnit.net Extensions&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/waitn-and-xunitnet-integration-testing.html" title="WaitN and xUnit.NET Integration testing" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=3796473144293903251" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/3796473144293903251/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3796473144293903251" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3796473144293903251" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-2371509846366771341</id><published>2008-05-02T10:16:00.001+02:00</published><updated>2008-05-02T10:56:59.733+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Design" /><category scheme="http://www.blogger.com/atom/ns#" term="TDD" /><title type="text">Handling Execution Context / User Session</title><content type="html">In most applications you usually store and cache some user information in a session object. Most actions are dependent on this information, which means that many services require this information. This problem can be solved using different approaches. What I usually end up with is creating a user ticket class which holds maybe a subset of the user information (or the complete user class) and other session specific information. The simplest approach is then to pass this object along to each service / method that needs it:   &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;WishListService&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="type"&gt;IWishListRepository&lt;/span&gt; wishListRepository;

  &lt;span class="kwrd"&gt;public&lt;/span&gt; WishListService(&lt;span class="type"&gt;IWishListRepository&lt;/span&gt; wishListRepository)
  {
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.wishListRepository = wishListRepository;
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AddToWishList(&lt;span class="type"&gt;IUserTicket&lt;/span&gt; ticket, &lt;span class="type"&gt;Product&lt;/span&gt; product)
  {
    &lt;span class="rem"&gt;// handle all the important stuff&lt;/span&gt;
  }
}&lt;/pre&gt;

&lt;p&gt;The problem with this approach is that all callers need to fetch the user ticket. If you have deep method stacks and the deepest component needs the session information then all methods needs to pass the object along. &lt;/p&gt;

&lt;p&gt;A sometimes nicer approach is to let the components fetch the session information on their own (through an interface): &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;WishListService&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="type"&gt;IWishListRepository&lt;/span&gt; wishListRepository;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="type"&gt;ITicketAccessor&lt;/span&gt; ticketAccessor;

  &lt;span class="kwrd"&gt;public&lt;/span&gt; WishListService(&lt;span class="type"&gt;IWishListRepository&lt;/span&gt; wishListRepository, &lt;span class="type"&gt;ITicketAccessor&lt;/span&gt; ticketAccessor)
  {
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.wishListRepository = wishListRepository;
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.ticketAccessor = ticketAccessor;
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AddToWishList(&lt;span class="type"&gt;Product&lt;/span&gt; product)
  {
    &lt;span class="type"&gt;IUserTicket&lt;/span&gt; ticket = ticketAccessor.Current();
    &lt;span class="rem"&gt;// handle all the important stuff&lt;/span&gt;
  }
}&lt;/pre&gt;

&lt;p&gt;This approach makes the component easier to use and the method calls are simpler, dependencies to the session (ticket) information is handled by the ITicketAccessor which can be inject by a IoC container. &lt;/p&gt;

&lt;p&gt;Another approach is to have a static RuntimeContext class which static properties to access the session information from anywhere in your application: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;RuntimeContext&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; KEY_TICKET = &lt;span class="str"&gt;&amp;quot;RuntimeContext.Ticket&amp;quot;&lt;/span&gt;;        

  &lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// Used to access the ticket for the current request&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="type"&gt;IUserTicket&lt;/span&gt; Ticket
  {
    get
    {
      &lt;span class="rem"&gt;// try local execution context first&lt;/span&gt;
      &lt;span class="type"&gt;IUserTicket&lt;/span&gt; ticket = &lt;span class="type"&gt;Local&lt;/span&gt;.Data[KEY_TICKET] &lt;span class="kwrd"&gt;as&lt;/span&gt; &lt;span class="type"&gt;IUserTicket&lt;/span&gt;;
      &lt;span class="kwrd"&gt;if&lt;/span&gt; (ticket != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
        &lt;span class="kwrd"&gt;return&lt;/span&gt; ticket;

      &lt;span class="rem"&gt;// try session&lt;/span&gt;
      &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="type"&gt;Local&lt;/span&gt;.RunningInWeb &amp;amp;&amp;amp; &lt;span class="type"&gt;HttpContext&lt;/span&gt;.Current.Session != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
      {
        ticket = &lt;span class="type"&gt;HttpContext&lt;/span&gt;.Current.Session[KEY_TICKET] &lt;span class="kwrd"&gt;as&lt;/span&gt; &lt;span class="type"&gt;IUserTicket&lt;/span&gt;;
        &lt;span class="rem"&gt;// cache in local &lt;/span&gt;
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (ticket != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
          &lt;span class="type"&gt;Local&lt;/span&gt;.Data[KEY_TICKET] = ticket;
      }

      &lt;span class="kwrd"&gt;return&lt;/span&gt; ticket;
    }
    set
    {
      &lt;span class="type"&gt;Local&lt;/span&gt;.Data[KEY_TICKET] = &lt;span class="kwrd"&gt;value&lt;/span&gt;;

      &lt;span class="rem"&gt;// store in session if running in web &lt;/span&gt;
      &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="type"&gt;Local&lt;/span&gt;.RunningInWeb)
      {
        &lt;span class="type"&gt;HttpContext&lt;/span&gt;.Current.Session[KEY_TICKET] = &lt;span class="kwrd"&gt;value&lt;/span&gt;;
      }
    }
  }
}&lt;/pre&gt;

&lt;p&gt;The Local class in the above code is an abstraction over HttpContext.Current.Items and Thread data depending on if the code is being run in web context or not. This last approach is very easy to work with but you have less control over where and how the data is accessed. &lt;/p&gt;

&lt;p&gt;There is also Thread.CurrentPrincipal which is a good to use, especially for user authorization. I am not sure which of the approaches I like more, the second one is probably the best one from a purist / TDD point of view. I will post a question in the ALT.NET mailing list to find out what solutions smarter people than me have arrived at. &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/05/handling-execution-context-user-session.html" title="Handling Execution Context / User Session" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=2371509846366771341" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/2371509846366771341/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/2371509846366771341" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/2371509846366771341" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-3510282463200398362</id><published>2008-04-29T20:05:00.001+02:00</published><updated>2008-04-29T20:09:43.236+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="MVC" /><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET MVC" /><category scheme="http://www.blogger.com/atom/ns#" term="MonoRail" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title type="text">ASP.NET MVC Controller Areas, ControllerTypeCache limitations and IViewLocator</title><content type="html">&lt;p&gt;I am currently trying to prototype how a portal application could be build using ASP.NET MVC (I would prefer to use MonoRail but can't). &lt;/p&gt;  &lt;p&gt;There is a big problem in the way the default implementation of the IControllerFactory is handling controller types. It is using a simple dictionary to map controller names to controller types. The key in the dictionary is only the controller name (like &amp;quot;Home&amp;quot; for a HomeController type), this means that you cannot have controllers with the same type name (no matter what namespace or assembly the controller is in). In big applications you probably want to group your controllers into areas in which case a controller of the same name could be likely. &lt;/p&gt;  &lt;p&gt;So currently it is not possible to group controllers into what MonoRail calls Areas.&amp;#160; To do this you would have to implement IControllerFactory from scratch since the root of the problem is the ControllerTypeCache which is being used by the DefaultControllerFactory, and the ControllerTypeCache is of course internal and sealed. There are probably other changes that would need to be made to introduce the concept of areas. &lt;/p&gt;  &lt;p&gt;There is a extensibility point named IViewLocator used by the WebFormViewEngine which can be exchanged to change the way the view engine locates views. A simple example:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;PortalViewLocator&lt;/span&gt; : &lt;span class="type"&gt;ViewLocator&lt;/span&gt;
{
      &lt;span class="kwrd"&gt;public&lt;/span&gt; PortalViewLocator ()
      {
          ViewLocationFormats = &lt;span class="kwrd"&gt;new&lt;/span&gt;[] {
              &lt;span class="str"&gt;&amp;quot;~/CustomViewDir/{1}/{0}.aspx&amp;quot;&lt;/span&gt;,
              &lt;span class="str"&gt;&amp;quot;~/CustomViewDir/{1}/{0}.ascx&amp;quot;&lt;/span&gt;,
              &lt;span class="str"&gt;&amp;quot;~/CustomViewDir/Shared/{0}.aspx&amp;quot;&lt;/span&gt;,
              &lt;span class="str"&gt;&amp;quot;~/CustomViewDir/Shared/{0}.ascx&amp;quot;&lt;/span&gt;
          };
          MasterLocationFormats = &lt;span class="kwrd"&gt;new&lt;/span&gt;[] {
              &lt;span class="str"&gt;&amp;quot;~/CustomViewDir/{1}/{0}.master&amp;quot;&lt;/span&gt;,
              &lt;span class="str"&gt;&amp;quot;~/CustomViewDir/Shared/{0}.master&amp;quot;&lt;/span&gt;
          };
      }
}&lt;/pre&gt;

&lt;p&gt;To solve the problem with controller areas MonoRail has something it calls a Controller Tree which serves the same role as the ASP.NET MVC ControllerTypeCache. In MonoRail the area of a controller is specified using the optional ControllerDetails attribute: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; Castle.MonoRail.Framework;

[&lt;span class="type"&gt;ControllerDetails&lt;/span&gt;(Area=&lt;span class="str"&gt;&amp;quot;admin&amp;quot;&lt;/span&gt;)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; &lt;span class="type"&gt;UsersController&lt;/span&gt; : &lt;span class="type"&gt;Controller&lt;/span&gt;
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Index()
    {
    }
}&lt;/pre&gt;
With the default routing the above index function would correspond the URL &amp;quot;/admin/users/index&amp;quot;. If ASP.NET MVC adopted a similar approach it could check for an attribute in it's clever Html helper functions which takes in lambda functions (i.e. expression trees): 

&lt;pre class="csharpcode"&gt;Html.ActionLink&amp;lt;&lt;span class="type"&gt;UserController&lt;/span&gt;&amp;gt;(c =&amp;gt; c.Register(), &lt;span class="str"&gt;&amp;quot;Register now!&amp;quot;&lt;/span&gt;)&lt;/pre&gt;

&lt;p&gt;I understand that they want the keep the ASP.NET MVC framework as lightweight and simple as possible and only add features when they are really needed (which is a good philosophy) and have extensibility points for specific scenarios. However I think that a concept like controller areas should built into the framework. &lt;/p&gt;

&lt;p&gt;I also hope they start looking at scenarios where you might want to create a modular web applications composed of multiple sub projects. I guess it would be possible to do that now but it would be very hard and would require you to replace many of the default implementations in the MVC framework. &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/04/aspnet-mvc-controller-areas.html" title="ASP.NET MVC Controller Areas, ControllerTypeCache limitations and IViewLocator" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=3510282463200398362" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/3510282463200398362/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3510282463200398362" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3510282463200398362" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-3367295024510580779</id><published>2008-04-29T09:10:00.001+02:00</published><updated>2008-04-29T09:12:28.237+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="IoC" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title type="text">Managed Extensibility Framework</title><content type="html">&lt;p&gt;Microsoft seems to be about reinventing the wheel again, Krzysztof blogged about a &lt;a href="http://blogs.msdn.com/kcwalina/archive/2008/04/25/MEF.aspx" target="_blank"&gt;new framework&lt;/a&gt; being worked on with these goals: &lt;/p&gt;  &lt;blockquote&gt;&lt;em&gt;MEF is a set of features referred in the academic community and in the industry as a Naming and Activation Service (returns an object given a &amp;#8220;name&amp;#8221;), Dependency Injection (DI) framework, and a Structural Type System (duck typing)&lt;/em&gt;&lt;/blockquote&gt;  &lt;p&gt;They are currently just experimenting with different approaches and a CTP is likely to be released soon. The example that Krzysztof showed might not be indicative of how it will eventually turn out but it doesn't look very promising (requiring property attributes to declare dependencies, etc). &lt;/p&gt;  &lt;p&gt;The approach I was hoping that Microsoft would take was to try and incorporate the concepts of an IoC container but make the concrete container pluggable. Maybe even to introduce this concept on the CLR level or maybe just C#/VB. Maybe something like this: &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;this&lt;/span&gt;.authService = &lt;span class="kwrd"&gt;resolve&lt;/span&gt; &lt;span class="type"&gt;IAuthentificationService&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;If C# could introduce a new keyword (resolve) that would request a component from a container. The .NET framework would probably need a basic implementation of the container but it should be completely pluggable so you can exchange it with for example Castle Windsor or StructureMap. I haven't really thought this through but If Microsoft is going to include an IoC Container in the core framework this is the approach I wish they would at least try (maybe they have?). &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/04/managed-extensibility-framework.html" title="Managed Extensibility Framework" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=3367295024510580779" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/3367295024510580779/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3367295024510580779" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3367295024510580779" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-2994139464906709293</id><published>2008-04-24T18:07:00.001+02:00</published><updated>2008-04-25T13:30:47.087+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Presentations" /><category scheme="http://www.blogger.com/atom/ns#" term="Logging" /><category scheme="http://www.blogger.com/atom/ns#" term="NHibernate" /><title type="text">Open Source and the .NET Platform</title><content type="html">&lt;p&gt;Yesterday I held a short seminar (2 hours) on Open Source and .NET for the Systems Development team at Cybercom Sweden East. The seminar was split into three separate presentations, I will try to give a short summery of them here. At the end of the post I will post links to the powerpoints and application examples.&lt;/p&gt;  &lt;p&gt;&lt;u&gt;&lt;/u&gt;&lt;/p&gt;  &lt;p&gt;&lt;u&gt;Open Source and .NET&lt;/u&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;This presentation covered a short introduction to open source. I began with explaining the most common licences (GPL, LGPL, Apache) and then moved on to list a few interesting framework and development tools. But mostly it was about why I think utilizing open source is something that we as .NET developers need to be better at, and why this will be very important if the .NET platform is going to stay competitive. &lt;/p&gt;  &lt;p&gt;I have never worked professionally as a java developer but my understanding is that tools like Eclipse and frameworks like Struts, Hibernate and Spring are used to a very a large extent (30 - 70% according to some studies). And what types of platforms do java applications run on? They usually run on an open source OS and use an open source web server (Apache) or application server. This means that the devolvement environment, tools and frameworks are largely based on open source software.&lt;/p&gt;  &lt;p&gt;I think this fact contributes to the mindset of java developers and project managers to actively search for, and be more open to, open source solutions. I feel that many .NET developers are prone to constantly reinvent the wheel, for example by creating their own logging framework or a basic data layer tool without ever searching for existing alternatives, be that open source or commercial. &lt;/p&gt;  &lt;p&gt;&lt;u&gt;Open Source benefits&lt;/u&gt;&lt;/p&gt;  &lt;p&gt;I also talked about some of the benefits I see with open source frameworks compared to Microsoft's offerings. One of the main things I mentioned here was innovation, I think that a lot of innovation in development methodologies (TDD), design, frameworks and tools are coming to large extent from the open source community. The fact that open source software starts without commercial aspirations or requirements results in software that is more focused on solving real problems and less on flashy designers. &lt;/p&gt;  &lt;p&gt;&lt;u&gt;Open Source problems&lt;/u&gt;&lt;/p&gt;  &lt;p&gt;The major problem I see with open source is the lack of commercial support services. I don't see this personally as a problem but as a problem when trying to sell open source solutions to management. There are many companies that are offering training and support for open source frameworks and tools on the java side but very few for the .NET equivalents. I think this point is also one of the major reasons why .NET&amp;#160; is so behind java when it comes to open source adoption. The lack of commercial support is something I partly blame on Microsoft who instead of promoting and supporting open source actively compete with it. &lt;/p&gt;  &lt;p&gt;&lt;u&gt;Open Source trends&lt;/u&gt;&lt;/p&gt;  &lt;p&gt;I ended the presentation by showing some statistics from the &lt;a href="http://www.ioug.org/IOUG_Open_Source_07.pdf" target="_blank"&gt;IOUG Open Source 07 Report&lt;/a&gt;. This report really shows how much open source software is currently being used by big enterprise companies (almost exclusive non .NET software) and that this is an increasing trend. Just between 2006 and 2007 the increase in the use of open source software was 26%. The report also showed the reasons why open source software is being used. The two main reasons were cost savings and no proprietary vendor lock-in. &lt;/p&gt;  &lt;p&gt;Not to be misunderstood, I am not an open source fundamentalist, I just think there is a lot of value in some open source frameworks and tools and I think .NET developers in general (maybe not those who happen to read this blog) should utilize this resource more.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;u&gt;Log4Net &amp;amp; NHibernate&lt;/u&gt;&lt;/p&gt;  &lt;p&gt;I also held a presentation about Log4Net and an hour long presentation about object-relational mapping with NHibernate which included a short live coding demo.&amp;#160; &lt;/p&gt;  &lt;p&gt;Here are the powerpoints (they are in Swedish):&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.codinginstinct.com-a.googlepages.com/OpenSourceand.NET.pptx" target="_blank"&gt;Open Source och .NET&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.codinginstinct.com-a.googlepages.com/LoggningmedLog4net.pptx" target="_blank"&gt;Loggning med Log4Net&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.codinginstinct.com-a.googlepages.com/Nhibernate.pptx" target="_blank"&gt;NHibernate&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I also made some sample applications:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.codinginstinct.com-a.googlepages.com/Cybercom.Log4NetDemo.zip" target="_blank"&gt;Cybercom.Log4NetDemo.zip&lt;/a&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.codinginstinct.com-a.googlepages.com/Cybercom.NHibernateExampleSimple.zip" target="_blank"&gt;Cybercom.NHibernateExampleSimple.zip&lt;/a&gt; (A very simple console application showing some NHibernate basics) &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.codinginstinct.com-a.googlepages.com/Cybercom.NhibernateDemo.zip" target="_blank"&gt;Cybercom.NhibernateDemo.zip&lt;/a&gt;&amp;#160; (A small application showing how to use NHibernate in a web application, not to complicate things I choose not use use an IoC container or NHibernate Query Generator,&amp;#160; I did use a repository pattern though) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I wanted some code in this post so here is snippet from the NHibernateDemo application that shows how simple property projection is with the NHibernate Critiera API:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="type"&gt;IList&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; GetAllBlogOwnerNames()
{
  &lt;span class="kwrd"&gt;return&lt;/span&gt; Session.CreateCriteria(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(User))
    .Add(&lt;span class="type"&gt;Expression&lt;/span&gt;.IsNotEmpty(&lt;span class="str"&gt;&amp;quot;Blogs&amp;quot;&lt;/span&gt;))
    .SetProjection(&lt;span class="type"&gt;Projections&lt;/span&gt;.Property(&lt;span class="str"&gt;&amp;quot;UserName&amp;quot;&lt;/span&gt;))
    .List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
}&lt;/pre&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/04/open-source-and-net-platform.html" title="Open Source and the .NET Platform" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=2994139464906709293" title="4 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/2994139464906709293/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/2994139464906709293" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/2994139464906709293" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-3573027260202102654</id><published>2008-04-17T21:54:00.001+02:00</published><updated>2008-05-05T21:35:53.991+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="IoC" /><category scheme="http://www.blogger.com/atom/ns#" term="Benchmarks" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title type="text">IoC Benchmark Revisited - Ninject</title><content type="html">&lt;p&gt;Someone (Joshua) mentioned Ninject in the comments to in my &lt;a href="http://www.codinginstinct.com/2008/04/ioc-container-benchmark-unity-windsor.html"&gt;IoC Benchmark&lt;/a&gt;. I hadn't heard of this project before but after checking out &lt;a href="http://ninject.org"&gt;ninject.org&lt;/a&gt; and seeing the project slogan &amp;quot;lighning-fast dependency injection&amp;quot; I felt that it deserved be included in the test. &lt;/p&gt;  &lt;p&gt;I am not sure what the slogan refers to though, lightning-fast usage and setup or runtime performance? Anyway it has a nice fluent registration API: &lt;/p&gt;  &lt;pre class="csharpcode"&gt;Bind&amp;lt;&lt;span class="type"&gt;IUserRepository&lt;/span&gt;&amp;gt;()
  .To&amp;lt;&lt;span class="type"&gt;LdapUserRepository&lt;/span&gt;&amp;gt;()
  .Using&amp;lt;&lt;span class="type"&gt;SingletonBehavior&lt;/span&gt;&amp;gt;();
  
Bind&amp;lt;&lt;span class="type"&gt;IAuthentificationService&lt;/span&gt;&amp;gt;()
  .To&amp;lt;&lt;span class="type"&gt;DefaultAuthentificationService&lt;/span&gt;&amp;gt;()
  .Using&amp;lt;&lt;span class="type"&gt;SingletonBehavior&lt;/span&gt;&amp;gt;();

Bind&amp;lt;&lt;span class="type"&gt;UserController&lt;/span&gt;&amp;gt;()
  .ToSelf()
  .Using&amp;lt;&lt;span class="type"&gt;SingletonBehavior&lt;/span&gt;&amp;gt;(); &lt;/pre&gt;

&lt;p&gt;The tests were made with the release build of RC1 downloaded from the project homepage. I was kind of surprised by the results: &lt;/p&gt;
&lt;img style="display: block; margin-left: auto; margin-right: auto" alt="IoCSingleton_WithNinject" src="http://lh5.ggpht.com/torkel.odegaard/SAepieJA30I/AAAAAAAAAWw/ASYh_ADK4Sw/IoCSingleton_WithNinject_thumb%5B2%5D.png?imgmax=800" border="0" /&gt; 

&lt;br /&gt;&lt;img style="display: block; margin-left: auto; margin-right: auto" alt="IoCTransient_WithNinject" src="http://lh5.ggpht.com/torkel.odegaard/SAeq1eJA32I/AAAAAAAAAXA/6-XMKr66sqk/IoCTransient_WithNinject_thumb%5B2%5D.png?imgmax=800" border="0" /&gt; 

&lt;p&gt;I might be doing something wrong here but this is the result I got. For the transient case there seems to be a big memory leak. The Ninject kernel seems to keep references to transient objects. I tried the kernel's Release function but the memory leak was still evident. &lt;/p&gt;

&lt;p&gt;Just to check that it was not something wrong with my code I did a profiling trace with JetBrains dotTrace: &lt;/p&gt;
&lt;img style="display: block; margin-left: auto; margin-right: auto" alt="NinjectTrace" src="http://lh3.ggpht.com/torkel.odegaard/SAeq1-JA33I/AAAAAAAAAXI/UtSJd7vjjMo/NinjectTrace_thumb%5B12%5D.png?imgmax=800" border="0" /&gt; 

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;It could still be me setting something up in the wrong way, but it looks like it's a bug in the Ninject Core. &lt;/p&gt;

&lt;p&gt;&lt;u&gt;Just a note:&lt;/u&gt; I think that doing premature optimization can result in bad design and architecture. The reason I did this and the previous test was not to find the fastest container, it was firstly to get a change to play with new (to me) containers, and secondly to see if there were any significant performance difference between them worthy of taking into account when choosing a container. &lt;/p&gt;

&lt;p&gt;My conclusion in the previous test was that the difference in performance was not big enough to be relevant compared to other aspects of the containers, like how much you like the API or the features. The Ninject result for the transient test above is very significant, however it is probably caused by a memory bug in the release candidate and will likely be fixed in the next release. If you disregard this bug I actually kind of liked Ninject, it a had a nice API and a way of doing things, but it's slogan is currently a little misleading :) &lt;/p&gt;

&lt;p&gt;For the complete code: &lt;a href="http://www.codinginstinct.com-a.googlepages.com/IoCBenchmark_Revisited.zip"&gt;IoCBenchmark_Revisited.zip&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Updated (2008-05-05):&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;Nate Kohari has fixed the performance issue, the results are now inline with the other containers. For the new results (which also includes Autofac) please view &lt;a href="http://www.codinginstinct.com/2008/05/ioc-container-benchmark-rerevisted.html"&gt;this post&lt;/a&gt;. &lt;/p&gt;  </content><link rel="alternate" type="text/html" href="http://www.codinginstinct.com/2008/04/ioc-benchmark-revisited-ninject.html" title="IoC Benchmark Revisited - Ninject" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=3198935374994345981&amp;postID=3573027260202102654" title="4 Comments" /><link rel="replies" type="application/atom+xml" href="http://www.codinginstinct.com/feeds/3573027260202102654/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3573027260202102654" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3198935374994345981/posts/default/3573027260202102654" /><author><name>Torkel Ödegaard</name><email>noreply@blogger.com</email></author></entry><entry><id>tag:blogger.com,1999:blog-3198935374994345981.post-5300835300607745472</id><published>2008-04-16T22:17:00.001+02:00</published><updated>2008-04-16T22:46:16.939+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title type="text">Querying across relations with LINQ using lambdas</title><content type="html">&lt;p&gt;Here is an interesting problem, try writing the bellow Linq query using lambda expressions. &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; usersWithBigOrders =
  &lt;span class="kwrd"&gt;from&lt;/span&gt; usr &lt;span class="kwrd"&gt;in&lt;/span&gt; context.Users
  &lt;span class="kwrd"&gt;from&lt;/span&gt; ordr &lt;span class="kwrd"&gt;in&lt;/span&gt; usr.Orders
  &lt;span class="kwrd"&gt;where&lt;/span&gt; ordr.Total &amp;gt; 10
  &lt;span class="kwrd"&gt;select&lt;/span&gt; usr;&lt;/pre&gt;

&lt;p&gt;I ran into this interesting Linq question when writing yesterday's post. To figure out what the above query actually does I used Reflector. The code bellow is what the C# compiler will generate (when reverted back from IL to C#):&lt;/p&gt;

&lt;pre class="csharpcode" style="font-size: 8pt"&gt;context.Users.SelectMany(
Expression.Lambda&amp;lt;Func&amp;lt;User, IEnumerable&amp;lt;Order&amp;gt;&amp;gt;&amp;gt;(
  Expression.Property(CS$0$0000 = Expression.Parameter(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(User), &lt;span class="str"&gt;&amp;quot;user&amp;quot;&lt;/span&gt;),
   (MethodInfo) methodof(User.get_Orders)), &lt;span class="kwrd"&gt;new&lt;/span&gt; ParameterExpression[] { CS$0$0000 }),
    Expression.Lambda(
      Expression.New((ConstructorInfo) methodof(&amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;..ctor,
       &amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;), 
       &lt;span class="kwrd"&gt;new&lt;/span&gt; Expression[] { CS$0$0000 = Expression.Parameter(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(User), &lt;span class="str"&gt;&amp;quot;user&amp;quot;&lt;/span&gt;), 
       CS$0$0002 = Expression.Parameter(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Order), &lt;span class="str"&gt;&amp;quot;order&amp;quot;&lt;/span&gt;) }, 
       &lt;span class="kwrd"&gt;new&lt;/span&gt; MethodInfo[] { (MethodInfo) methodof(&amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;.get_user, 
       &amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;), 
       (MethodInfo) methodof(&amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;.get_order, 
       &amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;) }), 
       &lt;span class="kwrd"&gt;new&lt;/span&gt; ParameterExpression[] { CS$0$0000, CS$0$0002 }))
.Where(Expression.Lambda(Expression.GreaterThan(
  Expression.Property(Expression.Property(
    CS$0$0000 = Expression.Parameter(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;),
     &lt;span class="str"&gt;&amp;quot;&amp;lt;&amp;gt;h__TransparentIdentifier0&amp;quot;&lt;/span&gt;),
      (MethodInfo) methodof(&amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;.get_order,
       &amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;)), (MethodInfo) methodof(Order.get_Total)), 
       Expression.Convert(Expression.Constant(10, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="kwrd"&gt;int&lt;/span&gt;)), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="kwrd"&gt;int&lt;/span&gt;?))), 
       &lt;span class="kwrd"&gt;new&lt;/span&gt; ParameterExpression[] { CS$0$0000 }))
        .Select(Expression.Lambda(Expression.Property(
          CS$0$0000 = Expression.Parameter(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;),
           &lt;span class="str"&gt;&amp;quot;&amp;lt;&amp;gt;h__TransparentIdentifier0&amp;quot;&lt;/span&gt;), 
           (MethodInfo) methodof(&amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;.get_user,
            &amp;lt;&amp;gt;f__AnonymousType0&amp;lt;User, Order&amp;gt;)), 
            &lt;span class="kwrd"&gt;new&lt;/span&gt; ParameterExpression[] { CS$0$0000 })).ToList&amp;lt;User&amp;gt;();&lt;/pre&gt;

&lt;p&gt;It is quite surprising how much code that the compiler actually generates. The reason for the amount of code above is because the LinqToSql table class implements IQueryable. When the compiler detects this interface instead of generating IL that performs the query it will generate IL that builds up an expression tree that describes the query. &lt;/p&gt;

&lt;p&gt;So in order to understand what the above code actually describes I wrote the same Linq query but instead of querying LinqToSql I queried a normal .NET collection. The code that Reflector generates now looks like this: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;List&amp;lt;User&amp;gt; users = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;User&amp;gt;();
&lt;span class="kwrd"&gt;if&lt;/span&gt; (CS$&amp;lt;&amp;gt;9__CachedAnonymousMethodDelegate6 == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
{
    CS$&amp;lt;&amp;gt;9__CachedAnonymousMethodDelegate6 = &lt;span class="kwrd"&gt;delegate&lt;/span&gt; (User usr) {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; usr.Orders;
    };
}
&lt;span class="kwrd"&gt;if&lt;/span&gt; (CS$&amp;lt;&amp;gt;9__CachedAnonymousMethodDelegate7 == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
{
    CS$&amp;lt;&amp;gt;9__CachedAnonymousMethodDelegate7 = &lt;span class="kwrd"&gt;delegate&lt;/span&gt; (User usr, Order ordr) {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; { usr = usr, ordr = ordr };
    };
}
&lt;span class="kwrd"&gt;if&lt;/span&gt; (CS$&amp;lt;&amp;gt