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

<channel>
	<title>Crafting .NET</title>
	<atom:link href="http://bengtbe.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://bengtbe.com/blog</link>
	<description>My thoughts about .NET and development</description>
	<lastBuildDate>Thu, 07 Jul 2011 18:20:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>NerdDinner with Fluent NHibernate Part 3 &#8211; The infrastructure</title>
		<link>http://bengtbe.com/blog/2009/10/08/nerddinner-with-fluent-nhibernate-part-3-the-infrastructure/</link>
		<comments>http://bengtbe.com/blog/2009/10/08/nerddinner-with-fluent-nhibernate-part-3-the-infrastructure/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 03:00:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[NerdDinner]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">/blog/post/2009/10/08/NerdDinner-with-Fluent-NHibernate-Part-3-The-infrastructure.aspx</guid>
		<description><![CDATA[This is the final post in a series of three where I&#8217;m going to see how we can change the NerdDinner project to use Fluent NHibernate instead of LINQ to SQL: Part 1 &#8211; The domain model Part 2 &#8211; The mapping Part 3 &#8211; The infrastructure Introduction In the first post we took a look [...]]]></description>
			<content:encoded><![CDATA[<p>This is the final post in a series of three where I&#8217;m going to see how we can change the NerdDinner project to use Fluent NHibernate instead of LINQ to SQL:</p>
<ul>
<li>
<a href="/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx">Part 1 &#8211; The domain model</a></li>
<li>
<a href="/blog/post/2009/08/25/NerdDinner-with-Fluent-NHibernate-Part-2-The-mapping.aspx">Part 2 &#8211; The mapping</a></li>
<li>
<a href="/blog/post/2009/10/08/NerdDinner-with-Fluent-NHibernate-Part-3-The-infrastructure.aspx">Part 3 &#8211; The infrastructure</a></li>
</ul>
<h3>Introduction</h3>
<p>In the first post we took a look at the domain model of <a href="http://www.nerddinner.com/" target="_blank"><span style="color: #2180bc;">NerdDinner.com</span></a>, and recreated and improved the code that was auto generated by the LINQ to SQL designer. In the second post we saw how to map this domain model to the database using <a href="http://fluentnhibernate.org/" target="_blank"><span style="color: #2180bc;">Fluent NHibernate</span></a>. In this final post we are going to take a look at the required changes to the rest of the application.</p>
<h3>Session per request</h3>
<p>In order for the repository to use NHibernate it needs to get a hold of an <span style="text-decoration: underline;">ISession</span>. In this application I have chosen to follow the session per request pattern, in which a session is created at the beginning of the HTTP request, and closed at the end of the HTTP request. I also wanted to keep the changes to the NerdDinner project as small as possible; hence the entire infrastructure for NHibernate is isolated in a single class:<br />
<code></p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">NHibernateSessionPerRequest</span> : <span style="color: #2b91af;">IHttpModule</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">static</span> <span style="color: #ff8000;">readonly</span> <span style="color: #2b91af;">ISessionFactory</span> _sessionFactory;</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">static</span> NHibernateSessionPerRequest()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        _sessionFactory = CreateSessionFactory();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> Init(<span style="color: yellow;">HttpApplication</span> context)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        context.BeginRequest += BeginRequest;</p>
<p style="margin: 0px;">        context.EndRequest += EndRequest;</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">static</span> <span style="color: #2b91af;">ISession</span> GetCurrentSession()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> _sessionFactory.GetCurrentSession();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> Dispose() { }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">static</span> <span style="color: #ff8000;">void</span> BeginRequest(<span style="color: #ff8000;">object</span> sender, <span style="color: yellow;">EventArgs</span> e)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #2b91af;">ISession</span> session = _sessionFactory.OpenSession();</p>
<p style="margin: 0px;">        session.BeginTransaction();</p>
<p style="margin: 0px;">        <span style="color: yellow;">CurrentSessionContext</span>.Bind(session);</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">static</span> <span style="color: #ff8000;">void</span> EndRequest(<span style="color: #ff8000;">object</span> sender, <span style="color: yellow;">EventArgs</span> e)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #2b91af;">ISession</span> session = <span style="color: yellow;">CurrentSessionContext</span>.Unbind(_sessionFactory);</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">if</span> (session == <span style="color: #ff8000;">null</span>) <span style="color: #ff8000;">return</span>;</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">try</span></p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            session.Transaction.Commit();</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">catch</span> (<span style="color: yellow;">Exception</span>)</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            session.Transaction.Rollback();</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">finally</span></p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            session.Close();</p>
<p style="margin: 0px;">            session.Dispose();</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">static</span> <span style="color: #2b91af;">ISessionFactory</span> CreateSessionFactory()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">string</span> connString = <span style="color: lime;">"NerdDinnerConnectionString"</span>;</p>
<p style="margin: 0px;">        <span style="color: yellow;">FluentConfiguration</span> configuration = <span style="color: yellow;">Fluently</span>.Configure()</p>
<p style="margin: 0px;">        .Database(<span style="color: yellow;">MsSqlConfiguration</span>.MsSql2005.ConnectionString(</p>
<p style="margin: 0px;">           x =&gt; x.FromConnectionStringWithKey(connString)))</p>
<p style="margin: 0px;">        .ExposeConfiguration(</p>
<p style="margin: 0px;">            c =&gt; c.SetProperty(<span style="color: lime;">"current_session_context_class"</span>, <span style="color: lime;">"web"</span>))</p>
<p style="margin: 0px;">        .Mappings(m =&gt; m.FluentMappings.AddFromAssemblyOf&lt;<span style="color: yellow;">Dinner</span>&gt;());</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> configuration.BuildSessionFactory();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p></code><br />
Some comments about the infrastructure:</p>
<ul>
<li>It implements the <span style="text-decoration: underline;">IHttpModule</span>, in order to plug into the request handling pipeline.</li>
<li>Since it is expensive to create an <span style="text-decoration: underline;">ISessionFactory</span> you only want to create this once. This is why the factory is stored in a static field that is initialized by the static constructor.</li>
<li>At the beginning of the HTTP request the <span style="text-decoration: underline;">ISession</span> is created and &#8220;stored&#8221; using the <span style="text-decoration: underline;">CurrentSessionContext.Bind</span> method.</li>
<li>Other code can get a hold of this session by calling the <span style="text-decoration: underline;">GetCurrentSession</span> method.</li>
<li>At the end of the HTTP request we &#8220;remove&#8221; the session by using the <span style="text-decoration: underline;">CurrentSessionContext.Unbind</span> method. We also commit any changes, and close the session.</li>
</ul>
<p>There are some drawbacks to this approach. We create a session for every request, even if it is not needed. However, a session is very lightweight, and we can easily tweak this behavior later. Another drawback is that we commit the transaction at the end of the HTTP request. In a more complex business application you probably want more control over your unit of work.</p>
<p>In order to activate this <span style="text-decoration: underline;">IHttpModule</span> we need to add the following to <strong>httpModules</strong>/<strong>modules</strong> section of the <span style="text-decoration: underline;">Web.config</span>:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;">&lt;add <span style="color: #ff8000;">name</span>=&#8221;<span style="color: lime;">NHibernateSessionPerRequest</span>&#8221; <span style="color: #ff8000;">type</span>=&#8221;<span style="color: lime;">NerdDinner.Models.NHibernateSessionPerRequest</span>&#8221; /&gt;</p>
</div>
<h3>Changes to the repository</h3>
<p>In the <span style="text-decoration: underline;">DinnerRepository</span> we are mainly going to use LINQ to NHibernate to replace the LINQ to SQL queries:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">DinnerRepository</span> : <span style="color: #2b91af;">IDinnerRepository</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #2b91af;">ISession</span> Session</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">get</span> { <span style="color: #ff8000;">return</span> <span style="color: yellow;">NHibernateSessionPerRequest</span>.GetCurrentSession(); }</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #2b91af;">IQueryable</span>&lt;<span style="color: yellow;">Dinner</span>&gt; FindAllDinners()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> Session.Linq&lt;<span style="color: yellow;">Dinner</span>&gt;();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #2b91af;">IQueryable</span>&lt;<span style="color: yellow;">Dinner</span>&gt; FindUpcomingDinners()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> <span style="color: #ff8000;">from</span> dinner <span style="color: #ff8000;">in</span> FindAllDinners()</p>
<p style="margin: 0px;">               <span style="color: #ff8000;">where</span> dinner.EventDate &gt;= <span style="color: #2b91af;">DateTime</span>.Now</p>
<p style="margin: 0px;">               <span style="color: #ff8000;">orderby</span> dinner.EventDate</p>
<p style="margin: 0px;">               <span style="color: #ff8000;">select</span> dinner;</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #2b91af;">IQueryable</span>&lt;<span style="color: yellow;">Dinner</span>&gt; FindByLocation(<span style="color: #ff8000;">float</span> latitude, <span style="color: #ff8000;">float</span> longitude)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> Session.CreateSQLQuery(</p>
<p style="margin: 0px;">                <span style="color: #a31515;">@&#8221;SELECT d.* </span></p>
<p style="margin: 0px;"><span style="color: #a31515;">                    FROM Dinners d </span></p>
<p style="margin: 0px;"><span style="color: #a31515;">                    JOIN NearestDinners(:Latitude, :Longitude) n</span></p>
<p style="margin: 0px;"><span style="color: #a31515;">                      ON d.DinnerId = n.DinnerId</span></p>
<p style="margin: 0px;"><span style="color: #a31515;">                   WHERE EventDate &gt;= :EventDate</span></p>
<p style="margin: 0px;"><span style="color: #a31515;">                   ORDER BY EventDate Desc&#8221;</span>)</p>
<p style="margin: 0px;">            .AddEntity(<span style="color: #ff8000;">typeof</span>(<span style="color: yellow;">Dinner</span>))</p>
<p style="margin: 0px;">            .SetDouble(<span style="color: lime;">&#8220;Latitude&#8221;</span>, latitude)</p>
<p style="margin: 0px;">            .SetDouble(<span style="color: lime;">&#8220;Longitude&#8221;</span>, longitude)</p>
<p style="margin: 0px;">            .SetDateTime(<span style="color: lime;">&#8220;EventDate&#8221;</span>, <span style="color: #2b91af;">DateTime</span>.Now)</p>
<p style="margin: 0px;">            .List&lt;<span style="color: yellow;">Dinner</span>&gt;().AsQueryable();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: yellow;">Dinner</span> GetDinner(<span style="color: #ff8000;">int</span> id)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> Session.Linq&lt;<span style="color: yellow;">Dinner</span>&gt;()</p>
<p style="margin: 0px;">            .SingleOrDefault(d =&gt; d.DinnerID == id);</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> Add(<span style="color: yellow;">Dinner</span> dinner)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        Session.SaveOrUpdate(dinner);</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> Delete(<span style="color: yellow;">Dinner</span> dinner)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        Session.Delete(dinner);</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p>The LINQ to SQL and NHibernate Linq syntax are similar, so the changes to this class were fairly simple. However in the <span style="text-decoration: underline;">FindByLocation</span> method I had to create a custom SQL query, because I don&#8217;t think (not sure) that LINQ to NHibernate supports calling the database function NearestDinners.</p>
<p><strong>Update</strong>: It seems that NHibernate Linq supports database functions. However I couldn&#8217;t find much information about the functionality except for one simple example in the source code.</p>
<p>The <span style="text-decoration: underline;">ISession</span> is retrieved by calling the <span style="text-decoration: underline;">GetCurrentSession()</span> method. In an application with an IoC container I would prefer to inject the session in the constructor.</p>
<h3>finally {}</h3>
<p>In the final post in this series we have taken a look at the necessary changes to the infrastructure. We used a session per request pattern to create the session, and LINQ to NHibernate in the repository. As you hopefully have seen it was not very difficult to replace LINQ to SQL with Fluent NHibernate. As a benefit the domain part of the application has been greatly improved over the auto generated code from the LINQ to SQL designer.</p>
<p>If you liked this post then please shout and kick me <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/10/08/NerdDinner-with-Fluent-NHibernate-Part-3-The-infrastructure.aspx&amp;title=NerdDinner%20with%20Fluent%20NHibernate%20Part%203%20-%20The%20infrastructure" target="_blank"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/10/08/NerdDinner-with-Fluent-NHibernate-Part-3-The-infrastructure.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Submit?url=http://www.bengtbe.com/blog/post/2009/10/08/NerdDinner-with-Fluent-NHibernate-Part-3-The-infrastructure.aspx&amp;title=NerdDinner%20with%20Fluent%20NHibernate%20Part%203%20-%20The%20infrastructure" rev="vote-for" target="_blank"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http://www.bengtbe.com/blog/post/2009/10/08/NerdDinner-with-Fluent-NHibernate-Part-3-The-infrastructure.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/10/08/nerddinner-with-fluent-nhibernate-part-3-the-infrastructure/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Auto-mocking hierarchies (a.k.a. recursive mocks) with Moq</title>
		<link>http://bengtbe.com/blog/2009/08/27/auto-mocking-hierarchies-a-k-a-recursive-mocks-with-moq/</link>
		<comments>http://bengtbe.com/blog/2009/08/27/auto-mocking-hierarchies-a-k-a-recursive-mocks-with-moq/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 03:35:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Moq]]></category>

		<guid isPermaLink="false">/blog/post/2009/08/27/Auto-mocking-hierarchies-(aka-recursive-mocks)-with-Moq.aspx</guid>
		<description><![CDATA[I have just read a good post by Richard Dingwall called Law of Demeter is easy to spot when you need extra mock. He shows how you can spot violations of the Law of Demeter when you have to create extra mocks in order to stub a single method. While I totally agree with his [...]]]></description>
			<content:encoded><![CDATA[<p>I have just read a good post by Richard Dingwall called <a href="http://richarddingwall.name/2009/08/26/law-of-demeter-is-easy-to-spot-when-you-need-extra-mocks/" target="_blank">Law of Demeter is easy to spot when you need extra mock</a>. He shows how you can spot violations of the <strong>Law of Demeter</strong> when you have to create extra mocks in order to stub a single method.</p>
<p>While I totally agree with his points about the Law of Demeter, it might not be so easy to spot violations thanks to a feature of Moq called auto-mocking hierarchies (a.k.a. recursive mocks). In this post I will show how this cool feature can simplify your tests.</p>
<h3>System under test</h3>
<p>Below is the code from Richard&#8217;s post that are under test:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">ClassUnderTest</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> DoSomething(<span style="color: #2b91af;">IFoo</span> foo)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> foo.Profile.GetStatus();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
<p style="margin: 0px;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">interface</span> <span style="color: #2b91af;">IFoo</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #2b91af;">IProfile</span> Profile { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">}</p>
<p style="margin: 0px;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">interface</span> <span style="color: #2b91af;">IProfile</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">string</span> GetStatus();</p>
<p style="margin: 0px;">}</p>
</div>
<p>The <span style="text-decoration: underline;">DoSomething</span> method calls into the privates of <span style="text-decoration: underline;">IProfile</span> (this is the violations of the law).</p>
<h3>Test without recursive mocks</h3>
<p>Below is the test without recursive mocks:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;">[<span style="color: yellow;">Test</span>]</p>
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> Test_Without_Recursive_Mocks()</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">const</span> <span style="color: #ff8000;">string</span> SOME_RETURN_VALUE = <span style="color: lime;">&#8220;SomeReturnValue&#8221;</span>;</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> foo = <span style="color: #ff8000;">new</span> <span style="color: yellow;">Mock</span>&lt;<span style="color: #2b91af;">IFoo</span>&gt;();</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> profile = <span style="color: #ff8000;">new</span> <span style="color: yellow;">Mock</span>&lt;<span style="color: #2b91af;">IProfile</span>&gt;();</p>
<p style="margin: 0px;">    profile.Setup(p =&gt; p.GetStatus()).Returns(SOME_RETURN_VALUE);</p>
<p style="margin: 0px;">    foo.SetupGet(f =&gt; f.Profile).Returns(profile.Object);</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> sut = <span style="color: #ff8000;">new</span> <span style="color: yellow;">ClassUnderTest</span>();</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">string</span> returnValue = sut.DoSomething(foo.Object);</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: yellow;">Assert</span>.AreEqual(SOME_RETURN_VALUE, returnValue);</p>
<p style="margin: 0px;">}</p>
</div>
<p>In this test we need to create an extra mock of the type <span style="text-decoration: underline;">IProfile</span> to be able to mock <span style="text-decoration: underline;">IFoo</span>. This makes the test much harder to read. Imagine the horror if another class was also part of the call chain.</p>
<h3>Test with recursive mocks</h3>
<p>Below is a simplified test that uses the recursive mocks feature of Moq:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;">[<span style="color: yellow;">Test</span>]</p>
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> Test_With_Recursive_Mocks()</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">const</span> <span style="color: #ff8000;">string</span> SOME_RETURN_VALUE = <span style="color: lime;">&#8220;SomeReturnValue&#8221;</span>;</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> foo = <span style="color: #ff8000;">new</span> <span style="color: yellow;">Mock</span>&lt;<span style="color: #2b91af;">IFoo</span>&gt;();</p>
<p style="margin: 0px;">    foo.Setup(f =&gt; f.Profile.GetStatus()).Returns(SOME_RETURN_VALUE);</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> sut = <span style="color: #ff8000;">new</span> <span style="color: yellow;">ClassUnderTest</span>();</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">string</span> returnValue = sut.DoSomething(foo.Object);</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: yellow;">Assert</span>.AreEqual(SOME_RETURN_VALUE, returnValue);</p>
<p style="margin: 0px;">}</p>
</div>
<p>As you can see, we have eliminated the need for the <span style="text-decoration: underline;">IProfile</span> mock. This results in a much cleaner test.</p>
<h3>finally{}</h3>
<p>In this post I have shown you a cool feature of Moq that can greatly simplify your mocking code. Of course you should still try to spot violations of the Law of Demeter, even though the extra mocks will no longer help you with this. Just remember that the law is really more of a guideline, but I guess <strong>Rule of thumb of Demeter</strong> doesn&#8217;t sound as catchy <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>If you want to read a great post (and discussion) about this law (eh guideline) check out <a href="http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx" target="_blank">The Law of Demeter Is Not A Dot Counting Exercise</a> by Phil Haacked.</p>
<p>If you liked this post then please shout and kick me <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/08/27/Auto-mocking-hierarchies-%28aka-recursive-mocks%29-with-Moq.aspx&amp;title=Auto-mocking%20hierarchies%20%28a.k.a.%20recursive%20mocks%29%20with%20Moq" target="_blank"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/08/27/Auto-mocking-hierarchies-(aka-recursive-mocks)-with-Moq.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Submit?url=http://www.bengtbe.com/blog/post/2009/08/27/Auto-mocking-hierarchies-%28aka-recursive-mocks%29-with-Moq.aspx&amp;title=Auto-mocking%20hierarchies%20%28a.k.a.%20recursive%20mocks%29%20with%20Moq" rev="vote-for" target="_blank"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http://www.bengtbe.com/blog/post/2009/08/27/Auto-mocking-hierarchies-%28aka-recursive-mocks%29-with-Moq.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/08/27/auto-mocking-hierarchies-a-k-a-recursive-mocks-with-moq/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NerdDinner with Fluent NHibernate Part 2 &#8211; The mapping</title>
		<link>http://bengtbe.com/blog/2009/08/25/nerddinner-with-fluent-nhibernate-part-2-the-mapping/</link>
		<comments>http://bengtbe.com/blog/2009/08/25/nerddinner-with-fluent-nhibernate-part-2-the-mapping/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 04:00:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[NerdDinner]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">/blog/post/2009/08/25/NerdDinner-with-Fluent-NHibernate-Part-2-The-mapping.aspx</guid>
		<description><![CDATA[This is the second post in a series of three where I&#8217;m going to see how we can change the NerdDinner project to use Fluent NHibernate instead of LINQ to SQL: Part 1 &#8211; The domain model Part 2 &#8211; The mapping Part 3 &#8211; The infrastructure Introduction In the first post we took a look at [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second post in a series of three where I&#8217;m going to see how we can change the NerdDinner project to use Fluent NHibernate instead of LINQ to SQL:</p>
<ul>
<li>
<a href="/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx">Part 1 &#8211; The domain model</a></li>
<li>
<a href="/blog/post/2009/08/25/NerdDinner-with-Fluent-NHibernate-Part-2-The-mapping.aspx">Part 2 &#8211; The mapping</a></li>
<li>
<a href="/blog/post/2009/10/08/NerdDinner-with-Fluent-NHibernate-Part-3-The-infrastructure.aspx">Part 3 &#8211; The infrastructure</a></li>
</ul>
<h3>Introduction</h3>
<p>In the first post we took a look at the domain model of <a href="http://www.nerddinner.com" target="_blank">NerdDinner.com</a>, and recreated and improved the code that was auto generated by the LINQ to SQL designer. In this post we are going to look at how to map this domain model to the database using <a href="http://fluentnhibernate.org/" target="_blank">Fluent NHibernate</a>.</p>
<h3>Fluent NHibernate</h3>
<p>Fluent NHibernate gives you an alternative to NHibernate&#8217;s XML mapping files. It lets you write mapping in strongly typed (and ReSharper friendly) C# code. In order to map an entity, you create a mapping class that derives from <span style="text-decoration: underline;">ClassMap&lt;T&gt;</span>. All the mapping code is done inside the constructor by calling methods from the base class.</p>
<p>Last week the Release Candidate for Fluent NHibernate 1.0 was <a href="http://www.lostechies.com/blogs/jagregory/archive/2009/08/16/fluent-nhibernate-1-0rc.aspx" target="_blank">released</a>. The code in this post has been updated with the changes in this release.</p>
<h3>The mapping for the Dinner entity</h3>
<p>The code for <span style="text-decoration: underline;">DinnerClassMap</span> is shown below:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">DinnerClassMap</span> : <span style="color: yellow;">ClassMap</span>&lt;<span style="color: yellow;">Dinner</span>&gt;</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> DinnerClassMap()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        Table(<span style="color: lime;">&#8220;Dinners&#8221;</span>);</p>
<p style="margin: 0px;">        Id(d =&gt; d.DinnerID).GeneratedBy.Identity();</p>
<p style="margin: 0px;">        Map(d =&gt; d.Title).Not.Nullable().Length(50);</p>
<p style="margin: 0px;">        Map(d =&gt; d.EventDate).Not.Nullable();</p>
<p style="margin: 0px;">        Map(d =&gt; d.Description).Not.Nullable().Length(256);</p>
<p style="margin: 0px;">        Map(d =&gt; d.HostedBy).Not.Nullable().Length(20);</p>
<p style="margin: 0px;">        Map(d =&gt; d.ContactPhone).Not.Nullable().Length(20);</p>
<p style="margin: 0px;">        Map(d =&gt; d.Address).Not.Nullable().Length(50);</p>
<p style="margin: 0px;">        Map(d =&gt; d.Country).Not.Nullable().Length(30);</p>
<p style="margin: 0px;">        Map(d =&gt; d.Latitude).Not.Nullable();</p>
<p style="margin: 0px;">        Map(d =&gt; d.Longitude).Not.Nullable();</p>
<p style="margin: 0px;">        HasMany(d =&gt; d.RSVPs).KeyColumn(<span style="color: lime;">&#8220;DinnerId&#8221;</span>).Cascade.All();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p>Explaination of code:</p>
<ul>
<li>The <span style="text-decoration: underline;">Table</span> method maps &#8220;Dinners&#8221; as the name of the table. By default Fluent NHibernate assumes it to be &#8220;Dinner&#8221;.</li>
<li>The <span style="text-decoration: underline;">Id</span> method maps <span style="text-decoration: underline;">DinnerId</span> as the primary key, and specifies that an identity column in SQL Server is used to generate ids.</li>
<li>The <span style="text-decoration: underline;">Map</span> method is used to map simple properties to columns.</li>
<li>The <span style="text-decoration: underline;">HasMany</span> method maps the one-to-many relationship to the RSVP table. <span style="text-decoration: underline;">Cascade.All()</span> is used to make sure that RSVPs are saved/updated/deleded when the dinner is saved/updated/deleded.</li>
</ul>
<h3>The RSVP mapping</h3>
<p>The code for the <span style="text-decoration: underline;">RSVPClassMap</span> is shown below:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">RSVPClassMap</span> : <span style="color: yellow;">ClassMap</span>&lt;<span style="color: yellow;">RSVP</span>&gt;</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> RSVPClassMap()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        Id(r =&gt; r.RsvpID).GeneratedBy.Identity(); ;</p>
<p style="margin: 0px;">        Map(r =&gt; r.AttendeeName).Not.Nullable().Length(30);</p>
<p style="margin: 0px;">        References(r =&gt; r.Dinner, <span style="color: lime;">&#8220;DinnerId&#8221;</span>).Not.Nullable();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p>Explaination of code:</p>
<ul>
<li>No need to call the <span style="text-decoration: underline;">Table</span> method, since Fluent NHibernate correctly assumes that the table name is &#8220;RSVP&#8221;.</li>
<li>The <span style="text-decoration: underline;">References</span> method maps the &#8220;other side&#8221; of the <span style="text-decoration: underline;">HasMany</span> relationship in the <span style="text-decoration: underline;">DinnerClassMap</span>.</li>
</ul>
<h3>Is all this mapping code needed?</h3>
<p>The mapping code shown above contains a lot of information about the database schema. In this case, where we just wanted to map the domain to an existing database we could remove the following:</p>
<ul>
<li>Not.Nullable()</li>
<li>Length(int length)</li>
</ul>
<p>In Greenfield projects I prefer to start with the domain, and then write the mapping, and finally automatically generate the database schema. You then need to include this information in the mappings. In the post <a href="/blog/post/2009/05/24/Mapping-a-Twitter-like-domain-with-Fluent-NHibernate.aspx">Mapping a Twitter like domain with Fluent NHibernate</a> I showed how you generate the database from the mapping.</p>
<p>If you have an existing database you can also use this to troubleshoot your mapping code. Generate a new database from your schema and check it against the existing database.</p>
<h3>Give me a new identity!</h3>
<p>NerdDinner uses the identity column of SQL Server as primary key. In most cases this works just fine, however it can cause problems with the <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html" target="_blank">Unit of Work</a> functionality of NHibernate. If I designed this application from scratch I would rather choose the <strong>Guid.Comb</strong> or <strong>HiLo</strong> algorithm to generate primary keys.</p>
<p>If you want to read more about this, check out the post <a href="http://nhforge.org/blogs/nhibernate/archive/2009/03/20/nhibernate-poid-generators-revealed.aspx" target="_blank">NHibernate POID Generators revealed</a>.</p>
<h3>Do you prefer to live in XML hell?</h3>
<p>If you miss the good old days of XML (???), then Fluent NHibernate can help you with this. The code below shows how to export your Fluent Mappings to XML-files:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;">[<span style="color: yellow;">TestMethod</span>]</p>
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> ExportMappings()</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: yellow;">FluentConfiguration</span> conf =</p>
<p style="margin: 0px;"><span style="color: yellow;">       NHibernateConfiguration</span>.CreateConfiguration(<span style="color: #ff8000;">false</span>);</p>
<p style="margin: 0px;">    conf.Mappings(m =&gt;</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        m.FluentMappings.ExportTo(<span style="color: #a31515;">@&#8221;PATH_TO_EXPORT_FOLDER&#8221;</span>);</p>
<p style="margin: 0px;">    });</p>
<p style="margin: 0px;">    conf.BuildSessionFactory();</p>
<p style="margin: 0px;">}</p>
</div>
<p>This technique is actually quite useful for several reasons:</p>
<ul>
<li>First, if you are skeptical about using Fluent NHibernate because it has not reached 1.0, or because it might not support all mapping options, you can easily switch back to XML-files later.</li>
<li>Secondly, it can also be useful to troubleshoot mapping problems, because there is currently more information on the web regarding XML-mapping.</li>
</ul>
<h3>finally{}</h3>
<p>In this post we have taken a look at how to use Fluent NHibernate to specify the mapping between the domain model and the database. In the next post we will take a look at the rest of the changes that was necessary in order to use the new domain and Fluent NHibernate.</p>
<p>If you liked this post then please shout and kick me <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/08/25/NerdDinner-with-Fluent-NHibernate-Part-2-The-mapping.aspx&amp;title=NerdDinner%20with%20Fluent%20NHibernate%20Part%202%20-%20The%20mapping" target="_blank"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/08/25/NerdDinner-with-Fluent-NHibernate-Part-2-The-mapping.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Submit?url=http://www.bengtbe.com/blog/post/2009/08/25/NerdDinner-with-Fluent-NHibernate-Part-2-The-mapping.aspx&amp;title=NerdDinner%20with%20Fluent%20NHibernate%20Part%202%20-%20The%20mapping" rev="vote-for" target="_blank"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http://www.bengtbe.com/blog/post/2009/08/25/NerdDinner-with-Fluent-NHibernate-Part-2-The-mapping.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/08/25/nerddinner-with-fluent-nhibernate-part-2-the-mapping/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>NerdDinner with Fluent NHibernate Part 1 &#8211; The domain model</title>
		<link>http://bengtbe.com/blog/2009/08/10/nerddinner-with-fluent-nhibernate-part-1-the-domain-model/</link>
		<comments>http://bengtbe.com/blog/2009/08/10/nerddinner-with-fluent-nhibernate-part-1-the-domain-model/#comments</comments>
		<pubDate>Mon, 10 Aug 2009 04:00:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[NerdDinner]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx</guid>
		<description><![CDATA[This is the first post in a series of three where I&#8217;m going to see how we can change the NerdDinner project to use Fluent NHibernate instead of LINQ to SQL: Part 1 &#8211; The domain model Part 2 &#8211; The mapping Part 3 &#8211; The infrastructure Introduction NerdDinner.com is a site where you can [...]]]></description>
			<content:encoded><![CDATA[<p>This is the first post in a series of three where I&#8217;m going to see how we can change the NerdDinner project to use Fluent NHibernate instead of LINQ to SQL:</p>
<ul>
<li>
<div><a href="/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx">Part 1 &#8211; The domain model</a></div>
</li>
<li>
<div><a href="/blog/post/2009/08/25/NerdDinner-with-Fluent-NHibernate-Part-2-The-mapping.aspx">Part 2 &#8211; The mapping</a></div>
</li>
<li>
<div><a href="/blog/post/2009/10/08/NerdDinner-with-Fluent-NHibernate-Part-3-The-infrastructure.aspx">Part 3 &#8211; The infrastructure</a></div>
</li>
</ul>
<h3>Introduction</h3>
<p><a href="http://www.nerddinner.com/" target="_blank">NerdDinner.com</a> is a site where you can organize dinner meetings for nerds, but even more, it is a great tutorial to the ASP.NET MVC framework. If you want to learn this framework (you should!) download the free tutorial (186 pages) from the site and get going!</p>
<p>NerdDinner uses LINQ to SQL as a data access layer generator. LINQ to SQL is perfectly suitable for this project, since the domain is small, and not very complex. However in these posts I would like to explore how the project would look using a real Object/Relational Mapper (O/RM). More specifically, I&#8217;m going to use Fluent NHibernate.</p>
<h3>Preperations</h3>
<p>First I downloaded the latest source code from <a href="http://nerddinner.codeplex.com" target="_blank">CodePlex</a> using the Subversion client <a href="http://tortoisesvn.tigris.org/" target="_blank">TortoiseSVN</a>. Then I added references to the <a href="https://www.hibernate.org/343.html" target="_blank">NHibernate</a>, <a href="http://fluentnhibernate.org/" target="_blank">Fluent NHibernate</a>, and <a href="http://nhforge.org" target="_blank">LINQ to NHibernate</a> assemblies.</p>
<h3>The existing domain model</h3>
<p>Most of the domain model in NerdDinner is auto generated from the database as partial classes by the LINQ to SQL designer. You can find the <span style="text-decoration: underline;">Dinner</span> and <span style="text-decoration: underline;">RSVP</span> class in the <a href="http://nerddinner.codeplex.com/SourceControl/changeset/view/23425#440022" target="_blank">NerdDinner.Designer.cs</a> file; however since they are auto generated they are not very readable.</p>
<p>The <span style="text-decoration: underline;">Dinner</span> class is also extended (using partial classes) with additional methods in the <a href="http://nerddinner.codeplex.com/SourceControl/changeset/view/23425#439965" target="_blank">Dinner.cs</a> file.</p>
<h3>The new domain model</h3>
<p>Since most of the existing domain model is auto generated we need to write a new domain model. The new <span style="text-decoration: underline;">Dinner</span> class looks as follows:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">Dinner</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> Dinner()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        RSVPs = <span style="color: #ff8000;">new</span> <span style="color: yellow;">List</span>&lt;<span style="color: yellow;">RSVP</span>&gt;();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">int</span> DinnerID { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">private set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Title { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Description { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #2b91af;">DateTime</span> EventDate { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">double</span> Latitude { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">double</span> Longitude { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Country { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Address { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> HostedBy { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> ContactPhone { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">RSVP</span>&gt; RSVPs { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">private set</span>;}</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">void</span> AddRSVP(<span style="color: #ff8000;">string</span> attendeeName)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;"><span style="color: #ff8000;">        if</span> (dinner.IsUserRegistered(User.Identity.Name)) <span style="color: #ff8000;">return</span>;</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        RSVPs.Add(<span style="color: #ff8000;">new</span> <span style="color: yellow;">RSVP</span></p>
<p style="margin: 0px;">                      {</p>
<p style="margin: 0px;">                          AttendeeName = attendeeName,</p>
<p style="margin: 0px;">                          Dinner = <span style="color: #ff8000;">this</span></p>
<p style="margin: 0px;">                      });</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">bool</span> IsHostedBy(<span style="color: #ff8000;">string</span> userName) { &#8230; }</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">bool</span> IsUserRegistered(<span style="color: #ff8000;">string</span> userName) { &#8230; }</div>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">bool</span> IsValid { &#8230; }</div>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: yellow;">RuleViolation</span>&gt; GetRuleViolations() { &#8230; }</p>
<p style="margin: 0px;">}</p>
</div>
<p>The new <span style="text-decoration: underline;">RSVP</span> class looks as follows:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">RSVP</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">int</span> RsvpID { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">private set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: yellow;">Dinner</span> Dinner { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> AttendeeName { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">}</p>
</div>
<p>If you wonder why every method is marked by virtual, this is a requirement of NHibernate in order to support Lazy-Loading. I explained this in more detail in the post <a href="/blog/post/2009/05/24/Mapping-a-Twitter-like-domain-with-Fluent-NHibernate.aspx" target="_blank">Mapping a Twitter like domain with Fluent NHibernate</a>.</p>
<p>The public interface of the domain model is more or less identical to the existing domain model. However I did make some changes.</p>
<h3>Protect thy privates!</h3>
<p>One of the changes I made was to make some of the property setters private; <span style="text-decoration: underline;">DinnerID</span>, <span style="text-decoration: underline;">RSVPs</span>, and <span style="text-decoration: underline;">RsvpID</span>. Since the consumer code (the controllers) is not supposed to change to these properties we want to communicate this to our fellow programmers. The next change is also about protecting privates.</p>
<h3>New method to add a RSVP to a dinner</h3>
<p>To the <span style="text-decoration: underline;">Dinner</span> class I added a new method called <span style="text-decoration: underline;">AddRSVP</span>. By using terms from Domain Driven Design, the <span style="text-decoration: underline;">Dinner</span> entity is the aggregate root of the <span style="text-decoration: underline;">RSVP</span> entity. This basically means that a RSVP must belong to a Dinner; hence I want the <span style="text-decoration: underline;">Dinner</span> class to control the list of RSVPs.</p>
<p>This change will help reduce code in the controllers and remove duplication. Previously the creating and adding of RSVPs was done both in the <span style="text-decoration: underline;">RSVPController.Register</span> and the <span style="text-decoration: underline;">DinnerController.Create</span> action methods. The <span style="text-decoration: underline;">Register</span> method is shown below:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;">[<span style="color: yellow;">Authorize</span>, <span style="color: yellow;">AcceptVerbs</span>(<span style="color: #2b91af;">HttpVerbs</span>.Post)]</p>
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: yellow;">ActionResult</span> Register(<span style="color: #ff8000;">int</span> id) {</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: yellow;">Dinner</span> dinner = dinnerRepository.GetDinner(id);</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">if</span> (!dinner.IsUserRegistered(User.Identity.Name)) {</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        <span style="color: yellow;">RSVP</span> rsvp = <span style="color: #ff8000;">new</span> <span style="color: yellow;">RSVP</span>();</p>
<p style="margin: 0px;">        rsvp.AttendeeName = User.Identity.Name;</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        dinner.RSVPs.Add(rsvp);</p>
<p style="margin: 0px;">        dinnerRepository.Save();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">return</span> Content(<span style="color: lime;">&#8220;Thanks &#8211; we&#8217;ll see you there!&#8221;</span>);</p>
<p style="margin: 0px;">}</p>
</div>
<p>Thanks to our new method, this can now be reduced to:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;">[<span style="color: yellow;">Authorize</span>, <span style="color: yellow;">AcceptVerbs</span>(<span style="color: #2b91af;">HttpVerbs</span>.Post)]</p>
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: yellow;">ActionResult</span> Register(<span style="color: #ff8000;">int</span> id) {</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: yellow;">Dinner</span> dinner = dinnerRepository.GetDinner(id);</p>
<p>    dinner.AddRSVP(User.Identity.Name);</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">return</span> Content(<span style="color: lime;">&#8220;Thanks &#8211; we&#8217;ll see you there!&#8221;</span>);</p>
<p style="margin: 0px;">}</p>
</div>
<p>Similar reduction can be done to the <span style="text-decoration: underline;">Create</span> method. BTW if you wonder what happened to the call to the <span style="text-decoration: underline;">Save</span> method then we will come back to this in part 3 (teaser!).</p>
<p>As a rule of thumb always try to keep your action methods as simple as possible!</p>
<h3>More object-oriented</h3>
<p>The last change is the removal of the <span style="text-decoration: underline;">DinnerId</span> property from the <span style="text-decoration: underline;">RSVP</span> class. This property is purly database related, and does not belong in an object-oriented domain model. You can use the <span style="text-decoration: underline;">Dinner</span> propety to get the <span style="text-decoration: underline;">DinnerId</span>.</p>
<h3>finally{}</h3>
<p>In my opinion one of the benefits of using an OR/M like NHibernate as supposed to LINQ to SQL is that the domain model is much clearer. When trying to understand a new project one of the best places to start is by looking at the domain. I also did some changes (improvements?) to the domain model to better communicate intent, and to reduce code duplication.</p>
<p>The next step is to tell NHibernate how to map this domain model to the database. This will be explained in the next post where we look at the mapping.</p>
<p>If you liked this post then please shout and kick me <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx&amp;title=NerdDinner%20with%20Fluent%20NHibernate%20Part%201%20-%20The%20domain%20model" target="_blank"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Submit?url=http://www.bengtbe.com/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx&amp;title=NerdDinner%20with%20Fluent%20NHibernate%20Part%201%20-%20The%20domain%20model" rev="vote-for" target="_blank"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http://www.bengtbe.com/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/08/10/nerddinner-with-fluent-nhibernate-part-1-the-domain-model/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>DotNetShoutout and DotNetKicks extensions for BlogEngine.NET</title>
		<link>http://bengtbe.com/blog/2009/07/28/dotnetshoutout-and-dotnetkicks-extensions-for-blogengine-net/</link>
		<comments>http://bengtbe.com/blog/2009/07/28/dotnetshoutout-and-dotnetkicks-extensions-for-blogengine-net/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 22:50:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BlogEngine.NET]]></category>

		<guid isPermaLink="false">/blog/post/2009/07/28/DotNetShoutout-and-DotNetKicks-extensions-for-BlogEngineNET.aspx</guid>
		<description><![CDATA[At the end of every .NET post I include counter buttons to DotNetKicks.com and DotNetShoutout.com. At first I manually created these buttons by copying some code from these sites after the post was submitted to them, however this quickly became tiresome. Now I just write [ kickit ] and [ shout ] (without the spaces!) [...]]]></description>
			<content:encoded><![CDATA[<p>At the end of every .NET post I include counter buttons to <a href="http://dotnetkicks.com/" target="_blank">DotNetKicks.com</a> and <a href="http://dotnetshoutout.com/" target="_blank">DotNetShoutout.com</a>. At first I manually created these buttons by copying some code from these sites after the post was submitted to them, however this quickly became tiresome. Now I just write <em>[ kickit ]</em> and <em>[ shout ]</em> (without the spaces!) at the end of the post to get these buttons.</p>
<h3>DotNetKicks.com</h3>
<p>In order to generate the DotNetKicks button I found an extension created by <strong>Sean Blakemore</strong>, described in this blog <a href="http://www.flawlesscode.com/post/2007/12/DotNetKicks-button-extension-for-BlogengineNET.aspx" target="_blank">post</a>. This extension was both simple and worked great!</p>
<h3>DotNetShoutout.com</h3>
<p>Inspired by the work of Sean, I created a similar extension for DotNetShoutout. If you want this functionality on your own blog then download the zip-file at the end of this post, unzip it, and finally upload the cs-file to the <strong>App_Code/Extensions</strong> catalog of your BlogEngine.NET installation.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/07/28/DotNetShoutout-and-DotNetKicks-extensions-for-BlogEngineNET.aspx&amp;title=DotNetShoutout%20and%20DotNetKicks%20extensions%20for%20BlogEngine.NET" target="_blank"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/07/28/DotNetShoutout-and-DotNetKicks-extensions-for-BlogEngineNET.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Submit?url=http://www.bengtbe.com/blog/post/2009/07/28/DotNetShoutout-and-DotNetKicks-extensions-for-BlogEngineNET.aspx&amp;title=DotNetShoutout%20and%20DotNetKicks%20extensions%20for%20BlogEngine.NET" rev="vote-for" target="_blank"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http://www.bengtbe.com/blog/post/2009/07/28/DotNetShoutout-and-DotNetKicks-extensions-for-BlogEngineNET.aspx" alt="Shout it" /></a></p>
<p>As you can see above they both work <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://bengtbe.com/blog/wp-content/uploads/2009/07/DotNetShoutout.zip">DotNetShoutout.zip (751.00 bytes)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/07/28/dotnetshoutout-and-dotnetkicks-extensions-for-blogengine-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Use specific return types in your ASP.NET MVC action methods</title>
		<link>http://bengtbe.com/blog/2009/07/01/use-specific-return-types-in-your-asp-net-mvc-action-methods/</link>
		<comments>http://bengtbe.com/blog/2009/07/01/use-specific-return-types-in-your-asp-net-mvc-action-methods/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 17:00:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">/blog/post/2009/07/01/Use-specific-return-types-in-your-ASPNET-MVC-action-methods.aspx</guid>
		<description><![CDATA[When looking at ASP.NET MVC examples on the web almost all action methods return ActionResult, even methods that could return a specific subclass. Here is an example from the NerdDinner source code: public ActionResult Index(int? page) {     const int pageSize = 25;     var upcoming = dinnerRepository.FindUpcomingDinners();     var paginated = new PaginatedList&#60;Dinner&#62;(upcoming, page [...]]]></description>
			<content:encoded><![CDATA[<p>When looking at ASP.NET MVC examples on the web almost all action methods return <span style="text-decoration: underline;">ActionResult</span>, even methods that could return a specific subclass. Here is an example from the <a href="http://nerddinner.com/" target="_blank">NerdDinner</a> source code:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: yellow;">ActionResult</span> Index(<span style="color: #ff8000;">int</span>? page)</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">const</span> <span style="color: #ff8000;">int</span> pageSize = 25;</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> upcoming = dinnerRepository.FindUpcomingDinners();</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> paginated = <span style="color: #ff8000;">new</span> <span style="color: yellow;">PaginatedList</span>&lt;<span style="color: yellow;">Dinner</span>&gt;(upcoming, page ?? 0, pageSize);</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">return</span> View(paginated);</p>
<p style="margin: 0px;">}</p>
</div>
<p>This method always returns a <span style="text-decoration: underline;">ViewResult</span>, still they declare the return type as the <span style="text-decoration: underline;">ActionResult</span> base class. This practice often leads to test code like the following:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: yellow;">ViewResult</span> result = controller.Index(0) <span style="color: #ff8000;">as</span> <span style="color: yellow;">ViewResult</span>;</p>
<p style="margin: 0px;"><span style="color: yellow;">Assert</span>.IsNotNull(result, <span style="color: lime;">&#8220;Controller should return a ViewResult&#8221;</span>);</p>
</div>
<div class="post-text">In NerdDinner they even have a whole test just to make sure that the result is a <span style="text-decoration: underline;">ViewResult</span>:</div>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;">[<span style="color: yellow;">TestMethod</span>]</p>
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> IndexAction_Should_Return_View()</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: lime;">// Arrange</span></p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> controller = CreateDinnersControllerAs(<span style="color: lime;">&#8220;robcon&#8221;</span>);</p>
<p style="margin: 0px;">    <span style="color: lime;">// Act</span></p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> result = controller.Index(0);</p>
<p style="margin: 0px;">    <span style="color: lime;">// Assert</span></p>
<p style="margin: 0px;">    <span style="color: yellow;">Assert</span>.IsInstanceOfType(result, <span style="color: #ff8000;">typeof</span>(<span style="color: yellow;">ViewResult</span>));</p>
<p style="margin: 0px;">}</p>
</div>
<div class="post-text">All this testing code are unnecessary, if you just let your action methods use specific return types, like shown below:</div>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: yellow;">ViewResult</span> Index(<span style="color: #ff8000;">int</span>? page)</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">const</span> <span style="color: #ff8000;">int</span> pageSize = 25;</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> upcoming = dinnerRepository.FindUpcomingDinners();</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">var</span> paginated = <span style="color: #ff8000;">new</span> <span style="color: yellow;">PaginatedList</span>&lt;<span style="color: yellow;">Dinner</span>&gt;(upcoming, page ?? 0, pageSize);</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">return</span> View(paginated);</p>
<p style="margin: 0px;">}</p>
</div>
<p>This also makes it immediately clear for people reading the code, what this action method returns.</p>
<p>The only time I would return <span style="text-decoration: underline;">ActionResult</span> is when different paths of the action method returns different subclasses. In these cases, you should of course write tests that verify the return types of the different paths.</p>
<p>In the book <a href="http://www.amazon.com/Pro-ASP-NET-Framework-Steven-Sanderson/dp/1430210079" rel="nofollow" target="_blank">Pro ASP.NET MVC Framework</a> Steven Sanderson also recommends returning specific types. Take a look at the quote below:</p>
<p><em>&#8220;This action method specifically declares that it returns an<br />
instance of ViewResult. It would work just the same if instead the<br />
method return type was ActionResult (the base class for all action<br />
results). In fact, some ASP.NET MVC programmers declare all their<br />
action methods as returning a nonspecific ActionResult, even if they<br />
know for sure that it will always return one particular subclass.<br />
However, it&#8217;s a well-established principle in object-oriented<br />
programming that methods should return the most specific type they can<br />
(as well as accepting the most general parameter types they can).<br />
Following this principle maximizes convenience and flexibility for code<br />
that calls your method, such as your unit tests.&#8221;</em></p>
<p>BTW: This blog post is not meant to criticize the NerdDinner tutorial. It is a great free tutorial, and is probably one of the best ways to get introduced to the ASP.NET MVC framework <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/07/01/Use-specific-return-types-in-your-ASPNET-MVC-action-methods.aspx&amp;title=Use%20specific%20return%20types%20in%20your%20ASP.NET%20MVC%20action%20methods" target="_blank"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/07/01/Use-specific-return-types-in-your-ASPNET-MVC-action-methods.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Submit?url=http://www.bengtbe.com/blog/post/2009/07/01/Use-specific-return-types-in-your-ASPNET-MVC-action-methods.aspx&amp;title=Use%20specific%20return%20types%20in%20your%20ASP.NET%20MVC%20action%20methods" rev="vote-for" target="_blank"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http://www.bengtbe.com/blog/post/2009/07/01/Use-specific-return-types-in-your-ASPNET-MVC-action-methods.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/07/01/use-specific-return-types-in-your-asp-net-mvc-action-methods/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Book review: NHibernate in Action</title>
		<link>http://bengtbe.com/blog/2009/06/04/book-review-nhibernate-in-action/</link>
		<comments>http://bengtbe.com/blog/2009/06/04/book-review-nhibernate-in-action/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 17:39:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Book]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">/blog/post/2009/06/04/Book-review-NHibernate-in-Action.aspx</guid>
		<description><![CDATA[Authors: Pierre Henri Kuaté, Tobin Harris, Christian Bauer, and Gavin King Publisher: Manning Publications Co. Purchase: Manning, Amazon.com, Amazon.co.uk Introduction As part of my goal to learn ORM and NHibernate I purchased the NHibernate in Action book from Manning Publications. Before I give my conclusion, let&#8217;s start with a summary of the different chapters in [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://bengtbe.com/blog/wp-content/uploads/2009/06/NHibernate_In_Action.jpg"><img class="alignright size-full wp-image-24" title="NHibernate In Action" src="http://bengtbe.com/blog/wp-content/uploads/2009/06/NHibernate_In_Action.jpg" alt="NHibernate In Action" width="191" height="239" /></a></p>
<p><strong>Authors:</strong> Pierre Henri Kuaté, Tobin Harris, Christian Bauer, and Gavin King<br />
<strong>Publisher:</strong> Manning Publications Co.<strong><br />
Purchase:</strong> <a href="http://www.manning.com/kuate/" target="_blank">Manning</a>, <a href="http://www.amazon.com/NHibernate-Action-Pierre-Henri-Kuaté/dp/1932394923" target="_blank">Amazon.com</a>, <a href="http://www.amazon.co.uk/NHibernate-Action-Pierre-Kuate/dp/1932394923">Amazon.co.uk</a></p>
<p><strong>Introduction</strong></p>
<p>As part of my goal to learn ORM and NHibernate I purchased the <em>NHibernate in Action</em> book from Manning Publications.<br />
Before I give my conclusion, let&#8217;s start with a summary of the different chapters in the book.</p>
<p><strong>1. Object/relation persistence in .NET</strong></p>
<p>This chapter starts the first part of the book, called <em>Discovering ORM with NHibernate</em>. Discusses object persistence, and briefly compares different approaches: hand coding, DataSets, LINQ-to-SQL, NHibernate, and ADO.NET Entity Framework. Describes Object/Relational mapping (ORM), and how it is used to solve the Object/Relational mismatch.</p>
<p><strong>2. Hello NHibernate</strong></p>
<p>Guides you through the process of setting up a project, creating a domain model, setting up the database, creating mapping file, configuring NHibernate, and doing some basic CRUD operations. Takes a high level look at NHibernate, its architecture and how it is configured.</p>
<p><strong>3. Writing and mapping classes </strong></p>
<p>This chapter starts the second part of the book, called <em>NHibernate deep dive</em>. Describes the most common scenarios when mapping a domain model to the database, including important concepts, such as object identity, inheritance, associations, entities vs. value-types, fine-grained object models, and transparent persistence. Finally, it shows three inheritance mapping strategies; table per concrete class, table per class hierarchy, and table per subclass. Covers both XML-mapping and attribute mapping.</p>
<p><strong>4. Working with persistent objects</strong></p>
<p>Describes the three object states (persistent, detached, and transient) that domain models have in a NHibernate application, and how they move from one state to another. It also gives an overview of different ways to get objects out of the database.</p>
<p><strong>5. Transactions, concurrency, and caching</strong></p>
<p>Shows how NHibernate handles transactions, short vs. long conversations, optimistic concurrency control and versioning. Finally it discusses caching and describes the first- and second-level cache that NHibernate provides.</p>
<p><strong>6. Advanced mapping concepts</strong></p>
<p>Goes into detail of more advanced mapping techniques, covering mapping types, custom mapping types, nullable types, enumerated types, collection of value types, mapping of entity associations, and mapping of polymorphic associations.</p>
<p><strong>7. Retrieving objects efficiently</strong></p>
<p>Describes object retrieval with both HQL, Query by Criteria, and native SQL. Topics covered are parameters, comparison operators, logical operators, ordering, joining, report queries, dynamic queries, and query optimization.</p>
<p><strong>8. Developing NHibernate applications</strong></p>
<p>This chapter starts the last part of the book, called <em>NHibernate in the real world</em>. Discusses N-tier development by going through the business, persistence, and presentation layer. Finally it shows how NHibernate can be used to implement audit logging.</p>
<p><strong>9. Writing real-world domain models</strong></p>
<p>Covers domain-model development processes and tools, legacy schema mapping, understanding persistence ignorance, implementing business logic, data binding entities in the GUI, and filling DataSets from entities.</p>
<p><strong>10. Architectural patterns for persistence</strong></p>
<p>Focuses on the design of the persistence layer. Covers designing the persistence layer, implementing reusable Data Access Objects, implementing conversations, and using NHibernate in an Enterprise Services application.</p>
<p><strong>Conclusion</strong></p>
<p>First let&#8217;s start with the things that I like about the book. As far as I know it is the only book published about NHibernate, and great OR/M deserves its own book. The book is well written and structured. It covers many aspects of NHibernate, and gives you enough information to start using NHibernate in your own project. The first part of the book is great for beginners of NHibernate. The second part covers more advanced topics and people with some experience with NHibernate should also find something useful in these chapters.</p>
<p>Unfortunately, there are some things that I don&#8217;t like about the book. It covers NHibernate 1.2, even though 2.0 was released when the book came out. I also think that the last part of the book covers to much basic stuff about Domain Driven Design and N-tier development, instead of focusing on how to utilize NHibernate. Hopefully, the authors will release a second edition that covers version 2+, and also covers more community project, like <a href="/blog/post/2009/05/24/Mapping-a-Twitter-like-domain-with-Fluent-NHibernate.aspx">Fluent NHibernate</a>.</p>
<p>Overall I give this book <strong>3.5 of 5 stars</strong> <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/06/04/Book-review-NHibernate-in-Action.aspx&amp;title=Book%20review:%20NHibernate%20in%20Action" target="_blank"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/06/04/Book-review-NHibernate-in-Action.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Submit?url=http://www.bengtbe.com/blog/post/2009/06/04/Book-review-NHibernate-in-Action.aspx&amp;title=Book%20review:%20NHibernate%20in%20Action" rev="vote-for" target="_blank"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http://www.bengtbe.com/blog/post/2009/06/04/Book-review-NHibernate-in-Action.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/06/04/book-review-nhibernate-in-action/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mapping a Twitter like domain with Fluent NHibernate</title>
		<link>http://bengtbe.com/blog/2009/05/24/mapping-a-twitter-like-domain-with-fluent-nhibernate/</link>
		<comments>http://bengtbe.com/blog/2009/05/24/mapping-a-twitter-like-domain-with-fluent-nhibernate/#comments</comments>
		<pubDate>Sun, 24 May 2009 08:00:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">/blog/post/2009/05/24/Mapping-a-Twitter-like-domain-with-Fluent-NHibernate.aspx</guid>
		<description><![CDATA[I&#8217;m currently learning NHibernate, and one of the best ways to learn is to blog about it Since I&#8217;m not a big fan of XML files, I also wanted to use Fluent NHibernate to do the mapping. As an example I will use a social messaging domain, similar to Twitter. I will also use a Top-down approach, starting with [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently learning NHibernate, and one of the best ways to learn is to blog about it <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Since I&#8217;m not a big fan of XML files, I also wanted to use Fluent NHibernate to do the mapping. As an example I will use a social messaging domain, similar to Twitter. I will also use a <strong>Top-down</strong> approach, starting with the domain model, writing the mapping, and finally creating the database schema using the <span style="text-decoration: underline;">SchemaExport</span> class in NHibernate.</p>
<h3>The domain model</h3>
<p>Let&#8217;s start with a look at the domain model:</p>
<p><a href="http://bengtbe.com/blog/wp-content/uploads/2009/05/Quacker_Domain.jpg"><img class="size-full wp-image-31 alignnone" title="Quacker Domain" src="http://bengtbe.com/blog/wp-content/uploads/2009/05/Quacker_Domain.jpg" alt="Quacker Domain" width="582" height="538" /></a></p>
<p>The domain model mainly consists of the <span style="text-decoration: underline;">User</span> entity and the <span style="text-decoration: underline;">Message</span> entity and their associations:</p>
<ul>
<li>The user has a list of <span style="text-decoration: underline;">Messages</span> that he/she has posted.</li>
<li>The user has a list of other users that are interested in his/hers messages, called <span style="text-decoration: underline;">Followers</span>.</li>
<li>The user has a list of other users whose messages he/she is interested, called <span style="text-decoration: underline;">Following</span>.</li>
<li>The message has a <span style="text-decoration: underline;">PostedBy</span> reference to the user who posted it.</li>
</ul>
<p>Both entities derive from the <span style="text-decoration: underline;">Entity&lt;T&gt;</span> base class that contains the <span style="text-decoration: underline;">Id</span> property and implements <span style="text-decoration: underline;">Equals</span> and <span style="text-decoration: underline;">GetHashCode</span> methods.</p>
<h3>The domain classes</h3>
<p>Let&#8217;s take a close look at the domain classes. Below is the class for the <span style="text-decoration: underline;">Message</span> entity:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">Message</span> : <span style="color: yellow;">Entity</span>&lt;<span style="color: yellow;">Message</span>&gt;</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Text { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: yellow;">User</span> PostedBy { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #2b91af;">DateTime</span> CreatedAt { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">}</p>
</div>
<p>It contains the message text, a reference to the user who posted it, and the time it was created.</p>
<p>Below is the class for the <span style="text-decoration: underline;">User</span> entity:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">User</span> : <span style="color: yellow;">Entity</span>&lt;<span style="color: yellow;">User</span>&gt;</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> User()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        Name = Url = Email = <span style="color: lime;">&#8220;&#8221;</span>;</p>
<p style="margin: 0px;">        Followers = <span style="color: #ff8000;">new</span> <span style="color: yellow;">List</span>&lt;<span style="color: yellow;">User</span>&gt;();</p>
<p style="margin: 0px;">        Following = <span style="color: #ff8000;">new</span> <span style="color: yellow;">List</span>&lt;<span style="color: yellow;">User</span>&gt;();</p>
<p style="margin: 0px;">        Messages = <span style="color: #ff8000;">new</span> <span style="color: yellow;">List</span>&lt;<span style="color: yellow;">Message</span>&gt;();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Name { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Username { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Email { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">string</span> Url { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">User</span>&gt; Followers { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">User</span>&gt; Following { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">Message</span>&gt; Messages { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">void</span> AddFollowing(<span style="color: yellow;">User</span> user)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">if</span> (Following.Contains(user)) <span style="color: #ff8000;">return</span>;</p>
<p style="margin: 0px;">        Following.Add(user);</p>
<p style="margin: 0px;">        user.Followers.Add(<span style="color: #ff8000;">this</span>);</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">virtual</span> <span style="color: #ff8000;">void</span> AddMessage(<span style="color: #ff8000;">string</span> messageText)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">var</span> message = <span style="color: #ff8000;">new</span> <span style="color: yellow;">Message</span></p>
<p style="margin: 0px;">                          {</p>
<p style="margin: 0px;">                              Text = messageText,</p>
<p style="margin: 0px;">                              PostedBy = <span style="color: #ff8000;">this</span>,</p>
<p style="margin: 0px;">                              CreatedAt = <span style="color: #2b91af;">DateTime</span>.Now</p>
<p style="margin: 0px;">                          };</p>
<p style="margin: 0px;">        Messages.Add(message);</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p>&nbsp;</p>
</div>
<p>The <span style="text-decoration: underline;">User</span> class contains some properties about the user, a list of followers, a list of following users, and a list of messages. It also contains two methods:</p>
<ul>
<li><span style="text-decoration: underline;">AddFollowing(User user)</span> - Adds another user to the list of users that the current user is following. Since this is a bidirectional relationship, it also adds the current user to the other user&#8217;s followers.</li>
<li><span style="text-decoration: underline;">AddMessage(string messageText)</span> &#8211; Adds a new message that the user has posted. Sets the <span style="text-decoration: underline;">PostedBy</span> to the current user.</li>
</ul>
<h3>Why is everything virtual?</h3>
<p>When using NHibernate the domain model can be close to <strong>Persistence Ignorant (PI)</strong>, which means that you don&#8217;t have to take any special considerations when designing the domain model, like derive from a specific base class. However to support transparent lazy-loading, NHibernate needs to return a proxy that inherit from your entity and override the properties.</p>
<p>If you dislike marking everything with virtual you can turn of lazy-loading, but I don&#8217;t recommend doing this.</p>
<h3>Mapping with Fluent NHibernate</h3>
<p>As mentioned, Fluent NHibernate lets you write mapping with strongly typed C# code, instead of the traditional NHibernate XML mapping files. This allows you to use tools like ReSharper to alter both the domain and mapping files when refactoring.</p>
<p>The mapping files must derive from <span style="text-decoration: underline;">ClassMap&lt;T&gt;</span> and the mapping code is done inside the constructor using lambda expressions and a fluent syntax.</p>
<p>Let&#8217;s take a look at the mapping file for the <span style="text-decoration: underline;">Message</span> entity:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">MessageClassMap</span> : <span style="color: yellow;">ClassMap</span>&lt;<span style="color: yellow;">Message</span>&gt;</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> MessageClassMap()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        Id(m =&gt; m.Id).GeneratedBy.GuidComb();</p>
<p style="margin: 0px;">        Map(m =&gt; m.Text).Not.Nullable().WithLengthOf(140);</p>
<p style="margin: 0px;">        Map(m =&gt; m.CreatedAt).Not.Nullable();</p>
<p style="margin: 0px;">        References(m =&gt; m.PostedBy, <span style="color: lime;">&#8220;PostedBy&#8221;</span>).Not.Nullable();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p>&nbsp;</p>
</div>
<p>Explanation of the mapping:</p>
<ul>
<li>The <span style="text-decoration: underline;">Id</span> method maps the <span style="text-decoration: underline;">Id</span> property as the identifier of the Message entity. It should be generated using the GuidComb algorithm.</li>
<li>The <span style="text-decoration: underline;">Map</span> method maps the <span style="text-decoration: underline;">Text</span> property. It also specifies that is should not be null, and that the max length is 120.</li>
<li>The <span style="text-decoration: underline;">Map</span> method also maps the <span style="text-decoration: underline;">CreatedAt</span> property.</li>
<li>The <span style="text-decoration: underline;">References</span> method maps the <span style="text-decoration: underline;">PostedBy</span> property as a <em>many-to-one</em> relationship between the message and user. Hence, one message belongs to a single user, but a user can have many messages. It also specifies that the column name in the database should be <strong>PostedBy</strong>.</li>
</ul>
<p>Let&#8217;s take a look at the mapping file for the <span style="text-decoration: underline;">User</span> entity:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">UserClassMap</span> : <span style="color: yellow;">ClassMap</span>&lt;<span style="color: yellow;">User</span>&gt;</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> UserClassMap()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        Id(u =&gt; u.Id);</p>
<p style="margin: 0px;">        Map(u =&gt; u.Name).Not.Nullable().WithLengthOf(50);</p>
<p style="margin: 0px;">        Map(u =&gt; u.Username).Not.Nullable().WithLengthOf(50).Unique();</p>
<p style="margin: 0px;">        Map(u =&gt; u.Email).Not.Nullable().WithLengthOf(100);</p>
<p style="margin: 0px;">        Map(u =&gt; u.Url).Not.Nullable().WithLengthOf(100);</p>
<p style="margin: 0px;">        HasMany(u =&gt; u.Messages).LazyLoad().Cascade.All()</p>
<p style="margin: 0px;">            .KeyColumnNames.Add(<span style="color: lime;">&#8220;PostedBy&#8221;</span>);</p>
<p style="margin: 0px;">        HasManyToMany(u =&gt; u.Following).LazyLoad()</p>
<p style="margin: 0px;">            .WithParentKeyColumn(<span style="color: lime;">&#8220;FollowerId&#8221;</span>)</p>
<p style="margin: 0px;">            .WithChildKeyColumn(<span style="color: lime;">&#8220;FollowingId&#8221;</span>);</p>
<p style="margin: 0px;">        HasManyToMany(u =&gt; u.Followers).LazyLoad()</p>
<p style="margin: 0px;">            .WithParentKeyColumn(<span style="color: lime;">&#8220;FollowingId&#8221;</span>)</p>
<p style="margin: 0px;">            .WithChildKeyColumn(<span style="color: lime;">&#8220;FollowerId&#8221;</span>).Inverse();</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
</div>
<p>&nbsp;</p>
</div>
<p>Explanation of the mapping:</p>
<ul>
<li>The mapping of the <span style="text-decoration: underline;">Id</span>, <span style="text-decoration: underline;">Name</span>, <span style="text-decoration: underline;">Email</span>, <span style="text-decoration: underline;">Url</span> does not contain any new syntax.</li>
<li>The mapping of the <span style="text-decoration: underline;">UserName</span> property uses the <span style="text-decoration: underline;">Unique</span> method to specify uniqueness. This will create a unique constrain in the database schema.</li>
<li>The <span style="text-decoration: underline;">HasMany</span> method maps the <span style="text-decoration: underline;">Messages</span> property as a <em>one-to-many</em> between the user entity and message entity. The <span style="text-decoration: underline;">Cascade.All</span> means the message will become persistent when you add it to a persistent user. The messages will also be deleted when you delete the user. It also specifies that the name of the column should be <strong>PostedBy</strong> in order to make sure that it uses the same column as specified in the message mapping.</li>
<li>The <span style="text-decoration: underline;">HasManyToMany</span> method maps the Following as a <em>many-to-many</em> mapping between users with specified column names.</li>
<li>The <span style="text-decoration: underline;">HasManyToMany</span> method maps the Followers as a <em>many-to-many</em> mapping between users. This is the inverse of the Following association, hence the call to Inverse().</li>
</ul>
<p>We also call <span style="text-decoration: underline;">LazyLoad()</span> to specify that we want support for lazy loading of the lists.</p>
<h3>Is something missing in the mapping?</h3>
<p>You might have noticed that we often don&#8217;t specify the table or column name in the mapping. In these cases the table will get the same name as the class, and the column will get the same name as the property. Below is an example of how to specify table and column names:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<p style="margin: 0px;">WithTable(<span style="color: lime;">&#8220;TBL_MESSAGES&#8221;</span>);</p>
</div>
<p style="margin: 0px;">Map(c =&gt; c.CreatedAt, <span style="color: lime;">&#8220;COL_CREATEDAT&#8221;</span>).Not.Nullable();</p>
</div>
<p>You also don&#8217;t need to specify the type of the properties (e.g. that <span style="text-decoration: underline;">PostedBy</span> is of type <span style="text-decoration: underline;">User</span>). NHibernate uses reflection to determine the type.</p>
<h3>Creating the database</h3>
<p>In a top-down approach you change the database after you make changes to the domain or the mapping. During development you can recreate the database using the <span style="text-decoration: underline;">SchemaExport</span> class in a test or console application. Below is an example using an explicit test in NUnit:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-size: 10pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: white; font-family: Courier New;">
<p style="margin: 0px;">    [<span style="color: yellow;">TestFixture</span>]</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">DatabaseSetup</span></p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        [<span style="color: yellow;">Test</span>, <span style="color: yellow;">Explicit</span>]</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> SetupDatabase()</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            <span style="color: yellow;">FluentConfiguration</span> conf = <span style="color: yellow;">NHConfiguration</span>.CreateConfiguration(<span style="color: #ff8000;">false</span>);</p>
<p style="margin: 0px;">            conf.ExposeConfiguration(BuildSchema)</p>
<p style="margin: 0px;">                .BuildSessionFactory();</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">static</span> <span style="color: #ff8000;">void</span> BuildSchema(<span style="color: yellow;">Configuration</span> conf)</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            <span style="color: #ff8000;">new</span> <span style="color: yellow;">SchemaExport</span>(conf).Drop(<span style="color: #ff8000;">false</span>, <span style="color: #ff8000;">true</span>);</p>
<p style="margin: 0px;">            <span style="color: #ff8000;">new</span> <span style="color: yellow;">SchemaExport</span>(conf).Create(<span style="color: #ff8000;">false</span>, <span style="color: #ff8000;">true</span>);</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p>The test is marked with the <span style="text-decoration: underline;">Explicit</span> attribute because you want to control when this test is run, e.g. you do not want to run it every time you run your tests. The <span style="text-decoration: underline;">SetupDatabase()</span> test receives a <span style="text-decoration: underline;">FluentConfiguration</span> from the NHibernate configuration class in the project. The database is created in the <span style="text-decoration: underline;">BuildSchema</span> method that is passed to the <span style="text-decoration: underline;">ExposeConfiguration</span> method. The call to <span style="text-decoration: underline;">BuildSessionFactory()</span> is needed to trigger the <span style="text-decoration: underline;">FluentConfiguration</span> to actually execute the call to the <span style="text-decoration: underline;">BuildSchema</span> method.</p>
<h3>Finally the database schema</h3>
<p>Below is the database schema that has been created from the domain model and the mappings:</p>
<p><a href="http://bengtbe.com/blog/wp-content/uploads/2009/05/Quacker_DatabaseSchema.jpg"><img class="size-full wp-image-33 alignnone" title="Quacker Database Schema" src="http://bengtbe.com/blog/wp-content/uploads/2009/05/Quacker_DatabaseSchema.jpg" alt="Quacker Database Schema" width="619" height="429" /></a></p>
<p>Some notes about the database schema:</p>
<ul>
<li>The length of the nvarchar fields are according to the <span style="text-decoration: underline;">WithLengthOf</span> call in the mappings.</li>
<li>All fields are not nullable because of the <span style="text-decoration: underline;">Not.Nullable()</span> call in the mappings.</li>
<li>The many-to-many association between users are represented using the <strong>UserToUser</strong> junction table.</li>
<li>The one-to-many association between the message and users are done by the <strong>PostedBy</strong> column in the <strong>Message</strong> table.</li>
<li>It is not shown in the diagram, but <strong>Username</strong> has a unique constrain due to the <span style="text-decoration: underline;">Unique()</span> call in the mappings.</li>
</ul>
<h3>Conclusion</h3>
<p>In this post I have shown how to use Fluent NHibernate in a top-down approach in a Twitter like domain. Since I&#8217;m fairly new to NHibernate I welcome any comments and suggestions!</p>
<p style="vertical-align: middle;"><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/05/24/Mapping-a-Twitter-like-domain-with-Fluent-NHibernate.aspx&amp;title=Mapping%20a%20Twitter%20like%20domain%20with%20Fluent%20NHibernate" target="_blank"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/05/24/Mapping-a-Twitter-like-domain-with-Fluent-NHibernate.aspx" alt="kick it on DotNetKicks.com" width="82" height="18" border="0" /></a> <a href="http://dotnetshoutout.com/Mapping-a-Twitter-like-domain-with-Fluent-NHibernate" rev="vote-for"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fwww.bengtbe.com%2Fblog%2Fpost%2F2009%2F05%2F24%2FMapping-a-Twitter-like-domain-with-Fluent-NHibernate.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/05/24/mapping-a-twitter-like-domain-with-fluent-nhibernate/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using AutoMapper to map view models in ASP.NET MVC</title>
		<link>http://bengtbe.com/blog/2009/04/14/using-automapper-to-map-view-models-in-asp-net-mvc/</link>
		<comments>http://bengtbe.com/blog/2009/04/14/using-automapper-to-map-view-models-in-asp-net-mvc/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 04:27:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[AutoMapper]]></category>

		<guid isPermaLink="false">/blog/post/2009/04/14/Using-AutoMapper-to-map-view-models-in-ASPNET-MVC.aspx</guid>
		<description><![CDATA[In projects that have complex domain models it is often necessary to map the domain models to simpler objects such as Data Transfer Objects (DTO) which is &#8220;an object that carries data between processes in order to reduce the number of method calls&#8221; or Presentation Models which &#8220;represent the state and behavior of the presentation independently of [...]]]></description>
			<content:encoded><![CDATA[<p>In projects that have complex domain models it is often necessary to map the domain models to simpler objects such as <a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html" target="_blank">Data Transfer Objects (DTO)</a> which is &#8220;<em>an object that carries data between processes in order to reduce the number of method calls&#8221;</em> or <a href="http://martinfowler.com/eaaDev/PresentationModel.html" target="_blank">Presentation Models</a> which &#8220;<em>represent the state and behavior of the presentation independently of the GUI controls used in the interface</em>&#8220;.</p>
<p>The mapping code is often boring and tedious to write, so when I first read about <a href="http://automapper.codeplex.com/" target="_blank">AutoMapper</a> it triggered my interest. In this post I will take a first look at AutoMapper, and show how it can be used to map a complex domain model to a view model in an ASP.NET MVC application.</p>
<p><strong>About AutoMapper</strong></p>
<p><span>The project homepage describes AutoMapper as &#8220;<em>a fluent configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to<br />
match up source to destination values. Currently, AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.</em>&#8220;</span></p>
<p>AutoMapper is a fairly new project; the current version is 0.30 Beta, and it seems to be in active development.</p>
<p><strong>A complex domain model</strong></p>
<p>The domain model that I&#8217;m going to use in this example is a <span style="text-decoration: underline;">Customer</span> class that has a reference to an <span style="text-decoration: underline;">Address</span> class:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">Customer</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> FirstName { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> LastName { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> Email { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: yellow;">Address</span> HomeAddress { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> GetFullName()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> <span style="color: #ff8000;">string</span>.Format(<span style="color: lime;">&#8220;{0} {1}&#8221;</span>, FirstName, LastName);</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p>The <span style="text-decoration: underline;">Address</span> class is as follows:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">Address</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> Address1 { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> Address2 { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> City { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> PostalCode { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> Country { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">}</p>
</div>
<p>Ok, I admit that this domain model is not very complex, but it will serve the purpose of this post <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>The simple view model</strong></p>
<p>The view is going to show a list of customers with name, email and country. We therefore create a view model called <span style="text-decoration: underline;">CustomerListViewModel</span>:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">CustomerListViewModel</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> FullName { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> Email { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: #ff8000;">string</span> HomeAddressCountry { <span style="color: #ff8000;">get</span>; <span style="color: #ff8000;">set</span>; }</p>
<p style="margin: 0px;">}</p>
</div>
<p>I save this view model in the file <span style="text-decoration: underline;">ViewModel/Customers/CustomerListViewModel.cs</span> in the web-project. In an ASP.NET MVC application the view models belong to the Web-project, they are not part of the domain model. Usually a view model belongs to a single controller, and its views.</p>
<p><strong>The controller</strong></p>
<p>The URL used to display the customers should be <span style="text-decoration: underline;">http://application/Customers/</span>, hence the name of the controller is <span style="text-decoration: underline;">CustomersController</span>, and the action used is the <span style="text-decoration: underline;">Index()</span>:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">class</span> <span style="color: yellow;">CustomersController</span> : <span style="color: yellow;">Controller</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: #ff8000;">private</span> <span style="color: #ff8000;">readonly</span> <span style="color: #2b91af;">ICustomerService</span> m_CustomerService;</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> CustomersController(<span style="color: #2b91af;">ICustomerService</span> customerService)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        m_CustomerService = customerService;</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    <span style="color: lime;">// GET: /Customers/</span></p>
<p style="margin: 0px;">    <span style="color: #ff8000;">public</span> <span style="color: yellow;">ActionResult</span> Index()</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">Customer</span>&gt; customers = m_CustomerService.GetCustomers();</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        <span style="color: yellow;">Mapper</span>.CreateMap&lt;<span style="color: yellow;">Customer</span>, <span style="color: yellow;">CustomerListViewModel</span>&gt;();</p>
<p style="margin: 0px;">        <span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">CustomerListViewModel</span>&gt; viewModelList =</p>
<p style="margin: 0px;"><span style="color: yellow;">           Mapper</span>.Map&lt;<span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">Customer</span>&gt;, <span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">CustomerListViewModel</span>&gt;&gt;(customers);</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        <span style="color: #ff8000;">return</span> View(viewModelList);</p>
<p style="margin: 0px;">    }</p>
<p style="margin: 0px;">}</p>
</div>
<p>In the above controller I use Dependency Injection to inject the <span style="text-decoration: underline;">CustomerService</span> in the constructor. In a <a href="/blog/post/2009/02/27/Using-StructureMap-with-the-ASPNET-MVC-framework.aspx" target="_blank">previous post</a> I have shown how to use Dependency Injection in the controllers.</p>
<p>When using AutoMapper you first have to create a map between the two classes:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: yellow;">Mapper</span>.CreateMap&lt;<span style="color: yellow;">Customer</span>, <span style="color: yellow;">CustomerListViewModel</span>&gt;();</p>
</div>
<p>The following line maps the list of <span style="text-decoration: underline;">Customers</span> to a list of <span style="text-decoration: underline;">CustomerListViewModel</span>:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">CustomerListViewModel</span>&gt; viewModelList =</p>
<p style="margin: 0px;"><span style="color: yellow;">   Mapper</span>.Map&lt;<span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">Customer</span>&gt;, <span style="color: #2b91af;">IList</span>&lt;<span style="color: yellow;">CustomerListViewModel</span>&gt;&gt;(customers);</p>
</div>
<p>If you just wanted to map a single instance you would use:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: yellow;">CustomerListViewModel</span> viewModel = <span style="color: yellow;">Mapper</span>.Map&lt;<span style="color: yellow;">Customer</span>, <span style="color: yellow;">CustomerListViewModel</span>&gt;(customer);</p>
</div>
<p>AutoMapper will perform the following mapping automatically:</p>
<ul>
<li><span style="text-decoration: underline;">FullName</span> gets its value by calling the <span style="text-decoration: underline;">Customer.GetFullName()</span> method.</li>
<li><span style="text-decoration: underline;">Email</span> gets its value from the <span style="text-decoration: underline;">Customer.Email</span> propery.</li>
<li><span style="text-decoration: underline;">HomeAddressCountry</span> gets its value from the <span style="text-decoration: underline;">Customer.HomeAddress.Country</span> property.</li>
</ul>
<p><strong>The view</strong></p>
<p>Below is the view used to display the view model:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">&lt;%</span>@ <span style="color: #ff8000;">Page</span> <span style="color: yellow;">Title</span>=&#8221;" <span style="color: yellow;">Language</span>=&#8221;C#&#8221; <span style="color: yellow;">MasterPageFile</span>=&#8221;~/Views/Shared/Site.Master&#8221;</p>
<p style="margin: 0px;"><span style="color: yellow;">       Inherits</span>=&#8221;System.Web.Mvc.ViewPage&lt;IEnumerable&lt;CustomerListViewModel&gt;&gt;&#8221; <span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">%&gt;</span></p>
<p style="margin: 0px;"><span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">&lt;%</span>@ <span style="color: #ff8000;">Import</span> <span style="color: yellow;">Namespace</span>=&#8221;MyApp.Web.ViewModels.Customers&#8221;<span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">%&gt;</span></p>
<p style="margin: 0px;">
<p style="margin: 0px;">&lt;<span style="color: #ff8000;">asp</span>:<span style="color: #ff8000;">Content</span> <span style="color: yellow;">ID</span>=&#8221;Content1&#8243; <span style="color: yellow;">ContentPlaceHolderID</span>=&#8221;MainContent&#8221; <span style="color: yellow;">runat</span>=&#8221;server&#8221;&gt;</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    &lt;<span style="color: #ff8000;">h2</span>&gt;Customer list&lt;/<span style="color: #ff8000;">h2</span>&gt;</p>
<p style="margin: 0px;">
<p style="margin: 0px;">    &lt;<span style="color: #ff8000;">table</span>&gt;</p>
<p style="margin: 0px;">        &lt;<span style="color: #ff8000;">tr</span>&gt;</p>
<p style="margin: 0px;">            &lt;<span style="color: #ff8000;">th</span>&gt;Name&lt;/<span style="color: #ff8000;">th</span>&gt;</p>
<p style="margin: 0px;">            &lt;<span style="color: #ff8000;">th</span>&gt;Email&lt;/<span style="color: #ff8000;">th</span>&gt;</p>
<p style="margin: 0px;">            &lt;<span style="color: #ff8000;">th</span>&gt;Country&lt;/<span style="color: #ff8000;">th</span>&gt;</p>
<p style="margin: 0px;">        &lt;/<span style="color: #ff8000;">tr</span>&gt;</p>
<p style="margin: 0px;">    <span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">&lt;%</span> <span style="color: #ff8000;">foreach</span> (<span style="color: #ff8000;">var</span> customer <span style="color: #ff8000;">in</span> Model) { <span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">%&gt;</span></p>
<p style="margin: 0px;">        &lt;<span style="color: #ff8000;">tr</span>&gt;</p>
<p style="margin: 0px;">            &lt;<span style="color: #ff8000;">td</span>&gt;<span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">&lt;%</span>= Html.Encode(customer.FullName) <span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">%&gt;</span>&lt;/<span style="color: #ff8000;">td</span>&gt;</p>
<p style="margin: 0px;">            &lt;<span style="color: #ff8000;">td</span>&gt;<span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">&lt;%</span>= Html.Encode(customer.Email) <span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">%&gt;</span>&lt;/<span style="color: #ff8000;">td</span>&gt;</p>
<p style="margin: 0px;">            &lt;<span style="color: #ff8000;">td</span>&gt;<span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">&lt;%</span>= Html.Encode(customer.HomeAddressCountry) <span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">%&gt;</span>&lt;/<span style="color: #ff8000;">td</span>&gt;</p>
<p style="margin: 0px;">        &lt;/<span style="color: #ff8000;">tr</span>&gt;</p>
<p style="margin: 0px;">    <span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">&lt;%</span> } <span style="background: #ffee62 none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">%&gt;</span></p>
<p style="margin: 0px;">    &lt;/<span style="color: #ff8000;">table</span>&gt;</p>
<p style="margin: 0px;">&lt;/<span style="color: #ff8000;">asp</span>:<span style="color: #ff8000;">Content</span>&gt;</p>
<p style="margin: 0px;">
<p style="margin: 0px;">&lt;<span style="color: #ff8000;">asp</span>:<span style="color: #ff8000;">Content</span> <span style="color: yellow;">ID</span>=&#8221;Content2&#8243; <span style="color: yellow;">ContentPlaceHolderID</span>=&#8221;head&#8221; <span style="color: yellow;">runat</span>=&#8221;server&#8221;&gt;&lt;/<span style="color: #ff8000;">asp</span>:<span style="color: #ff8000;">Content</span>&gt;</p>
</div>
<p>As you can see from the <span style="text-decoration: underline;">Inherits</span> attribute, this view is strongly typed to the <span style="text-decoration: underline;">IEnuerable&lt;CustomerListViewModel&gt;</span>. The <span style="text-decoration: underline;">foreach</span> uses the <span style="text-decoration: underline;">Model</span> property to retrieve the list of <span style="text-decoration: underline;">CustomerListViewModel</span>, and creates a table row for each instance.</p>
<p><strong>Some advanced features of AutoMapper</strong></p>
<p>In the example above I have shown some simple usages of AutoMapper. I will now take a quick look at some of its more advanced features:</p>
<p>Let&#8217;s say that the <span style="text-decoration: underline;">Customer</span> has a <span style="text-decoration: underline;">Birthday</span> property of type <span style="text-decoration: underline;">DateTime</span> that we want to map to a <span style="text-decoration: underline;">YearOfBirth</span> property of type <span style="text-decoration: underline;">int</span>:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: yellow;">Mapper</span>.CreateMap&lt;<span style="color: yellow;">Customer</span>, <span style="color: yellow;">CustomerListViewModel</span>&gt;()</p>
<p style="margin: 0px;">    .ForMember(dest =&gt; dest.YearOfBirth, opt =&gt; opt.MapFrom(src =&gt; src.Birthday.Year));</p>
</div>
<p>Don&#8217;t get confused by all the lamdas (=&gt;). The <span style="text-decoration: underline;">ForMember</span> method just says <span style="text-decoration: underline;">YearOfBirth</span> should get its value from <span style="text-decoration: underline;">Birthday.Year</span>.</p>
<p>AutoMapper can also help you test the mapping:</p>
<div style="background: #191919 none repeat scroll 0% 0%; font-family: Courier New; font-size: 10pt; color: white; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;">[<span style="color: yellow;">Test</span>]</p>
<p style="margin: 0px;"><span style="color: #ff8000;">public</span> <span style="color: #ff8000;">void</span> Should_be_able_to_map_Customer_to_CustomerListViewModel()</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">    <span style="color: yellow;">Mapper</span>.CreateMap&lt;<span style="color: yellow;">Customer</span>, <span style="color: yellow;">CustomerListViewModel</span>&gt;()</p>
<p style="margin: 0px;">        .ForMember(dest =&gt; dest.ThisIsMappedElsewhere, opt =&gt; opt.Ignore());</p>
<p style="margin: 0px;">    <span style="color: yellow;">Mapper</span>.AssertConfigurationIsValid();</p>
<p style="margin: 0px;">}</p>
</div>
<p>In the above test AutoMapper will check to make sure that every single member on <span style="text-decoration: underline;">CustomerListViewModel</span> has a corresponding member on the <span style="text-decoration: underline;">Customer</span>, except for the property <span style="text-decoration: underline;">ThisIsMappedElsewhere</span> that we told it to ignore.</p>
<p>There are many more features that I haven&#8217;t covered. You can find more information in the following places:</p>
<ul>
<li><a href="http://automapper.codeplex.com" target="_blank">AutoMapper on CodePlex</a></li>
<li><a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/tags/AutoMapper/default.aspx" target="_blank">The Blog of Jimmy Bogard</a></li>
<li><a href="http://groups.google.com/group/automapper-users" target="_blank">D<span>iscussion group</span></a></li>
</ul>
<p style="vertical-align: middle;"><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/04/14/Using-AutoMapper-to-map-view-models-in-ASPNET-MVC.aspx&amp;title=Using%20AutoMapper%20to%20map%20view%20models%20in%20ASP.NET%20MVC" target="_blank"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/04/14/Using-AutoMapper-to-map-view-models-in-ASPNET-MVC.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Using-AutoMapper-to-map-view-models-in-ASPNET-MVC" rev="vote-for"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fwww.bengtbe.com%2Fblog%2Fpost%2F2009%2F04%2F14%2FUsing-AutoMapper-to-map-view-models-in-ASPNET-MVC.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/04/14/using-automapper-to-map-view-models-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Book review: Microsoft .NET: Architecting Applications for the Enterprise</title>
		<link>http://bengtbe.com/blog/2009/03/09/book-review-microsoft-net-architecting-applications-for-the-enterprise/</link>
		<comments>http://bengtbe.com/blog/2009/03/09/book-review-microsoft-net-architecting-applications-for-the-enterprise/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 07:17:00 +0000</pubDate>
		<dc:creator>bengtbe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Book]]></category>

		<guid isPermaLink="false">/blog/post/2009/03/09/Book-review-Microsoft-NET-Architecting-Applications-for-the-Enterprise.aspx</guid>
		<description><![CDATA[Authors: Dino Esposito &#38; Andrea Saltarello Publisher: Microsoft Press Purchase: Amazon.com, Amazon.co.uk Introduction I first heard of this book when Jeremy Miller (the maker of StructureMap) wrote that he was impressed by it. So I decided to purchase it, and now I have finished reading it. Before I give my conclusion, lets start with a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://bengtbe.com/blog/wp-content/uploads/2009/03/ArchitectingApplicationsForTheEnterprise.jpg"><img class="alignright size-full wp-image-36" title="ArchitectingApplicationsForTheEnterprise" src="http://bengtbe.com/blog/wp-content/uploads/2009/03/ArchitectingApplicationsForTheEnterprise.jpg" alt="" width="196" height="239" /></a></p>
<p><strong>Authors:</strong> Dino Esposito &amp; Andrea Saltarello<br />
<strong>Publisher:</strong> Microsoft Press<br />
<strong>Purchase: </strong><a href="http://www.amazon.com/Microsoft%C2%AE-NET-Architecting-Applications-PRO-Developer/dp/073562609X/" target="_blank">Amazon.com</a>, <a href="http://www.amazon.co.uk/Microsoft-NET-Architecting-Applications-PRO-Developer/dp/073562609X">Amazon.co.uk</a></p>
<p><strong>Introduction</strong></p>
<p>I first heard of this book when Jeremy Miller (the maker of StructureMap) <a href="http://codebetter.com/blogs/jeremy.miller/archive/2008/12/04/stuff-i-do-like.aspx" target="_blank">wrote</a> that he was impressed by it. So I decided to purchase it, and now I have finished reading it. Before I give my conclusion, lets start with a summary of the different chapters in the book.</p>
<p><strong> 1. Architects and Architecture Today<br />
</strong></p>
<p>Discusses the design of architecture and the role of the architect. Also gives a brief overview of different models for software development: Waterfall, Agile and Microsoft Solutions Framework.</p>
<p><strong> 2. UML Essentials</strong></p>
<p>Covers the most important UML diagram types &#8211; Use Case, Class, and Sequence Diagrams. Describes three main modes of using UML &#8211; Sketch mode (emerging design), Blueprint mode (up front design), and Programming mode (Model-Driven Architecture).  The authors prefer to use UML as a sketching tool to communicate ideas, which seems like a sensible choice.</p>
<p><strong> 3. Design Principles and Patterns<br />
</strong></p>
<p>Looks at goals of design principles and design &#8211; High Cohesion, Low Couping, and Separation of Concerns. Also looks at more advanced Object-Oriented Design principles &#8211; Open/Closed Principle, Liskov&#8217;s Substitution Principle, and Dependency Inversion Principle. Aspect-Oriented programming (AOP) is also explained by looking at <a href="http://msdn.microsoft.com/en-us/library/cc511729.aspx" target="_blank">Microsft&#8217;s Policy Injection Application Block</a>.</p>
<p>This concludes the first part of the book, the rest of it looks at how to design a system by going through each application layer.</p>
<p><strong>4. The Business Layer<br />
</strong></p>
<p>Discusses different ways to organize business logic. The business logic can either be organized around user actions or around the domain. When organizing the logic around user actions, either the Transaction Script (TS) or Table Module (TM) pattern can be applied. These are best suited for low complexity in the domain. When organizing around the domain a Domain Model (DM) pattern can be applied. This pattern can deal with high complexity in the domain.</p>
<p><strong>5. The Service Layer<br />
</strong></p>
<p>The service layer is placed between the presentation layer and the business layer, it can also be thought as the upper part of the business layer. It basically is a list of actions that can be triggered from the user interface. One of its main responsibilities is dealing with roles and security. The chapter also discusses the following patterns that are related to the service layer &#8211; the Remote Facade Pattern, the Data Transfer Object Pattern, and the Adapter Pattern. It has a good discussion on when to use DTO&#8217;s and when it can be considered overkill. It gives a brief introduction to Service-Oriented Arhcitecture (SOA). Finally, it discusses the Serivice Layer in regards to AJAX.</p>
<p><strong>6. The Data Access Layer<br />
</strong></p>
<p>Starts off with a discussion of the responsibilities of a Data Access Layer (DAL), and how it &#8220;communicates&#8221; with the other layers. Then it describes patterns and principles to use when manually designing your own DAL &#8211; Service Locator, Inversion of Control, Transactions, Data Context, Query by Criteria, Unit of Work, Concurrency, and Lazy Loading. Afterwards it looks how an Object/Relational Mapper (OR/M) tool can be used to power the DAL, using <a href="http://www.nhibernate.org">NHibernate</a> as an example. The authors consider NHibernate to be the <em>de facto</em> standard for O/RM tools, while Entity Framework (EF) is not yet mature enough. At the end of the chapter there is a great section called &#8220;To SP or Not to SP&#8221;, where the authors dispel many myths about Stored Procedures. At last, a book from Microsoft where SP are not described as the core of a DAL <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>7. The Presentation Layer<br />
</strong></p>
<p>Presents the responsibilities of the presentation layer, and splits it into two segments &#8211; the user interface and presentation logic. Gives a great overview of the evolution of presentation patterns &#8211; Autonomous Views (AV), Model-View-Controller (MVC), Model2, Model-View-Presenter (MVP), and Presentation Model (PM). Also shows examples from different presentation frameworks &#8211; <a href="http://msdn.microsoft.com/en-us/library/cc304793.aspx" target="_blank">Web Client Software Factory</a>, <a href="http://www.asp.net/mvc/" target="_blank">ASP.NET MVC Framework</a>, <a href="http://www.mvcsharp.org/" target="_blank">MVC# Framework</a>, and Windows Presentation Foundation.</p>
<p><strong>Conclusion</strong></p>
<p>I truly recommend this book to both intermediate and senior .NET developers. It has a great coverage of many current thoughts and aspects of system architecture. Many of the patterns in the book are from <a href="http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420/" target="_blank">Patterns of Enterprise Application Architecture</a> by Martin Fowler, and the book sets them into perspective in an enterprise .NET application. I like that a Microsoft Press book describes and even recommends Open Source tools, e.g. the book recommends NHibernate over Entity Framework. Dino&#8217;s writing is very consise and clear, and the book is full of code-examples, not just theory. However, since the scope of the book is very big, it cannot go into too much detail. So don&#8217;t expect to learn all you need about e.g. Domain Driven Design or NHibernate by reading this book.</p>
<p>Overall I give this book <strong>4.5 of 5 stars</strong> <img src='http://bengtbe.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p style="vertical-align: middle;"><a href="http://www.dotnetkicks.com/kick/?url=http://www.bengtbe.com/blog/post/2009/03/09/Book-review-Microsoft-NET-Architecting-Applications-for-the-Enterprise.aspx&amp;title=Book%20review:%20Microsoft%20.NET:%20Architecting%20Applications%20for%20the%20Enterprise" target="_blank"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.bengtbe.com/blog/post/2009/03/09/Book-review-Microsoft-NET-Architecting-Applications-for-the-Enterprise.aspx" alt="kick it on DotNetKicks.com" border="0" /></a> <a href="http://dotnetshoutout.com/Book-review-Microsoft-NET-Architecting-Applications-for-the-Enterprise30" rev="vote-for"><img style="border: 0px none;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fwww.bengtbe.com%2Fblog%2Fpost%2F2009%2F03%2F09%2FBook-review-Microsoft-NET-Architecting-Applications-for-the-Enterprise.aspx" alt="Shout it" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://bengtbe.com/blog/2009/03/09/book-review-microsoft-net-architecting-applications-for-the-enterprise/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

